forked from MahdiGraph/DollarBaan
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
1577 lines (1464 loc) · 56.3 KB
/
app.js
File metadata and controls
1577 lines (1464 loc) · 56.3 KB
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
'use strict';
require('dotenv').config();
const express = require('express');
const bodyParser = require('body-parser');
const cron = require('node-cron');
const path = require('path');
const axios = require('axios');
const { Sequelize, DataTypes, Op } = require('sequelize');
const moment = require('moment-jalaali');
const cors = require('cors');
const winston = require('winston');
const fs = require('fs');
const session = require('express-session');
const cookieParser = require('cookie-parser');
const FileStore = require('session-file-store')(session);
const logDir = process.env.LOG_DIR || './logs';
if (!fs.existsSync(logDir)) {
fs.mkdirSync(logDir, { recursive: true });
}
const logger = winston.createLogger({
level: process.env.LOG_LEVEL || 'info',
format: winston.format.combine(
winston.format.timestamp(),
winston.format.json()
),
transports: [
new winston.transports.File({ filename: `${logDir}/error.log`, level: 'error' }),
new winston.transports.File({ filename: `${logDir}/combined.log` })
]
});
if (process.env.NODE_ENV !== 'production') {
logger.add(new winston.transports.Console({
format: winston.format.combine(
winston.format.colorize(),
winston.format.simple()
)
}));
}
const PERSIAN_NAMES = {
// Currencies
'usd_sell': 'دلار آمریکا',
'eur_sell': 'یورو',
'eur_hav': 'حواله یورو',
'eur_pp': 'یورو پی پال',
'gbp': 'پوند انگلیس',
'gbp_hav': 'حواله پوند انگلیس',
'cad': 'دلار کانادا',
'cad_hav': 'حواله دلار کانادا',
'aud': 'دلار استرالیا',
'aud_hav': 'حواله دلار استرالیا',
'nzd': 'دلار نیوزیلند',
'try': 'لیر ترکیه',
'try_hav': 'حواله لیر ترکیه',
'aed_sell': 'درهم امارات',
'dirham_dubai': 'درهم دوبی',
'sar': 'ریال سعودی',
'qar': 'ریال قطر',
'omr': 'ریال عمان',
'bhd': 'دینار بحرین',
'kwd': 'دینار کویت',
'iqd': 'دینار عراق',
'jod': 'دلار اردن',
'lbp': 'پوند لبنان',
'syp': 'پوند سوریه',
'cny': 'یوان چین',
'cny_hav': 'حواله یوان چین',
'jpy': 'ین ژاپن',
'jpy_hav': 'حواله ین ژاپن',
'inr': 'روپیه هند',
'krw': 'وون کره',
'myr': 'رینگیت مالزی',
'myr_hav': 'حواله رینگیت مالزی',
'sgd': 'دلار سنگاپور',
'hkd': 'دلار هنگ کنگ',
'zar': 'رند افریقای جنوبی',
'egp': 'پوند مصر',
'ngn': 'نایرا نیجریه',
'dzd': 'دینار الجزایر',
'mad': 'درهم مراکش',
'tnd': 'دینار تونس',
'xaf': 'فرانک آفریقای مرکزی',
'xof': 'فرانک آفریقای غربی',
'chf': 'فرانک سوئیس',
'sek': 'کرون سوئد',
'nok': 'کرون نروژ',
'dkk': 'کرون دانمارک',
'pln': 'زلوتی لهستانی',
'czk': 'کرون چک',
'rub': 'روبل روسیه',
'hrk': 'کونا کرواسی',
'bgn': 'لو بلغارستان',
'isk': 'کرون ایسلند',
'brl': 'رئال برزیل',
'mxn': 'پزو مکزیک',
'clp': 'پزو شیلی',
'cop': 'پزو کلمبیا',
'ars': 'پزو آرژانتین',
'pen': 'سولوی پرو',
'uyu': 'پزو اروگوئه',
'afn': 'افغانی',
'gel': 'لاری گرجستان',
'azn': 'منات آذربایجان',
'tmt': 'منات ترکمنستان',
'uzs': 'سام ازبکستان',
'tjs': 'سامونی تاجیکستان',
'kzt': 'تنگه قزاقستان',
'amd': 'درام ارمنستان',
// harat
'harat_naghdi_sell': 'دلار هرات',
'dolar_harat_sell': 'دلار هرات نقد',
'dolar_soleimanie_sell': 'دلار سلیمانیه',
'dolar_kordestan_sell': 'دلار کردستان',
'dolar_mashad_sell': 'دلار مشهد',
'usd_farda_sell': 'دلار تهران فردایی',
// dollar types
'mob_usd': 'دلار مبادلهای',
'mex_usd_sell': 'دلار صرافی ملی',
'usd_shakhs': 'دلار حواله شخص',
'usd_sherkat': 'دلار حواله شرکت',
'usd_pp': 'دلار پی پال',
// euro types
'mob_eur': 'یورو مبادلهای',
'mex_eur_sell': 'یورو صرافی ملی',
// gold and coin
'sekkeh': 'سکه امامی',
'coin': 'سکه تمام بهار آزادی',
'bahar': 'سکه بهار آزادی',
'nim': 'نیم سکه',
'rob': 'ربع سکه',
'gerami': 'سکه گرمی',
'gold': 'طلای ۱۸ عیار',
'18ayar': 'گرم طلای ۱۸ عیار',
'abshodeh': 'مثقال طلای آبشده',
'usd_xau': 'اونس جهانی طلا',
'xau': 'اونس طلا',
// Crypto
'bitcoin': 'بیتکوین',
'ethereum': 'اتریوم',
'usdt': 'تتر',
'ltc': 'لایتکوین',
'xrp': 'ریپل',
'bch': 'بیتکوین کش',
'bnb': 'بایننس',
'eos': 'ایاواس',
'ada': 'کاردانو',
'dash': 'دش',
'doge': 'دوجکوین',
'shib': 'شیبا اینو',
'aave': 'آوه',
'avax': 'آوالانچ',
'sol': 'سولانا',
'matic': 'متیک',
'trx': 'ترون',
'dot': 'پولکادات',
'link': 'چینلینک',
'xlm': 'استلار',
'uni': 'یونیسواپ',
'atom': 'کازموس',
'ton': 'تونکوین',
'etc': 'اتریوم کلاسیک',
'xmr': 'مونرو',
'fil': 'فایلکوین',
'icp': 'آیسیپی',
'hbar': 'هدرا',
'vet': 'ویچین',
'near': 'نییر پروتکل',
'qnt': 'کوانت',
'mkr': 'میکر',
'grt': 'گراف',
'algo': 'آلگورند',
'axs': 'اَکسی',
'stx': 'استک',
'egld': 'مولتیورس',
'sand': 'سندباکس',
'theta': 'تتا',
};
const PRIORITY_TYPES = [
'usd_sell', 'cad', 'sekkeh', 'abshodeh', 'usdt', 'try',
'bitcoin', 'ethereum', 'gold', '18ayar', 'eur_sell', 'coin'
];
const apiStatus = {
lastConnectionTime: null,
lastConnectionSuccess: true,
lastError: null,
errorMessage: null
};
const cache = {
timelineChartData: null,
timelineChartDataTimestamp: null,
typeChartData: {},
validityPeriod: 15 * 60 * 1000,
isValid: function(timestamp) {
return timestamp && (Date.now() - timestamp) < this.validityPeriod;
},
clearAll: function() {
this.timelineChartData = null;
this.timelineChartDataTimestamp = null;
this.typeChartData = {};
logger.info('Cache cleared');
}
};
class NavasanAPIClient {
constructor(apiKey) {
if (!apiKey) throw new Error('API key is required');
this.apiKey = apiKey.trim();
this.baseUrl = process.env.NAVASAN_BASE_URL || 'https://api.navasan.tech';
this.timeout = parseInt(process.env.NAVASAN_TIMEOUT || '120000');
this.maxRetries = parseInt(process.env.NAVASAN_MAX_RETRIES || '3');
this.requestQueue = [];
this.isProcessingQueue = false;
this.requestDelay = 500;
setInterval(() => this.processQueue(), this.requestDelay);
}
async processQueue() {
if (this.isProcessingQueue || this.requestQueue.length === 0) return;
this.isProcessingQueue = true;
const request = this.requestQueue.shift();
try {
const result = await this.executeRequest(
request.endpoint,
request.params,
request.maxRetries
);
request.resolve(result);
} catch (error) {
request.reject(error);
} finally {
this.isProcessingQueue = false;
}
}
async executeRequest(endpoint, params = {}, maxRetries = this.maxRetries) {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
logger.info(`Attempt ${attempt}: Fetching ${endpoint}`);
apiStatus.lastConnectionTime = new Date();
const response = await axios.get(`${this.baseUrl}/${endpoint}`, {
params: { ...params, api_key: this.apiKey },
timeout: this.timeout
});
apiStatus.lastConnectionSuccess = true;
apiStatus.lastError = null;
apiStatus.errorMessage = null;
return response.data;
} catch (error) {
const errorMessage = error.response ?
`Status: ${error.response.status}, ${error.response.statusText}` :
error.message;
logger.error(`Fetch attempt ${attempt} failed: ${errorMessage}`);
if (attempt === maxRetries) {
apiStatus.lastConnectionSuccess = false;
apiStatus.lastError = error;
apiStatus.errorMessage = `Error connecting to Navasan service: ${errorMessage}`;
throw error;
}
await new Promise(resolve => setTimeout(resolve, 1000 * attempt));
}
}
}
fetchWithRetry(endpoint, params = {}) {
return new Promise((resolve, reject) => {
this.requestQueue.push({
endpoint, params, maxRetries: this.maxRetries, resolve, reject
});
});
}
getLatestPrices() {
return this.fetchWithRetry('latest');
}
getHistoricalPrices(type, startDate, endDate) {
return this.fetchWithRetry('ohlcSearch', {
item: type,
start: startDate,
end: endDate
});
}
}
const API_KEY = process.env.API_KEY;
if (!API_KEY) {
logger.error('CRITICAL: API_KEY is not set in .env file');
process.exit(1);
}
const navasanClient = new NavasanAPIClient(API_KEY);
let sequelize;
const getDecimalType = () => {
return process.env.DB_DIALECT === 'sqlite' ?
DataTypes.FLOAT :
DataTypes.DECIMAL(15, 2);
};
if (process.env.DB_DIALECT === 'sqlite') {
const storagePath = process.env.SQLITE_PATH || './database.sqlite';
sequelize = new Sequelize({
dialect: 'sqlite',
storage: storagePath,
logging: false
});
logger.info(`Using SQLite database at ${storagePath}`);
} else {
sequelize = new Sequelize(
process.env.DB_NAME,
process.env.DB_USER,
process.env.DB_PASSWORD,
{
host: process.env.DB_HOST,
port: process.env.DB_PORT || 3306,
dialect: process.env.DB_DIALECT || 'mysql',
logging: false,
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
}
}
);
logger.info(`Using ${process.env.DB_DIALECT || 'mysql'} database`);
}
const InvestmentType = sequelize.define('InvestmentType', {
type: {
type: DataTypes.STRING,
primaryKey: true,
unique: true
},
currentPrice: {
type: getDecimalType(),
allowNull: false
},
lastUpdated: {
type: DataTypes.DATE,
defaultValue: DataTypes.NOW
},
persianName: {
type: DataTypes.STRING,
allowNull: true
}
});
const Investment = sequelize.define('Investment', {
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true
},
type: {
type: DataTypes.STRING,
allowNull: false
},
amount: {
type: getDecimalType(),
allowNull: false
},
date: {
type: DataTypes.DATE,
allowNull: false
}
});
const HistoricalPrice = sequelize.define('HistoricalPrice', {
type: {
type: DataTypes.STRING,
allowNull: false
},
date: {
type: DataTypes.DATEONLY,
allowNull: false
},
open: {
type: getDecimalType(),
allowNull: false
},
high: {
type: getDecimalType(),
allowNull: false
},
low: {
type: getDecimalType(),
allowNull: false
},
close: {
type: getDecimalType(),
allowNull: false
}
}, {
indexes: [
{
unique: true,
fields: ['type', 'date']
}
]
});
Investment.belongsTo(InvestmentType, {
foreignKey: 'type',
targetKey: 'type'
});
async function getInvestedTypes() {
if (process.env.DB_DIALECT === 'sqlite') {
const query = "SELECT DISTINCT type FROM Investments";
const result = await sequelize.query(query, {
type: sequelize.QueryTypes.SELECT
});
return result.map(row => ({ type: row.type }));
} else {
return await Investment.findAll({
attributes: ['type'],
group: ['type']
});
}
}
async function getLatestPrice(type) {
try {
const latestPrice = await HistoricalPrice.findOne({
where: { type },
order: [['date', 'DESC']]
});
if (latestPrice) {
return latestPrice.close;
}
const currentPrice = await InvestmentType.findByPk(type);
return currentPrice ? currentPrice.currentPrice : null;
} catch (error) {
logger.error(`Error getting latest price for ${type}`, error);
return null;
}
}
async function calculateInvestmentValue(investment, investmentType) {
try {
const historicalPrice = await HistoricalPrice.findOne({
where: {
type: investment.type,
date: {
[Op.lte]: moment(investment.date).format('YYYY-MM-DD')
}
},
order: [['date', 'DESC']]
});
const currentPrice = await getLatestPrice(investment.type) ||
(investmentType ? investmentType.currentPrice : 0);
const purchasePrice = historicalPrice ? historicalPrice.close : currentPrice;
const unitsPurchased = purchasePrice > 0 ? investment.amount / purchasePrice : 0;
const currentValue = unitsPurchased * currentPrice;
const profit = currentValue - investment.amount;
return {
initialInvestment: parseFloat(investment.amount),
purchasePrice: parseFloat(purchasePrice),
unitsPurchased: parseFloat(unitsPurchased),
currentValue: parseFloat(currentValue),
currentPrice: parseFloat(currentPrice),
profit: parseFloat(profit)
};
} catch (error) {
logger.error(`Investment value calculation error: ${error.message}`);
return {
initialInvestment: parseFloat(investment.amount),
purchasePrice: 0,
unitsPurchased: 0,
currentValue: 0,
currentPrice: 0,
profit: 0
};
}
}
async function fetchHistoricalDataForType(type, startDate, endDate) {
try {
logger.info(`Fetching historical data for ${type}`);
const historicalData = await navasanClient.getHistoricalPrices(type, startDate, endDate);
if (!historicalData || !Array.isArray(historicalData) || historicalData.length === 0) {
logger.warn(`No historical data found for ${type}`);
return [];
}
logger.info(`Received ${historicalData.length} historical records for ${type}`);
const historicalPrices = historicalData.map(price => {
if (!price.date) {
logger.warn(`Missing date in historical data record for ${type}`);
return null;
}
try {
const gregorianDate = moment(price.date, 'jYYYY-jM-jD').format('YYYY-MM-DD');
const open = parseFloat(price.open) || 0;
const high = parseFloat(price.high) || 0;
const low = parseFloat(price.low) || 0;
const close = parseFloat(price.close) || 0;
return {
type,
date: gregorianDate,
open,
high,
low,
close
};
} catch (error) {
logger.error(`Error processing historical data record for ${type}`);
return null;
}
}).filter(item => item !== null);
if (historicalPrices.length === 0) {
logger.warn(`No valid historical data found for ${type}`);
return [];
}
if (process.env.DB_DIALECT === 'sqlite') {
for (const record of historicalPrices) {
try {
const existingRecord = await HistoricalPrice.findOne({
where: {
type: record.type,
date: record.date
}
});
if (existingRecord) {
await existingRecord.update({
open: record.open,
high: record.high,
low: record.low,
close: record.close
});
} else {
await HistoricalPrice.create(record);
}
} catch (err) {
logger.error(`Error saving historical price for ${type} on date ${record.date}: ${err.message}`);
}
}
} else {
await HistoricalPrice.bulkCreate(historicalPrices, {
updateOnDuplicate: ['open', 'high', 'low', 'close']
});
}
logger.info(`Stored ${historicalPrices.length} historical prices for ${type}`);
return historicalPrices;
} catch (error) {
logger.error(`Historical data fetch error for ${type}: ${error.message}`);
return [];
}
}
async function updateInvestmentPrices() {
try {
logger.info('Starting comprehensive price update...');
const investedTypes = await getInvestedTypes();
if (investedTypes.length === 0) {
logger.info('No invested types found. Skipping price update.');
return;
}
let latestPrices;
try {
latestPrices = await navasanClient.getLatestPrices();
logger.info(`Received latest prices for ${Object.keys(latestPrices).length} types`);
} catch (error) {
logger.error('Failed to fetch latest prices from Navasan API', error);
throw new Error('Error fetching latest prices from Navasan service');
}
for (const typeObj of investedTypes) {
const type = typeObj.type;
if (!latestPrices[type]) {
logger.warn(`Type ${type} not found in latest prices. Skipping update.`);
continue;
}
await InvestmentType.upsert({
type,
currentPrice: parseFloat(latestPrices[type].value),
lastUpdated: new Date(),
persianName: PERSIAN_NAMES[type] || type
});
const lastHistoricalPrice = await HistoricalPrice.findOne({
where: { type },
order: [['date', 'DESC']]
});
let startDate;
if (lastHistoricalPrice) {
startDate = moment(lastHistoricalPrice.date).add(1, 'day').format('jYYYY-jM-jD');
} else {
const firstInvestment = await Investment.findOne({
where: { type },
order: [['date', 'ASC']]
});
if (firstInvestment) {
startDate = moment(firstInvestment.date).subtract(1, 'month').format('jYYYY-jM-jD');
} else {
startDate = moment().subtract(3, 'years').format('jYYYY-jM-jD');
}
}
const endDate = moment().format('jYYYY-jM-jD');
if (startDate < endDate) {
try {
await fetchHistoricalDataForType(type, startDate, endDate);
} catch (error) {
logger.error(`Error fetching historical data for ${type}`, error);
}
}
// =====================================================================
// WARNING: This section is commented out to prevent storing latest API
// prices in the HistoricalPrice table.
//
// The "latest" API often returns prices with fewer decimal places than
// the historical API, which can cause calculation inconsistencies.
//
// Uncommenting this section may lead to inaccurate historical prices
// and affect investment value calculations.
// =====================================================================
/*
const today = moment().format('YYYY-MM-DD');
const todayPriceExists = await HistoricalPrice.findOne({
where: {
type,
date: today
}
});
if (!todayPriceExists && latestPrices[type]) {
const currentPrice = parseFloat(latestPrices[type].value);
await HistoricalPrice.create({
type,
date: today,
open: currentPrice,
high: currentPrice,
low: currentPrice,
close: currentPrice
});
logger.info(`Added today's price for ${type}: ${currentPrice}`);
}
*/
// =====================================================================
}
cache.clearAll();
logger.info('Comprehensive price update completed successfully');
} catch (error) {
logger.error('Comprehensive price update failed', error);
apiStatus.lastConnectionSuccess = false;
apiStatus.lastError = error;
apiStatus.errorMessage = `Error updating prices: ${error.message}`;
throw error;
}
}
async function calculateInvestmentValueAtDate(investment, investmentType, targetDate, priceMap = null) {
try {
let purchasePrice, priceAtTargetDate;
if (priceMap && priceMap[investment.type]) {
const investmentDateISO = moment(investment.date).format('YYYY-MM-DD');
purchasePrice = findClosestPriceInMap(priceMap[investment.type], investmentDateISO);
priceAtTargetDate = findClosestPriceInMap(priceMap[investment.type], targetDate);
if (!purchasePrice && investmentType) {
purchasePrice = investmentType.currentPrice;
}
if (!priceAtTargetDate && purchasePrice) {
priceAtTargetDate = purchasePrice;
}
} else {
const historicalPrice = await HistoricalPrice.findOne({
where: {
type: investment.type,
date: {
[Op.lte]: moment(investment.date).format('YYYY-MM-DD')
}
},
order: [['date', 'DESC']]
});
const targetPrice = await HistoricalPrice.findOne({
where: {
type: investment.type,
date: {
[Op.lte]: targetDate
}
},
order: [['date', 'DESC']]
});
purchasePrice = historicalPrice ? historicalPrice.close :
(investmentType ? investmentType.currentPrice : 0);
priceAtTargetDate = targetPrice ? targetPrice.close : purchasePrice;
}
const unitsPurchased = purchasePrice > 0 ? investment.amount / purchasePrice : 0;
const valueAtTargetDate = unitsPurchased * priceAtTargetDate;
return {
initialInvestment: parseFloat(investment.amount),
purchasePrice: parseFloat(purchasePrice || 0),
unitsPurchased: parseFloat(unitsPurchased),
currentValue: parseFloat(valueAtTargetDate),
currentPrice: parseFloat(priceAtTargetDate || 0),
profit: parseFloat(valueAtTargetDate - investment.amount)
};
} catch (error) {
logger.error(`Investment value calculation error at date ${targetDate}: ${error.message}`);
return {
initialInvestment: parseFloat(investment.amount),
purchasePrice: 0,
unitsPurchased: 0,
currentValue: 0,
currentPrice: 0,
profit: 0
};
}
}
function findClosestPriceInMap(pricesByDate, targetDate) {
const targetTime = moment(targetDate).valueOf();
let closestDate = null;
let closestDistance = Infinity;
for (const dateStr in pricesByDate) {
const currentTime = moment(dateStr).valueOf();
const distance = Math.abs(currentTime - targetTime);
if (currentTime <= targetTime && distance < closestDistance) {
closestDistance = distance;
closestDate = dateStr;
}
}
return closestDate ? pricesByDate[closestDate].close : null;
}
async function generateTimelineChartData() {
if (cache.timelineChartData && cache.isValid(cache.timelineChartDataTimestamp)) {
logger.debug('Using cached timeline chart data');
return cache.timelineChartData;
}
logger.info('Generating timeline chart data for all investments...');
const summaryChartMonths = parseInt(process.env.SUMMARY_CHART_MONTHS) || 12;
const startDate = moment().subtract(summaryChartMonths, 'months').startOf('day');
const endDate = moment().endOf('day');
const dataPoints = [];
let currentDate = moment(startDate);
while (currentDate.isSameOrBefore(endDate)) {
dataPoints.push({
date: currentDate.format('YYYY-MM-DD'),
jalaliDate: currentDate.format('jYYYY/jMM/jDD'),
totalValue: 0,
investments: {}
});
currentDate.add(1, 'week');
}
const investments = await Investment.findAll();
const investmentTypes = await InvestmentType.findAll();
const typeMap = {};
investmentTypes.forEach(type => {
typeMap[type.type] = type;
});
const investedTypes = [...new Set(investments.map(inv => inv.type))];
const historicalPrices = await HistoricalPrice.findAll({
where: {
type: { [Op.in]: investedTypes },
date: { [Op.gte]: startDate.format('YYYY-MM-DD') }
}
});
const priceMap = {};
historicalPrices.forEach(price => {
if (!priceMap[price.type]) {
priceMap[price.type] = {};
}
priceMap[price.type][price.date] = price;
});
for (let dataPoint of dataPoints) {
const pointDate = moment(dataPoint.date);
for (const investment of investments) {
if (moment(investment.date).isAfter(pointDate)) {
continue;
}
const investmentValue = await calculateInvestmentValueAtDate(
investment,
typeMap[investment.type],
dataPoint.date,
priceMap
);
dataPoint.totalValue += investmentValue.currentValue;
if (!dataPoint.investments[investment.type]) {
dataPoint.investments[investment.type] = 0;
}
dataPoint.investments[investment.type] += investmentValue.currentValue;
}
}
const maxChartPoints = parseInt(process.env.MAX_CHART_POINTS) || 52;
const limitedDataPoints = limitDataPoints(dataPoints, maxChartPoints);
cache.timelineChartData = limitedDataPoints;
cache.timelineChartDataTimestamp = Date.now();
logger.info(`Generated ${limitedDataPoints.length} timeline data points`);
return limitedDataPoints;
}
async function generateTypeChartData(type) {
if (cache.typeChartData[type] && cache.isValid(cache.typeChartData[type].timestamp)) {
logger.debug(`Using cached chart data for ${type}`);
return cache.typeChartData[type].data;
}
logger.info(`Generating chart data for ${type}...`);
try {
const investmentChartMonths = parseInt(process.env.INVESTMENT_CHART_MONTHS) || 6;
const startDate = moment().subtract(investmentChartMonths, 'months').format('YYYY-MM-DD');
const historicalPrices = await HistoricalPrice.findAll({
where: {
type,
date: {
[Op.gte]: startDate
}
},
order: [['date', 'ASC']]
});
if (historicalPrices.length === 0) {
logger.warn(`No historical data found for ${type} in the specified period`);
return { labels: [], datasets: [{ label: PERSIAN_NAMES[type] || type, data: [] }] };
}
const rawChartData = historicalPrices.map(price => ({
date: moment(price.date).format('YYYY-MM-DD'),
jalaliDate: moment(price.date).format('jYYYY/jMM/jDD'),
price: parseFloat(price.close)
}));
const chartData = limitDataPoints(rawChartData);
const chartDataObject = {
labels: chartData.map(point => point.jalaliDate),
datasets: [{
label: `قیمت ${PERSIAN_NAMES[type] || type}`,
data: chartData.map(point => point.price)
}]
};
cache.typeChartData[type] = {
data: chartDataObject,
timestamp: Date.now()
};
logger.info(`Generated chart data for ${type} with ${chartData.length} points`);
return chartDataObject;
} catch (error) {
logger.error(`Error generating chart data for ${type}:`, error);
return {
labels: [],
datasets: [{
label: `قیمت ${PERSIAN_NAMES[type] || type}`,
data: []
}]
};
}
}
function limitDataPoints(data, maxPoints = 52) {
if (!data || data.length <= maxPoints) return data;
const step = Math.ceil(data.length / maxPoints);
const result = [];
for (let i = 0; i < data.length; i += step) {
result.push(data[i]);
}
if (result.length > 0 && data.length > 0 &&
result[result.length - 1] !== data[data.length - 1]) {
result.push(data[data.length - 1]);
}
return result;
}
const app = express();
const sessionDir = './sessions';
if (!fs.existsSync(sessionDir)) {
fs.mkdirSync(sessionDir, { recursive: true });
}
const sessionOptions = {
store: new FileStore({
path: sessionDir,
ttl: 86400,
retries: 0,
logFn: function (message) {
if (!message.includes('ENOENT')) {
logger.debug(message);
}
}
}),
secret: process.env.SESSION_SECRET || 'dollarbaan-default-secret',
resave: false,
saveUninitialized: false,
cookie: {
maxAge: parseInt(process.env.SESSION_MAX_AGE) || 24 * 60 * 60 * 1000
},
rolling: true,
unset: 'destroy'
};
if (process.env.NODE_ENV === 'production' && process.env.ALLOW_INSECURE_COOKIES !== 'true') {
sessionOptions.cookie.secure = true;
if (process.env.TRUST_PROXY === 'true') {
app.set('trust proxy', 1);
}
}
app.use((req, res, next) => {
const originalErrorHandler = req.socket.listeners('error').shift();
req.socket.on('error', err => {
if (err.message.includes('ENOENT') && err.message.includes('session')) {
req.session = null;
if (req.xhr || req.path.startsWith('/api/')) {
return res.status(401).json({ error: 'جلسه نامعتبر است. لطفا دوباره وارد شوید.' });
}
return res.redirect('/login?error=invalid_session');
}
originalErrorHandler(err);
});
next();
});
app.use(cookieParser());
app.use(session(sessionOptions));
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
const isAuthenticated = (req, res, next) => {
if (req.session.isAuthenticated) {
return next();
}
req.session.returnTo = req.originalUrl;
res.redirect('/login');
};
app.get('/', isAuthenticated);
app.use([
'/investments',
'/investment-types',
'/invested-types',
'/api-status',
'/update-prices',
'/clear-cache'
], isAuthenticated);
app.use(express.static(path.join(__dirname, 'public')));
app.get('/login', (req, res) => {
if (req.session.isAuthenticated) {
return res.redirect('/');
}
res.sendFile(path.join(__dirname, 'public', 'login.html'));
});
app.post('/login', (req, res) => {
const { username, password } = req.body;
const isSecure = req.secure || req.headers['x-forwarded-proto'] === 'https';
if (process.env.NODE_ENV === 'production' && !isSecure && sessionOptions.cookie.secure) {
return res.redirect('/login?error=production_http');
}
if (username === process.env.AUTH_USERNAME && password === process.env.AUTH_PASSWORD) {
req.session.isAuthenticated = true;
req.session.username = username;
const returnTo = req.session.returnTo || '/';
delete req.session.returnTo;
return res.redirect(returnTo);
}
res.redirect('/login?error=invalid_credentials');
});
app.get('/logout', (req, res) => {
req.session.destroy();
res.redirect('/login');
});
app.get('/api-status', (req, res) => {
res.json({
lastConnectionTime: apiStatus.lastConnectionTime,
lastConnectionSuccess: apiStatus.lastConnectionSuccess,
lastError: apiStatus.errorMessage,
isConnected: apiStatus.lastConnectionSuccess
});
});
app.post('/clear-cache', async (req, res) => {
try {
cache.clearAll();
res.json({ success: true, message: 'Cache cleared successfully' });
} catch (error) {
logger.error('Error clearing cache:', error);
res.status(500).json({ success: false, error: error.message });
}