Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
1768 lines (1480 loc) · 54.5 KB
/
Copy pathscript.js
File metadata and controls
1768 lines (1480 loc) · 54.5 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
/**
* Reactorcore's Revenue Share System - Main JavaScript
* Handles tab navigation and interactive features
*/
// ========================================
// TAB NAVIGATION
// ========================================
/**
* Initialize tab navigation system
*/
function initTabNavigation() {
const navButtons = document.querySelectorAll('.nav-btn');
const tabContents = document.querySelectorAll('.tab-content');
// Add click event listeners to all navigation buttons
navButtons.forEach(button => {
button.addEventListener('click', () => {
const targetTab = button.getAttribute('data-tab');
switchTab(targetTab, navButtons, tabContents);
});
});
}
/**
* Switch to a specific tab
* @param {string} tabId - The ID of the tab to switch to
* @param {NodeList} navButtons - All navigation buttons
* @param {NodeList} tabContents - All tab content sections
*/
function switchTab(tabId, navButtons, tabContents) {
// Remove active class from all buttons
navButtons.forEach(btn => btn.classList.remove('active'));
// Remove active class from all tab contents
tabContents.forEach(content => content.classList.remove('active'));
// Add active class to clicked button
const activeButton = document.querySelector(`[data-tab="${tabId}"]`);
if (activeButton) {
activeButton.classList.add('active');
}
// Show corresponding tab content
const activeTab = document.getElementById(`tab-${tabId}`);
if (activeTab) {
activeTab.classList.add('active');
// Scroll to top of content smoothly
window.scrollTo({
top: 0,
behavior: 'smooth'
});
}
}
/**
* Initialize burger menu for mobile navigation
*/
function initBurgerMenu() {
const burgerBtn = document.getElementById('burger-menu');
const navMenu = document.getElementById('nav-menu');
const navButtons = document.querySelectorAll('.nav-btn');
if (!burgerBtn || !navMenu) return;
// Toggle menu on burger button click
burgerBtn.addEventListener('click', (e) => {
e.stopPropagation();
burgerBtn.classList.toggle('active');
navMenu.classList.toggle('active');
});
// Close menu when clicking a nav button
navButtons.forEach(button => {
button.addEventListener('click', () => {
burgerBtn.classList.remove('active');
navMenu.classList.remove('active');
});
});
// Close menu when clicking outside
document.addEventListener('click', (e) => {
if (navMenu.classList.contains('active')) {
if (!navMenu.contains(e.target) && !burgerBtn.contains(e.target)) {
burgerBtn.classList.remove('active');
navMenu.classList.remove('active');
}
}
});
// Close menu on escape key
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && navMenu.classList.contains('active')) {
burgerBtn.classList.remove('active');
navMenu.classList.remove('active');
}
});
}
// ========================================
// UTILITY FUNCTIONS
// ========================================
/**
* Debounce function to limit how often a function can run
* Useful for resize and scroll events
* @param {Function} func - The function to debounce
* @param {number} wait - Time to wait in milliseconds
*/
function debounce(func, wait) {
let timeout;
return function executedFunction(...args) {
const later = () => {
clearTimeout(timeout);
func(...args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
}
/**
* Handle responsive navbar behavior on scroll
*/
function handleNavbarScroll() {
const navbar = document.getElementById('navbar');
let lastScroll = 0;
window.addEventListener('scroll', debounce(() => {
const currentScroll = window.pageYOffset;
// Add shadow when scrolled
if (currentScroll > 10) {
navbar.style.boxShadow = '0 4px 20px rgba(0, 0, 0, 0.7)';
} else {
navbar.style.boxShadow = '0 4px 15px rgba(0, 0, 0, 0.5)';
}
lastScroll = currentScroll;
}, 50));
}
// ========================================
// FILE STATUS INTERACTION
// ========================================
/**
* Initialize file status click/tap interaction
* Both Desktop and Mobile: Click/Tap to toggle between square and expanded
*/
function initFileStatusInteraction() {
const fileStatus = document.getElementById('file-status');
if (!fileStatus) return;
// Click/Tap to toggle minimized state (works on both desktop and mobile)
fileStatus.addEventListener('click', () => {
fileStatus.classList.toggle('minimized');
});
}
// ========================================
// INITIALIZATION
// ========================================
/**
* Initialize all functionality when DOM is ready
*/
document.addEventListener('DOMContentLoaded', () => {
// Initialize tab navigation
initTabNavigation();
// Initialize burger menu for mobile
initBurgerMenu();
// Initialize navbar scroll behavior
handleNavbarScroll();
// Initialize file status hover/tap behavior
initFileStatusInteraction();
// Initialize file management system (save/load/drag-drop)
initFileManagement();
// Initialize Team & Credits tab
initTeamTab();
// Initialize Payout Calculator tab
initCalculatorTab();
// Initialize History tab
initDashboardTab();
// Log initialization
console.log('Reactorcore Revenue Share System initialized successfully');
console.log('Version: 1.0.0');
console.log('Burger Menu ready');
console.log('File Management ready');
console.log('Team & Credits tab ready');
console.log('Payout Calculator tab ready');
console.log('History tab ready');
});
// ========================================
// DATA MANAGEMENT
// ========================================
/**
* Application data structure
*/
const AppData = {
project: {
name: '',
description: ''
},
members: [],
payouts: []
};
/**
* Save data to localStorage
*/
function saveData() {
try {
localStorage.setItem('revshare_data', JSON.stringify(AppData));
} catch (error) {
console.error('Error saving data:', error);
}
}
/**
* Load data from localStorage
*/
function loadData() {
try {
const saved = localStorage.getItem('revshare_data');
if (saved) {
const parsed = JSON.parse(saved);
AppData.project = parsed.project || AppData.project;
AppData.members = parsed.members || AppData.members;
AppData.payouts = parsed.payouts || AppData.payouts;
return true;
}
} catch (error) {
console.error('Error loading data:', error);
}
return false;
}
// ========================================
// TEAM & CREDITS TAB
// ========================================
/**
* Initialize Team & Credits tab functionality
*/
function initTeamTab() {
// Load existing data
loadData();
// Initialize project info
initProjectInfo();
// Initialize member form
initMemberForm();
// Initialize toggle buttons for tier groups
initTierToggles();
// Initialize export functionality
initExportButtons();
// Render initial team list
renderTeamList();
}
/**
* Initialize project information section
*/
function initProjectInfo() {
const nameInput = document.getElementById('project-name');
const descInput = document.getElementById('project-description');
const descCount = document.getElementById('desc-count');
// Load saved values
if (nameInput) nameInput.value = AppData.project.name;
if (descInput) {
descInput.value = AppData.project.description;
if (descCount) descCount.textContent = descInput.value.length;
}
// Add event listeners
if (nameInput) {
nameInput.addEventListener('input', debounce(() => {
AppData.project.name = nameInput.value;
saveData();
}, 500));
}
if (descInput) {
descInput.addEventListener('input', debounce(() => {
AppData.project.description = descInput.value;
if (descCount) descCount.textContent = descInput.value.length;
saveData();
}, 500));
}
}
/**
* Initialize member form functionality
*/
function initMemberForm() {
const form = document.getElementById('add-member-form');
const roleTextarea = document.getElementById('member-role');
const roleCount = document.getElementById('role-count');
const cancelBtn = document.getElementById('cancel-edit-btn');
// Character counter for role field
if (roleTextarea && roleCount) {
roleTextarea.addEventListener('input', () => {
roleCount.textContent = roleTextarea.value.length;
});
}
// Form submission
if (form) {
form.addEventListener('submit', (e) => {
e.preventDefault();
const memberId = form.dataset.editingId;
if (memberId) {
updateMember(memberId);
} else {
addMember();
}
});
}
// Cancel edit button
if (cancelBtn) {
cancelBtn.addEventListener('click', () => {
resetMemberForm();
});
}
}
/**
* Add a new member
*/
function addMember() {
const name = document.getElementById('member-name').value.trim();
const tier = document.getElementById('member-tier').value;
const email = document.getElementById('member-email').value.trim();
const payment = document.getElementById('member-payment').value.trim();
const role = document.getElementById('member-role').value.trim();
if (!name || !tier) {
alert('Please fill in all required fields (Name and Tier).');
return;
}
const member = {
id: generateId(),
name,
tier,
email,
payment,
role,
joinDate: new Date().toISOString()
};
AppData.members.push(member);
saveData();
renderTeamList();
resetMemberForm();
// Show success feedback
showToast(`${name} has been added to the team!`);
}
/**
* Edit an existing member
*/
function editMember(memberId) {
const member = AppData.members.find(m => m.id === memberId);
if (!member) return;
// Populate form
document.getElementById('member-name').value = member.name;
document.getElementById('member-tier').value = member.tier;
document.getElementById('member-email').value = member.email || '';
document.getElementById('member-payment').value = member.payment || '';
document.getElementById('member-role').value = member.role || '';
document.getElementById('role-count').textContent = (member.role || '').length;
// Update form state
const form = document.getElementById('add-member-form');
const submitBtn = form.querySelector('button[type="submit"]');
const cancelBtn = document.getElementById('cancel-edit-btn');
form.dataset.editingId = memberId;
submitBtn.textContent = 'Update Member';
cancelBtn.style.display = 'block';
// Scroll to form
document.querySelector('.add-member-section').scrollIntoView({ behavior: 'smooth' });
}
/**
* Update an existing member
*/
function updateMember(memberId) {
const member = AppData.members.find(m => m.id === memberId);
if (!member) return;
member.name = document.getElementById('member-name').value.trim();
member.tier = document.getElementById('member-tier').value;
member.email = document.getElementById('member-email').value.trim();
member.payment = document.getElementById('member-payment').value.trim();
member.role = document.getElementById('member-role').value.trim();
saveData();
renderTeamList();
resetMemberForm();
showToast(`${member.name}'s information has been updated!`);
}
/**
* Delete a member
*/
function deleteMember(memberId) {
const member = AppData.members.find(m => m.id === memberId);
if (!member) return;
if (confirm(`Are you sure you want to remove ${member.name} from the team?`)) {
AppData.members = AppData.members.filter(m => m.id !== memberId);
saveData();
renderTeamList();
showToast(`${member.name} has been removed from the team.`);
}
}
/**
* Reset the member form
*/
function resetMemberForm() {
const form = document.getElementById('add-member-form');
const submitBtn = form.querySelector('button[type="submit"]');
const cancelBtn = document.getElementById('cancel-edit-btn');
form.reset();
delete form.dataset.editingId;
submitBtn.textContent = 'Add Member';
cancelBtn.style.display = 'none';
document.getElementById('role-count').textContent = '0';
}
/**
* Render the complete team list
*/
function renderTeamList() {
// Update stats
updateTeamStats();
// Render each tier
renderTier('main');
renderTier('assistant');
renderTier('thanks');
renderTier('fan');
}
/**
* Update team statistics
*/
function updateTeamStats() {
const stats = {
main: AppData.members.filter(m => m.tier === 'main').length,
assistant: AppData.members.filter(m => m.tier === 'assistant').length,
thanks: AppData.members.filter(m => m.tier === 'thanks').length,
fan: AppData.members.filter(m => m.tier === 'fan').length
};
document.getElementById('stat-main').textContent = stats.main;
document.getElementById('stat-assistant').textContent = stats.assistant;
document.getElementById('stat-thanks').textContent = stats.thanks;
document.getElementById('stat-fan').textContent = stats.fan;
}
/**
* Render a specific tier's member list
*/
function renderTier(tier) {
const listElement = document.getElementById(`${tier}-list`);
if (!listElement) return;
const members = AppData.members
.filter(m => m.tier === tier)
.sort((a, b) => a.name.localeCompare(b.name));
if (members.length === 0) {
listElement.innerHTML = '';
return;
}
listElement.innerHTML = members.map(member => createMemberCard(member)).join('');
// Add event listeners to action buttons
members.forEach(member => {
const editBtn = listElement.querySelector(`[data-edit-id="${member.id}"]`);
const deleteBtn = listElement.querySelector(`[data-delete-id="${member.id}"]`);
if (editBtn) {
editBtn.addEventListener('click', () => editMember(member.id));
}
if (deleteBtn) {
deleteBtn.addEventListener('click', () => deleteMember(member.id));
}
});
}
/**
* Create HTML for a member card
*/
function createMemberCard(member) {
const tierLabels = {
main: 'Main Tier',
assistant: 'Assistant Tier',
thanks: 'Special Thanks',
fan: 'Fan Tier'
};
const joinDate = new Date(member.joinDate).toLocaleDateString();
return `
<div class="member-card" data-member-id="${member.id}">
<div class="member-header">
<div>
<div class="member-name">${escapeHtml(member.name)}</div>
<div class="member-tier-label">${tierLabels[member.tier]}</div>
</div>
<div class="member-actions">
<button class="action-btn" data-edit-id="${member.id}">Edit</button>
<button class="action-btn delete" data-delete-id="${member.id}">Remove</button>
</div>
</div>
${member.email || member.payment ? `
<div class="member-details">
${member.email ? `
<div class="member-detail">
<div class="detail-label">Email</div>
<div class="detail-value">${escapeHtml(member.email)}</div>
</div>
` : ''}
${member.payment ? `
<div class="member-detail">
<div class="detail-label">Payment Address</div>
<div class="detail-value">${escapeHtml(member.payment)}</div>
</div>
` : ''}
</div>
` : ''}
${member.role ? `
<div class="member-role">${escapeHtml(member.role)}</div>
` : ''}
<div class="join-date">Joined: ${joinDate}</div>
</div>
`;
}
/**
* Initialize tier toggle functionality
*/
function initTierToggles() {
const toggleBtns = document.querySelectorAll('.toggle-btn');
toggleBtns.forEach(btn => {
btn.addEventListener('click', (e) => {
e.stopPropagation();
const targetId = btn.dataset.target;
const targetList = document.getElementById(targetId);
if (targetList) {
targetList.classList.toggle('collapsed');
btn.classList.toggle('collapsed');
}
});
});
// Also make headers clickable
const headers = document.querySelectorAll('.tier-header');
headers.forEach(header => {
header.addEventListener('click', () => {
const toggleBtn = header.querySelector('.toggle-btn');
if (toggleBtn) {
toggleBtn.click();
}
});
});
}
/**
* Initialize export functionality
*/
function initExportButtons() {
const exportBtn = document.getElementById('export-markdown-btn');
const copyBtn = document.getElementById('copy-markdown-btn');
if (exportBtn) {
exportBtn.addEventListener('click', exportCreditsAsFile);
}
if (copyBtn) {
copyBtn.addEventListener('click', copyCreditsToClipboard);
}
}
/**
* Generate credits markdown text
*/
function generateCreditsMarkdown() {
let markdown = '';
// Project header
if (AppData.project.name) {
markdown += `# ${AppData.project.name}\n\n`;
}
if (AppData.project.description) {
markdown += `${AppData.project.description}\n\n`;
}
markdown += `## Credits\n\n`;
// Generate credits by tier
const tiers = [
{ key: 'main', label: 'Main Tier - Essential Contributors' },
{ key: 'assistant', label: 'Assistant Tier - Valuable Contributors' },
{ key: 'thanks', label: 'Special Thanks - Meaningful Contributors' },
{ key: 'fan', label: 'Fan Tier - Minor Contributors' }
];
tiers.forEach(tier => {
const members = AppData.members
.filter(m => m.tier === tier.key)
.sort((a, b) => a.name.localeCompare(b.name));
if (members.length > 0) {
markdown += `### ${tier.label}\n\n`;
members.forEach(member => {
markdown += `- **${member.name}**`;
if (member.role) {
markdown += ` - ${member.role}`;
}
markdown += '\n';
});
markdown += '\n';
}
});
return markdown;
}
/**
* Export credits as markdown file
*/
function exportCreditsAsFile() {
const markdown = generateCreditsMarkdown();
const blob = new Blob([markdown], { type: 'text/markdown' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `${AppData.project.name || 'project'}_credits.md`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
showToast('Credits exported as markdown file!');
}
/**
* Copy credits to clipboard
*/
async function copyCreditsToClipboard() {
const markdown = generateCreditsMarkdown();
try {
await navigator.clipboard.writeText(markdown);
showToast('Credits copied to clipboard!');
} catch (error) {
// Fallback for older browsers
const textarea = document.createElement('textarea');
textarea.value = markdown;
textarea.style.position = 'fixed';
textarea.style.opacity = '0';
document.body.appendChild(textarea);
textarea.select();
document.execCommand('copy');
document.body.removeChild(textarea);
showToast('Credits copied to clipboard!');
}
}
// ========================================
// UTILITY FUNCTIONS
// ========================================
/**
* Generate a unique ID
*/
function generateId() {
return Date.now().toString(36) + Math.random().toString(36).substr(2);
}
/**
* Escape HTML to prevent XSS
*/
function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
/**
* Show a toast notification
*/
function showToast(message) {
// Create toast element
const toast = document.createElement('div');
toast.className = 'toast';
toast.textContent = message;
document.body.appendChild(toast);
// Trigger animation
setTimeout(() => toast.classList.add('show'), 10);
// Remove after 3 seconds
setTimeout(() => {
toast.classList.remove('show');
setTimeout(() => document.body.removeChild(toast), 300);
}, 3000);
}
// ========================================
// PAYOUT CALCULATOR TAB
// ========================================
/**
* Initialize Payout Calculator tab functionality
*/
function initCalculatorTab() {
const calculateBtn = document.getElementById('calculate-btn');
const commitBtn = document.getElementById('commit-payout-btn');
const clearBtn = document.getElementById('clear-calculation-btn');
const notesTextarea = document.getElementById('payout-notes');
const notesCount = document.getElementById('notes-count');
// Set default date to today
const dateInput = document.getElementById('payout-date');
if (dateInput) {
dateInput.valueAsDate = new Date();
}
// Character counter for notes
if (notesTextarea && notesCount) {
notesTextarea.addEventListener('input', () => {
notesCount.textContent = notesTextarea.value.length;
});
}
// Calculate button
if (calculateBtn) {
calculateBtn.addEventListener('click', calculatePayout);
}
// Commit button
if (commitBtn) {
commitBtn.addEventListener('click', commitPayoutToTimeline);
}
// Clear button
if (clearBtn) {
clearBtn.addEventListener('click', clearCalculation);
}
}
/**
* Calculate payout distribution
*/
function calculatePayout() {
const revenueInput = document.getElementById('revenue-amount');
const revenue = parseFloat(revenueInput.value);
if (!revenue || revenue <= 0) {
alert('Please enter a valid revenue amount.');
return;
}
// Get contributing members (exclude fan tier from payouts)
const contributingMembers = AppData.members.filter(m => m.tier !== 'fan');
if (contributingMembers.length === 0) {
alert('No contributing team members found. Please add members to Main, Assistant, or Special Thanks tiers first.');
return;
}
// Count members by tier
const mainCount = contributingMembers.filter(m => m.tier === 'main').length;
const assistantCount = contributingMembers.filter(m => m.tier === 'assistant').length;
const thanksCount = contributingMembers.filter(m => m.tier === 'thanks').length;
// Calculate base share units
const baseShareUnits = mainCount + (assistantCount * 0.5) + (thanksCount * 0.167);
// Calculate base individual shares
let mainShare = revenue / baseShareUnits;
let assistantShare = mainShare * 0.5;
let thanksShare = mainShare * 0.167;
// Check if self-adjusting fairness is needed
const assistantThankerRatio = (assistantCount + thanksCount) / (mainCount || 1);
let adjustmentApplied = false;
let adjustmentText = '';
if (assistantThankerRatio > 5) {
// Apply self-adjusting fairness algorithm
const mainTierMinimum = 0.30; // 30% minimum for main tier
const originalMainPercentage = (mainShare * mainCount) / revenue;
if (originalMainPercentage < mainTierMinimum) {
adjustmentApplied = true;
// Adjust to ensure main tier gets at least 30%
const mainTotalAmount = revenue * mainTierMinimum;
mainShare = mainTotalAmount / mainCount;
// Recalculate remaining for others
const remainingRevenue = revenue - mainTotalAmount;
const otherShareUnits = (assistantCount * 0.5) + (thanksCount * 0.167);
const otherBaseShare = remainingRevenue / otherShareUnits;
assistantShare = otherBaseShare * 0.5;
thanksShare = otherBaseShare * 0.167;
adjustmentText = `The assistant/thanker to main developer ratio (${assistantThankerRatio.toFixed(1)}:1) exceeded the threshold of 5:1. ` +
`The self-adjusting fairness algorithm ensured main tier contributors receive at least ${(mainTierMinimum * 100).toFixed(0)}% of total revenue ` +
`to maintain fair compensation for essential contributors.`;
}
}
// Store calculation results
window.currentCalculation = {
revenue,
mainShare,
assistantShare,
thanksShare,
mainCount,
assistantCount,
thanksCount,
contributingMembers,
adjustmentApplied,
adjustmentText,
date: document.getElementById('payout-date').value,
notes: document.getElementById('payout-notes').value
};
// Display results
displayCalculationResults();
}
/**
* Display calculation results
*/
function displayCalculationResults() {
const calc = window.currentCalculation;
// Hide empty state
document.getElementById('calculator-empty-state').style.display = 'none';
// Show team summary
const teamSummary = document.getElementById('team-summary');
teamSummary.style.display = 'block';
document.getElementById('summary-main').textContent = calc.mainCount;
document.getElementById('summary-assistant').textContent = calc.assistantCount;
document.getElementById('summary-thanks').textContent = calc.thanksCount;
document.getElementById('summary-total').textContent = calc.contributingMembers.length;
// Show payout recommendation
displayPayoutRecommendation(calc.revenue, calc.contributingMembers.length);
// Show calculation results
const resultsSection = document.getElementById('calculation-results');
resultsSection.style.display = 'block';
// Update summary cards
document.getElementById('result-total').textContent = `€${calc.revenue.toFixed(2)}`;
document.getElementById('result-per-main').textContent = `€${calc.mainShare.toFixed(2)}`;
document.getElementById('result-per-assistant').textContent = `€${calc.assistantShare.toFixed(2)}`;
document.getElementById('result-per-thanks').textContent = `€${calc.thanksShare.toFixed(2)}`;
// Show/hide adjustment notice
const adjustmentNotice = document.getElementById('adjustment-notice');
if (calc.adjustmentApplied) {
adjustmentNotice.style.display = 'block';
document.getElementById('adjustment-text').textContent = calc.adjustmentText;
} else {
adjustmentNotice.style.display = 'none';
}
// Display member breakdown
displayMemberBreakdown();
// Scroll to results
resultsSection.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
}
/**
* Display payout frequency recommendation
*/
function displayPayoutRecommendation(revenue, memberCount) {
const recommendationSection = document.getElementById('payout-recommendation');
const recommendationText = document.getElementById('recommendation-text');
const perMemberAmount = revenue / memberCount;
let recommendation = '';
if (perMemberAmount >= 50) {
recommendation = `<strong>Monthly payouts recommended.</strong> With €${perMemberAmount.toFixed(2)} per contributing member, ` +
`you have sufficient revenue to justify monthly distributions while keeping transfer fees reasonable.`;
} else if (perMemberAmount >= 15) {
recommendation = `<strong>Quarterly payouts recommended.</strong> With €${perMemberAmount.toFixed(2)} per contributing member, ` +
`it's better to wait and accumulate funds over 3 months to minimize the impact of transfer fees.`;
} else {
recommendation = `<strong>Hold and accumulate.</strong> With only €${perMemberAmount.toFixed(2)} per contributing member, ` +
`the revenue is too low to justify payout at this time. Transfer fees would consume a significant portion. ` +
`Wait until the next quarter when more revenue accumulates.`;
}
recommendationText.innerHTML = recommendation;
recommendationSection.style.display = 'block';
}
/**
* Display individual member breakdown by tier
*/
function displayMemberBreakdown() {
const calc = window.currentCalculation;
const container = document.getElementById('breakdown-container');
const tiers = [
{ key: 'main', label: 'Main Tier - Essential Contributors', share: calc.mainShare },
{ key: 'assistant', label: 'Assistant Tier - Valuable Contributors', share: calc.assistantShare },
{ key: 'thanks', label: 'Special Thanks - Meaningful Contributors', share: calc.thanksShare }
];
let html = '';
tiers.forEach(tier => {
const members = calc.contributingMembers
.filter(m => m.tier === tier.key)
.sort((a, b) => a.name.localeCompare(b.name));
if (members.length > 0) {
html += `<div class="breakdown-tier">`;
html += `<div class="breakdown-tier-header">${tier.label}</div>`;
members.forEach(member => {
html += `
<div class="breakdown-item">
<div class="breakdown-name">${escapeHtml(member.name)}</div>
<div class="breakdown-amount">€${tier.share.toFixed(2)}</div>
</div>
`;
});
html += `</div>`;
}
});
container.innerHTML = html;
}
/**
* Commit payout to timeline
*/
function commitPayoutToTimeline() {
const calc = window.currentCalculation;
if (!calc) {
alert('No calculation to commit. Please calculate a payout first.');
return;
}
// Create payout record
const payout = {