const express = require('express'); const path = require('path'); const CrudModule = require('klapi/base/CrudModule'); const OneToOne = require('klapi/base/OneToOne'); const RepositorySystem = require('klapi/systems/RepositorySystem'); const RoutingSystem = require('klapi/systems/RoutingSystem'); const Actions = require('klapi/systems/ActionSystem'); var db = require("../../db.js"); //const FilterService = require(;'') var knex = require('knex')(db); let CategoriesScheme = { fields: [ { key: "sku", type: "string", unique: true, keyLength: 50 }, { key: "link", type: "text" }, { key: "price", type: "decimal" }, { key: "title", type: "text" }, { key: "category", type: "text" } ] }; class SKUModule extends CrudModule { constructor(){ super('/skus', [1,0,1,1,0], 'SKU', '', ); this.repository = RepositorySystem.create('SKU', CategoriesScheme); this.setRepo(this.repository); this.categories = new OneToOne('Categories', 'SKU'); this.init(); Actions.on('getSKU', (sku) => { return this.selectSKU(sku); }) Actions.on('ArraygetSKU',(skus) => { return this.selectSKU(skus); }) Actions.on('getProducts',(product) => { return this.repository.get('sku',product.SKU) .then((sku) => { product['title'] = sku[0].title; return product; }) }) Actions.on('ArraygetProducts',(product) => { return this.repository.get('sku',product.SKU) .then((sku) => { product['title'] = sku[0].title; return product; }) }) } init(){ let routes = [ { type:"custom", method:"get", endpoint:"/notifications", customFn: (req,res) => { this.notifications() .then((prod) => { res.send(prod) }) .catch((e) => { console.log("errio form here",e) res.send(e); }) } } ]; RoutingSystem.loadRoutes(routes, this.router); } selectSKU(product){ return knex("Products").select('price').count('id as Shops').where({sku:product.sku}).groupBy('price').orderBy('Shops','desc')// .then((suggested_item) => { let price = suggested_item[0].price; let paravates = suggested_item.filter((item) => item.price < price ) let number_of_paraviaseis = paravates.reduce((accumulator,item) => accumulator+item.Shops,0) product['suggested_price'] = price; product['paraviaseis'] = number_of_paraviaseis; return product; }) } notifications(){ return knex('SKU').select('*').limit(48) .then((skus) => Promise.all(skus.map((sku) => { let suggested_price; return this.selectSKU(sku) .then((sku) => { suggested_price = sku['suggested_price']; return sku['suggested_price']}) .then((suggested_price) =>{ return knex('Products').select("*").where('price','<',suggested_price).where({sku:sku.sku}) }) .then((paravates) => paravates.map((item) => { item['actual_price'] = suggested_price; item['discount'] = (suggested_price - item.price)/suggested_price; item.link = sku.link; return item; })) .then((products) => Actions.emitArray('getProducts',products)) })) .then((result) => [].concat.apply([], result)) ) } } module.exports = SKUModule;