-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathcalcEarnings.js
More file actions
203 lines (176 loc) · 5.59 KB
/
calcEarnings.js
File metadata and controls
203 lines (176 loc) · 5.59 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
const moment = require('moment');
const Plugin = require('../entities/plugin');
const Download = require('../entities/download');
const UserEarnings = require('../entities/userEarnings');
const PurchaseOrder = require('../entities/purchaseOrder');
/**
* Calculate earnings from paid plugins
* @param {number} year
* @param {number} month
* @param {object} user
* @param {Array<object>} [report]
* @returns {Promise<number>}
*/
async function fromPaidPlugins(year, month, user, report) {
const { monthStart, monthEnd } = getDate(year, month);
const plugins = await Plugin.get([Plugin.ID], [Plugin.USER_ID, user.id]);
const orders = await PurchaseOrder.for('internal').get([
[PurchaseOrder.PLUGIN_ID, plugins.map((p) => p.id)],
[PurchaseOrder.CREATED_AT, [monthStart, monthEnd], 'BETWEEN'],
]);
const amounts = await Promise.all(
orders.map(async ({ id: rowId, order_id: orderId, amount, state }) => {
state = Number.parseInt(state, 10);
if (state === PurchaseOrder.STATE_CANCELED) {
return 0;
}
try {
const updates = [];
let calculatedAmount = 0;
if (report) {
const reportRows = report.filter((r) => r.Description === orderId);
if (!reportRows.length) {
calculatedAmount = amount * 0.65;
} else {
for (const row of reportRows) {
calculatedAmount += Number.parseFloat(row['Amount (Merchant Currency)']);
}
}
} else {
calculatedAmount = amount;
}
if (calculatedAmount !== amount) {
updates.push([PurchaseOrder.AMOUNT, calculatedAmount]);
}
if (updates.length) {
await PurchaseOrder.update(updates, [PurchaseOrder.ID, rowId]);
}
return calculatedAmount;
} catch (_error) {
return 0;
}
}),
);
return Math.round(amounts.reduce((a, b) => a + b, 0) * 100) / 100;
}
/**
* Gets earnings from downloads
* @param {number} year year
* @param {number} month month (0-11)
* @param {object} user
* @returns {Promise<number>}
*/
async function fromDownloads(year, month, user) {
const { monthStart, monthEnd } = getDate(year, month);
const plugins = await Plugin.get([Plugin.ID], [Plugin.USER_ID, user.id]);
const downloads = await Download.count([
[Download.PLUGIN_ID, plugins.map((p) => p.id)],
[Download.CREATED_AT, [monthStart, monthEnd], 'BETWEEN'],
[Download.PACKAGE_NAME, 'com.foxdebug.acodefree'],
]);
// INR 12 per 1000 downloads
return Math.round(downloads * 0.012 * 100) / 100;
}
/**
* Get total earnings for user
* @param {number} year
* @param {number} month month (0-11)
* @param {object} user
* @param {Array<object>} [report]
*/
async function total(year, month, user, report) {
let earnings = 0;
const paidPluginEarnings = await fromPaidPlugins(year, month, user, report);
earnings = (1 - process.env.PERCENTAGE_CUT) * paidPluginEarnings;
const freePluginDownloads = await fromDownloads(year, month, user);
earnings += freePluginDownloads;
earnings = Number.parseFloat(Math.round(earnings * 100) / 100);
return earnings;
}
/**
* @typedef {object} UnpaidEarnings
* @property {Array<number>} ids
* @property {number} earnings
* @property {moment.Moment} from
* @property {moment.Moment} to
*/
/**
* Get unpaid earnings for user
* @param {object} user user object
* @param {number} [year] year to exclude
* @param {number} [month] month to exclude
* @returns {Promise<UnpaidEarnings>}
*/
async function unpaid(user, year, month) {
let earnings = 0;
const ids = [];
const where = [
[UserEarnings.USER_ID, user.id],
[UserEarnings.PAYMENT_ID, null],
];
// Exclude current or future months if year/month is passed
if (year && month) {
where.push(
[UserEarnings.MONTH, month, '<'],
[UserEarnings.YEAR, year],
'OR',
[UserEarnings.YEAR, year, '<']
);
}
const unpaidEarnings = await UserEarnings.get(
[UserEarnings.AMOUNT, UserEarnings.ID, UserEarnings.MONTH, UserEarnings.YEAR],
where
);
let fromMonth = 31;
let fromYear = 9999;
let toMonth = 0;
let toYear = 0;
for (const earning of unpaidEarnings) {
const { id, amount, month: thisMonth, year: thisYear } = earning;
ids.push(id);
if (thisYear < fromYear || (thisYear === fromYear && thisMonth < fromMonth)) {
fromMonth = thisMonth;
fromYear = thisYear;
}
if (thisYear > toYear || (thisYear === toYear && thisMonth > toMonth)) {
toMonth = thisMonth;
toYear = thisYear;
}
earnings += Number.parseFloat(amount);
}
earnings = Number.parseFloat(Math.round(earnings * 100) / 100);
// ✅ Fix: Adjust 'to' date so it doesn’t go beyond current date
const now = moment();
let toMoment = moment({ year: toYear, month: toMonth });
if (toMoment.isSame(now, 'month') && toMoment.isSame(now, 'year')) {
// If unpaid includes the current month, cap it at today
toMoment = now.endOf('day');
} else {
// Otherwise use the full month end
toMoment = toMoment.endOf('month');
}
return {
ids,
earnings,
from: moment({ year: fromYear, month: fromMonth }).startOf('month'),
to: toMoment,
};
}
/**
* Get date range for month
* @param {number} year year
* @param {number} month month (0-11)
* @returns {[string, string]]}
*/
function getDate(year, month) {
const date = moment({ month, year });
const monthStart = date.startOf('month').format('YYYY-MM-DD');
const monthEnd = date.endOf('month').format('YYYY-MM-DD');
return { monthStart, monthEnd };
}
module.exports = {
fromPaidPlugins,
fromDownloads,
unpaid,
total,
};