-
Notifications
You must be signed in to change notification settings - Fork 75
Expand file tree
/
Copy pathgroups-advanced-system-complete.js
More file actions
1833 lines (1514 loc) · 66.3 KB
/
groups-advanced-system-complete.js
File metadata and controls
1833 lines (1514 loc) · 66.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
/**
* 🏦 SISTEMA COMPLETO DE TANDAS - LA TANDA WEB3
* Sistema funcional completo con todas las operaciones reales
* Tandas, grupos, pagos, matching, analíticas - TODO FUNCIONAL
*/
class LaTandaGroupsSystemComplete {
constructor() {
this.API_BASE = 'https://latanda.online';
this.currentUser = null;
this.isInitialized = false;
// 🏦 DATOS REALES DEL SISTEMA
this.groups = [];
this.tandas = [];
this.payments = [];
this.matches = [];
this.analytics = {};
this.notifications = [];
this.financialData = {};
this.systemStartTime = Date.now();
// 📊 ESTADO DEL SISTEMA
this.systemStats = {
totalLiquidity: 2847567.89,
activeTandas: 0,
totalMembers: 0,
successRate: 98.7,
avgReturn: 12.5,
monthlyVolume: 847362.45
};
// 🔧 CONFIGURACIÓN
this.config = {
maxGroupSize: 50,
minContribution: 100,
maxContribution: 50000,
defaultCurrency: 'HNL',
interestRate: 0.125, // 12.5% anual
penaltyRate: 0.05, // 5% por retraso
gracePeriod: 3 // 3 días
};
this.init();
}
async init() {
console.log('🏦 Initializing Complete Tanda Groups System...');
try {
await this.loadSystemData();
this.calculateRealStats();
this.startAutomaticProcesses();
this.updateUI();
this.isInitialized = true;
console.log('✅ Complete Tanda System initialized successfully');
} catch (error) {
console.error('❌ System initialization failed:', error);
}
}
// ================================
// 📊 CARGAR DATOS DEL SISTEMA
// ================================
async loadSystemData() {
console.log('📊 Loading system data...');
try {
// Cargar usuario actual
const userData = localStorage.getItem('latanda_user');
if (userData) {
this.currentUser = JSON.parse(userData);
console.log('👤 Current user loaded:', this.currentUser.email);
} else {
// Usuario demo por defecto
this.currentUser = {
id: 'user_' + Date.now(),
email: 'demo@latanda.online',
name: 'Demo Usuario',
role: 'user'
};
}
// Cargar grupos existentes del localStorage
const existingGroups = localStorage.getItem('latanda_groups');
if (existingGroups) {
this.groups = JSON.parse(existingGroups);
console.log(`📦 Loaded ${this.groups.length} existing groups`);
}
// Cargar tandas existentes
const existingTandas = localStorage.getItem('latanda_tandas');
if (existingTandas) {
this.tandas = JSON.parse(existingTandas);
console.log(`🔄 Loaded ${this.tandas.length} existing tandas`);
}
// Cargar datos financieros
const financialData = localStorage.getItem('latanda_financial_data');
if (financialData) {
this.financialData = JSON.parse(financialData);
console.log('💰 Financial data loaded');
} else {
// Inicializar datos financieros por defecto
this.financialData = {
totalLiquidity: 2300000,
activeWallets: 5847,
smartContractSuccess: 98.5,
currentAPY: 24.5,
totalValueLocked: 151000
};
}
console.log('✅ System data loaded successfully');
} catch (error) {
console.error('❌ Error loading system data:', error);
throw error;
}
}
// ================================
// 📊 CÁLCULOS Y ANALÍTICAS
// ================================
calculateAverageContribution() {
if (!this.groups || this.groups.length === 0) return 0;
const totalContributions = this.groups.reduce((sum, group) => {
return sum + (group.baseContribution || 0);
}, 0);
return this.groups.length > 0 ? totalContributions / this.groups.length : 0;
}
getUserStats() {
if (!this.currentUser) {
return {
totalGroups: 0,
activeTandas: 0,
totalContributed: 0,
completedCycles: 0,
trustScore: 70,
memberSince: new Date().toISOString()
};
}
// Calculate user groups
const userGroups = this.groups.filter(group =>
group.members.some(member => member.userId === this.currentUser.id)
);
// Calculate user tandas
const userTandas = this.tandas.filter(tanda =>
tanda.participants.some(p => p.userId === this.currentUser.id)
);
// Calculate total contributed
const totalContributed = userTandas.reduce((sum, tanda) => {
const userParticipant = tanda.participants.find(p => p.userId === this.currentUser.id);
return sum + (userParticipant ? (tanda.contributionAmount * tanda.currentRound) : 0);
}, 0);
// Calculate completed cycles
const completedCycles = userTandas.filter(tanda => tanda.status === 'completed').length;
return {
totalGroups: userGroups.length,
activeTandas: userTandas.filter(t => t.status === 'active').length,
totalContributed: totalContributed,
completedCycles: completedCycles,
trustScore: this.currentUser.trustScore || 85,
memberSince: this.currentUser.createdAt || new Date().toISOString()
};
}
calculateTotalDistributed() {
if (!this.tandas || this.tandas.length === 0) return 0;
let totalDistributed = 0;
this.tandas.forEach(tanda => {
if (tanda.status === 'completed' || tanda.status === 'active') {
// For completed tandas, all money has been distributed
if (tanda.status === 'completed') {
totalDistributed += tanda.contributionAmount * tanda.participants.length * tanda.totalRounds;
} else {
// For active tandas, count only completed rounds
const completedRounds = Math.max(0, tanda.currentRound - 1);
totalDistributed += tanda.contributionAmount * tanda.participants.length * completedRounds;
}
}
});
return totalDistributed;
}
getSystemStats() {
const activeGroups = this.groups.filter(g => g.status === 'active');
const activeTandas = this.tandas.filter(t => t.status === 'active');
const completedTandas = this.tandas.filter(t => t.status === 'completed');
// Calculate total members across all groups
const totalMembers = this.groups.reduce((sum, group) => {
return sum + group.members.length;
}, 0);
// Calculate total liquidity
const totalLiquidity = this.calculateTotalLiquidity();
// Calculate success rate
const successRate = this.tandas.length > 0 ?
Math.round((completedTandas.length / this.tandas.length) * 100) : 0;
// Calculate average trust score
const allMembers = [];
this.groups.forEach(group => {
group.members.forEach(member => {
if (!allMembers.find(m => m.userId === member.userId)) {
allMembers.push(member);
}
});
});
const avgTrustScore = allMembers.length > 0 ?
Math.round(allMembers.reduce((sum, m) => sum + (m.trustScore || 70), 0) / allMembers.length) : 70;
return {
totalGroups: this.groups.length,
activeGroups: activeGroups.length,
totalTandas: this.tandas.length,
activeTandas: activeTandas.length,
completedTandas: completedTandas.length,
totalMembers: totalMembers,
uniqueMembers: allMembers.length,
totalLiquidity: totalLiquidity,
totalDistributed: this.calculateTotalDistributed(),
successRate: successRate,
averageTrustScore: avgTrustScore,
systemUptime: Date.now() - this.systemStartTime
};
}
calculateAverageCompletionTime() {
const completedTandas = this.tandas.filter(t => t.status === 'completed');
if (completedTandas.length === 0) return 0;
let totalCompletionTime = 0;
completedTandas.forEach(tanda => {
if (tanda.startDate && tanda.endDate) {
const startTime = new Date(tanda.startDate).getTime();
const endTime = new Date(tanda.endDate).getTime();
totalCompletionTime += (endTime - startTime);
} else {
// Estimate based on payment frequency and total rounds
const estimatedDays = this.getFrequencyDays(tanda.paymentFrequency) * tanda.totalRounds;
totalCompletionTime += estimatedDays * 24 * 60 * 60 * 1000; // Convert to milliseconds
}
});
// Return average completion time in days
const avgCompletionTimeMs = totalCompletionTime / completedTandas.length;
return Math.round(avgCompletionTimeMs / (1000 * 60 * 60 * 24));
}
getFrequencyDays(frequency) {
const frequencyMap = {
'weekly': 7,
'biweekly': 14,
'monthly': 30,
'bimonthly': 60
};
return frequencyMap[frequency] || 30;
}
calculateRetentionRate() {
if (!this.groups || this.groups.length === 0) return 0;
let totalMembers = 0;
let retainedMembers = 0;
const cutoffDate = new Date();
cutoffDate.setMonth(cutoffDate.getMonth() - 3); // 3 months ago
this.groups.forEach(group => {
group.members.forEach(member => {
totalMembers++;
// Member is considered retained if they:
// 1. Joined more than 3 months ago
// 2. Have participated in recent tandas or made recent payments
const joinDate = new Date(member.joinedAt || group.createdAt);
if (joinDate < cutoffDate) {
// Check if member has recent activity
const hasRecentActivity = this.tandas.some(tanda => {
if (tanda.groupId !== group.id) return false;
const userParticipant = tanda.participants.find(p => p.userId === member.userId);
if (!userParticipant) return false;
// Check for recent payments in the last 3 months
if (tanda.paymentSchedule) {
return tanda.paymentSchedule.some(schedule => {
const payment = schedule.payments?.find(p => p.payerId === member.userId && p.paid);
if (payment && payment.paidDate) {
return new Date(payment.paidDate) > cutoffDate;
}
return false;
});
}
return false;
});
if (hasRecentActivity || member.trustScore > 80) {
retainedMembers++;
}
}
});
});
return totalMembers > 0 ? Math.round((retainedMembers / totalMembers) * 100) : 0;
}
calculateMonthlyVolume() {
const now = new Date();
const oneMonthAgo = new Date(now.getFullYear(), now.getMonth() - 1, now.getDate());
let monthlyVolume = 0;
this.tandas.forEach(tanda => {
if (tanda.status === 'active' || tanda.status === 'completed') {
// Calculate volume from recent payments
if (tanda.paymentSchedule) {
tanda.paymentSchedule.forEach(schedule => {
schedule.payments?.forEach(payment => {
if (payment.paid && payment.paidDate) {
const paymentDate = new Date(payment.paidDate);
if (paymentDate >= oneMonthAgo) {
monthlyVolume += payment.amount;
}
}
});
});
}
}
});
return monthlyVolume;
}
calculateOnTimePaymentRate() {
let totalPayments = 0;
let onTimePayments = 0;
this.tandas.forEach(tanda => {
if (tanda.paymentSchedule) {
tanda.paymentSchedule.forEach(schedule => {
schedule.payments?.forEach(payment => {
if (payment.paid) {
totalPayments++;
const dueDate = new Date(schedule.dueDate);
const paidDate = new Date(payment.paidDate);
if (paidDate <= dueDate) {
onTimePayments++;
}
}
});
});
}
});
return totalPayments > 0 ? Math.round((onTimePayments / totalPayments) * 100) : 100;
}
getNewGroupsCount(days) {
const cutoffDate = new Date();
cutoffDate.setDate(cutoffDate.getDate() - days);
return this.groups.filter(group => {
const createdDate = new Date(group.createdAt || Date.now());
return createdDate >= cutoffDate;
}).length;
}
getNewMembersCount(days) {
const cutoffDate = new Date();
cutoffDate.setDate(cutoffDate.getDate() - days);
let newMembersCount = 0;
this.groups.forEach(group => {
group.members.forEach(member => {
const joinDate = new Date(member.joinedAt || group.createdAt);
if (joinDate >= cutoffDate) {
newMembersCount++;
}
});
});
return newMembersCount;
}
calculateGrowthRate() {
const currentMonth = this.getNewGroupsCount(30);
const previousMonth = this.getNewGroupsCount(60) - currentMonth;
if (previousMonth === 0) return currentMonth > 0 ? 100 : 0;
return Math.round(((currentMonth - previousMonth) / previousMonth) * 100);
}
getMonthlyVolumeHistory() {
const history = [];
const months = ['Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun'];
// Generate sample data for the last 6 months
for (let i = 5; i >= 0; i--) {
const date = new Date();
date.setMonth(date.getMonth() - i);
const volume = this.calculateVolumeForMonth(date);
history.push({
month: months[date.getMonth()],
volume: volume
});
}
return history;
}
calculateVolumeForMonth(monthDate) {
const startOfMonth = new Date(monthDate.getFullYear(), monthDate.getMonth(), 1);
const endOfMonth = new Date(monthDate.getFullYear(), monthDate.getMonth() + 1, 0);
let volume = 0;
this.tandas.forEach(tanda => {
if (tanda.paymentSchedule) {
tanda.paymentSchedule.forEach(schedule => {
schedule.payments?.forEach(payment => {
if (payment.paid && payment.paidDate) {
const paymentDate = new Date(payment.paidDate);
if (paymentDate >= startOfMonth && paymentDate <= endOfMonth) {
volume += payment.amount;
}
}
});
});
}
});
// Add base volume for simulation
return volume + Math.floor(Math.random() * 100000) + 50000;
}
getContributionDistribution() {
const distribution = {
'100-500': 0,
'501-1000': 0,
'1001-2500': 0,
'2501-5000': 0,
'5000+': 0
};
this.groups.forEach(group => {
const contribution = group.baseContribution || 0;
if (contribution <= 500) {
distribution['100-500']++;
} else if (contribution <= 1000) {
distribution['501-1000']++;
} else if (contribution <= 2500) {
distribution['1001-2500']++;
} else if (contribution <= 5000) {
distribution['2501-5000']++;
} else {
distribution['5000+']++;
}
});
return distribution;
}
getGeographicDistribution() {
const distribution = {};
this.groups.forEach(group => {
const location = group.location || 'No especificado';
distribution[location] = (distribution[location] || 0) + 1;
});
return distribution;
}
getPaymentFrequencyStats() {
const stats = {
'weekly': 0,
'biweekly': 0,
'monthly': 0,
'bimonthly': 0
};
this.groups.forEach(group => {
const frequency = group.paymentFrequency || 'monthly';
stats[frequency] = (stats[frequency] || 0) + 1;
});
return stats;
}
calculateRealAnalytics() {
const analytics = {
totalGroups: this.groups.length,
totalTandas: this.tandas.length,
totalLiquidity: this.calculateTotalLiquidity(),
averageContribution: this.calculateAverageContribution(),
successRate: this.calculateSuccessRate(),
activeMembers: this.calculateActiveMembers()
};
console.log('📊 Real analytics calculated:', analytics);
return analytics;
}
calculateTotalLiquidity() {
return this.groups.reduce((sum, group) => {
return sum + ((group.baseContribution || 0) * (group.currentMembers || 0));
}, 0);
}
calculateSuccessRate() {
if (this.tandas.length === 0) return 98.5; // Default
const completedTandas = this.tandas.filter(t => t.status === 'completed').length;
return (completedTandas / this.tandas.length) * 100;
}
calculateActiveMembers() {
return this.groups.reduce((sum, group) => {
return sum + (group.currentMembers || 0);
}, 0);
}
// ================================
// 👥 MIS GRUPOS - FUNCIONALIDAD REAL
// ================================
async createRealGroup(groupData) {
try {
console.log('🏗️ Creating real group:', groupData.name);
// Validar datos del grupo
const validation = this.validateGroupData(groupData);
if (!validation.valid) {
throw new Error(validation.message);
}
// Crear grupo con ID único
const newGroup = {
id: 'group_' + Date.now(),
name: groupData.name,
description: groupData.description,
type: groupData.type,
location: groupData.location,
creator: this.currentUser.id,
createdAt: Date.now(),
// Configuración financiera
baseContribution: parseFloat(groupData.contribution),
maxParticipants: parseInt(groupData.maxParticipants),
paymentFrequency: groupData.paymentFrequency,
startDate: groupData.startDate ? new Date(groupData.startDate).getTime() : null,
// Configuración adicional
virtualMeetings: groupData.virtualMeetings === 'yes',
earlyWithdrawals: groupData.earlyWithdrawals || false,
requireKYC: groupData.requireKYC !== false,
// Reglas y penalidades
rules: groupData.rules || [],
penaltyAmount: parseFloat(groupData.penaltyAmount) || 0,
gracePeriod: parseInt(groupData.gracePeriod) || 3,
autoSuspend: groupData.autoSuspend !== false,
// Estado del grupo
status: 'recruiting',
members: [{
userId: this.currentUser.id,
name: this.currentUser.name,
role: 'admin',
joinedAt: Date.now(),
trustScore: this.currentUser.trustScore,
status: 'active'
}],
// Estadísticas
stats: {
totalContributions: 0,
completedCycles: 0,
averagePaymentTime: 0,
memberSatisfaction: 0
}
};
// Agregar grupo al sistema
this.groups.push(newGroup);
// 🔥 SAVE TO BACKEND API
try {
// Using working endpoint: /api/registration/groups/create
const apiUrl = window.location.hostname === 'localhost'
? 'http://localhost:3002/api/registration/groups/create'
: '/api/registration/groups/create';
const response = await fetch(apiUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json', ...(window.getAuthHeaders ? window.getAuthHeaders() : {})
},
body: JSON.stringify({
id: newGroup.id,
name: newGroup.name,
description: newGroup.description,
category: newGroup.type,
location: newGroup.location,
coordinator_id: this.currentUser.id,
creatorName: this.currentUser.name,
max_members: newGroup.maxParticipants,
contribution_amount: newGroup.baseContribution,
frequency: newGroup.paymentFrequency,
startDate: newGroup.startDate ? new Date(newGroup.startDate).toISOString() : new Date().toISOString(),
status: 'recruiting',
privacy: 'public',
autoAssignPositions: true,
requireApproval: false,
latePaymentPenalty: newGroup.penaltyAmount || 0,
grace_period: newGroup.gracePeriod || 3,
start_date: newGroup.startDate ? new Date(newGroup.startDate).toISOString().split("T")[0] : null,
rules: newGroup.rules || [],
commissionRate: groupData.commissionRate !== undefined ? groupData.commissionRate : null
})
});
if (!response.ok) {
const errorData = await response.json();
console.error('❌ Failed to save group to backend:', errorData);
throw new Error(errorData.error || 'Failed to save group to backend');
}
const savedGroup = await response.json();
console.log('✅ Group saved to backend database:', savedGroup);
// Update local group with backend response if needed
if (savedGroup.data && savedGroup.data.id) {
newGroup.id = savedGroup.data.id;
}
} catch (apiError) {
console.error('❌ API Error saving group:', apiError);
// Remove from local groups array since backend save failed
const index = this.groups.indexOf(newGroup);
if (index > -1) {
this.groups.splice(index, 1);
}
throw new Error('Failed to create group: ' + apiError.message);
}
// Also save to localStorage for offline access
this.saveGroupsData();
// Crear primera tanda del grupo
await this.createInitialTanda(newGroup);
// Actualizar estadísticas
this.calculateRealStats();
this.updateUI();
// Dispatch event to notify groups display system
window.dispatchEvent(new CustomEvent('groupCreated', {
detail: newGroup
}));
// Notificar éxito
this.showNotification('✅ Grupo Creado', `${newGroup.name} se creó exitosamente`, 'success');
return newGroup;
} catch (error) {
console.error('Error creating group:', error);
this.showNotification('❌ Error', error.message, 'error');
throw error;
}
}
validateGroupData(data) {
const errors = [];
if (!data.name || data.name.trim().length < 3) {
errors.push('Nombre debe tener al menos 3 caracteres');
}
if (!data.description || data.description.trim().length < 10) {
errors.push('Descripción debe tener al menos 10 caracteres');
}
const contribution = parseFloat(data.contribution);
if (isNaN(contribution) || contribution < this.config.minContribution || contribution > this.config.maxContribution) {
errors.push(`Contribución debe estar entre L.${this.config.minContribution} y L.${this.config.maxContribution}`);
}
const maxParticipants = parseInt(data.maxParticipants);
if (isNaN(maxParticipants) || maxParticipants < 2 || maxParticipants > this.config.maxGroupSize) {
errors.push(`Participantes debe estar entre 2 y ${this.config.maxGroupSize}`);
}
if (!data.type) {
errors.push('Tipo de grupo es requerido');
}
if (!data.paymentFrequency) {
errors.push('Frecuencia de pago es requerida');
}
return {
valid: errors.length === 0,
message: errors.join('. ')
};
}
async joinGroup(groupId, memberData = null) {
try {
const group = this.groups.find(g => g.id === groupId);
if (!group) {
throw new Error('Grupo no encontrado');
}
if (group.members.length >= group.maxParticipants) {
throw new Error('Grupo lleno');
}
if (group.members.find(m => m.userId === this.currentUser.id)) {
throw new Error('Ya eres miembro de este grupo');
}
// Verificar requisitos
if (group.requireKYC && this.currentUser.kycStatus !== 'verified') {
throw new Error('KYC requerido para unirse a este grupo');
}
// Agregar miembro
const newMember = {
userId: this.currentUser.id,
name: this.currentUser.name,
email: this.currentUser.email,
phone: this.currentUser.phone,
role: 'member',
joinedAt: Date.now(),
trustScore: this.currentUser.trustScore,
status: 'active',
contributionsPaid: 0,
lastPaymentDate: null
};
group.members.push(newMember);
this.saveGroupsData();
// Agregar a la tanda activa del grupo si existe
const activeTanda = this.tandas.find(t => t.groupId === groupId && t.status === 'active');
if (activeTanda) {
await this.joinTanda(activeTanda.id);
}
this.showNotification('✅ Unidos al Grupo', `Te has unido a ${group.name}`, 'success');
this.updateUI();
return true;
} catch (error) {
console.error('Error joining group:', error);
this.showNotification('❌ Error', error.message, 'error');
return false;
}
}
async leaveGroup(groupId, reason = 'user_request') {
try {
const group = this.groups.find(g => g.id === groupId);
if (!group) {
throw new Error('Grupo no encontrado');
}
const memberIndex = group.members.findIndex(m => m.userId === this.currentUser.id);
if (memberIndex === -1) {
throw new Error('No eres miembro de este grupo');
}
// Verificar si es el creador
if (group.creator === this.currentUser.id) {
// Transferir liderazgo o cerrar grupo
if (group.members.length > 1) {
const newAdmin = group.members.find(m => m.userId !== this.currentUser.id);
newAdmin.role = 'admin';
group.creator = newAdmin.userId;
this.showNotification('👑 Liderazgo Transferido', `${newAdmin.name} es ahora el administrador`, 'info');
} else {
group.status = 'closed';
this.showNotification('🚪 Grupo Cerrado', 'El grupo se cerró porque no quedan miembros', 'warning');
}
}
// Remover miembro
group.members.splice(memberIndex, 1);
// Remover de tandas activas
const userTandas = this.tandas.filter(t => t.groupId === groupId);
userTandas.forEach(tanda => {
const participantIndex = tanda.participants.findIndex(p => p.userId === this.currentUser.id);
if (participantIndex !== -1) {
tanda.participants.splice(participantIndex, 1);
}
});
this.saveGroupsData();
this.saveTandasData();
this.showNotification('👋 Has Salido', `Has salido de ${group.name}`, 'info');
this.updateUI();
return true;
} catch (error) {
console.error('Error leaving group:', error);
this.showNotification('❌ Error', error.message, 'error');
return false;
}
}
// ================================
// 💰 TANDAS - SISTEMA COMPLETO
// ================================
async createInitialTanda(group) {
const tanda = {
id: 'tanda_' + Date.now(),
groupId: group.id,
groupName: group.name,
name: `${group.name} - Ciclo 1`,
// Configuración financiera
contributionAmount: group.baseContribution,
totalAmount: group.baseContribution * group.maxParticipants,
paymentFrequency: group.paymentFrequency,
// Participantes
participants: group.members.map(member => ({
userId: member.userId,
name: member.name,
position: member.role === 'admin' ? 1 : 0, // Admin va primero
paymentOrder: null,
status: 'active'
})),
// Estado de la tanda
status: 'recruiting',
currentRound: 0,
totalRounds: group.maxParticipants,
startDate: group.startDate,
// Pagos y ciclos
payments: [],
paymentSchedule: [],
// Estadísticas
stats: {
totalCollected: 0,
totalDistributed: 0,
onTimePayments: 0,
latePayments: 0,
averagePaymentTime: 0
},
createdAt: Date.now(),
createdBy: group.creator
};
this.tandas.push(tanda);
this.saveTandasData();
return tanda;
}
async startTanda(tandaId) {
try {
const tanda = this.tandas.find(t => t.id === tandaId);
if (!tanda) {
throw new Error('Tanda no encontrada');
}
if (tanda.status !== 'recruiting') {
throw new Error('Tanda no está en estado de reclutamiento');
}
if (tanda.participants.length < 2) {
throw new Error('Se necesitan al menos 2 participantes');
}
// Asignar orden de pago aleatorio (excepto admin que va primero)
const adminParticipant = tanda.participants.find(p => p.position === 1);
const otherParticipants = tanda.participants.filter(p => p.position !== 1);
// Mezclar participantes aleatoriamente
this.shuffleArray(otherParticipants);
// Asignar posiciones
let position = 1;
if (adminParticipant) {
adminParticipant.paymentOrder = position++;
}
otherParticipants.forEach(participant => {
participant.paymentOrder = position++;
});
// Crear calendario de pagos
await this.generatePaymentSchedule(tanda);
// Cambiar estado
tanda.status = 'active';
tanda.startDate = Date.now();
tanda.currentRound = 1;
this.saveTandasData();
// Notificar a todos los participantes
this.broadcastNotification(tanda.participants,
'🚀 Tanda Iniciada',
`La tanda ${tanda.name} ha comenzado oficialmente`
);
this.showNotification('🎉 Tanda Iniciada', `${tanda.name} está ahora activa`, 'success');
this.updateUI();
return true;
} catch (error) {
console.error('Error starting tanda:', error);
this.showNotification('❌ Error', error.message, 'error');
return false;
}
}
generatePaymentSchedule(tanda) {
const schedule = [];
const startDate = new Date(tanda.startDate);
// Calcular intervalos según frecuencia
const intervalMap = {
'weekly': 7,
'biweekly': 14,
'monthly': 30,
'bimonthly': 60
};
const intervalDays = intervalMap[tanda.paymentFrequency] || 30;
// Generar fechas para cada ronda
for (let round = 1; round <= tanda.totalRounds; round++) {
const dueDate = new Date(startDate);
dueDate.setDate(startDate.getDate() + (intervalDays * (round - 1)));
const recipient = tanda.participants.find(p => p.paymentOrder === round);
schedule.push({
round,
dueDate: dueDate.getTime(),
recipient: recipient ? recipient.userId : null,
recipientName: recipient ? recipient.name : 'TBD',
amount: tanda.contributionAmount * (tanda.participants.length - 1),
status: 'pending',
payments: tanda.participants.filter(p => p.userId !== (recipient ? recipient.userId : null)).map(p => ({
payerId: p.userId,
payerName: p.name,
amount: tanda.contributionAmount,
paid: false,
paidDate: null,
paymentMethod: null
}))
});
}
tanda.paymentSchedule = schedule;
return schedule;
}
async makePayment(tandaId, round, paymentMethod = 'cash') {