Advertisement
Guest User

Untitled

a guest
Dec 11th, 2018
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var TelegramBot = require('node-telegram-bot-api');
  2. const mysql = require('mysql2/promise');
  3. const moment = require('moment')
  4. const ejs = require('ejs');
  5. const diff = require('deep-object-diff').detailedDiff;
  6. var token = '781591989:AAEhXXunW44d5pHwnLJbJyP-ybE3jRetMqE';
  7. var bot = new TelegramBot(token, { polling: true });
  8.  
  9. const Html2Pdf = require('./HtmlToPdf');
  10.  
  11.  
  12.  
  13. /** @type {Map<number, string>} */
  14. const chatStatuses = new Map();
  15. const chatNaklads = new Map();
  16. const chatItems = new Map();
  17. const userStatus = {
  18.     NEW: 'new',
  19.     CREATING_NAKLAD: {
  20.         NEW: 'creatingNaklad_new',
  21.         GOT_BILL: 'nakladHasBill',
  22.         GOT_NAMES: 'nakladHasNames',
  23.         GOT_AMOUNTS: 'nakladHasAmount',
  24.         GOT_PRICES: 'nakladHasPrices',
  25.         GOT_SUMM: 'nakladHasSumm',
  26.         GOT_WAREHOUSE: 'nakladHasWarehouse'
  27.     },
  28.     PRINT: {
  29.         BILL: 'printBill',
  30.         REESTR: 'printReestr',
  31.         NAKLAD: 'printNaklad',
  32.         ORDER: 'printOrder'
  33.     }
  34. }
  35. let connection;
  36. async function initDatabase() {
  37.     connection = await mysql.createConnection({
  38.         host: 'localhost',
  39.         user: 'root',
  40.         password: 'Password123',
  41.         database: 'compbotdb',
  42.         dateStrings: true
  43.     });
  44. }
  45.  
  46. async function registration(id, name, pass, role) {
  47.     const quer = await connection.query(`
  48.         INSERT INTO users (login,password_,role) VALUES('${name}','${pass}','${role}');
  49.      `);
  50.     if(quer[0].affectedRows>0){
  51.         return true;
  52.     }
  53.     return false;
  54. }
  55.  
  56. async function billHistory(count) {
  57.     if(count>=0){
  58.         const quer = await connection.query(`
  59.             SELECT bill.id, bill.bill_date, distributors.name, bill.summ, bill.payment FROM bill
  60.             LEFT JOIN distributors ON bill.distributor = distributors.id
  61.             ORDER BY bill.id
  62.             LIMIT 5 OFFSET ${count}
  63.         `);
  64.         return quer && quer[0];
  65.     }
  66.     return false;
  67.    
  68. } //список счет-фактур
  69. //смаржить все результаты в 1 массив
  70. async function getBill(Id){
  71.     const quer = await connection.query(`
  72.         SELECT catalog_prod.name, catalog_prod.measure, tovari_bills.amount, tovari_bills.price,
  73.             (tovari_bills.price - (tovari_bills.price * 20)/100) priceNoPDV,  
  74.             (bill.id) billId, (bill.bill_date) billDate,
  75.             (distributors.name) distName, (distributors.address) distAdress,
  76.             (distributors.ident_code) distCode, (distributors.t_number) distTel, (distributors.e_mail) distEmail
  77.         FROM bill
  78.             LEFT JOIN distributors ON bill.distributor = distributors.id
  79.             LEFT JOIN tovari_bills ON bill.id = tovari_bills.id_bill
  80.             LEFT JOIN catalog_prod ON tovari_bills.id_tovar = catalog_prod.id
  81.         WHERE bill.id = ${Id}
  82.     `);
  83.     const quer1 = await connection.query(`
  84.         SELECT (bill.summ) summPDV,(bill.summ - (bill.summ*20)/100) summNoPDV
  85.         FROM bill
  86.             LEFT JOIN tovari_bills ON bill.id = tovari_bills.id_bill
  87.         WHERE bill.id = ${Id}
  88.     `)
  89.     const bills = quer[0];
  90.     const summs = quer1[0];
  91.     const billDate = moment(bills.billDate).format('YYYY-MM-DD');
  92.     const foundBill = bills[0];
  93.     const foundSumm = summs[0];
  94.     const bill = {
  95.             billId: Id,
  96.             billDate: billDate,
  97.             distName: foundBill.distName,
  98.             distAdress: foundBill.distAdress,
  99.             distCode: foundBill.distCode,
  100.             distTel: foundBill.distTel,
  101.             distEmail: foundBill.distEmail,
  102.             summNoPDV: foundSumm.summNoPDV,
  103.             summPDV: foundSumm.summPDV
  104.     };
  105.  
  106.     const items = bills.map(i => {
  107.             return {
  108.                     name: i.name,  
  109.                     measure: i.measure,
  110.                     amount: i.amount,
  111.                     priceNoPDV: i.priceNoPDV,
  112.                     price: i.price  
  113.                     }
  114.                 });
  115.      bill.items = items;
  116.     return bill;
  117. }
  118.  
  119. async function billConfirmation(id) {
  120.     const billID = id;
  121.     const quer = await connection.execute(`UPDATE bill SET bill.confirm = 1 WHERE bill.id = ${billID}`);
  122.     console.dir(quer);
  123.     if(quer[0].changedRows>0){
  124.         return true;
  125.     }else{
  126.         return false;
  127.     }
  128. } //подтверждение~
  129. //common (1-2)
  130. async function countRowsNaklad(){
  131.     const countOfNaklad = await connection.execute(`
  132.         SELECT COUNT(id) AS countOfRows FROM naklad
  133.     `);
  134.     return countOfNaklad[0][0].countOfRows;
  135. }
  136.  
  137. async function countRowsOrder(){
  138.     const countOfOrders = await connection.execute(`
  139.         SELECT COUNT(id) AS countOfRows FROM orders
  140.     `);
  141.     return countOfOrders[0][0].countOfRows;
  142. }
  143.  
  144. async function countRowsBills(){
  145.     const countOfBills = await connection.execute(`
  146.         SELECT COUNT(id) AS countOfRows FROM bill
  147.     `);
  148.     return countOfBills[0][0].countOfRows;
  149. }
  150.  
  151. async function countRowsCatalog(){
  152.     const countOfGoods = await connection.execute(`
  153.         SELECT COUNT (id) AS countOfRows FROM catalog_prod
  154.     `);
  155.     return countOfGoods[0][0].countOfRows;
  156. }
  157.  
  158. async function viewCatalog(count) {
  159.     if(count>=0){
  160.             const resp = await connection.execute(`
  161.             SELECT * FROM catalog_prod LIMIT 5 OFFSET ${count};
  162.             `);
  163.         return resp && resp[0];
  164.     }
  165.     return false;
  166. }
  167.  
  168. async function viewGood(id) {
  169.     const goodID = id;
  170.     const quer = await connection.execute(`
  171.         SELECT * FROM catalog_prod WHERE catalog_prod.id = ${goodID}`);
  172.     const res = quer[0];
  173.     return res && res[0];
  174. }
  175.  
  176. async function editCatalog(id, Col, Val) {
  177.     const quer = await connection.execute(`
  178.         UPDATE catalog_prod SET catalog_prod.${Col} = ${sqlValue(Val)} WHERE id = ${id};
  179.     `);
  180.     if(quer[0].changedRows>0){
  181.         return true;
  182.     }
  183.     return false;
  184. }
  185.  
  186. async function deleteGood(id) {
  187.     const goodId = id;
  188.     const quer = await connection.execute(`
  189.         DELETE FROM catalog_prod WHERE id = ${goodId};
  190.     `);
  191.     if(quer[0].affectedRows>0){
  192.         return true;
  193.     }
  194.     return false;
  195. }
  196.  
  197. //common (1-3)
  198. //для менеджера
  199. async function checkOrderBill(orderId, billId) {
  200.     const getOrder = await connection.execute(`
  201.         SELECT  (orders.id) orderId, (orders.summ) orderSumm, (orders.order_date) orderDate,
  202.                 (tovar_order.amount) orderAmount, (tovar_order.price) orderPrice, (tovar_order.id_tovar) orderGood,
  203.                 (catalog_prod.name) orderGoods
  204.         FROM orders
  205.             LEFT JOIN tovar_order ON orders.id = tovar_order.id_order
  206.             LEFT JOIN catalog_prod ON tovar_order.id_tovar = catalog_prod.id
  207.         WHERE orders.id = ${orderId}
  208.         ORDER BY tovar_order.id_tovar`);
  209.     const getBill = await connection.execute(`
  210.         SELECT  (bill.id) billId, (bill.summ) billSumm, (bill.bill_date) billDate,
  211.                 (tovari_bills.amount) billAmount, (tovari_bills.price) billPrice, (tovari_bills.id_tovar) billGood,
  212.                 (catalog_prod.name) billGoods
  213.         FROM bill
  214.             LEFT JOIN tovari_bills ON bill.id = tovari_bills.id_bill
  215.             LEFT JOIN catalog_prod ON tovari_bills.id_tovar = catalog_prod.id
  216.         WHERE bill.id = ${billId}
  217.         ORDER BY tovari_bills.id_tovar`);
  218.     const foundOrder = getOrder[0];
  219.     const tempOrder = foundOrder[0];
  220.     const order = {
  221.         id: orderId,
  222.         date: tempOrder.orderDate,
  223.         summ: tempOrder.orderSumm
  224.     }
  225.     const orderGoods = foundOrder.map(i=>{
  226.         return{
  227.             name: i.orderGoods,
  228.             amount: i.orderAmount,
  229.             price: i.orderPrice
  230.         }
  231.     });
  232.     order.orderGoods = orderGoods;
  233.     const foundBill = getBill[0];
  234.     const tempBill = foundBill[0];
  235.     const bill = {
  236.         id: billId,
  237.         date: tempBill.billDate,
  238.         summ: tempBill.billSumm
  239.     };
  240.     const billGoods = foundBill.map(i=>{
  241.         return{
  242.             name:i.billGoods,
  243.             amount: i.billAmount,
  244.             price: i.billPrice
  245.         }
  246.     });
  247.     bill.billGoods = billGoods;
  248.     const differs = {};
  249.     const diffGoods = diff(bill.billGoods,order.orderGoods);
  250.     differs.goods = Object.entries(diffGoods.updated);
  251.     const difference = differs.goods.map(([i, obj]) => {
  252.         return {
  253.             ...billGoods[i],
  254.             updated: obj
  255.         };
  256.     });
  257.     difference.summ = bill.summ - order.summ;
  258.     console.dir(difference);
  259.     console.log(difference.length);
  260.     return difference;
  261.  
  262. }
  263.  
  264. async function getBills(name) {
  265.     const distr = name;
  266.     const res = await connection.execute(`
  267.         SELECT bill.id, bill.bill_date, distributors.name, bill.summ, bill.payment FROM bill
  268.         LEFT JOIN distributors ON bill.distributor = distributors.id
  269.         WHERE distributors.name LIKE '%${distr}%';`);
  270.     return res[0];
  271. } //выборка по счетам
  272.  
  273. async function getOrder({orderId, count}){
  274.     if(orderId){
  275.         const res = await connection.execute(`
  276.         SELECT orders.order_date, orders.summ,
  277.             (distributors.name) distName,
  278.             tovar_order.amount, tovar_order.price, (tovar_order.amount * tovar_order.price) summTov,
  279.             catalog_prod.name, catalog_prod.measure
  280.         FROM orders
  281.         LEFT JOIN distributors ON orders.distributor = distributors.id
  282.         LEFT JOIN tovar_order ON orders.id = tovar_order.id_order
  283.         LEFT JOIN catalog_prod ON tovar_order.id_tovar = catalog_prod.id
  284.         WHERE orders.id = ${orderId}
  285.                `);
  286.         const orderDate = moment(res.order_date).format('YYYY-MM-DD');
  287.         const foundOrder = res[0];
  288.         const tempOrder = foundOrder[0];
  289.         const order = {
  290.             id: orderId,
  291.             date: orderDate,
  292.             summ: tempOrder.summ,
  293.             distName: tempOrder.distName
  294.         };
  295.         const goods = foundOrder.map(i=>{
  296.             return{
  297.                 name: i.name,
  298.                 measure: i.measure,
  299.                 amount: i.amount,
  300.                 price: i.price,
  301.                 summTov: i.summTov
  302.             }
  303.         });
  304.         order.goods = goods;
  305.         console.dir(order);
  306.         return order;
  307.     }
  308.     if(count != undefined){
  309.         if(count >= 0){
  310.             const res = await connection.execute(`
  311.                 SELECT * FROM orders LIMIT 5 OFFSET ${count}
  312.             `);
  313.             return res[0];
  314.         }
  315.         return false;    
  316.     }
  317.    
  318. }
  319.  
  320. async function getBillConfirmed() {
  321.     const res = await connection.execute(`
  322.         SELECT bill.id, bill.bill_date, distributors.name, bill.summ, bill.payment FROM bill
  323.         LEFT JOIN distributors ON bill.distributor = distributors.id
  324.         WHERE bill.confirm = 1;    
  325.      `);
  326.     return res;
  327. } //выборку по оплач. счетам
  328.  
  329. async function getNaklad({ nakladId, count }){
  330.     if(nakladId){
  331.         const res = await connection.execute(`
  332.         SELECT (naklad.date_) nakladDate, naklad.bill_id, naklad.warehouse, naklad.summ, (naklad.summ - ((naklad.summ*20)/100)) summNoPDS,
  333.                naklad_order.amount, naklad_order.price, (naklad_order.price*naklad_order.amount) summTov,naklad_order.id_tovar,
  334.                (distributors.name) distName, distributors.address, distributors.ident_code, distributors.t_number, distributors.e_mail,
  335.                catalog_prod.name, catalog_prod.measure FROM naklad
  336.                LEFT JOIN bill ON naklad.bill_id = bill.id
  337.                LEFT JOIN distributors ON bill.distributor = distributors.id
  338.                LEFT JOIN naklad_order ON naklad.id = naklad_order.id_naklad
  339.                LEFT JOIN catalog_prod ON naklad_order.id_tovar = catalog_prod.id
  340.                WHERE naklad.id = ${nakladId};
  341.         `);
  342.         const nakladDate = moment(res.nakladDate).format('YYYY-MM-DD');
  343.         const foundNaklad = res[0];
  344.         const foundNaklad2 = foundNaklad[0];
  345.         const naklad = {
  346.             id : nakladId,
  347.             date : nakladDate,
  348.             warehouse: foundNaklad2.warehouse,
  349.             summ: foundNaklad2.summ,
  350.             summNoPDS: foundNaklad2.summNoPDS,
  351.             distName: foundNaklad2.distName,
  352.             distAdress: foundNaklad2.address,
  353.             distCode: foundNaklad2.ident_code,
  354.             distTel: foundNaklad2.t_number,
  355.             distEmail: foundNaklad2.e_mail,
  356.         }
  357.  
  358.         const goods = foundNaklad.map(i=>{
  359.             return{
  360.                 id: i.id_tovar,
  361.                 name: i.name,
  362.                 measure: i.measure,
  363.                 amount: i.amount,
  364.                 price: i.price,
  365.                 summTov: i.summTov
  366.             }
  367.         });
  368.         naklad.goods = goods;
  369.         return naklad;
  370.     }
  371.     if(count!=undefined){
  372.         if(count>=0){
  373.             const res = await connection.execute(`
  374.                 SELECT * FROM naklad LIMIT 5 OFFSET ${count};
  375.             `);
  376.             console.log('da');
  377.             return res[0];
  378.         }
  379.         console.log('net');
  380.         return false;
  381.     }
  382.    
  383. } //получение накладной
  384.  
  385. async function sendBillForConfirm(id) {
  386.     const resp = await connection.execute(`
  387.         SELECT password_ FROM users WHERE users.role = 'lead';
  388.     `);
  389.     return resp[0];
  390. } //отправить счет на проверку
  391. //для кладовщика
  392.  
  393. async function getGood({ goodId, goodName }){
  394.     if(goodId){
  395.         const quer = await connection.execute(`
  396.             SELECT * FROM catalog_prod
  397.             WHERE id = ${goodId}`);
  398.         return quer[0];
  399.     }
  400.     if(goodName){
  401.         const quer = await connection.execute(`
  402.             SELECT * FROM catalog_prod
  403.             WHERE name = '${goodName}'`);
  404.             return quer[0];
  405.     }
  406. }
  407.  
  408.  
  409. async function createNaklad(naklad) {
  410.     const insertNaklad = await connection.execute(`
  411.             INSERT INTO naklad (date_,bill_id,warehouse,summ)
  412.             VALUES('${naklad.date}',${naklad.billId},${naklad.warehouse}, ${naklad.summ})`);
  413.     //console.dir(insertNaklad);
  414.    for(const item of naklad.goods){
  415.        const getGoods = await getGood({goodName: item.name});
  416.        if(getGoods.length > 0){
  417.            const insertNakladTovar = await connection.execute(`
  418.             INSERT INTO naklad_order (id_naklad, id_tovar, amount, price)
  419.             VALUES (${insertNaklad[0].insertId}, ${getGoods[0].id}, ${item.amount}, ${item.price})`);
  420.             if(insertNakladTovar[0].changedRows > 0){
  421.                 return true;
  422.             }
  423.         }else{
  424.             const insertTovar = await connection.execute(`
  425.                     INSERT INTO catalog_prod (name, amount, price) VALUES ('${item.name}' ,${item.amount},${item.price})`);
  426.             const insertNakladTovar = await connection.execute(`
  427.                     INSERT INTO naklad_order (id_naklad, id_tovar, amount, price)
  428.                     VALUES (${insertNaklad[0].insertId}, ${insertTovar[0].insertId}, ${item.amount}, ${item.price})`);
  429.             if(insertNakladTovar[0].changedRows > 0){
  430.                 return true;
  431.            }
  432.         }
  433.    }
  434.    if(insertNaklad[0].changedRows > 0){
  435.        return true;
  436.    }
  437.    return true;
  438. } //накладная
  439.  
  440. async function createVedomostPostavok(date) {
  441.     const resp = await connection.execute(`
  442.         SELECT naklad.id, naklad.date_ , naklad.warehouse, naklad_order.amount, catalog_prod.name FROM naklad_order
  443.         LEFT JOIN naklad ON naklad_order.id_naklad = naklad.id
  444.         LEFT JOIN catalog_prod ON naklad_order.id_tovar = catalog_prod.id
  445.         WHERE naklad.date_ = '${date}'
  446.     `);
  447.     return resp[0];
  448. } //сформировать ведомость поcтавок для менеджера
  449.  
  450. async function getUnConfirmedBill(id){
  451.     if(!id){
  452.         const res = await connection.execute(`
  453.             SELECT bill.id, catalog_prod.name, tovari_bills.amount,bill.summ,bill.bill_date, distributors.name AS dist_name  FROM tovari_bills
  454.             LEFT JOIN catalog_prod ON tovari_bills.id_tovar = catalog_prod.id
  455.             LEFT JOIN bill ON tovari_bills.id_bill = bill.id
  456.             LEFT JOIN distributors ON bill.distributor = distributors.id
  457.             WHERE bill.confirm = 0;
  458.         `);
  459.         return res[0];
  460.     }else{
  461.         const resp = await connection.execute(`
  462.         SELECT bill.id, catalog_prod.name, tovari_bills.amount,bill.summ,bill.bill_date, distributors.name AS dist_name  FROM tovari_bills
  463.         LEFT JOIN catalog_prod ON tovari_bills.id_tovar = catalog_prod.id
  464.         LEFT JOIN bill ON tovari_bills.id_bill = bill.id
  465.         LEFT JOIN distributors ON bill.distributor = distributors.id
  466.         WHERE bill.id = ${id}
  467.         `);
  468.         return resp[0];
  469.     }
  470. }
  471.  
  472. // /n [billId] [warehouseId] [summ] [name,price,amount name,price,amount name,price,amount...]
  473. async function createNakladBotFunc(msg, match) {
  474.     const chatId = msg.chat.id;
  475.     const msgDate = msg.date;
  476.     const nakladDate = moment.unix(msgDate).format("YYYY-MM-DD");
  477.     const tempItems = {};
  478.     tempItems.date = nakladDate;
  479.     tempItems.billId = Number(match[1]);
  480.     tempItems.warehouse = Number(match[2]);
  481.     tempItems.summ = Number(match[3]);
  482.     tempItems.goods = [];
  483.     const goods = match[4].split(' ').map(i => i.split(','));
  484.     for(const item of goods) {
  485.         tempItems.goods.push({
  486.             name: item[0],
  487.             price: Number(item[1]),
  488.             amount: Number(item[2]),
  489.         });
  490.     }
  491.     const res = await createNaklad(tempItems);
  492.     if(res == true){
  493.         return true;
  494.     }
  495.     return false;
  496. }
  497.  
  498. // createBill [orderId] [distName] [summ] [name,price,amount name,price,amount name,price,amount...]
  499. async function createBillBotFunc(msg, match){
  500.     const billDate = moment.unix(msg.date).format('YYYY-MM-DD');
  501.     const tempBill={
  502.         date: billDate,
  503.         orderId: Number(match[1]),
  504.         distName: match[2],
  505.         summ: Number(match[3]),
  506.     };
  507.     tempBill.goods = [];
  508.     const goods = match[4].split(' ').map(i => i.split(','));
  509.     for(const item of goods) {
  510.         tempBill.goods.push({
  511.             name: item[0],
  512.             price: Number(item[1]),
  513.             amount: Number(item[2]),
  514.         });
  515.     }
  516.     const res =  await createBill(tempBill);
  517.     if(res===false){
  518.         return false;
  519.     }else{
  520.         return true;
  521.     }
  522. }
  523.  
  524. async function createBill(bill){
  525.     const getDistName = await connection.execute(`
  526.             SELECT id FROM distributors
  527.             WHERE name LIKE '%${bill.distName}%'`);
  528.     const distId = getDistName[0][0].id;
  529.     if(!distId){
  530.         return false;
  531.     }
  532.     const quer = await connection.execute(`
  533.             INSERT INTO bill (bill_date,distributor,summ,payment,confirm,order_id)
  534.             VALUES('${bill.date}',${distId},${bill.summ},0,0,${bill.orderId})`);
  535.     for(const item of bill.goods){
  536.         const getGoods = await getGood({goodName: item.name});
  537.         console.dir(getGoods);
  538.         if(getGoods.length === 0){
  539.             return false;
  540.         }
  541.         const insertBillGoods = await connection.execute(`
  542.                 INSERT INTO tovari_bills (id_bill, id_tovar, amount, price)
  543.                 VALUES (${quer[0].insertId},${getGoods[0].id},${item.amount},${item.price})`);
  544.         if(insertBillGoods[0].chengedRows > 0){
  545.             return true;
  546.         }
  547.     }
  548.     return  true;
  549. }
  550.  
  551. async function getReestr(date1, date2){
  552.     const res = await connection.execute(`
  553.         SELECT naklad.date_, naklad_order.amount, naklad_order.price, (naklad_order.price*naklad_order.amount) summTov,
  554.         (distributors.name) distName, catalog_prod.name, catalog_prod.measure
  555.         FROM naklad
  556.         LEFT JOIN bill ON naklad.bill_id = bill.id
  557.         LEFT JOIN distributors ON bill.distributor = distributors.id
  558.         LEFT JOIN naklad_order ON naklad.id = naklad_order.id_naklad
  559.         LEFT JOIN catalog_prod ON naklad_order.id_tovar = catalog_prod.id
  560.         WHERE date_ >= '${date1}' AND date_ <= '${date2}'
  561.         ORDER BY naklad.date_ `) ;
  562.        
  563.         const tempR = res[0];
  564.         const reestr = {
  565.                 date1 : date1,
  566.                 date2 : date2
  567.         };
  568.  
  569.         const goods = tempR.map(i=>{
  570.             return{
  571.                 distName : i.distName,
  572.                 name : i.name,
  573.                 amount: i.amount,
  574.                 price: i.price,
  575.                 measure: i.measure,
  576.                 summTov: i.summTov,
  577.                 date: moment(i.date_).format('YYYY-MM-DD')
  578.             }
  579.         });
  580.         reestr.goods = goods;
  581.         return reestr;
  582. }
  583.  
  584. async function getDistName(name){
  585.     const res = await connection.execute(`
  586.                     SELECT * FROM distributors
  587.                     WHERE name LIKE '%${name}%'`);
  588.     console.dir(res[0]);
  589.     return res[0];
  590. }
  591.  
  592. async function botInit() {
  593.     bot.onText(/\/start/, async (msg) => {
  594.         const chatId = msg.chat.id;
  595.         const user = await checkUsers(chatId);
  596.         if(user[0] && user[0].password_) {
  597.             await bot.sendMessage(chatId, `Доброго времени суток, ${user[0].login}\nДля просмотра списка доступных команд введите /main`);
  598.             return;
  599.         }
  600.         chatStatuses.set(chatId, userStatus.NEW);
  601.         await bot.sendMessage(chatId, [`Привет! Я - Бертруд, ваш персональный помощник по закаулкам нашей компании.`,
  602.                                         `Я помогу вам разобраться в том, что здесь происходит. Следуйте инструкциям!`,
  603.                                         `Для продолжения необходимо назначить вашу роль в системе (/setrole [lead, manager, worker]).`,
  604.                                         `Примечание: в [] приводятся доступные параметры`,
  605.                                        ].join('\n'));
  606.     });
  607.     bot.onText(/\/setrole (.+)/, async (msg, match) => {
  608.         const chatId = msg.chat.id;
  609.         const name = msg.from.username;
  610.         const role = match[1];
  611.         const pass = msg.chat.id;
  612.         if(name === undefined){
  613.             const fName = msg.from.first_name;
  614.             const sName = msg.from.last_name;
  615.             const fullName = `${fName}_${sName}`;
  616.             await registration(chatId, fullName, pass, role);
  617.             await bot.sendMessage(chatId, [`Вы успешно зарегестрированы в системе как ` + match[1] + `.`,
  618.                                         `Чтобы посмотреть список доступных команд введите /main'`,
  619.                                      ].join('\n'));
  620.  
  621.            chatStatuses.delete(chatId);
  622.            return;
  623.        }
  624.        await registration(chatId, name, pass, role);
  625.        await bot.sendMessage(chatId, [`Вы успешно зарегестрированы в системе как ` + match[1] + `.`,
  626.                                        `Чтобы посмотреть список доступных команд введите /main'`,
  627.                                       ].join('\n'));
  628.  
  629.         chatStatuses.delete(chatId);
  630.     });
  631.     bot.onText(/\/main/, async (msg) => {
  632.         const chatId = msg.chat.id;
  633.         const login = await checkUsers(chatId);
  634.        
  635.         if(login[0].role === 'lead'){
  636.             await bot.sendMessage(chatId,`Список доступных команд:`);
  637.             await bot.sendMessage(chatId, [
  638.                 `/billList - списко счет-фактур `,
  639.                 `/billsbyDist [имя_поставщика] -список счет-фактур от конкретного поставщика`,
  640.                 `/viewCatalog - каталог товаров в наличии `,
  641.                 `/getConfirmedBills - список подтвержденных счет-фактур `,
  642.                 `/getNaklad - список накладных `,
  643.                 `/orderList - список заказов`,
  644.                 `/addBill - зарегестрировать счет-фактуру`,
  645.             ].join('\n'));
  646.         }
  647.         if(login[0].role === 'manager'){
  648.             await bot.sendMessage(chatId,`Список доступных команд:`);
  649.             await bot.sendMessage(chatId, [
  650.                 `/billList - список счет-фактур`,
  651.                 `/billsbyDist [имя_поставщика] - список счет-фактур от конкретного поставщика`,
  652.                 `/viewCatalog - каталог товаров в наличии `,
  653.                 `/getConfirmedBills - список подтвержденных счет-фактур`,
  654.                 `/getNaklad - список накладных`,
  655.                 `/getUnconfBills - список неподтвержденных счет-фактур`,
  656.                 `/orderList - список заказов`,
  657.                 `/compareOrderBill [номер_заказа] [номер_счета]`,
  658.                 `/addBill - зарегестрировать счет-фактуру`,
  659.             ].join('\n'));
  660.         }
  661.         if(login[0].role === 'worker'){
  662.             await bot.sendMessage(chatId,`Список доступных команд:`);
  663.             await bot.sendMessage(chatId, [
  664.                 `/viewCatalog - каталог товаров в наличии`,
  665.                 `/createReestr - получить реестр поступлений за период `,
  666.                 `/createNaklad [номер_счет-фактуры] [номер_склада] [сумма] [[наименование,цена,количество] ...] - создать накладную`,
  667.             ].join('\n'));
  668.         }
  669.     });
  670.     //lead-manager
  671.     bot.onText(/\/billList/, async (msg) => {
  672.         const chatId = msg.chat.id;
  673.         const login = await checkUsers(chatId);
  674.         if(login[0].role != 'worker'){
  675.             chatStatuses.set(chatId,userStatus.PRINT.BILL);
  676.             await bot.sendMessage(chatId,[`Вы можете получить любой из доступных счет-фактур в виде файла.`,
  677.                                          `Для этого введите /print [billId]`,
  678.                                          ].join('\n'));
  679.             const resp = await billHistory(0);
  680.             const mess = [];
  681.             const options ={
  682.                 reply_markup:JSON.stringify({
  683.                     inline_keyboard:[
  684.                         [{text:'➡️',callback_data: 'bills_1'}],
  685.                     ]
  686.                 })
  687.             };
  688.             if(!resp){
  689.                 await bot.sendMessage(chatId,`Error 01`);
  690.             }else{
  691.                 await bot.sendMessage(chatId, `Cписок счет-фактур: `);
  692.                 console.dir(resp);
  693.                 for (const item of resp) {
  694.                     const payment = item.payment === 1 ? 'done' : 'undone';
  695.                     const message = `/${item.id} - ${item.bill_date}. ${item.name} - ${item.summ}, payment: ${payment}`;
  696.                     mess.push(message);
  697.                 }
  698.                 await bot.sendMessage(chatId, mess.join('\n'),options);
  699.                 console.dir(mess);
  700.             }
  701.         }else{
  702.             await bot.sendMessage(chatId, `Команда недоступна`);
  703.         }
  704.     });
  705.     //worker
  706.     bot.onText(/\/createReestr/, async (msg) => {
  707.         const chatId = msg.chat.id;
  708.         const login = await checkUsers(chatId);
  709.         if(login[0].role === 'worker'){
  710.             chatStatuses.set(chatId, userStatus.PRINT.REESTR);
  711.             await bot.sendMessage(chatId,[`Для получения реестра за период введите /print [нижняя_дата] [верхняя_дата]`,
  712.                                         `Дата вводится в формате ГГГГ-ММ-ДД`,
  713.                                         ].join('\n'));
  714.         }else{
  715.             await bot.sendMessage(chatId, `Команда недоступна`);
  716.         }
  717.        
  718.     });
  719.     //ALL
  720.     bot.onText(/\/viewCatalog/, async (msg) => {
  721.         const chatId = msg.chat.id;
  722.         //chatStatuses.set(chatId, userStatus.PRINT.REESTR);
  723.         const options ={
  724.             reply_markup:JSON.stringify({
  725.                 inline_keyboard:[
  726.                     [{text:'➡️',callback_data: 'goods_1'}],
  727.                 ]
  728.             })
  729.         };
  730.         const mess = [];
  731.         const resp = await viewCatalog(0);
  732.         if (!resp) {
  733.             await bot.sendMessage(chatId, `Ошибка`);
  734.         } else {
  735.             for(const item of resp){
  736.                 const message = `${item.id}. ${item.name}, Количество: ${item.amount}(${item.measure}), Цена ${item.price}`;
  737.                 mess.push(message);
  738.             }
  739.             console.dir(mess);
  740.             await bot.sendMessage(chatId, mess.join('\n'), options);
  741.            
  742.         }
  743.     });
  744.     //ALL
  745.     bot.onText(/\/viewGood (.+)/i, async (msg, match) => {
  746.         const chatId = msg.chat.id;
  747.         const goodId = Number(match[1]);
  748.         const good = await viewGood(goodId);
  749.         if(!good){
  750.             await bot.sendMessage(chatId,`Товар не найден`);
  751.         }
  752.         else{
  753.             const mess= [];
  754.             const field = Object.keys(good);
  755.             for (const item of field) {
  756.                 const message =`${item}: ${good[item]}`;
  757.                 mess.push(message);
  758.             }
  759.             await bot.sendMessage(chatId, mess.join('\n'));
  760.             await bot.sendMessage(chatId, [`Для редактирования записи воспользуйтейсь командой `,
  761.                                            `/edit [id] [field] [new_value]`,
  762.                                             ].join('\n'));
  763.         }
  764.         });
  765.     //lead-manager
  766.     bot.onText(/\/edit (.+?) (.+?) (.+)/i, async (msg, match) => {
  767.         const chatId = msg.chat.id;
  768.         const login = await checkUsers(chatId);
  769.         if(login[0].role != 'worker'){
  770.             const respId = Number(match[1]);
  771.             const respCol = match[2];
  772.             const respVal = parseVariable(match[3]);
  773.             if(respCol ===undefined || respId === undefined || respVal === undefined){
  774.                 await bot.sendMessage(chatId,`Проверьте правильность ввода команды`);
  775.                 return;
  776.             }
  777.             const resp = await editCatalog(respId, respCol, respVal);
  778.             if(resp){
  779.                 await bot.sendMessage(chatId,`Error 03`);
  780.             }else{
  781.                 await bot.sendMessage(chatId, `Успешно`);
  782.             }
  783.         }else{
  784.             await bot.sendMessage(chatId,`Команда недоступна`);
  785.         }
  786.     });
  787.     //lead-manager
  788.     bot.onText(/\/delete (.+)/, async (msg, match) => {
  789.         const chatId = msg.chat.id;
  790.         const login = await checkUsers(chatId);
  791.         if(login[0].role != 'worker'){
  792.                 const respId = Number(match[1]);
  793.             const resp = await deleteGood(respId);
  794.             if (resp === true) {
  795.                 await bot.sendMessage(chatId, 'Успешно удалено');
  796.             } else {
  797.                 await bot.sendMessage(chatId, 'Запись не найдена.');
  798.             }
  799.         }else{
  800.             await bot.sendMessage(chatId,`Команда недоступна`);
  801.         }
  802.        
  803.     });
  804.     //manager
  805.     bot.onText(/\/compareOrderBill (.+?) (.+)/, async (msg, match) => {
  806.         const chatId = msg.chat.id;
  807.         const login = await checkUsers(chatId);
  808.         if(login[0].role === 'manager'){
  809.             const orderID = Number(match[1]);
  810.             const billID = Number(match[2]);
  811.             if(orderID === undefined || billID === undefined){
  812.                 await bot.sendMessage(chatId,[`Проверьте правильность ввода команды`,
  813.                                              `/команда [номер_заказа] [номер_счета]`,
  814.                                              ].join('\n'));
  815.                 return;
  816.             }
  817.             const resp = await checkOrderBill(orderID, billID);
  818.             console.dir(resp)
  819.             if (resp.length>0){
  820.                 await bot.sendMessage(chatId, [`Имеются расхождения:`,
  821.                                               `Разница суммы (Счет-Заказ): ${resp.summ}`,
  822.                                               ].join('\n'));
  823.                 for (const item of resp) {
  824.                     const name = item.name === undefined ? '-' : item.name;
  825.                     const upName = item.updated.name === undefined ? '-' : item.updated.name;
  826.                     const price = item.price === undefined ? '-': item.price;
  827.                     const upPrice = item.updated.price === undefined ? '-' : item.updated.price;
  828.                     const amount = item.amount === undefined ? '-' : item.amount;
  829.                     const upAmount = item.updated.price === undefined ? '-' : item.updated.amount;
  830.                     await bot.sendMessage(chatId,[`ЗАКАЗАНЫЙ ТОВАР: ${name}, ПРЕДЛОЖЕННЫЙ: ${upName}`,
  831.                                                 `СТОИМОСТЬ: ${price}, ПРЕДЛОЖЕННАЯ: ${upPrice}`,
  832.                                                 `КОЛИЧЕСТВО: ${amount}, ПРЕДЛОЖЕННОЕ: ${upAmount}`,
  833.                                                 ].join('\n'));
  834.                 }
  835.                 await bot.sendMessage(chatId, [`Для подтверждения оплаты введите /confirm ${billID}`,
  836.                                                 ].join('\n'));
  837.             }else{
  838.                 await bot.sendMessage(chatId,`Расхождений не выявлено`);
  839.             }
  840.         }else{
  841.             await bot.sendMessage(chatId,`Команда недоступна`);
  842.             return;
  843.         }
  844.     });
  845.     bot.onText(/\/confirm (.+)/, async (msg, match) => {
  846.         const chatId = msg.chat.id;
  847.         const respId = Number(match[1]);
  848.         if(respId === undefined){
  849.             await bot.sendMessage(chatId,`Не указан номер счета!`);
  850.             return;
  851.         }
  852.         const resp = await billConfirmation(respId);
  853.         if(resp === true){
  854.             await bot.sendMessage(chatId, `Успешно`);  
  855.         }
  856.         else{
  857.             await bot.sendMessage(chatId,`Error 02`);
  858.         }
  859.     });
  860.     //lead-manager
  861.     bot.onText(/\/billsbyDist (.+)/, async (msg, match) => {
  862.         const chatId = msg.chat.id;
  863.         const login = await checkUsers(chatId);
  864.         if(login[0].role!='worker'){
  865.             const name = String(match[1]);
  866.             if(name === undefined){
  867.                 await bot.sendMessage(chatId,'Проверьте правильность ввода команды');
  868.                 return;
  869.             }
  870.             chatStatuses.set(chatId,userStatus.PRINT.BILL);
  871.             const mess = [];
  872.             const resp = await getBills(name);
  873.             if(resp){
  874.                 const bills = resp;
  875.                 console.dir(bills)
  876.                 for (const item of bills) {
  877.                     const payment = item.payment === 1 ? 'done' : 'undone';
  878.                     const message = `/${item.id} - ${item.bill_date}. ${item.name} - ${item.summ}, payment: ${payment}`;
  879.                     mess.push(message);
  880.                 }
  881.                 await bot.sendMessage(chatId, mess.join('\n'));
  882.             }else{
  883.                 await bot.sendMessage(chatId,`Error 04`);
  884.             }
  885.         }else{
  886.             await bot.sendMessage(chatId,`Команда недоступна`);
  887.         }
  888.        
  889.     });
  890.    
  891.     //manager-lead
  892.     bot.onText(/\/getConfirmedBills/, async msg => {
  893.         const chatId = msg.chat.id;
  894.         const login = await checkUsers(chatId);
  895.         if(login[0].role != 'worker'){
  896.             const resp = await getBillConfirmed();
  897.             const bills = resp[0];
  898.             console.dir(bills);
  899.             await bot.sendMessage(chatId, `Список подтвержденных счет-фактур: `);
  900.             for (const item of bills) {
  901.                 await bot.sendMessage(chatId, `/${item.id}. ${item.bill_date} - ${item.name}. Сумма: ${item.summ}`);
  902.             }
  903.         }else{
  904.             await bot.sendMessage(chatId, `Команда недоступна`);
  905.         }
  906.     });
  907.     //manager-lead
  908.     bot.onText(/\/getNaklad/, async msg => {
  909.         const chatId = msg.chat.id;
  910.         const login = await checkUsers(chatId);
  911.         if(login[0].role != 'worker'){
  912.             chatStatuses.set(chatId, userStatus.PRINT.NAKLAD);
  913.             const options ={
  914.                 reply_markup:JSON.stringify({
  915.                     inline_keyboard:[
  916.                         [{text:'➡️',callback_data: 'naklad_1'}],
  917.                     ]
  918.                 })
  919.             };
  920.             const mess = [];
  921.             const resp = await getNaklad({count : 0});
  922.             console.dir(resp);
  923.             await bot.sendMessage(chatId, `Список приходных накладных: `);
  924.             for (const item of resp){
  925.                 const message = [`/${item.id}. ${item.date_};`,
  926.                                 `Номер счет-фактуры ${item.bill_id}, на сумму: ${item.summ}.`,
  927.                                 `Товар пришел на склад №${item.warehouse}`,
  928.                                 ].join('\n');
  929.                 mess.push(message);
  930.             }
  931.             await bot.sendMessage(chatId, `Для получения файла введите /print [id]`);
  932.             await bot.sendMessage(chatId, mess.join('\n'),options);
  933.         }else{
  934.             await bot.sendMessage(chatId, `Команда недоступна`);
  935.         }
  936.        
  937.     });
  938.     //lead- manager
  939.     bot.onText(/\/getUnconfBills/, async (msg) => {
  940.         const chatId = msg.chat.id;
  941.         const login = await checkUsers(chatId);
  942.         if(login[0].role === 'manager'){  
  943.             const bills = await getUnConfirmedBill();
  944.             if(bills.length == 0){
  945.                 await bot.sendMessage(chatId, `Нет неподтвержденных`);
  946.                 return;
  947.             }
  948.             const billIds = new Set(bills.map(b=>b.id));
  949.             for (const billId of billIds) {
  950.                 const bill = bills.find(b=>b.id === billId);
  951.                 const items = bills.filter(b=>b.id === billId);
  952.                 await bot.sendMessage(chatId, [`/${billId}\nДата: ${bill.bill_date}.`,
  953.                                                         `${items.map(b => `  - ${b.name} (кол:${b.amount})`).join(',\n')}.`,
  954.                                                         `Сумма: ${bill.summ} грн.`,
  955.                                                         `Поставщик: ${bill.dist_name}.`,
  956.                                                         ].join('\n'));
  957.             }
  958.             await bot.sendMessage(chatId,`Для отправки счета на проверку: /sendBill [billId]`);
  959.         }else{
  960.             await bot.sendMessage(chatId,`Команда недоступна`);
  961.         }
  962.     });
  963.  
  964.     bot.onText(/\/sendBill (.+)/, async (msg,match)=>{
  965.         const chatId = msg.chat.id;
  966.         const id = Number(match[1]);
  967.         const users = await sendBillForConfirm();//id лида
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement