@hasna/microservices 0.0.3 → 0.0.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/index.js +63 -0
- package/bin/mcp.js +63 -0
- package/dist/index.js +63 -0
- package/microservices/microservice-ads/package.json +27 -0
- package/microservices/microservice-ads/src/cli/index.ts +605 -0
- package/microservices/microservice-ads/src/db/campaigns.ts +797 -0
- package/microservices/microservice-ads/src/db/database.ts +93 -0
- package/microservices/microservice-ads/src/db/migrations.ts +60 -0
- package/microservices/microservice-ads/src/index.ts +39 -0
- package/microservices/microservice-ads/src/mcp/index.ts +480 -0
- package/microservices/microservice-contracts/package.json +27 -0
- package/microservices/microservice-contracts/src/cli/index.ts +770 -0
- package/microservices/microservice-contracts/src/db/contracts.ts +925 -0
- package/microservices/microservice-contracts/src/db/database.ts +93 -0
- package/microservices/microservice-contracts/src/db/migrations.ts +141 -0
- package/microservices/microservice-contracts/src/index.ts +43 -0
- package/microservices/microservice-contracts/src/mcp/index.ts +617 -0
- package/microservices/microservice-domains/package.json +27 -0
- package/microservices/microservice-domains/src/cli/index.ts +691 -0
- package/microservices/microservice-domains/src/db/database.ts +93 -0
- package/microservices/microservice-domains/src/db/domains.ts +1164 -0
- package/microservices/microservice-domains/src/db/migrations.ts +60 -0
- package/microservices/microservice-domains/src/index.ts +65 -0
- package/microservices/microservice-domains/src/mcp/index.ts +536 -0
- package/microservices/microservice-hiring/package.json +27 -0
- package/microservices/microservice-hiring/src/cli/index.ts +741 -0
- package/microservices/microservice-hiring/src/db/database.ts +93 -0
- package/microservices/microservice-hiring/src/db/hiring.ts +1085 -0
- package/microservices/microservice-hiring/src/db/migrations.ts +89 -0
- package/microservices/microservice-hiring/src/index.ts +80 -0
- package/microservices/microservice-hiring/src/lib/scoring.ts +206 -0
- package/microservices/microservice-hiring/src/mcp/index.ts +709 -0
- package/microservices/microservice-payments/package.json +27 -0
- package/microservices/microservice-payments/src/cli/index.ts +609 -0
- package/microservices/microservice-payments/src/db/database.ts +93 -0
- package/microservices/microservice-payments/src/db/migrations.ts +81 -0
- package/microservices/microservice-payments/src/db/payments.ts +1204 -0
- package/microservices/microservice-payments/src/index.ts +51 -0
- package/microservices/microservice-payments/src/mcp/index.ts +683 -0
- package/microservices/microservice-payroll/package.json +27 -0
- package/microservices/microservice-payroll/src/cli/index.ts +643 -0
- package/microservices/microservice-payroll/src/db/database.ts +93 -0
- package/microservices/microservice-payroll/src/db/migrations.ts +95 -0
- package/microservices/microservice-payroll/src/db/payroll.ts +1377 -0
- package/microservices/microservice-payroll/src/index.ts +48 -0
- package/microservices/microservice-payroll/src/mcp/index.ts +666 -0
- package/microservices/microservice-shipping/package.json +27 -0
- package/microservices/microservice-shipping/src/cli/index.ts +606 -0
- package/microservices/microservice-shipping/src/db/database.ts +93 -0
- package/microservices/microservice-shipping/src/db/migrations.ts +69 -0
- package/microservices/microservice-shipping/src/db/shipping.ts +1093 -0
- package/microservices/microservice-shipping/src/index.ts +53 -0
- package/microservices/microservice-shipping/src/mcp/index.ts +533 -0
- package/microservices/microservice-social/package.json +27 -0
- package/microservices/microservice-social/src/cli/index.ts +689 -0
- package/microservices/microservice-social/src/db/database.ts +93 -0
- package/microservices/microservice-social/src/db/migrations.ts +88 -0
- package/microservices/microservice-social/src/db/social.ts +1046 -0
- package/microservices/microservice-social/src/index.ts +46 -0
- package/microservices/microservice-social/src/mcp/index.ts +655 -0
- package/microservices/microservice-subscriptions/package.json +27 -0
- package/microservices/microservice-subscriptions/src/cli/index.ts +715 -0
- package/microservices/microservice-subscriptions/src/db/database.ts +93 -0
- package/microservices/microservice-subscriptions/src/db/migrations.ts +125 -0
- package/microservices/microservice-subscriptions/src/db/subscriptions.ts +1256 -0
- package/microservices/microservice-subscriptions/src/index.ts +41 -0
- package/microservices/microservice-subscriptions/src/mcp/index.ts +631 -0
- package/package.json +1 -1
|
@@ -0,0 +1,1204 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Payment, Dispute, and Payout CRUD operations
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import { getDatabase } from "./database.js";
|
|
6
|
+
|
|
7
|
+
// --- Payment Types ---
|
|
8
|
+
|
|
9
|
+
export type PaymentType = "charge" | "refund" | "transfer" | "payout";
|
|
10
|
+
export type PaymentStatus = "pending" | "succeeded" | "failed" | "disputed" | "refunded";
|
|
11
|
+
export type PaymentProvider = "stripe" | "square" | "mercury" | "manual";
|
|
12
|
+
|
|
13
|
+
export interface Payment {
|
|
14
|
+
id: string;
|
|
15
|
+
type: PaymentType;
|
|
16
|
+
amount: number;
|
|
17
|
+
currency: string;
|
|
18
|
+
status: PaymentStatus;
|
|
19
|
+
customer_name: string | null;
|
|
20
|
+
customer_email: string | null;
|
|
21
|
+
description: string | null;
|
|
22
|
+
provider: PaymentProvider | null;
|
|
23
|
+
provider_id: string | null;
|
|
24
|
+
invoice_id: string | null;
|
|
25
|
+
metadata: Record<string, unknown>;
|
|
26
|
+
created_at: string;
|
|
27
|
+
completed_at: string | null;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
interface PaymentRow {
|
|
31
|
+
id: string;
|
|
32
|
+
type: string;
|
|
33
|
+
amount: number;
|
|
34
|
+
currency: string;
|
|
35
|
+
status: string;
|
|
36
|
+
customer_name: string | null;
|
|
37
|
+
customer_email: string | null;
|
|
38
|
+
description: string | null;
|
|
39
|
+
provider: string | null;
|
|
40
|
+
provider_id: string | null;
|
|
41
|
+
invoice_id: string | null;
|
|
42
|
+
metadata: string;
|
|
43
|
+
created_at: string;
|
|
44
|
+
completed_at: string | null;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function rowToPayment(row: PaymentRow): Payment {
|
|
48
|
+
return {
|
|
49
|
+
...row,
|
|
50
|
+
type: row.type as PaymentType,
|
|
51
|
+
status: row.status as PaymentStatus,
|
|
52
|
+
provider: row.provider as PaymentProvider | null,
|
|
53
|
+
metadata: JSON.parse(row.metadata || "{}"),
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export interface CreatePaymentInput {
|
|
58
|
+
type: PaymentType;
|
|
59
|
+
amount: number;
|
|
60
|
+
currency?: string;
|
|
61
|
+
status?: PaymentStatus;
|
|
62
|
+
customer_name?: string;
|
|
63
|
+
customer_email?: string;
|
|
64
|
+
description?: string;
|
|
65
|
+
provider?: PaymentProvider;
|
|
66
|
+
provider_id?: string;
|
|
67
|
+
invoice_id?: string;
|
|
68
|
+
metadata?: Record<string, unknown>;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export function createPayment(input: CreatePaymentInput): Payment {
|
|
72
|
+
const db = getDatabase();
|
|
73
|
+
const id = crypto.randomUUID();
|
|
74
|
+
const metadata = JSON.stringify(input.metadata || {});
|
|
75
|
+
|
|
76
|
+
db.prepare(
|
|
77
|
+
`INSERT INTO payments (id, type, amount, currency, status, customer_name, customer_email, description, provider, provider_id, invoice_id, metadata)
|
|
78
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
|
|
79
|
+
).run(
|
|
80
|
+
id,
|
|
81
|
+
input.type,
|
|
82
|
+
input.amount,
|
|
83
|
+
input.currency || "USD",
|
|
84
|
+
input.status || "pending",
|
|
85
|
+
input.customer_name || null,
|
|
86
|
+
input.customer_email || null,
|
|
87
|
+
input.description || null,
|
|
88
|
+
input.provider || null,
|
|
89
|
+
input.provider_id || null,
|
|
90
|
+
input.invoice_id || null,
|
|
91
|
+
metadata
|
|
92
|
+
);
|
|
93
|
+
|
|
94
|
+
return getPayment(id)!;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export function getPayment(id: string): Payment | null {
|
|
98
|
+
const db = getDatabase();
|
|
99
|
+
const row = db.prepare("SELECT * FROM payments WHERE id = ?").get(id) as PaymentRow | null;
|
|
100
|
+
return row ? rowToPayment(row) : null;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export interface ListPaymentsOptions {
|
|
104
|
+
status?: PaymentStatus;
|
|
105
|
+
type?: PaymentType;
|
|
106
|
+
provider?: PaymentProvider;
|
|
107
|
+
customer_email?: string;
|
|
108
|
+
limit?: number;
|
|
109
|
+
offset?: number;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export function listPayments(options: ListPaymentsOptions = {}): Payment[] {
|
|
113
|
+
const db = getDatabase();
|
|
114
|
+
const conditions: string[] = [];
|
|
115
|
+
const params: unknown[] = [];
|
|
116
|
+
|
|
117
|
+
if (options.status) {
|
|
118
|
+
conditions.push("status = ?");
|
|
119
|
+
params.push(options.status);
|
|
120
|
+
}
|
|
121
|
+
if (options.type) {
|
|
122
|
+
conditions.push("type = ?");
|
|
123
|
+
params.push(options.type);
|
|
124
|
+
}
|
|
125
|
+
if (options.provider) {
|
|
126
|
+
conditions.push("provider = ?");
|
|
127
|
+
params.push(options.provider);
|
|
128
|
+
}
|
|
129
|
+
if (options.customer_email) {
|
|
130
|
+
conditions.push("customer_email = ?");
|
|
131
|
+
params.push(options.customer_email);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
let sql = "SELECT * FROM payments";
|
|
135
|
+
if (conditions.length > 0) {
|
|
136
|
+
sql += " WHERE " + conditions.join(" AND ");
|
|
137
|
+
}
|
|
138
|
+
sql += " ORDER BY created_at DESC";
|
|
139
|
+
|
|
140
|
+
if (options.limit) {
|
|
141
|
+
sql += " LIMIT ?";
|
|
142
|
+
params.push(options.limit);
|
|
143
|
+
}
|
|
144
|
+
if (options.offset) {
|
|
145
|
+
sql += " OFFSET ?";
|
|
146
|
+
params.push(options.offset);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
const rows = db.prepare(sql).all(...params) as PaymentRow[];
|
|
150
|
+
return rows.map(rowToPayment);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export interface UpdatePaymentInput {
|
|
154
|
+
status?: PaymentStatus;
|
|
155
|
+
customer_name?: string;
|
|
156
|
+
customer_email?: string;
|
|
157
|
+
description?: string;
|
|
158
|
+
provider?: PaymentProvider;
|
|
159
|
+
provider_id?: string;
|
|
160
|
+
invoice_id?: string;
|
|
161
|
+
metadata?: Record<string, unknown>;
|
|
162
|
+
completed_at?: string;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
export function updatePayment(id: string, input: UpdatePaymentInput): Payment | null {
|
|
166
|
+
const db = getDatabase();
|
|
167
|
+
const existing = getPayment(id);
|
|
168
|
+
if (!existing) return null;
|
|
169
|
+
|
|
170
|
+
const sets: string[] = [];
|
|
171
|
+
const params: unknown[] = [];
|
|
172
|
+
|
|
173
|
+
if (input.status !== undefined) {
|
|
174
|
+
sets.push("status = ?");
|
|
175
|
+
params.push(input.status);
|
|
176
|
+
}
|
|
177
|
+
if (input.customer_name !== undefined) {
|
|
178
|
+
sets.push("customer_name = ?");
|
|
179
|
+
params.push(input.customer_name);
|
|
180
|
+
}
|
|
181
|
+
if (input.customer_email !== undefined) {
|
|
182
|
+
sets.push("customer_email = ?");
|
|
183
|
+
params.push(input.customer_email);
|
|
184
|
+
}
|
|
185
|
+
if (input.description !== undefined) {
|
|
186
|
+
sets.push("description = ?");
|
|
187
|
+
params.push(input.description);
|
|
188
|
+
}
|
|
189
|
+
if (input.provider !== undefined) {
|
|
190
|
+
sets.push("provider = ?");
|
|
191
|
+
params.push(input.provider);
|
|
192
|
+
}
|
|
193
|
+
if (input.provider_id !== undefined) {
|
|
194
|
+
sets.push("provider_id = ?");
|
|
195
|
+
params.push(input.provider_id);
|
|
196
|
+
}
|
|
197
|
+
if (input.invoice_id !== undefined) {
|
|
198
|
+
sets.push("invoice_id = ?");
|
|
199
|
+
params.push(input.invoice_id);
|
|
200
|
+
}
|
|
201
|
+
if (input.metadata !== undefined) {
|
|
202
|
+
sets.push("metadata = ?");
|
|
203
|
+
params.push(JSON.stringify(input.metadata));
|
|
204
|
+
}
|
|
205
|
+
if (input.completed_at !== undefined) {
|
|
206
|
+
sets.push("completed_at = ?");
|
|
207
|
+
params.push(input.completed_at);
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
if (sets.length === 0) return existing;
|
|
211
|
+
|
|
212
|
+
params.push(id);
|
|
213
|
+
db.prepare(`UPDATE payments SET ${sets.join(", ")} WHERE id = ?`).run(...params);
|
|
214
|
+
|
|
215
|
+
return getPayment(id);
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
export function deletePayment(id: string): boolean {
|
|
219
|
+
const db = getDatabase();
|
|
220
|
+
const result = db.prepare("DELETE FROM payments WHERE id = ?").run(id);
|
|
221
|
+
return result.changes > 0;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/**
|
|
225
|
+
* Refund a payment — creates a new refund payment linked to the original
|
|
226
|
+
*/
|
|
227
|
+
export function refundPayment(paymentId: string, amount?: number): Payment | null {
|
|
228
|
+
const db = getDatabase();
|
|
229
|
+
const original = getPayment(paymentId);
|
|
230
|
+
if (!original) return null;
|
|
231
|
+
if (original.status !== "succeeded") return null;
|
|
232
|
+
|
|
233
|
+
const refundAmount = amount || original.amount;
|
|
234
|
+
|
|
235
|
+
// Create the refund record
|
|
236
|
+
const refund = createPayment({
|
|
237
|
+
type: "refund",
|
|
238
|
+
amount: refundAmount,
|
|
239
|
+
currency: original.currency,
|
|
240
|
+
status: "succeeded",
|
|
241
|
+
customer_name: original.customer_name || undefined,
|
|
242
|
+
customer_email: original.customer_email || undefined,
|
|
243
|
+
description: `Refund for payment ${paymentId}`,
|
|
244
|
+
provider: original.provider || undefined,
|
|
245
|
+
metadata: { original_payment_id: paymentId },
|
|
246
|
+
});
|
|
247
|
+
|
|
248
|
+
// Mark original as refunded
|
|
249
|
+
updatePayment(paymentId, { status: "refunded" });
|
|
250
|
+
|
|
251
|
+
return refund;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
export function searchPayments(query: string): Payment[] {
|
|
255
|
+
const db = getDatabase();
|
|
256
|
+
const q = `%${query}%`;
|
|
257
|
+
const rows = db
|
|
258
|
+
.prepare(
|
|
259
|
+
`SELECT * FROM payments
|
|
260
|
+
WHERE customer_name LIKE ? OR customer_email LIKE ? OR description LIKE ? OR provider_id LIKE ? OR invoice_id LIKE ?
|
|
261
|
+
ORDER BY created_at DESC`
|
|
262
|
+
)
|
|
263
|
+
.all(q, q, q, q, q) as PaymentRow[];
|
|
264
|
+
return rows.map(rowToPayment);
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
export function listByProvider(provider: PaymentProvider): Payment[] {
|
|
268
|
+
return listPayments({ provider });
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
export function countPayments(): number {
|
|
272
|
+
const db = getDatabase();
|
|
273
|
+
const row = db.prepare("SELECT COUNT(*) as count FROM payments").get() as { count: number };
|
|
274
|
+
return row.count;
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
// --- Revenue & Analytics ---
|
|
278
|
+
|
|
279
|
+
export interface RevenueReport {
|
|
280
|
+
total_revenue: number;
|
|
281
|
+
total_refunds: number;
|
|
282
|
+
net_revenue: number;
|
|
283
|
+
payment_count: number;
|
|
284
|
+
refund_count: number;
|
|
285
|
+
currency: string;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
export function getRevenueReport(startDate: string, endDate: string): RevenueReport {
|
|
289
|
+
const db = getDatabase();
|
|
290
|
+
|
|
291
|
+
const revenueRow = db
|
|
292
|
+
.prepare(
|
|
293
|
+
`SELECT COALESCE(SUM(amount), 0) as total, COUNT(*) as count
|
|
294
|
+
FROM payments
|
|
295
|
+
WHERE type = 'charge' AND status = 'succeeded'
|
|
296
|
+
AND created_at >= ? AND created_at <= ?`
|
|
297
|
+
)
|
|
298
|
+
.get(startDate, endDate) as { total: number; count: number };
|
|
299
|
+
|
|
300
|
+
const refundRow = db
|
|
301
|
+
.prepare(
|
|
302
|
+
`SELECT COALESCE(SUM(amount), 0) as total, COUNT(*) as count
|
|
303
|
+
FROM payments
|
|
304
|
+
WHERE type = 'refund'
|
|
305
|
+
AND created_at >= ? AND created_at <= ?`
|
|
306
|
+
)
|
|
307
|
+
.get(startDate, endDate) as { total: number; count: number };
|
|
308
|
+
|
|
309
|
+
return {
|
|
310
|
+
total_revenue: revenueRow.total,
|
|
311
|
+
total_refunds: refundRow.total,
|
|
312
|
+
net_revenue: revenueRow.total - refundRow.total,
|
|
313
|
+
payment_count: revenueRow.count,
|
|
314
|
+
refund_count: refundRow.count,
|
|
315
|
+
currency: "USD",
|
|
316
|
+
};
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
export interface CustomerRevenue {
|
|
320
|
+
customer_email: string;
|
|
321
|
+
customer_name: string | null;
|
|
322
|
+
total_amount: number;
|
|
323
|
+
payment_count: number;
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
export function getRevenueByCustomer(): CustomerRevenue[] {
|
|
327
|
+
const db = getDatabase();
|
|
328
|
+
const rows = db
|
|
329
|
+
.prepare(
|
|
330
|
+
`SELECT customer_email, customer_name,
|
|
331
|
+
SUM(amount) as total_amount, COUNT(*) as payment_count
|
|
332
|
+
FROM payments
|
|
333
|
+
WHERE type = 'charge' AND status = 'succeeded' AND customer_email IS NOT NULL
|
|
334
|
+
GROUP BY customer_email
|
|
335
|
+
ORDER BY total_amount DESC`
|
|
336
|
+
)
|
|
337
|
+
.all() as CustomerRevenue[];
|
|
338
|
+
return rows;
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
export function reconcileWithInvoice(paymentId: string, invoiceId: string): Payment | null {
|
|
342
|
+
return updatePayment(paymentId, { invoice_id: invoiceId });
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
export interface PaymentStats {
|
|
346
|
+
total_payments: number;
|
|
347
|
+
total_charges: number;
|
|
348
|
+
total_refunds: number;
|
|
349
|
+
total_transfers: number;
|
|
350
|
+
total_payouts: number;
|
|
351
|
+
by_status: Record<string, number>;
|
|
352
|
+
by_provider: Record<string, number>;
|
|
353
|
+
total_amount: number;
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
export function getPaymentStats(): PaymentStats {
|
|
357
|
+
const db = getDatabase();
|
|
358
|
+
|
|
359
|
+
const total = db.prepare("SELECT COUNT(*) as count FROM payments").get() as { count: number };
|
|
360
|
+
|
|
361
|
+
const typeRows = db
|
|
362
|
+
.prepare("SELECT type, COUNT(*) as count FROM payments GROUP BY type")
|
|
363
|
+
.all() as { type: string; count: number }[];
|
|
364
|
+
const typeCounts: Record<string, number> = {};
|
|
365
|
+
for (const r of typeRows) typeCounts[r.type] = r.count;
|
|
366
|
+
|
|
367
|
+
const statusRows = db
|
|
368
|
+
.prepare("SELECT status, COUNT(*) as count FROM payments GROUP BY status")
|
|
369
|
+
.all() as { status: string; count: number }[];
|
|
370
|
+
const statusCounts: Record<string, number> = {};
|
|
371
|
+
for (const r of statusRows) statusCounts[r.status] = r.count;
|
|
372
|
+
|
|
373
|
+
const providerRows = db
|
|
374
|
+
.prepare(
|
|
375
|
+
"SELECT COALESCE(provider, 'unknown') as provider, COUNT(*) as count FROM payments GROUP BY provider"
|
|
376
|
+
)
|
|
377
|
+
.all() as { provider: string; count: number }[];
|
|
378
|
+
const providerCounts: Record<string, number> = {};
|
|
379
|
+
for (const r of providerRows) providerCounts[r.provider] = r.count;
|
|
380
|
+
|
|
381
|
+
const amountRow = db
|
|
382
|
+
.prepare(
|
|
383
|
+
"SELECT COALESCE(SUM(amount), 0) as total FROM payments WHERE type = 'charge' AND status = 'succeeded'"
|
|
384
|
+
)
|
|
385
|
+
.get() as { total: number };
|
|
386
|
+
|
|
387
|
+
return {
|
|
388
|
+
total_payments: total.count,
|
|
389
|
+
total_charges: typeCounts["charge"] || 0,
|
|
390
|
+
total_refunds: typeCounts["refund"] || 0,
|
|
391
|
+
total_transfers: typeCounts["transfer"] || 0,
|
|
392
|
+
total_payouts: typeCounts["payout"] || 0,
|
|
393
|
+
by_status: statusCounts,
|
|
394
|
+
by_provider: providerCounts,
|
|
395
|
+
total_amount: amountRow.total,
|
|
396
|
+
};
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
export interface ProviderBalance {
|
|
400
|
+
provider: string;
|
|
401
|
+
total_charges: number;
|
|
402
|
+
total_refunds: number;
|
|
403
|
+
net_balance: number;
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
export function getBalanceByProvider(): ProviderBalance[] {
|
|
407
|
+
const db = getDatabase();
|
|
408
|
+
const rows = db
|
|
409
|
+
.prepare(
|
|
410
|
+
`SELECT
|
|
411
|
+
COALESCE(provider, 'unknown') as provider,
|
|
412
|
+
COALESCE(SUM(CASE WHEN type = 'charge' AND status = 'succeeded' THEN amount ELSE 0 END), 0) as total_charges,
|
|
413
|
+
COALESCE(SUM(CASE WHEN type = 'refund' THEN amount ELSE 0 END), 0) as total_refunds
|
|
414
|
+
FROM payments
|
|
415
|
+
GROUP BY provider`
|
|
416
|
+
)
|
|
417
|
+
.all() as { provider: string; total_charges: number; total_refunds: number }[];
|
|
418
|
+
|
|
419
|
+
return rows.map((r) => ({
|
|
420
|
+
provider: r.provider,
|
|
421
|
+
total_charges: r.total_charges,
|
|
422
|
+
total_refunds: r.total_refunds,
|
|
423
|
+
net_balance: r.total_charges - r.total_refunds,
|
|
424
|
+
}));
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
// --- Disputes ---
|
|
428
|
+
|
|
429
|
+
export type DisputeStatus = "open" | "under_review" | "won" | "lost";
|
|
430
|
+
|
|
431
|
+
export interface Dispute {
|
|
432
|
+
id: string;
|
|
433
|
+
payment_id: string;
|
|
434
|
+
reason: string | null;
|
|
435
|
+
status: DisputeStatus;
|
|
436
|
+
amount: number | null;
|
|
437
|
+
evidence: Record<string, unknown>;
|
|
438
|
+
opened_at: string;
|
|
439
|
+
resolved_at: string | null;
|
|
440
|
+
created_at: string;
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
interface DisputeRow {
|
|
444
|
+
id: string;
|
|
445
|
+
payment_id: string;
|
|
446
|
+
reason: string | null;
|
|
447
|
+
status: string;
|
|
448
|
+
amount: number | null;
|
|
449
|
+
evidence: string;
|
|
450
|
+
opened_at: string;
|
|
451
|
+
resolved_at: string | null;
|
|
452
|
+
created_at: string;
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
function rowToDispute(row: DisputeRow): Dispute {
|
|
456
|
+
return {
|
|
457
|
+
...row,
|
|
458
|
+
status: row.status as DisputeStatus,
|
|
459
|
+
evidence: JSON.parse(row.evidence || "{}"),
|
|
460
|
+
};
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
export interface CreateDisputeInput {
|
|
464
|
+
payment_id: string;
|
|
465
|
+
reason?: string;
|
|
466
|
+
amount?: number;
|
|
467
|
+
evidence?: Record<string, unknown>;
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
export function createDispute(input: CreateDisputeInput): Dispute {
|
|
471
|
+
const db = getDatabase();
|
|
472
|
+
const id = crypto.randomUUID();
|
|
473
|
+
const evidence = JSON.stringify(input.evidence || {});
|
|
474
|
+
|
|
475
|
+
db.prepare(
|
|
476
|
+
`INSERT INTO disputes (id, payment_id, reason, amount, evidence)
|
|
477
|
+
VALUES (?, ?, ?, ?, ?)`
|
|
478
|
+
).run(id, input.payment_id, input.reason || null, input.amount || null, evidence);
|
|
479
|
+
|
|
480
|
+
// Mark the payment as disputed
|
|
481
|
+
updatePayment(input.payment_id, { status: "disputed" });
|
|
482
|
+
|
|
483
|
+
return getDispute(id)!;
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
export function getDispute(id: string): Dispute | null {
|
|
487
|
+
const db = getDatabase();
|
|
488
|
+
const row = db.prepare("SELECT * FROM disputes WHERE id = ?").get(id) as DisputeRow | null;
|
|
489
|
+
return row ? rowToDispute(row) : null;
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
export function listDisputes(status?: DisputeStatus): Dispute[] {
|
|
493
|
+
const db = getDatabase();
|
|
494
|
+
let sql = "SELECT * FROM disputes";
|
|
495
|
+
const params: unknown[] = [];
|
|
496
|
+
|
|
497
|
+
if (status) {
|
|
498
|
+
sql += " WHERE status = ?";
|
|
499
|
+
params.push(status);
|
|
500
|
+
}
|
|
501
|
+
sql += " ORDER BY created_at DESC";
|
|
502
|
+
|
|
503
|
+
const rows = db.prepare(sql).all(...params) as DisputeRow[];
|
|
504
|
+
return rows.map(rowToDispute);
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
export interface RespondDisputeInput {
|
|
508
|
+
status: DisputeStatus;
|
|
509
|
+
evidence?: Record<string, unknown>;
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
export function respondDispute(id: string, input: RespondDisputeInput): Dispute | null {
|
|
513
|
+
const db = getDatabase();
|
|
514
|
+
const existing = getDispute(id);
|
|
515
|
+
if (!existing) return null;
|
|
516
|
+
|
|
517
|
+
const sets: string[] = ["status = ?"];
|
|
518
|
+
const params: unknown[] = [input.status];
|
|
519
|
+
|
|
520
|
+
if (input.evidence) {
|
|
521
|
+
sets.push("evidence = ?");
|
|
522
|
+
params.push(JSON.stringify(input.evidence));
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
if (input.status === "won" || input.status === "lost") {
|
|
526
|
+
sets.push("resolved_at = datetime('now')");
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
params.push(id);
|
|
530
|
+
db.prepare(`UPDATE disputes SET ${sets.join(", ")} WHERE id = ?`).run(...params);
|
|
531
|
+
|
|
532
|
+
return getDispute(id);
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
export function deleteDispute(id: string): boolean {
|
|
536
|
+
const db = getDatabase();
|
|
537
|
+
const result = db.prepare("DELETE FROM disputes WHERE id = ?").run(id);
|
|
538
|
+
return result.changes > 0;
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
// --- Payouts ---
|
|
542
|
+
|
|
543
|
+
export type PayoutStatus = "pending" | "in_transit" | "paid" | "failed";
|
|
544
|
+
|
|
545
|
+
export interface Payout {
|
|
546
|
+
id: string;
|
|
547
|
+
amount: number;
|
|
548
|
+
currency: string;
|
|
549
|
+
destination: string | null;
|
|
550
|
+
status: PayoutStatus;
|
|
551
|
+
initiated_at: string;
|
|
552
|
+
arrived_at: string | null;
|
|
553
|
+
created_at: string;
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
interface PayoutRow {
|
|
557
|
+
id: string;
|
|
558
|
+
amount: number;
|
|
559
|
+
currency: string;
|
|
560
|
+
destination: string | null;
|
|
561
|
+
status: string;
|
|
562
|
+
initiated_at: string;
|
|
563
|
+
arrived_at: string | null;
|
|
564
|
+
created_at: string;
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
function rowToPayout(row: PayoutRow): Payout {
|
|
568
|
+
return {
|
|
569
|
+
...row,
|
|
570
|
+
status: row.status as PayoutStatus,
|
|
571
|
+
};
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
export interface CreatePayoutInput {
|
|
575
|
+
amount: number;
|
|
576
|
+
currency?: string;
|
|
577
|
+
destination?: string;
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
export function createPayout(input: CreatePayoutInput): Payout {
|
|
581
|
+
const db = getDatabase();
|
|
582
|
+
const id = crypto.randomUUID();
|
|
583
|
+
|
|
584
|
+
db.prepare(
|
|
585
|
+
`INSERT INTO payouts (id, amount, currency, destination)
|
|
586
|
+
VALUES (?, ?, ?, ?)`
|
|
587
|
+
).run(id, input.amount, input.currency || "USD", input.destination || null);
|
|
588
|
+
|
|
589
|
+
return getPayout(id)!;
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
export function getPayout(id: string): Payout | null {
|
|
593
|
+
const db = getDatabase();
|
|
594
|
+
const row = db.prepare("SELECT * FROM payouts WHERE id = ?").get(id) as PayoutRow | null;
|
|
595
|
+
return row ? rowToPayout(row) : null;
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
export function listPayouts(status?: PayoutStatus): Payout[] {
|
|
599
|
+
const db = getDatabase();
|
|
600
|
+
let sql = "SELECT * FROM payouts";
|
|
601
|
+
const params: unknown[] = [];
|
|
602
|
+
|
|
603
|
+
if (status) {
|
|
604
|
+
sql += " WHERE status = ?";
|
|
605
|
+
params.push(status);
|
|
606
|
+
}
|
|
607
|
+
sql += " ORDER BY created_at DESC";
|
|
608
|
+
|
|
609
|
+
const rows = db.prepare(sql).all(...params) as PayoutRow[];
|
|
610
|
+
return rows.map(rowToPayout);
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
export interface UpdatePayoutInput {
|
|
614
|
+
status?: PayoutStatus;
|
|
615
|
+
destination?: string;
|
|
616
|
+
arrived_at?: string;
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
export function updatePayout(id: string, input: UpdatePayoutInput): Payout | null {
|
|
620
|
+
const db = getDatabase();
|
|
621
|
+
const existing = getPayout(id);
|
|
622
|
+
if (!existing) return null;
|
|
623
|
+
|
|
624
|
+
const sets: string[] = [];
|
|
625
|
+
const params: unknown[] = [];
|
|
626
|
+
|
|
627
|
+
if (input.status !== undefined) {
|
|
628
|
+
sets.push("status = ?");
|
|
629
|
+
params.push(input.status);
|
|
630
|
+
}
|
|
631
|
+
if (input.destination !== undefined) {
|
|
632
|
+
sets.push("destination = ?");
|
|
633
|
+
params.push(input.destination);
|
|
634
|
+
}
|
|
635
|
+
if (input.arrived_at !== undefined) {
|
|
636
|
+
sets.push("arrived_at = ?");
|
|
637
|
+
params.push(input.arrived_at);
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
if (sets.length === 0) return existing;
|
|
641
|
+
|
|
642
|
+
params.push(id);
|
|
643
|
+
db.prepare(`UPDATE payouts SET ${sets.join(", ")} WHERE id = ?`).run(...params);
|
|
644
|
+
|
|
645
|
+
return getPayout(id);
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
export function deletePayout(id: string): boolean {
|
|
649
|
+
const db = getDatabase();
|
|
650
|
+
const result = db.prepare("DELETE FROM payouts WHERE id = ?").run(id);
|
|
651
|
+
return result.changes > 0;
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
// --- Auto-Reconciliation ---
|
|
655
|
+
|
|
656
|
+
export interface AutoReconcileResult {
|
|
657
|
+
matched: Array<{ payment_id: string; invoice_id: string; confidence: string }>;
|
|
658
|
+
unmatched_payments: Payment[];
|
|
659
|
+
unmatched_invoices: string[];
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
/**
|
|
663
|
+
* Auto-reconcile payments to invoices by matching amount + customer_email + date (+-3 days tolerance).
|
|
664
|
+
* This looks at payments that have no invoice_id and tries to match them against
|
|
665
|
+
* payments that DO have an invoice_id (as a proxy for invoice records).
|
|
666
|
+
*/
|
|
667
|
+
export function autoReconcile(dateFrom?: string, dateTo?: string): AutoReconcileResult {
|
|
668
|
+
const db = getDatabase();
|
|
669
|
+
|
|
670
|
+
// Build date conditions
|
|
671
|
+
const dateConditions: string[] = [];
|
|
672
|
+
const dateParams: unknown[] = [];
|
|
673
|
+
if (dateFrom) {
|
|
674
|
+
dateConditions.push("created_at >= ?");
|
|
675
|
+
dateParams.push(dateFrom);
|
|
676
|
+
}
|
|
677
|
+
if (dateTo) {
|
|
678
|
+
dateConditions.push("created_at <= ?");
|
|
679
|
+
dateParams.push(dateTo);
|
|
680
|
+
}
|
|
681
|
+
const dateWhere = dateConditions.length > 0 ? " AND " + dateConditions.join(" AND ") : "";
|
|
682
|
+
|
|
683
|
+
// Get unreconciled payments (no invoice_id, type=charge, succeeded)
|
|
684
|
+
const unreconciledRows = db
|
|
685
|
+
.prepare(
|
|
686
|
+
`SELECT * FROM payments
|
|
687
|
+
WHERE invoice_id IS NULL AND type = 'charge' AND status = 'succeeded'${dateWhere}
|
|
688
|
+
ORDER BY created_at DESC`
|
|
689
|
+
)
|
|
690
|
+
.all(...dateParams) as PaymentRow[];
|
|
691
|
+
const unreconciled = unreconciledRows.map(rowToPayment);
|
|
692
|
+
|
|
693
|
+
// Get reconciled payments (have invoice_id) as our "invoice" reference
|
|
694
|
+
const reconciledRows = db
|
|
695
|
+
.prepare(
|
|
696
|
+
`SELECT * FROM payments
|
|
697
|
+
WHERE invoice_id IS NOT NULL AND type = 'charge'${dateWhere}
|
|
698
|
+
ORDER BY created_at DESC`
|
|
699
|
+
)
|
|
700
|
+
.all(...dateParams) as PaymentRow[];
|
|
701
|
+
const reconciled = reconciledRows.map(rowToPayment);
|
|
702
|
+
|
|
703
|
+
// Collect known invoice IDs
|
|
704
|
+
const invoiceIds = new Set(reconciled.map((p) => p.invoice_id!));
|
|
705
|
+
const matchedInvoiceIds = new Set<string>();
|
|
706
|
+
|
|
707
|
+
const matched: Array<{ payment_id: string; invoice_id: string; confidence: string }> = [];
|
|
708
|
+
const unmatchedPayments: Payment[] = [];
|
|
709
|
+
|
|
710
|
+
for (const payment of unreconciled) {
|
|
711
|
+
let bestMatch: Payment | null = null;
|
|
712
|
+
for (const candidate of reconciled) {
|
|
713
|
+
if (matchedInvoiceIds.has(candidate.invoice_id!)) continue;
|
|
714
|
+
// Match by amount
|
|
715
|
+
if (candidate.amount !== payment.amount) continue;
|
|
716
|
+
// Match by customer email
|
|
717
|
+
if (
|
|
718
|
+
candidate.customer_email &&
|
|
719
|
+
payment.customer_email &&
|
|
720
|
+
candidate.customer_email === payment.customer_email
|
|
721
|
+
) {
|
|
722
|
+
// Match by date proximity (+-3 days)
|
|
723
|
+
const payDate = new Date(payment.created_at).getTime();
|
|
724
|
+
const candDate = new Date(candidate.created_at).getTime();
|
|
725
|
+
const dayDiff = Math.abs(payDate - candDate) / (1000 * 60 * 60 * 24);
|
|
726
|
+
if (dayDiff <= 3) {
|
|
727
|
+
bestMatch = candidate;
|
|
728
|
+
break;
|
|
729
|
+
}
|
|
730
|
+
}
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
if (bestMatch && bestMatch.invoice_id) {
|
|
734
|
+
// Link the payment to the invoice
|
|
735
|
+
updatePayment(payment.id, { invoice_id: bestMatch.invoice_id });
|
|
736
|
+
matched.push({
|
|
737
|
+
payment_id: payment.id,
|
|
738
|
+
invoice_id: bestMatch.invoice_id,
|
|
739
|
+
confidence: "high",
|
|
740
|
+
});
|
|
741
|
+
matchedInvoiceIds.add(bestMatch.invoice_id);
|
|
742
|
+
} else {
|
|
743
|
+
unmatchedPayments.push(payment);
|
|
744
|
+
}
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
// Unmatched invoices = invoice IDs not used in matching
|
|
748
|
+
const unmatchedInvoices = [...invoiceIds].filter((id) => !matchedInvoiceIds.has(id));
|
|
749
|
+
|
|
750
|
+
return {
|
|
751
|
+
matched,
|
|
752
|
+
unmatched_payments: unmatchedPayments,
|
|
753
|
+
unmatched_invoices: unmatchedInvoices,
|
|
754
|
+
};
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
// --- Failed Payment Retry ---
|
|
758
|
+
|
|
759
|
+
export type RetryStatus = "pending" | "retrying" | "succeeded" | "failed";
|
|
760
|
+
|
|
761
|
+
export interface RetryAttempt {
|
|
762
|
+
id: string;
|
|
763
|
+
payment_id: string;
|
|
764
|
+
attempt: number;
|
|
765
|
+
status: RetryStatus;
|
|
766
|
+
attempted_at: string | null;
|
|
767
|
+
error: string | null;
|
|
768
|
+
created_at: string;
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
interface RetryAttemptRow {
|
|
772
|
+
id: string;
|
|
773
|
+
payment_id: string;
|
|
774
|
+
attempt: number;
|
|
775
|
+
status: string;
|
|
776
|
+
attempted_at: string | null;
|
|
777
|
+
error: string | null;
|
|
778
|
+
created_at: string;
|
|
779
|
+
}
|
|
780
|
+
|
|
781
|
+
function rowToRetryAttempt(row: RetryAttemptRow): RetryAttempt {
|
|
782
|
+
return {
|
|
783
|
+
...row,
|
|
784
|
+
status: row.status as RetryStatus,
|
|
785
|
+
};
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
export function retryPayment(paymentId: string): RetryAttempt | null {
|
|
789
|
+
const db = getDatabase();
|
|
790
|
+
const payment = getPayment(paymentId);
|
|
791
|
+
if (!payment) return null;
|
|
792
|
+
if (payment.status !== "failed") return null;
|
|
793
|
+
|
|
794
|
+
// Get current attempt count
|
|
795
|
+
const lastAttempt = db
|
|
796
|
+
.prepare(
|
|
797
|
+
"SELECT MAX(attempt) as max_attempt FROM retry_attempts WHERE payment_id = ?"
|
|
798
|
+
)
|
|
799
|
+
.get(paymentId) as { max_attempt: number | null };
|
|
800
|
+
|
|
801
|
+
const attemptNum = (lastAttempt?.max_attempt || 0) + 1;
|
|
802
|
+
const id = crypto.randomUUID();
|
|
803
|
+
|
|
804
|
+
// Create the retry attempt as retrying
|
|
805
|
+
db.prepare(
|
|
806
|
+
`INSERT INTO retry_attempts (id, payment_id, attempt, status, attempted_at)
|
|
807
|
+
VALUES (?, ?, ?, 'retrying', datetime('now'))`
|
|
808
|
+
).run(id, paymentId, attemptNum);
|
|
809
|
+
|
|
810
|
+
// Simulate retry — mark as succeeded (in a real system, this would call the provider)
|
|
811
|
+
db.prepare(
|
|
812
|
+
`UPDATE retry_attempts SET status = 'succeeded', attempted_at = datetime('now') WHERE id = ?`
|
|
813
|
+
).run(id);
|
|
814
|
+
|
|
815
|
+
// Update the original payment status
|
|
816
|
+
updatePayment(paymentId, { status: "succeeded", completed_at: new Date().toISOString() });
|
|
817
|
+
|
|
818
|
+
return getRetryAttempt(id);
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
function getRetryAttempt(id: string): RetryAttempt | null {
|
|
822
|
+
const db = getDatabase();
|
|
823
|
+
const row = db.prepare("SELECT * FROM retry_attempts WHERE id = ?").get(id) as RetryAttemptRow | null;
|
|
824
|
+
return row ? rowToRetryAttempt(row) : null;
|
|
825
|
+
}
|
|
826
|
+
|
|
827
|
+
export function listRetries(paymentId: string): RetryAttempt[] {
|
|
828
|
+
const db = getDatabase();
|
|
829
|
+
const rows = db
|
|
830
|
+
.prepare("SELECT * FROM retry_attempts WHERE payment_id = ? ORDER BY attempt ASC")
|
|
831
|
+
.all(paymentId) as RetryAttemptRow[];
|
|
832
|
+
return rows.map(rowToRetryAttempt);
|
|
833
|
+
}
|
|
834
|
+
|
|
835
|
+
export interface RetryStats {
|
|
836
|
+
total_retries: number;
|
|
837
|
+
succeeded: number;
|
|
838
|
+
failed: number;
|
|
839
|
+
pending: number;
|
|
840
|
+
retrying: number;
|
|
841
|
+
success_rate: number;
|
|
842
|
+
}
|
|
843
|
+
|
|
844
|
+
export function getRetryStats(): RetryStats {
|
|
845
|
+
const db = getDatabase();
|
|
846
|
+
const total = db.prepare("SELECT COUNT(*) as count FROM retry_attempts").get() as { count: number };
|
|
847
|
+
const statusRows = db
|
|
848
|
+
.prepare("SELECT status, COUNT(*) as count FROM retry_attempts GROUP BY status")
|
|
849
|
+
.all() as { status: string; count: number }[];
|
|
850
|
+
|
|
851
|
+
const statusCounts: Record<string, number> = {};
|
|
852
|
+
for (const r of statusRows) statusCounts[r.status] = r.count;
|
|
853
|
+
|
|
854
|
+
const succeeded = statusCounts["succeeded"] || 0;
|
|
855
|
+
const totalCount = total.count || 0;
|
|
856
|
+
|
|
857
|
+
return {
|
|
858
|
+
total_retries: totalCount,
|
|
859
|
+
succeeded,
|
|
860
|
+
failed: statusCounts["failed"] || 0,
|
|
861
|
+
pending: statusCounts["pending"] || 0,
|
|
862
|
+
retrying: statusCounts["retrying"] || 0,
|
|
863
|
+
success_rate: totalCount > 0 ? (succeeded / totalCount) * 100 : 0,
|
|
864
|
+
};
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
// --- Multi-Currency Conversion ---
|
|
868
|
+
|
|
869
|
+
const CURRENCY_RATES: Record<string, Record<string, number>> = {
|
|
870
|
+
USD: { EUR: 0.92, GBP: 0.79, CAD: 1.36, AUD: 1.53, USD: 1.0 },
|
|
871
|
+
EUR: { USD: 1.09, GBP: 0.86, CAD: 1.48, AUD: 1.66, EUR: 1.0 },
|
|
872
|
+
GBP: { USD: 1.27, EUR: 1.16, CAD: 1.72, AUD: 1.93, GBP: 1.0 },
|
|
873
|
+
CAD: { USD: 0.74, EUR: 0.68, GBP: 0.58, AUD: 1.13, CAD: 1.0 },
|
|
874
|
+
AUD: { USD: 0.65, EUR: 0.60, GBP: 0.52, CAD: 0.89, AUD: 1.0 },
|
|
875
|
+
};
|
|
876
|
+
|
|
877
|
+
export interface CurrencyConversion {
|
|
878
|
+
original_amount: number;
|
|
879
|
+
converted_amount: number;
|
|
880
|
+
from: string;
|
|
881
|
+
to: string;
|
|
882
|
+
rate: number;
|
|
883
|
+
}
|
|
884
|
+
|
|
885
|
+
export function convertCurrency(amount: number, from: string, to: string): CurrencyConversion | null {
|
|
886
|
+
const fromUpper = from.toUpperCase();
|
|
887
|
+
const toUpper = to.toUpperCase();
|
|
888
|
+
|
|
889
|
+
const fromRates = CURRENCY_RATES[fromUpper];
|
|
890
|
+
if (!fromRates) return null;
|
|
891
|
+
|
|
892
|
+
const rate = fromRates[toUpper];
|
|
893
|
+
if (rate === undefined) return null;
|
|
894
|
+
|
|
895
|
+
return {
|
|
896
|
+
original_amount: amount,
|
|
897
|
+
converted_amount: Math.round(amount * rate * 100) / 100,
|
|
898
|
+
from: fromUpper,
|
|
899
|
+
to: toUpper,
|
|
900
|
+
rate,
|
|
901
|
+
};
|
|
902
|
+
}
|
|
903
|
+
|
|
904
|
+
// --- Fee Analysis ---
|
|
905
|
+
|
|
906
|
+
const PROVIDER_FEES: Record<string, { percent: number; fixed: number }> = {
|
|
907
|
+
stripe: { percent: 2.9, fixed: 0.30 },
|
|
908
|
+
square: { percent: 2.6, fixed: 0.10 },
|
|
909
|
+
mercury: { percent: 0, fixed: 0 },
|
|
910
|
+
manual: { percent: 0, fixed: 0 },
|
|
911
|
+
};
|
|
912
|
+
|
|
913
|
+
export interface ProviderFeeBreakdown {
|
|
914
|
+
provider: string;
|
|
915
|
+
gross: number;
|
|
916
|
+
fees: number;
|
|
917
|
+
net: number;
|
|
918
|
+
transaction_count: number;
|
|
919
|
+
}
|
|
920
|
+
|
|
921
|
+
export interface FeeAnalysisResult {
|
|
922
|
+
month: string;
|
|
923
|
+
providers: ProviderFeeBreakdown[];
|
|
924
|
+
total_gross: number;
|
|
925
|
+
total_fees: number;
|
|
926
|
+
total_net: number;
|
|
927
|
+
}
|
|
928
|
+
|
|
929
|
+
export function feeAnalysis(month: string): FeeAnalysisResult {
|
|
930
|
+
const db = getDatabase();
|
|
931
|
+
const [year, mon] = month.split("-").map(Number);
|
|
932
|
+
const startDate = `${year}-${String(mon).padStart(2, "0")}-01`;
|
|
933
|
+
const lastDay = new Date(year, mon, 0).getDate();
|
|
934
|
+
const endDate = `${year}-${String(mon).padStart(2, "0")}-${String(lastDay).padStart(2, "0")} 23:59:59`;
|
|
935
|
+
|
|
936
|
+
const rows = db
|
|
937
|
+
.prepare(
|
|
938
|
+
`SELECT COALESCE(provider, 'manual') as provider, SUM(amount) as total, COUNT(*) as count
|
|
939
|
+
FROM payments
|
|
940
|
+
WHERE type = 'charge' AND status = 'succeeded'
|
|
941
|
+
AND created_at >= ? AND created_at <= ?
|
|
942
|
+
GROUP BY provider`
|
|
943
|
+
)
|
|
944
|
+
.all(startDate, endDate) as { provider: string; total: number; count: number }[];
|
|
945
|
+
|
|
946
|
+
const providers: ProviderFeeBreakdown[] = rows.map((r) => {
|
|
947
|
+
const feeConfig = PROVIDER_FEES[r.provider] || PROVIDER_FEES["manual"];
|
|
948
|
+
const fees = (r.total * feeConfig.percent) / 100 + feeConfig.fixed * r.count;
|
|
949
|
+
return {
|
|
950
|
+
provider: r.provider,
|
|
951
|
+
gross: Math.round(r.total * 100) / 100,
|
|
952
|
+
fees: Math.round(fees * 100) / 100,
|
|
953
|
+
net: Math.round((r.total - fees) * 100) / 100,
|
|
954
|
+
transaction_count: r.count,
|
|
955
|
+
};
|
|
956
|
+
});
|
|
957
|
+
|
|
958
|
+
return {
|
|
959
|
+
month,
|
|
960
|
+
providers,
|
|
961
|
+
total_gross: Math.round(providers.reduce((s, p) => s + p.gross, 0) * 100) / 100,
|
|
962
|
+
total_fees: Math.round(providers.reduce((s, p) => s + p.fees, 0) * 100) / 100,
|
|
963
|
+
total_net: Math.round(providers.reduce((s, p) => s + p.net, 0) * 100) / 100,
|
|
964
|
+
};
|
|
965
|
+
}
|
|
966
|
+
|
|
967
|
+
// --- Decline Analytics ---
|
|
968
|
+
|
|
969
|
+
export interface DeclineEntry {
|
|
970
|
+
description: string | null;
|
|
971
|
+
count: number;
|
|
972
|
+
total_amount: number;
|
|
973
|
+
provider: string | null;
|
|
974
|
+
}
|
|
975
|
+
|
|
976
|
+
export interface DeclineReport {
|
|
977
|
+
entries: DeclineEntry[];
|
|
978
|
+
total_declined: number;
|
|
979
|
+
total_amount: number;
|
|
980
|
+
}
|
|
981
|
+
|
|
982
|
+
export function declineReport(provider?: PaymentProvider): DeclineReport {
|
|
983
|
+
const db = getDatabase();
|
|
984
|
+
const conditions = ["status = 'failed'"];
|
|
985
|
+
const params: unknown[] = [];
|
|
986
|
+
|
|
987
|
+
if (provider) {
|
|
988
|
+
conditions.push("provider = ?");
|
|
989
|
+
params.push(provider);
|
|
990
|
+
}
|
|
991
|
+
|
|
992
|
+
const whereClause = conditions.join(" AND ");
|
|
993
|
+
|
|
994
|
+
const rows = db
|
|
995
|
+
.prepare(
|
|
996
|
+
`SELECT description, COALESCE(provider, 'unknown') as provider, COUNT(*) as count, SUM(amount) as total_amount
|
|
997
|
+
FROM payments
|
|
998
|
+
WHERE ${whereClause}
|
|
999
|
+
GROUP BY description, provider
|
|
1000
|
+
ORDER BY count DESC`
|
|
1001
|
+
)
|
|
1002
|
+
.all(...params) as { description: string | null; provider: string; count: number; total_amount: number }[];
|
|
1003
|
+
|
|
1004
|
+
const entries: DeclineEntry[] = rows.map((r) => ({
|
|
1005
|
+
description: r.description,
|
|
1006
|
+
count: r.count,
|
|
1007
|
+
total_amount: r.total_amount,
|
|
1008
|
+
provider: r.provider,
|
|
1009
|
+
}));
|
|
1010
|
+
|
|
1011
|
+
return {
|
|
1012
|
+
entries,
|
|
1013
|
+
total_declined: entries.reduce((s, e) => s + e.count, 0),
|
|
1014
|
+
total_amount: entries.reduce((s, e) => s + e.total_amount, 0),
|
|
1015
|
+
};
|
|
1016
|
+
}
|
|
1017
|
+
|
|
1018
|
+
// --- Dispute Evidence ---
|
|
1019
|
+
|
|
1020
|
+
export function addDisputeEvidence(
|
|
1021
|
+
disputeId: string,
|
|
1022
|
+
description: string,
|
|
1023
|
+
fileRef?: string
|
|
1024
|
+
): Dispute | null {
|
|
1025
|
+
const db = getDatabase();
|
|
1026
|
+
const dispute = getDispute(disputeId);
|
|
1027
|
+
if (!dispute) return null;
|
|
1028
|
+
|
|
1029
|
+
// Get existing evidence — treat as array if it has "items", otherwise start fresh
|
|
1030
|
+
const evidence = dispute.evidence as Record<string, unknown>;
|
|
1031
|
+
const items = Array.isArray(evidence.items) ? [...evidence.items] : [];
|
|
1032
|
+
|
|
1033
|
+
const entry: Record<string, unknown> = {
|
|
1034
|
+
description,
|
|
1035
|
+
added_at: new Date().toISOString(),
|
|
1036
|
+
};
|
|
1037
|
+
if (fileRef) {
|
|
1038
|
+
entry.file_ref = fileRef;
|
|
1039
|
+
}
|
|
1040
|
+
items.push(entry);
|
|
1041
|
+
|
|
1042
|
+
const newEvidence = { ...evidence, items };
|
|
1043
|
+
db.prepare("UPDATE disputes SET evidence = ? WHERE id = ?").run(
|
|
1044
|
+
JSON.stringify(newEvidence),
|
|
1045
|
+
disputeId
|
|
1046
|
+
);
|
|
1047
|
+
|
|
1048
|
+
return getDispute(disputeId);
|
|
1049
|
+
}
|
|
1050
|
+
|
|
1051
|
+
// --- Payment Split ---
|
|
1052
|
+
|
|
1053
|
+
export interface PaymentSplit {
|
|
1054
|
+
payment_id: string;
|
|
1055
|
+
splits: Record<string, number>;
|
|
1056
|
+
total_percent: number;
|
|
1057
|
+
}
|
|
1058
|
+
|
|
1059
|
+
export function splitPayment(paymentId: string, splits: Record<string, number>): Payment | null {
|
|
1060
|
+
const payment = getPayment(paymentId);
|
|
1061
|
+
if (!payment) return null;
|
|
1062
|
+
|
|
1063
|
+
const totalPercent = Object.values(splits).reduce((s, v) => s + v, 0);
|
|
1064
|
+
|
|
1065
|
+
// Store split info in metadata
|
|
1066
|
+
const metadata = { ...payment.metadata, splits, split_total_percent: totalPercent };
|
|
1067
|
+
return updatePayment(paymentId, { metadata });
|
|
1068
|
+
}
|
|
1069
|
+
|
|
1070
|
+
// --- Revenue Forecast ---
|
|
1071
|
+
|
|
1072
|
+
export interface RevenueForecastResult {
|
|
1073
|
+
months_projected: number;
|
|
1074
|
+
historical: Array<{ month: string; revenue: number }>;
|
|
1075
|
+
forecast: Array<{ month: string; projected_revenue: number }>;
|
|
1076
|
+
trend: "growing" | "declining" | "stable";
|
|
1077
|
+
average_monthly_revenue: number;
|
|
1078
|
+
}
|
|
1079
|
+
|
|
1080
|
+
export function revenueForecast(months: number): RevenueForecastResult {
|
|
1081
|
+
const db = getDatabase();
|
|
1082
|
+
|
|
1083
|
+
// Get last 3 months of revenue
|
|
1084
|
+
const now = new Date();
|
|
1085
|
+
const historical: Array<{ month: string; revenue: number }> = [];
|
|
1086
|
+
|
|
1087
|
+
for (let i = 3; i >= 1; i--) {
|
|
1088
|
+
const d = new Date(now.getFullYear(), now.getMonth() - i, 1);
|
|
1089
|
+
const year = d.getFullYear();
|
|
1090
|
+
const mon = d.getMonth() + 1;
|
|
1091
|
+
const startDate = `${year}-${String(mon).padStart(2, "0")}-01`;
|
|
1092
|
+
const lastDay = new Date(year, mon, 0).getDate();
|
|
1093
|
+
const endDate = `${year}-${String(mon).padStart(2, "0")}-${String(lastDay).padStart(2, "0")} 23:59:59`;
|
|
1094
|
+
|
|
1095
|
+
const row = db
|
|
1096
|
+
.prepare(
|
|
1097
|
+
`SELECT COALESCE(SUM(amount), 0) as total
|
|
1098
|
+
FROM payments
|
|
1099
|
+
WHERE type = 'charge' AND status = 'succeeded'
|
|
1100
|
+
AND created_at >= ? AND created_at <= ?`
|
|
1101
|
+
)
|
|
1102
|
+
.get(startDate, endDate) as { total: number };
|
|
1103
|
+
|
|
1104
|
+
historical.push({
|
|
1105
|
+
month: `${year}-${String(mon).padStart(2, "0")}`,
|
|
1106
|
+
revenue: row.total,
|
|
1107
|
+
});
|
|
1108
|
+
}
|
|
1109
|
+
|
|
1110
|
+
// Calculate trend
|
|
1111
|
+
const revenues = historical.map((h) => h.revenue);
|
|
1112
|
+
const avgRevenue = revenues.reduce((s, r) => s + r, 0) / (revenues.length || 1);
|
|
1113
|
+
|
|
1114
|
+
let trend: "growing" | "declining" | "stable" = "stable";
|
|
1115
|
+
if (revenues.length >= 2) {
|
|
1116
|
+
const first = revenues[0];
|
|
1117
|
+
const last = revenues[revenues.length - 1];
|
|
1118
|
+
if (last > first * 1.05) trend = "growing";
|
|
1119
|
+
else if (last < first * 0.95) trend = "declining";
|
|
1120
|
+
}
|
|
1121
|
+
|
|
1122
|
+
// Calculate monthly growth rate
|
|
1123
|
+
let growthRate = 0;
|
|
1124
|
+
if (revenues.length >= 2 && revenues[0] > 0) {
|
|
1125
|
+
growthRate = (revenues[revenues.length - 1] - revenues[0]) / revenues[0] / (revenues.length - 1);
|
|
1126
|
+
}
|
|
1127
|
+
|
|
1128
|
+
// Project future months
|
|
1129
|
+
const forecast: Array<{ month: string; projected_revenue: number }> = [];
|
|
1130
|
+
const baseRevenue = revenues[revenues.length - 1] || avgRevenue;
|
|
1131
|
+
|
|
1132
|
+
for (let i = 0; i < months; i++) {
|
|
1133
|
+
const d = new Date(now.getFullYear(), now.getMonth() + i, 1);
|
|
1134
|
+
const year = d.getFullYear();
|
|
1135
|
+
const mon = d.getMonth() + 1;
|
|
1136
|
+
const projected = Math.round(baseRevenue * Math.pow(1 + growthRate, i + 1) * 100) / 100;
|
|
1137
|
+
|
|
1138
|
+
forecast.push({
|
|
1139
|
+
month: `${year}-${String(mon).padStart(2, "0")}`,
|
|
1140
|
+
projected_revenue: projected,
|
|
1141
|
+
});
|
|
1142
|
+
}
|
|
1143
|
+
|
|
1144
|
+
return {
|
|
1145
|
+
months_projected: months,
|
|
1146
|
+
historical,
|
|
1147
|
+
forecast,
|
|
1148
|
+
trend,
|
|
1149
|
+
average_monthly_revenue: Math.round(avgRevenue * 100) / 100,
|
|
1150
|
+
};
|
|
1151
|
+
}
|
|
1152
|
+
|
|
1153
|
+
// --- Reconciliation Gaps ---
|
|
1154
|
+
|
|
1155
|
+
export interface ReconciliationGaps {
|
|
1156
|
+
payments_without_invoice: Payment[];
|
|
1157
|
+
invoice_ids_without_payment: string[];
|
|
1158
|
+
gap_count: number;
|
|
1159
|
+
}
|
|
1160
|
+
|
|
1161
|
+
export function findReconciliationGaps(dateFrom: string, dateTo: string): ReconciliationGaps {
|
|
1162
|
+
const db = getDatabase();
|
|
1163
|
+
|
|
1164
|
+
// Payments without invoice_id (type=charge, succeeded)
|
|
1165
|
+
const unreconciledRows = db
|
|
1166
|
+
.prepare(
|
|
1167
|
+
`SELECT * FROM payments
|
|
1168
|
+
WHERE invoice_id IS NULL AND type = 'charge' AND status = 'succeeded'
|
|
1169
|
+
AND created_at >= ? AND created_at <= ?
|
|
1170
|
+
ORDER BY created_at DESC`
|
|
1171
|
+
)
|
|
1172
|
+
.all(dateFrom, dateTo) as PaymentRow[];
|
|
1173
|
+
const paymentsWithoutInvoice = unreconciledRows.map(rowToPayment);
|
|
1174
|
+
|
|
1175
|
+
// Get invoice_ids that have at least one succeeded payment
|
|
1176
|
+
const succeededInvoiceRows = db
|
|
1177
|
+
.prepare(
|
|
1178
|
+
`SELECT DISTINCT invoice_id FROM payments
|
|
1179
|
+
WHERE invoice_id IS NOT NULL AND status = 'succeeded'
|
|
1180
|
+
AND created_at >= ? AND created_at <= ?`
|
|
1181
|
+
)
|
|
1182
|
+
.all(dateFrom, dateTo) as { invoice_id: string }[];
|
|
1183
|
+
const succeededInvoiceIds = new Set(succeededInvoiceRows.map((r) => r.invoice_id));
|
|
1184
|
+
|
|
1185
|
+
// Get all distinct invoice_ids in the date range
|
|
1186
|
+
const allInvoiceRows = db
|
|
1187
|
+
.prepare(
|
|
1188
|
+
`SELECT DISTINCT invoice_id FROM payments
|
|
1189
|
+
WHERE invoice_id IS NOT NULL
|
|
1190
|
+
AND created_at >= ? AND created_at <= ?`
|
|
1191
|
+
)
|
|
1192
|
+
.all(dateFrom, dateTo) as { invoice_id: string }[];
|
|
1193
|
+
|
|
1194
|
+
// Invoice IDs that have no succeeded payment
|
|
1195
|
+
const invoiceIdsWithoutSucceededPayment = allInvoiceRows
|
|
1196
|
+
.map((r) => r.invoice_id)
|
|
1197
|
+
.filter((id) => !succeededInvoiceIds.has(id));
|
|
1198
|
+
|
|
1199
|
+
return {
|
|
1200
|
+
payments_without_invoice: paymentsWithoutInvoice,
|
|
1201
|
+
invoice_ids_without_payment: invoiceIdsWithoutSucceededPayment,
|
|
1202
|
+
gap_count: paymentsWithoutInvoice.length + invoiceIdsWithoutSucceededPayment.length,
|
|
1203
|
+
};
|
|
1204
|
+
}
|