forked from StellarSplit/StellarSplit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquickbooks-generator.service.ts
More file actions
377 lines (334 loc) · 10.9 KB
/
Copy pathquickbooks-generator.service.ts
File metadata and controls
377 lines (334 loc) · 10.9 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
import { Injectable } from "@nestjs/common";
import { ExportJob } from "./entities/export-job.entity";
import { Builder } from "xml2js";
// ── Shared line-item interfaces ───────────────────────────────────────────────
interface AccountRef {
FullName: string;
}
interface EntityRef {
FullName: string;
}
interface JournalLine {
AccountRef: AccountRef;
Amount: number;
Memo: string;
EntityRef?: EntityRef;
}
interface JournalEntry {
TxnDate: string;
JournalCreditLine: JournalLine[];
JournalDebitLine: JournalLine[];
}
interface InvoiceRecord {
CustomerRef: { FullName: string };
TxnDate: string;
BillAddress: Record<string, string>;
InvoiceLineAdd: {
ItemRef: { FullName: string };
Desc: string;
Quantity: number;
Rate: number;
}[];
}
interface BillRecord {
VendorRef: { FullName: string };
TxnDate: string;
DueDate: string;
ExpenseLineAdd: {
AccountRef: AccountRef;
Amount: number;
Memo: string;
}[];
}
// ── Service ───────────────────────────────────────────────────────────────────
@Injectable()
export class QuickBooksGeneratorService {
/**
* Generate QBO (QuickBooks Online) file
*/
async generateQbo(data: any, job: ExportJob): Promise<Buffer> {
const builder = new Builder({
xmldec: { version: "1.0", encoding: "UTF-8" },
renderOpts: { pretty: true, indent: " ", newline: "\n" },
});
const qboData = this.formatForQuickBooks(data, job);
const xml = builder.buildObject(qboData);
return Buffer.from(xml, "utf8");
}
// ── Private formatters ──────────────────────────────────────────────────────
private formatForQuickBooks(data: any, job: ExportJob): any {
return {
QBXML: {
$: { version: "13.0" },
QBXMLMsgsRq: {
$: { onError: "stopOnError" },
VendorAddRq: this.formatVendors(data),
CustomerAddRq: this.formatCustomers(data),
AccountAddRq: this.formatAccounts(),
ItemServiceAddRq: this.formatItems(data),
InvoiceAddRq: this.formatInvoices(data),
BillAddRq: this.formatBills(data),
JournalEntryAddRq: this.formatJournalEntries(data, job),
},
},
};
}
private formatVendors(data: any): any[] {
const vendors = new Map<string, any>();
data.expenses.forEach((expense: any) => {
if (expense.paidBy !== expense.userId) {
const vendorId: string = expense.paidBy;
if (!vendors.has(vendorId)) {
vendors.set(vendorId, {
Name:
expense.paidByUser?.name ?? `Vendor-${vendorId.substring(0, 8)}`,
CompanyName: expense.paidByUser?.name ?? "Individual",
FirstName: expense.paidByUser?.firstName ?? "",
LastName: expense.paidByUser?.lastName ?? "",
VendorAddress: {
Addr1: "N/A",
City: "N/A",
State: "N/A",
PostalCode: "N/A",
Country: "N/A",
},
});
}
}
});
return Array.from(vendors.values()).map((vendor) => ({
VendorAdd: vendor,
}));
}
private formatCustomers(data: any): any[] {
const customers = new Map<string, any>();
if (data.partners) {
data.partners.forEach((partner: any) => {
if (partner.totalOwedToYou > 0) {
customers.set(partner.partnerId, {
Name:
partner.partnerName ??
`Customer-${partner.partnerId.substring(0, 8)}`,
CompanyName: partner.partnerName ?? "Individual",
FirstName: partner.partnerName?.split(" ")[0] ?? "",
LastName: partner.partnerName?.split(" ").slice(1).join(" ") ?? "",
CustomerAddress: {
Addr1: "N/A",
City: "N/A",
State: "N/A",
PostalCode: "N/A",
Country: "N/A",
},
});
}
});
}
return Array.from(customers.values()).map((customer) => ({
CustomerAdd: customer,
}));
}
private formatAccounts(): any[] {
return [
{
AccountAdd: {
Name: "Accounts Receivable",
AccountType: "AccountsReceivable",
Desc: "Money owed to you",
},
},
{
AccountAdd: {
Name: "Accounts Payable",
AccountType: "AccountsPayable",
Desc: "Money you owe to others",
},
},
{
AccountAdd: {
Name: "Expense Account",
AccountType: "Expense",
Desc: "General expense account",
},
},
{
AccountAdd: {
Name: "Income Account",
AccountType: "Income",
Desc: "Income from settlements",
},
},
];
}
private formatItems(data: any): any[] {
const items = new Map<string, any>();
data.expenses.forEach((expense: any) => {
if (!items.has(expense.category)) {
items.set(expense.category, {
Name: `Service-${expense.category}`,
SalesOrPurchase: {
Desc: `${expense.category} expense`,
AccountRef: { FullName: "Expense Account" },
},
});
}
});
return Array.from(items.values()).map((item) => ({ ItemServiceAdd: item }));
}
private formatInvoices(data: any): any[] {
// Explicitly typed so TypeScript doesn't infer never[]
const invoices: InvoiceRecord[] = [];
if (data.partners) {
data.partners.forEach((partner: any) => {
if (partner.totalOwedToYou > 0) {
invoices.push({
CustomerRef: {
FullName:
partner.partnerName ??
`Customer-${partner.partnerId.substring(0, 8)}`,
},
TxnDate: new Date().toISOString().split("T")[0],
BillAddress: {
Addr1: "N/A",
City: "N/A",
State: "N/A",
PostalCode: "N/A",
Country: "N/A",
},
InvoiceLineAdd: [
{
ItemRef: { FullName: "Service-General" },
Desc: "Amount owed from shared expenses",
Quantity: 1,
Rate: partner.totalOwedToYou,
},
],
});
}
});
}
return invoices.map((invoice) => ({ InvoiceAdd: invoice }));
}
private formatBills(data: any): any[] {
// Explicitly typed so TypeScript doesn't infer never[]
const bills: BillRecord[] = [];
if (data.partners) {
data.partners.forEach((partner: any) => {
if (partner.totalYouOwe > 0) {
bills.push({
VendorRef: {
FullName:
partner.partnerName ??
`Vendor-${partner.partnerId.substring(0, 8)}`,
},
TxnDate: new Date().toISOString().split("T")[0],
DueDate: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000)
.toISOString()
.split("T")[0],
ExpenseLineAdd: [
{
AccountRef: { FullName: "Accounts Payable" },
Amount: partner.totalYouOwe,
Memo: "Amount owed for shared expenses",
},
],
});
}
});
}
return bills.map((bill) => ({ BillAdd: bill }));
}
private formatJournalEntries(data: any, job: ExportJob): any[] {
// Explicitly typed so .push() knows what it accepts — resolves all TS2345 errors
const journalEntries: JournalEntry[] = [];
data.expenses.forEach((expense: any) => {
const entry: JournalEntry = {
TxnDate: new Date(expense.createdAt).toISOString().split("T")[0],
JournalCreditLine: [],
JournalDebitLine: [],
};
entry.JournalDebitLine.push({
AccountRef: { FullName: "Expense Account" },
Amount: expense.amount,
Memo: expense.description,
EntityRef: { FullName: expense.paidByUser?.name ?? "Self" },
});
expense.participants.forEach((participant: any) => {
if (participant.amount > 0) {
const line: JournalLine = {
AccountRef: {
FullName:
expense.paidBy === expense.userId
? "Accounts Receivable"
: "Accounts Payable",
},
Amount: participant.amount,
Memo: `Share of ${expense.description}`,
EntityRef: {
FullName:
participant.user?.name ??
`User-${participant.userId.substring(0, 8)}`,
},
};
entry.JournalCreditLine.push(line);
}
});
journalEntries.push(entry);
});
data.settlements.forEach((settlement: any) => {
const entry: JournalEntry = {
TxnDate: new Date(settlement.createdAt).toISOString().split("T")[0],
JournalCreditLine: [],
JournalDebitLine: [],
};
if (settlement.direction === "incoming") {
entry.JournalDebitLine.push({
AccountRef: { FullName: "Bank Account" },
Amount: settlement.amount,
Memo: settlement.description,
});
entry.JournalCreditLine.push({
AccountRef: { FullName: "Accounts Receivable" },
Amount: settlement.amount,
Memo: `Payment from ${settlement.counterpartyName}`,
});
} else {
entry.JournalDebitLine.push({
AccountRef: { FullName: "Accounts Payable" },
Amount: settlement.amount,
Memo: `Payment to ${settlement.counterpartyName}`,
});
entry.JournalCreditLine.push({
AccountRef: { FullName: "Bank Account" },
Amount: settlement.amount,
Memo: settlement.description,
});
}
journalEntries.push(entry);
});
if (job.isTaxCompliant) {
const taxEntry: JournalEntry = {
TxnDate: new Date().toISOString().split("T")[0],
JournalCreditLine: [],
JournalDebitLine: [],
};
const deductibleAmount: number = data.summary?.deductibleAmount ?? 0;
const taxableIncome: number = data.summary?.taxableIncome ?? 0;
if (deductibleAmount > 0) {
taxEntry.JournalDebitLine.push({
AccountRef: { FullName: "Tax Deductions" },
Amount: deductibleAmount,
Memo: "Business expense deductions",
});
}
if (taxableIncome > 0) {
taxEntry.JournalCreditLine.push({
AccountRef: { FullName: "Taxable Income" },
Amount: taxableIncome,
Memo: "Income from expense settlements",
});
}
journalEntries.push(taxEntry);
}
return journalEntries.map((entry) => ({ JournalEntryAdd: entry }));
}
}