-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile-list.txt
4899 lines (4464 loc) · 156 KB
/
file-list.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
| .env.botazon-local
DBHOST=[PLACEHOLDER]
DBUSER=[PLACEHOLDER]
DBPASSWORD=[PLACEHOLDER]
DBDATABASE=[PLACEHOLDER]
SPORT=[PLACEHOLDER]
SELLING_PARTNER_APP_CLIENT_ID=[PLACEHOLDER]
SELLING_PARTNER_APP_CLIENT_SECRET=[PLACEHOLDER]
AWS_ACCESS_KEY_ID=[PLACEHOLDER]
AWS_SECRET_ACCESS_KEY=[PLACEHOLDER]
AWS_SELLING_PARTNER_ROLE=[PLACEHOLDER]
sellerId=[PLACEHOLDER]
AmzToken=[PLACEHOLDER]
market_id=[PLACEHOLDER]
teleToken=[PLACEHOLDER]
| .env.botazon-server
DBHOST=[PLACEHOLDER]
DBUSER=[PLACEHOLDER]
DBPASSWORD=[PLACEHOLDER]
DBDATABASE=[PLACEHOLDER]
SPORT=[PLACEHOLDER]
SELLING_PARTNER_APP_CLIENT_ID=[PLACEHOLDER]
SELLING_PARTNER_APP_CLIENT_SECRET=[PLACEHOLDER]
AWS_ACCESS_KEY_ID=[PLACEHOLDER]
AWS_SECRET_ACCESS_KEY=[PLACEHOLDER]
AWS_SELLING_PARTNER_ROLE=[PLACEHOLDER]
sellerId=[PLACEHOLDER]
AmzToken=[PLACEHOLDER]
market_id=[PLACEHOLDER]
teleToken=[PLACEHOLDER]
| .env.fireball
DBHOST=[PLACEHOLDER]
DBUSER=[PLACEHOLDER]
DBPASSWORD=[PLACEHOLDER]
DBDATABASE=[PLACEHOLDER]
SPORT=[PLACEHOLDER]
SELLING_PARTNER_APP_CLIENT_ID=[PLACEHOLDER]
SELLING_PARTNER_APP_CLIENT_SECRET=[PLACEHOLDER]
AWS_ACCESS_KEY_ID=[PLACEHOLDER]
AWS_SECRET_ACCESS_KEY=[PLACEHOLDER]
AWS_SELLING_PARTNER_ROLE=[PLACEHOLDER]
sellerId=[PLACEHOLDER]
AmzToken=[PLACEHOLDER]
market_id=[PLACEHOLDER]
teleToken=[PLACEHOLDER]
| .env.fourseasons
DBHOST=[PLACEHOLDER]
DBUSER=[PLACEHOLDER]
DBPASSWORD=[PLACEHOLDER]
DBDATABASE=[PLACEHOLDER]
SPORT=[PLACEHOLDER]
SELLING_PARTNER_APP_CLIENT_ID=[PLACEHOLDER]
SELLING_PARTNER_APP_CLIENT_SECRET=[PLACEHOLDER]
AWS_ACCESS_KEY_ID=[PLACEHOLDER]
AWS_SECRET_ACCESS_KEY=[PLACEHOLDER]
AWS_SELLING_PARTNER_ROLE=[PLACEHOLDER]
sellerId=[PLACEHOLDER]
AmzToken=[PLACEHOLDER]
market_id=[PLACEHOLDER]
teleToken=[PLACEHOLDER]
| .env.fourseasons2
DBHOST=[PLACEHOLDER]
DBUSER=[PLACEHOLDER]
DBPASSWORD=[PLACEHOLDER]
DBDATABASE=[PLACEHOLDER]
SPORT=[PLACEHOLDER]
SELLING_PARTNER_APP_CLIENT_ID=[PLACEHOLDER]
SELLING_PARTNER_APP_CLIENT_SECRET=[PLACEHOLDER]
AWS_ACCESS_KEY_ID=[PLACEHOLDER]
AWS_SECRET_ACCESS_KEY=[PLACEHOLDER]
AWS_SELLING_PARTNER_ROLE=[PLACEHOLDER]
sellerId=[PLACEHOLDER]
AmzToken=[PLACEHOLDER]
market_id=[PLACEHOLDER]
| .env.rakoon
---
| .env.winter
DBHOST=[PLACEHOLDER]
DBUSER=[PLACEHOLDER]
DBPASSWORD=[PLACEHOLDER]
DBDATABASE=[PLACEHOLDER]
SPORT=[PLACEHOLDER]
SELLING_PARTNER_APP_CLIENT_ID=[PLACEHOLDER]
SELLING_PARTNER_APP_CLIENT_SECRET=[PLACEHOLDER]
AWS_ACCESS_KEY_ID=[PLACEHOLDER]
AWS_SECRET_ACCESS_KEY=[PLACEHOLDER]
AWS_SELLING_PARTNER_ROLE=[PLACEHOLDER]
sellerId=[PLACEHOLDER]
AmzToken=[PLACEHOLDER]
market_id=[PLACEHOLDER]
teleToken=[PLACEHOLDER]
| .env.winter2
DBHOST=[PLACEHOLDER]
DBUSER=[PLACEHOLDER]
DBPASSWORD=[PLACEHOLDER]
DBDATABASE=[PLACEHOLDER]
SPORT=[PLACEHOLDER]
SELLING_PARTNER_APP_CLIENT_ID=[PLACEHOLDER]
SELLING_PARTNER_APP_CLIENT_SECRET=[PLACEHOLDER]
AWS_ACCESS_KEY_ID=[PLACEHOLDER]
AWS_SECRET_ACCESS_KEY=[PLACEHOLDER]
AWS_SELLING_PARTNER_ROLE=[PLACEHOLDER]
sellerId=[PLACEHOLDER]
AmzToken=[PLACEHOLDER]
market_id=[PLACEHOLDER]
| .gitattributes
# Auto detect text files and perform LF normalization
* text=auto
---
| .gitignore
*.env*
*.log
endpoints*
*.json
---
| app.js
const express = require('express');
const app = express();
const routes = require('./routes/routes.js');
const logRoutes = require('./routes/log');
require('dotenv').config({path: `.env.${process.env.NODE_ENV}`})
port = process.env.SPORT;
require ('./src/cronjobs');
app.use(express.json());
app.use('/',routes);
app.use('/logs',logRoutes);
app.listen(port,()=> {
console.log(`Listening on port ${port}`);
});
---
---
public/
| README.md
[ README.md ]
# AnmaSoftV3
AnmaSoft V3 with telegram Support. Several fixes and code cleaning.
Saves into a MySQL database. No front end (yet) since I'm migrating from an old script.
MAIN FEATURES:
- Calculates zero-profit costs for all items in FBA.
- Track your supplier's payments. - (UNDER DEV)
- Track the amount of stock you have based on the cost and FBA information.
- Estimate how many days in stock you've got.
- Download and show inventory.
- Download, update and calculate orders.
- Calculate Customer Refunds
- Download Shipment Information (UNDER DEV)
- Calculate Profits on a Supplier's Pricelist.
- Advisor on which items to make S&L on FBA.
- Get all that information on a telegram bot. (UNDER DEV BUT WORKING)
----------------------------------------------------------------
Interested on collaborating? Give me a shout.
---
routes/
| | log.js
const express = require('express');
const router = express.Router();
/**
*
* SORRY
* LOGS WERE
* DEPRECATED
*
*/
///* --------------------------------------------------------- */
///* ---------------------ROUTES------------------------------ */
///* --------------------------------------------------------- */
//
///* ---------------------BASICS------------------------------ */
//
//router.get('/', (req, res) => {
// res.sendFile(path.resolve('public/verLogs.html'));;
//});
//
///* -----------------INVENTORY REPORTS--------------------- */
//
//router.get("/createInventoryReportLog/",(req, res)=> {
// res.sendFile(path.resolve('logs/createInventoryReport.log'));
//});
//
//router.get("/getInventoryReportLog/",(req, res)=> {
// res.sendFile(path.resolve('logs/getInventoryReport.log'));
//});
//
//router.get('/updateInventoryInfoLog/', (req, res) => {
// res.sendFile(path.resolve('logs/updateInventoryInfo.log'))
//});
//
///* -------------------ORDER REPORTS----------------------- */
//
//router.get("/createOrdersReportLog",(req, res)=> {
// res.sendFile(path.resolve('logs/createOrdersReport.log'));
//});
//
//router.get("/createOrdersReportYesLog",(req, res)=> {
// res.sendFile(path.resolve('logs/createOrdersReportYes.log'));
//});
//
//router.get("/createOrdersReportLMLog",(req, res)=> {
// res.sendFile(path.resolve('logs/createOrdersReportLM.log'));
//});
//
//router.get("/getOrdersReportLog",(req, res)=>{
// res.sendFile(path.resolve('logs/getOrdersReport.log'));
//});
//
//router.get("/updateMissingOrdersLog",(req, res)=> {
// res.sendFile(path.resolve('logs/updateMissingOrders.log'));
//});
//
//router.get('/estimateOrdersLog',(req, res)=>{
// res.sendFile(path.resolve('logs/estimateOrders.log'));
//});
//
///* -------------------RETURN REPORTS----------------------- */
//
//router.get("/createReturnsReportLog",(req, res)=>{
// res.sendFile(path.resolve('logs/createReturnsReport.log'));
//});
//
//router.get("/createReturnsReportYesLog",(req, res)=> {
// res.sendFile(path.resolve('logs/createReturnsReportYes.log'));
//});
//
//router.get("/getReturnsReportLog",(req, res)=>{
// res.sendFile(path.resolve('logs/getReturnsReport.log'));
//});
//
///* -------------------CALCULAR CEROS----------------------- */
//
//router.get('/calcularCostosLog', (req, res)=> {
// res.sendFile(path.resolve('logs/calcularCostos.log'));
//});
//
///* ---------------------TOOLS------------------------------ */
//
//router.get('/smallAndLightLog', (req, res)=> {
// res.sendFile(path.resolve('logs/smallAndLight.log'));
//});
//
///* ----------------- FOREVER -------------------------------*/
//router.get('/forever1', (req, res)=> {
// res.sendFile(path.resolve('/root/.forever/qpT_.log'));
//});
//
//router.get('/forever2', (req, res)=> {
// res.sendFile(path.resolve('/root/.forever/fyim.log'));
//});
//
//router.get('/forever3', (req, res)=> {
// res.sendFile(path.resolve('/root/.forever/Reip.log'));
//});
//
//
//
module.exports = router;
---
| | routes.js
const express = require('express');
const router = express.Router();
var path = require('path');
/* --------------------------------------------------------- */
/* ---------------------REQUIREMENTS------------------------ */
/* --------------------------------------------------------- */
/* ------------------INVENTORY REPORTS---------------------- */
const inventoryUpdater = require('../src/inventory/updateInventory');
const {calcularStock} = require('../src/inventory/stock/calcularStock')
const {select} = require('../src/shipments/shipmentAdvisor');
/* --------------------ORDER REPORTS------------------------ */
const {orderHandler} = require('../src/orders/orderHandler');
const {profitCalc} = require('../src/orders/profitCalculator');
///* -------------------RETURN REPORTS----------------------- */
const {refundHandler} = require('../src/refunds/refundHandler');
///* -------------------CALCULAR CEROS----------------------- */
const {calcularCostos} = require('../src/finances/calcularCostos.js');
///* ---------------------TOOLS------------------------------ */
const {smallAndLightTool} = require('../src/tools/smallAndLight.js');
const {telebot} = require ('../src/telegramBot')
const {restockCalculator} = require('../src/inventory/stock/restock');
const {feedbackReport} = require ('../src/tools/feedback')
/* --------------------------------------------------------- */
/* ---------------------ROUTES------------------------------ */
/* --------------------------------------------------------- */
/* ---------------------BASICS------------------------------ */
router.get('/', (req, res) => {
res.send(`Panel de control`);
});
router.get('/controlPanel', (req, res) => {
res.sendFile(path.resolve('public/controlPanel.html'));
});
/* -----------------INVENTORY REPORTS--------------------- */
router.get("/inventory/",(req, res)=> {
inventoryUpdater.inventory();
res.send('Lanzado inventory');
});
router.get("/calcularStock/",(req, res)=> {
calcularStock();
restockCalculator();
res.send('Lanzado Calcular Stock y Restock');
});
/* -------------------ORDER REPORTS----------------------- */
router.get("/orderHandler/",(req, res)=> {
orderHandler();
res.send('Lanzado Order Handler');
});
router.get("/profitCalculator/",(req, res)=> {
profitCalc();
res.send('Lanzado Profit Calculator');
});
/* -------------------RETURN REPORTS----------------------- */
router.get("/refundHandler/",(req, res)=> {
refundHandler();
res.send('Lanzado Refund Handler');
});
/* -------------------CALCULAR CEROS----------------------- */
router.get('/calcularCostos', (req, res)=> {
calcularCostos();
res.send(`Se estan calculando costos.`);
});
/* -------------------SHIPMENT TOOLS----------------------- */
router.get('/shipments', (req, res)=> {
select();
res.send(`Probando shipments.`);
});
/* ---------------------TOOLS------------------------------ */
router.get('/smallAndLightTool', (req, res)=> {
smallAndLightTool();
res.send(`Reporte de Small and Light en proceso. Ver LOG!.`);
});
router.get('/restock', (req, res)=> {
restockCalculator();
res.send(`Restock a la vista..`);
});
router.get('/feedback', (req, res)=> {
feedbackReport();
res.send(`Feedback stuff`);
});
module.exports = router;
---
src/
| | basicReq.js
//requests for mysql and SP-API, promises, telegram bot. This
const mysql = require('mysql2');
require('dotenv').config({path: `.env.${process.env.NODE_ENV}`})
const util = require('util');
const pool = mysql.createPool({
connectionLimit : 50, //important
host : process.env.DBHOST,
user : process.env.DBUSER,
password : process.env.DBPASSWORD,
database : process.env.DBDATABASE,
debug : false
},()=>console.log('Connected!'));
let query = util.promisify(pool.query).bind(pool);
module.exports = {query}
---
| | cronjobs.js
const CronJob = require("cron").CronJob;
const { calcularCostos } = require("./finances/calcularCostos");
const { updInventory } = require("./inventory/updateInventory");
const { calcularStock } = require("./inventory/stock/calcularStock");
const { orderHandler } = require("./orders/orderHandler");
const { profitCalc } = require("./orders/profitCalculator");
const { refundHandler } = require("./refunds/refundHandler");
const { feedbackHandler } = require("./telegramBot");
const { updateStorageFees } = require("./finances/calcularStorage");
const {query} = require("./basicReq");
//EVERY 30 MINUTES:
const cron30min = new CronJob(
"*/30 * * * *",
() => {
feedbackHandler();
calcularCostos();
console.log("cron30min iniciado");
},
null,
true,
"Atlantic/St_Helena"
);
//EVERY 2 HOURS:
const cron2hs1 = new CronJob(
"00 */2 * * *",
() => {
orderHandler();
console.log("cron2hs1 iniciado");
},
null,
true,
"Atlantic/St_Helena"
);
const cron2hs2 = new CronJob(
"10 */2 * * *",
() => {
profitCalc();
console.log("cron2hs2 iniciado");
},
null,
true,
"Atlantic/St_Helena"
);
//EVERY 4 HOURS:
const cron4hs1 = new CronJob(
"04 */4 * * *",
() => {
updInventory();
console.log("cron4hs1 iniciado");
},
null,
true,
"Atlantic/St_Helena"
);
const cron4hs2 = new CronJob(
"15 */4 * * *",
() => {
calcularStock();
console.log("cron4hs2 iniciado");
},
null,
true,
"Atlantic/St_Helena"
);
const cron4hs3 = new CronJob(
"08 */4 * * *",
() => {
refundHandler();
console.log("cron4hs1 iniciado");
},
null,
true,
"Atlantic/St_Helena"
);
//EVERYDAY:
const cronEveryday = new CronJob(
"30 0 * * *",
async () => {
await query("UPDATE datos_pos SET needs_update = 1 WHERE active = 1");
updateStorageFees();
console.log("cronEveryday iniciado");
},
null,
true,
"Atlantic/St_Helena"
);
---
| finances/
| | | calcularCostos.js
//getMyFeesEstimateForSKU
const {query} = require('../basicReq');
let sellingPartner = require (`../sellerApiReq`);
class precioItem {
constructor(sku,precio,fee,costo,cero,offset,last_update,supplierId,buyerId) {
this.sku = sku;
this.precio = precio;
this.fee = fee;
this.costo = costo;
this.cero = cero;
this.offset = offset;
this.last_update = last_update;
this.supplierId = supplierId;
this.buyerId = buyerId;
}
}
itemsList = [];
async function queryDB(){
let res = await query(`SELECT * FROM datos_pos WHERE active = '1' AND needs_update = '1' GROUP BY sku ORDER BY sku`);
let res2 = await query(`SELECT * FROM datos_costos`);
let i = 0;
let skuList = [];
//console.log(res.length);
while (i < res.length) {
let lpm = new precioItem(res[i].sku,100,0,res[i].total_cost,100,100,null,res[i].provider_id,res[i].buyer_id);
for (let j=1;j<res.length;j++){
if (typeof res[j]?.length != 'undefined'){
if (res[i].sku == res2[j].sku){
lpm.cero = parseFloat(res2[j].cero).toFixed(3);
lpm.precio = parseFloat(res2[j].cero).toFixed(3);
}
else
break;
}
}
skuList.push(lpm);
i++;
}
if (i> 0){
console.log(`Son ${i} SKUs`);
return skuList;
}
else
{
console.log('No hay skus pendientes');
return 0;
}
}
async function calcularFee(id){
let res = await sellingPartner.callAPI({
operation:'getMyFeesEstimateForSKU',
endpoint:'productFees',
body:{
FeesEstimateRequest: {
MarketplaceId: 'ATVPDKIKX0DER',
IsAmazonFulfilled: true,
PriceToEstimateFees:{
ListingPrice:{
Amount: id.precio,
CurrencyCode: 'USD',
},
},
Identifier: id.sku,
}
},
path: {
SellerSKU: id.sku
}
}
);
//console.log(res);
if(typeof res.FeesEstimateResult?.FeesEstimate == 'undefined' || res.FeesEstimateResult?.Status == 'ClientError'){
console.log(`Error por status ${res?.FeesEstimateResult?.Status} ${res.toString()}`);
console.table(res?.FeesEstimateResult?.Error)
return 0;
}
console.log(res.FeesEstimateResult?.FeesEstimate?.TotalFeesEstimate?.Amount)
id.fee = res.FeesEstimateResult?.FeesEstimate?.TotalFeesEstimate?.Amount;
return (id);
}
function calcularOffset(id){
let fee = id.fee;
let retorno = id;
let offset = retorno.precio - fee - retorno.costo;
if ((offset > 0.02) || (offset < 0.02))
{
if (retorno.last_update == null)
console.log(`Primera vuelta de ${retorno.sku}`);
retorno.precio -= offset;
retorno.offset = offset;
retorno.fee = fee;
retorno.last_update = new Date().toISOString().slice(0,19) + '+00:00';
//console.log(retorno);
return retorno;
}
else
//console.log(retorno);
console.log(`Todo sigue igual.`)
}
async function actualizarDB(id){
//Check if exists
res = await query (`SELECT * FROM datos_costos WHERE sku = '${id.sku}'`);
if (res.length > 0)
{
await query (`UPDATE datos_costos SET cero = '${id.cero}',check_cero = '${id.offset}',last_updated = '${id.last_update}' WHERE sku = '${id.sku}'`);
await query (`UPDATE datos_pos SET needs_update = 0 WHERE sku = '${id.sku}'`);
console.log(`SKU ${id.sku} Actualizado.`);
}
else
{
await query (`INSERT INTO datos_costos (sku,costo,cero,profit30,profit50,check_cero,last_updated,hard_top,hard_low_MAP,buyerId,supplierId) VALUES ('${id.sku}','${id.costo}','${id.cero}','0','0','${id.offset}','${id.last_update}','0','0','${id.buyerId}','${id.supplierId}')`);
await query (`UPDATE datos_pos SET needs_update = 0 WHERE sku = '${id.sku}'`);
console.log(`SKU: ${id.sku} Agregado.`)
}
}
async function calcularCostos(){
let item = await queryDB();
//console.log(item);
if (typeof item === 'undefined'){
return 0;
}
for (let i = 0; i < item.length; i++) {
console.log(`Actualizando ${item[i].sku}`);
let vuelta1 = await calcularFee(item[i]);
if (vuelta1 == 0){
console.log(`ERROR CATASTROFICO ${item[i].sku}`)
continue;
}
let vuelta2 = calcularOffset(vuelta1);
while (vuelta2?.offset >0.02)
{
vuelta1 = await calcularFee(vuelta2);
vuelta2 = calcularOffset(vuelta1);
};
test = vuelta2;
if (!test) continue;
test.cero = test?.precio;
console.log(`El precio se ha actualizado. Ahora es ${test?.cero}`);
await actualizarDB(test);
}
}
module.exports = {calcularCostos};
---
| | | calcularStorage.js
const {query} = require('../basicReq');
const feetToInches = 1/12;
async function getItems(){
return await query(`SELECT * FROM datos_items WHERE weight > 0`);
}
async function getPos(sku) {
return await query(`SELECT * FROM datos_pos WHERE sku = '${sku}'`);
}
async function updateStorageFees() {
const fecha = new Date().getMonth();
let items = await getItems();
if (items.length > 0) {
for (const item of items){
let width = item.width * feetToInches;
let length = item.length * feetToInches;
let height = item.height * feetToInches;
let weight = item.weight * feetToInches;
let cubicFeet = width * height * length;
let tipo ="";
let storage = 0;
if (length > 18 || width > 14 || height > 8 || weight > 20){
if (fecha >= 10){
tipo = 'OVERSIZE - Q4';
storage = cubicFeet * 1.20;
}
else
{
tipo = 'OVERSIZE - Q1/2/3';
storage = cubicFeet * 0.48;
}
}
else
{
if (fecha>= 10){
tipo = 'STANDARD - Q4';
storage = cubicFeet * 2.4;
}
else
{
tipo = 'STANDARD - Q1/2/3';
storage = cubicFeet * 0.75;
}
}
let todo = await getPos(item.sku);
todo.forEach(itemEnPo=>{
//console.log(itemEnPo.cost ," ",itemEnPo.label ," ", itemEnPo.shipment ," ", storage ," ", itemEnPo.manualfee);
let totalcost = itemEnPo.cost + itemEnPo.label + itemEnPo.shipment + storage + itemEnPo.manualfee;
totalcost = parseFloat(totalcost.toFixed(3));
saveItem({storage: storage,totalcost:totalcost,id:itemEnPo.id});
console.log(`Saved: ${item.sku} antes: ${itemEnPo.monthlyfee?.toFixed(3)} y ahora: ${storage.toFixed(3)}.`);
})
}
}
console.log(`Actualizado Strorage Fee. Procediendo a actualizar los monthly en suma.`);
await updateMonthlyStorageFees();
}
async function saveItem(item){
await query(`UPDATE datos_pos SET monthlyfee = '${item.storage.toFixed(3)}', total_cost = ${parseFloat(item.totalcost).toFixed(3)} WHERE id = '${item.id}'`);
}
async function getAllPOs(){
return await query (`SELECT * FROM datos_pos WHERE date_po != '-'`);
}
async function updateMonthlyStorageFees(){
let hoy = new Date();
let pos = await getAllPOs();
for (let item of pos){
let fecha = new Date (item.date_po);
let meses = Math.ceil(Math.abs(fecha-hoy) / (1000 * 60 * 60 * 24 * 30));
let monthlyNuevo = parseFloat(item.monthlyfee * meses).toFixed(3);
let totalcost = item.cost + item.label + item.shipment + item.manualfee + monthlyNuevo;
await saveNewMonthly(monthlyNuevo,totalcost,item.id);
console.log(`Saved ${item.sku} de ${item.monthlyfee_total} a ${monthlyNuevo}`);
}
console.log(`monthlyfee total actualizado.`)
}
async function saveNewMonthly(mft,tc,id){
mft = parseFloat(mft).toFixed(3);
tc = parseFloat(tc).toFixed(3);
await query (`UPDATE datos_pos SET monthlyfee_total = '${mft}', total_cost = '${tc}' WHERE id = ${id}`);
}
module.exports = {updateStorageFees};
---
| | ganancias/
| | | | calcularGanancias.js
const {query} = require('../basicReq');
let sellingPartner = require (`../sellerApiReq`);
---
| | payments/
| | | | payments.js
/*
UNDER DEVELOPMENT
Bueno, me la re complique al pedo. Si es un pago parcial que se maneje.
Si es un pago de una PO, se paga la PO, si es un expense, se maneja sin PO.
Si es pago parcial, se paga parcial y se deja ahi boyando. UN SOLO PAGO. no subpagos.
*/
/*
UN PAGO CONTIENE:
this.id; //PAYMENT ID.
this.type = type; //Supplier - Expense - Settlement - Refund - Sale
this.amount = amount; //Amount PAID.
this.description = description; //Some reference.
this.supplierId = supplierId; // Supplier Tied to
this.invoiceId = invoiceId; //Invoice Id for search
this.netTerms = netTerms; //Terms. (EN DIAS)
this.paymentDate = paymentDate; //When we paid
this.dueDate = dueDate; //When should have been paid by
this.poNumber = poNumber; // PO
----------------------------------------------------------------*/
const {query} = require('../../basicReq');
class Payment {
constructor(type,amount,description,supplierId,invoiceId,netTerms,paymentDate,dueDate,poNumber,id){
if (typeof id !== 'undefined')
this.id = id; //PAYMENT ID.
else
this.id;
this.type = type; //Supplier - Expense - Settlement - Refund - Sale
this.amount = amount; //Amount PAID.
this.description = description; //Some reference.
this.supplierId = supplierId; // Supplier Tied to
this.invoiceId = invoiceId; //Invoice Id for search
console.log(`Acabo de guardar como invoice id: ${this.invoiceId} que vino como ${invoiceId}`);
this.netTerms = netTerms; //Terms. (EN DIAS)
this.paymentDate = paymentDate; //When we paid
this.dueDate = dueDate; //When should have been paid by
this.poNumber = poNumber; // PO
}
static async loadPayment(id) {
//if the idea is to update a payment, I can load it just for you.
try {
let pago = await query(`SELECT * FROM payments WHERE id = '${id}'`);
if (typeof pago !== 'undefined') {
return new Payment (pago[0].type, pago[0].amount, pago[0].description,pago[0].supplierId,pago[0].invoiceId,pago[0].netTerms,pago[0].paymentDate,pago[0].dueDate,pago[0].poNumber,pago[0].id);
}
else {console.warn(`Payment ID: ${id} not found`); return 0;}}
catch (e) {
console.warn(`Catched! `,e);
return -1;
}
}
async savePayment(){
//Once everything's said and done, save the payment, and save the payment into said PO.
try {
if (typeof this.id == 'undefined') {
query(`INSERT INTO payments (type,amount,description,supplierId,invoiceId,netTerms,paymentDate,dueDate,poNumber) VALUES ('${this.type}','${this.amount}','${this.description}','${this.supplierId}','${this.invoiceId}','${this.netTerms}','${this.paymentDate}','${this.dueDate}','${this.poNumber}')`); //INSERTS NEW ROW
}
else{
query(`REPLACE INTO payments (id,type,amount,description,supplierId,invoiceId,netTerms,paymentDate,dueDate,poNumber) VALUES ('${this.id}','${this.type}','${this.amount}','${this.description}','${this.supplierId}','${this.invoiceId}','${this.netTerms}','${this.paymentDate}','${this.dueDate}','${this.poNumber}')`); //TRIES TO UPDATE DB
}
}
catch (e){
console.warn(`Catched! `,e);
return -1; // ERROR CODE -1
}
return true; //EVERYTHING WELL
}
async paymentPOVerification(poNumber){
//te dice si hay un pago para esta PO.
let res = await query(`SELECT * FROM payments WHERE poNumber = '${poNumber}'`)
if ( typeof res != 'undefined')
{ //hay un pago. Devolver id
return res[0].id;
}
return 0;
}
pay(amount){
this.amount += amount;
this.paymentDate = new Date ().toISOString();
}
static async payByPO(poNumber,amount){
//PO Number es obvio, el numero de PO. Amount, cuanto se paga / agrega si ya existe.
//Hay que ver si existe...
let pago;
let id = await this.paymentPOVerification(poNumber);
if (id != 0 || typeof id != 'undefined'){
//Si existe, cargo el pago.
pago = await Payment.loadPayment(pago.id);
//Cargado el pago, ahora le sumo el amount.
if (pago != -1){
pago.pay(amount);
return await pago.savePayment() // TRUE O ERROR DE SAVE
}
return -1; //PAGO MAL CARGADO.
}
return 0; //ERROR DE PAYBYPO. No existe la PO.
}
static async telePayment (obj){
//Recibo un pago de Telegram. Subo al toque.
let newTelePay = new Payment (obj.type,obj.amount,obj.description,obj.supplierId, obj.invoiceId ,obj.netTerms,obj.paymentDate,obj.dueDate,obj.poNumber,obj.id);
let res = newTelePay.savePayment();
return res;
}
}
module.exports = Payment;
---
| inventory/
| | | newUpdateInvInfo.js
//Updates the images, dimensions and weight of an item once a day.
const {query} = require('../basicReq');
let sellingPartner = require (`../sellerApiReq`);
async function cleanResponse(someRes){
let cmtoi = 1 / 2.54;
let length,width,height,weight = 0;
if (someRes?.attributes?.item_package_dimensions){
if (someRes.attributes.item_package_dimensions[0]?.length?.unit == 'centimeters'){
length = someRes.attributes.item_package_dimensions[0]?.length?.value * cmtoi;
width = someRes.attributes.item_package_dimensions[0]?.width?.value * cmtoi;
height = someRes.attributes.item_package_dimensions[0]?.height?.value * cmtoi;
}
else
{console.log(`HAY UNO QUE NO TRAIA CMS`)}
if (someRes?.attributes?.item_package_weight[0]?.unit == 'kilograms'){
weight = someRes?.attributes?.item_package_weight[0]?.value * 2.205;
}
else if(someRes?.attributes?.item_package_weight[0]?.unit == 'pounds'){
weight = someRes?.attributes?.item_package_weight[0]?.value;
}
else
console.log(`HAY UNO QUE NO TRAIA KG NI LB!!!`)
if (!length || !height || !width || !weight){
console.log(`Error en alguno.`)
return 0;
}
else
{
length = parseFloat(length.toFixed(3));
height = parseFloat(height.toFixed(3));
width = parseFloat(width.toFixed(3));
weight = parseFloat(weight.toFixed(3))
return {width:width,height:height,length:length,weight:weight}
}
};
}
async function getListingsItem(sku){
try {
let res = await sellingPartner.callAPI({
operation:'getListingsItem',
endpoint:'listingsItems',
query:
{
marketplaceIds : process.env.market_id,
//includedData : includedData
},
path: {
sku: sku,
sellerId: process.env.sellerId,
}
}
);
//console.log(res.summaries[0]?.mainImage?.link)
return res.summaries[0]?.mainImage?.link;
}
catch (e){
e.code=='NOT_FOUND'?console.log('No estaba la imagen'):console.log(e);
return 'https://static8.depositphotos.com/1009634/988/v/450/depositphotos_9883921-stock-illustration-no-user-profile-picture.jpg';
}
}
async function saveItem(item){
try{
await query (`UPDATE datos_items SET height = '${item.height}', width ='${item.width}', length = '${item.length}', weight = '${item.weight}',imageurl = '${item.url}' WHERE 'sku' = '${item.sku}'`)
}
catch (e){
console.log(e)
}
}
async function getCatalogItem(asin) {
try {
let res = await sellingPartner.callAPI({
operation:'getCatalogItem',
endpoint: 'catalogItems',
query: {
marketplaceIds: ['ATVPDKIKX0DER'],
includedData: ['attributes'],
},
path: {
asin: asin
},
options:{
version:'2020-12-01'
}
})
//console.log(res.attributes.item_package_dimensions[0]);
let clean = await cleanResponse(res);
clean.asin = asin;
return clean;
}
catch (e){
e.code=='NOT_FOUND'?console.log('No existe mas el item'):console.log(e);
return 0;
}