index.js 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. const express = require('express');
  2. const Module = require('../../base/Module');
  3. const RepositorySystem = require('../../systems/RepositorySystem');
  4. const RoutingSystem = require('../../systems/RoutingSystem');
  5. const request = require('request');
  6. const config = require('./config');
  7. const rp = require('request-promise');
  8. const xml2js = require('xml2js');
  9. const knex = require('../../database/db');
  10. class XmlSyncModule extends Module {
  11. constructor(){
  12. super();
  13. this.repository = RepositorySystem.create('Products');
  14. this.CatRepo = RepositorySystem.create('Category');
  15. this.CompRepo = RepositorySystem.create('Company');
  16. this.parser = new xml2js.Parser();
  17. this.router = express.Router();
  18. this.init();
  19. }
  20. init() {
  21. let routes = [
  22. {
  23. type: 'custom',
  24. method: 'get',
  25. endpoint: '/sync',
  26. customFn: (req,res) => {
  27. this.parseXml()
  28. .then((products) => this.SyncDB(products))
  29. .then(() => res.status(200).send())
  30. .catch((e) => res.status(400).send(e))
  31. }
  32. },
  33. {
  34. type: 'custom',
  35. method: 'get',
  36. endpoint: '/test',
  37. customFn: (req,res) => {
  38. this.test()
  39. .then(() => res.status(200).send())
  40. .catch((e) => res.status(400))
  41. }
  42. },
  43. ];
  44. RoutingSystem.loadRoutes(routes, this.router);
  45. }
  46. test() {
  47. return this.repository.insert({
  48. id : 1,
  49. name: 'skata'
  50. }).catch(() => console.log("EROR"))
  51. }
  52. parseXml() {
  53. let options = {
  54. method:"GET",
  55. uri: config.xml.api
  56. }
  57. return new Promise((resolve,reject) => {
  58. console.log("Requesting xml...");
  59. rp(options).then((data) => {
  60. console.log("Data received...");
  61. this.parser.parseString(data,(err,result) => {
  62. console.log(err, result);
  63. if(err) reject(err);
  64. try{
  65. let products = result.store.products[0].product;
  66. resolve(products);
  67. }catch(e){
  68. reject(e);
  69. }
  70. })
  71. })
  72. .catch((err) => {
  73. console.log("Error Receiving:");
  74. console.log(err);
  75. throw err;
  76. })
  77. })
  78. }
  79. SyncDB(products){
  80. var DBprods,XmlProds;
  81. console.log("Syncing...");
  82. return this.repository.getPage(1,10000)
  83. .then((prods) => {
  84. DBprods = prods.reduce((dict,item) => {
  85. let id = item.id;
  86. dict[id] = item;
  87. return dict;
  88. }, {})
  89. XmlProds = products.reduce((dict,item) => {
  90. let id = item.productId[0];
  91. dict[id] = item;
  92. return dict;
  93. }, {})
  94. console.log("Length ---> ",products.length)
  95. let Promises = Object.keys(XmlProds).map((key,indx) => {
  96. //return new Promise((resolve,reject) => {
  97. //})
  98. let data = {};
  99. try {
  100. data.id = parseInt(XmlProds[key].productId[0]);
  101. //data.name = XmlProds[key].name[0];
  102. data.price = parseFloat(XmlProds[key].price[0]);
  103. data.name = XmlProds[key].productname[0];
  104. data.quantity = XmlProds[key].quantity[0];
  105. data.description = XmlProds[key].description[0];
  106. data.shortdescription = XmlProds[key]["description-short"][0];
  107. data.weight = parseFloat(XmlProds[key].weight[0]);
  108. data.image = XmlProds[key].image.length ? XmlProds[key].image[0] : '';
  109. data.reference = XmlProds[key].reference.length ? XmlProds[key].reference[0] : '';
  110. //extracting company and category name --> Category_path structure --> [' home > Toners > Hp']
  111. let extra_data = XmlProds[key].Category_Path[0].split('>');
  112. var category = extra_data[1] && extra_data[1].replace(' ','');
  113. var company = extra_data[2] && extra_data[2].replace(' ','');
  114. } catch(e) {
  115. console.log("INIT FAILED : ", data);
  116. console.log("ERROR: ", e);
  117. return () => Promise.resolve(true);
  118. }
  119. let keys = key;
  120. return () => Promise.resolve()
  121. .then(() => {if(category) return this.getCategoryId(category).then((id) => data.Category_id = id)})
  122. .then(() => {if(company) return this.getCompanyId(company).then((comp_id) => data.Company_id = comp_id)})
  123. .then(() => {
  124. return DBprods[keys] ? this.updateProduct(keys,data) : this.insertProduct(data)
  125. })
  126. });
  127. let ptimeout = (d,t) => new Promise((r,e) => setTimeout(() => r(d),t));
  128. return Promises.reduce((promiseChain, currentTask) => {
  129. return promiseChain.then(chainResults => {
  130. return currentTask()
  131. .then(currentResult => [ ...chainResults, currentResult ])
  132. });
  133. }, Promise.resolve([]));
  134. })
  135. .then(() => this.removeExtra(DBprods, XmlProds))
  136. .catch((e) => console.log(e))
  137. }
  138. removeExtra(db, xml) {
  139. console.log("REMOVING EXTRA...");
  140. for(var i in xml) {
  141. delete db[i];
  142. }
  143. let dbids = Object.keys(db);
  144. dbids = dbids.map((i) => parseInt(i));
  145. let Promises = [];
  146. for(let i=0; i < dbids.length -1 ; i+=1 ) {
  147. if(!dbids[i])continue;
  148. var k = i;
  149. let sub = dbids.slice(k, k+1);
  150. Promises.push(
  151. this.repository.raw()
  152. .whereIn('id', sub)
  153. .update({deleted : 1})
  154. );
  155. }
  156. return Promise.all(Promises);
  157. }
  158. getCompanyId(comp) {
  159. return this.CompRepo.get('name',comp)
  160. .then((company) => {
  161. if(company.length){
  162. return company[0].id;
  163. }else{
  164. let data = {
  165. name:comp
  166. }
  167. return this.CompRepo.insert(data).returning('id');
  168. }
  169. })
  170. }
  171. getCategoryId(cat){
  172. return this.CatRepo.get('name',cat)
  173. .then((category) => {
  174. if(category.length){
  175. return category[0].id;
  176. }else{
  177. let data = {
  178. name:cat
  179. }
  180. return this.CatRepo.insert(data).returning('id');
  181. }
  182. })
  183. }
  184. disableProduct(id) {
  185. return this.repository.update(''+id, { deleted:1 });
  186. }
  187. insertProduct(data) {
  188. data.updatedAt = knex.fn.now()
  189. return this.repository.insert(data)
  190. }
  191. updateProduct(id,data) {
  192. data.updatedAt = knex.fn.now()
  193. return this.repository.update(id,data);
  194. }
  195. }
  196. module.exports = XmlSyncModule;