forked from StellarSplit/StellarSplit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsplits.service.ts
More file actions
316 lines (275 loc) · 10.1 KB
/
Copy pathsplits.service.ts
File metadata and controls
316 lines (275 loc) · 10.1 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
import { Injectable, NotFoundException, BadRequestException, Logger } from '@nestjs/common';
import { InjectDataSource, InjectRepository } from '@nestjs/typeorm';
import { DataSource, EntityManager, Repository } from 'typeorm';
import { Split } from '../../entities/split.entity';
import { Item } from '../../entities/item.entity';
import { Participant } from '../../entities/participant.entity';
import { Receipt } from '../../receipts/entities/receipt.entity';
import { OcrService } from '../../ocr/ocr.service';
import { SplitCalculationService } from './split-calculation.service';
import { FraudDetectionService } from '../../fraud-detection/fraud-detection.service';
import { AnalyzeSplitRequestDto } from '../../fraud-detection/dto/analyze-split.dto';
import {
CreateSplitDto,
UpdateSplitDto,
CreateDraftSplitDto,
FinalizeDraftSplitDto,
SplitAllocationDto
} from './dto/split.dto';
@Injectable()
export class SplitsService {
private readonly logger = new Logger(SplitsService.name);
constructor(
@InjectRepository(Split)
private readonly splitRepository: Repository<Split>,
@InjectRepository(Item)
private readonly itemRepository: Repository<Item>,
@InjectRepository(Participant)
private readonly participantRepository: Repository<Participant>,
@InjectRepository(Receipt)
private readonly receiptRepository: Repository<Receipt>,
private readonly ocrService: OcrService,
private readonly splitCalculationService: SplitCalculationService,
@InjectDataSource()
private readonly dataSource: DataSource,
private readonly fraudDetectionService: FraudDetectionService,
) {}
/**
* Create a new split from scratch
*/
async createSplit(
createSplitDto: CreateSplitDto,
manager?: EntityManager,
): Promise<Split> {
// If no transaction manager is provided, run everything atomically.
if (!manager) {
return this.dataSource.transaction(async (txManager) => {
return this.createSplit(createSplitDto, txManager);
});
}
const splitRepository = manager.getRepository(Split);
const itemRepository = manager.getRepository(Item);
const participantRepository = manager.getRepository(Participant);
const split = splitRepository.create({
totalAmount: createSplitDto.totalAmount,
description: createSplitDto.description,
creatorWalletAddress: createSplitDto.creatorWalletAddress,
preferredCurrency: createSplitDto.preferredCurrency || 'XLM',
dueDate: createSplitDto.dueDate,
});
const savedSplit = await splitRepository.save(split);
// Create participants
if (createSplitDto.participants) {
await this.createParticipants(
savedSplit.id,
createSplitDto.participants,
participantRepository,
);
}
// Create items if provided
if (createSplitDto.items) {
await this.createItems(savedSplit.id, createSplitDto.items, itemRepository);
}
const createdSplit = await splitRepository.findOne({
where: { id: savedSplit.id },
relations: ['items', 'participants', 'category'],
});
if (!createdSplit) {
throw new NotFoundException(`Split ${savedSplit.id} not found`);
}
// Perform fraud detection check
try {
const fraudRequest: AnalyzeSplitRequestDto = {
split_data: {
split_id: savedSplit.id,
creator_id: createSplitDto.creatorWalletAddress,
total_amount: createSplitDto.totalAmount,
participant_count: createSplitDto.participants?.length || 0,
description: createSplitDto.description,
preferred_currency: createSplitDto.preferredCurrency || 'XLM',
creator_wallet_address: createSplitDto.creatorWalletAddress,
created_at: savedSplit.createdAt,
},
};
const fraudResult = await this.fraudDetectionService.checkSplit(fraudRequest);
if (!fraudResult.allowed) {
// Log the block, but still allow the split for now (or throw error)
this.logger.warn(`Split ${savedSplit.id} blocked due to fraud risk: ${fraudResult.riskLevel}`);
}
} catch (error) {
// Log but don't fail the split creation
this.logger.error(`Fraud detection failed for split ${savedSplit.id}:`, error);
}
return createdSplit;
}
/**
* Create a draft split from receipt OCR data
*/
async createDraftSplitFromReceipt(receiptId: string, creatorId: string): Promise<Split> {
const receipt = await this.receiptRepository.findOne({ where: { id: receiptId } });
if (!receipt) {
throw new NotFoundException(`Receipt ${receiptId} not found`);
}
// Process OCR if not already done
if (!receipt.ocrProcessed || !receipt.extractedData) {
throw new BadRequestException('Receipt OCR processing not completed');
}
const ocrData = receipt.extractedData;
// Create draft split
const split = this.splitRepository.create({
totalAmount: ocrData.total || 0,
description: `Split from receipt: ${receipt.originalFilename}`,
creatorWalletAddress: creatorId,
preferredCurrency: 'XLM',
status: 'active', // Could use 'draft' status if added to entity
});
const savedSplit = await this.splitRepository.save(split);
// Create items from OCR data
if (ocrData.items && ocrData.items.length > 0) {
const items = ocrData.items.map((ocrItem: any) => ({
name: ocrItem.name,
quantity: ocrItem.quantity || 1,
unitPrice: ocrItem.price,
totalPrice: ocrItem.price * (ocrItem.quantity || 1),
category: ocrItem.category,
assignedToIds: [], // Initially unassigned
}));
await this.createItems(savedSplit.id, items);
}
// Link receipt to split
await this.receiptRepository.update(receiptId, { splitId: savedSplit.id });
return this.getSplitById(savedSplit.id);
}
/**
* Update split allocations based on OCR data
*/
async updateSplitAllocations(splitId: string, allocationDto: SplitAllocationDto): Promise<Split> {
const split = await this.getSplitById(splitId);
// Update items assignments
if (allocationDto.itemAssignments) {
for (const assignment of allocationDto.itemAssignments) {
await this.itemRepository.update(assignment.itemId, {
assignedToIds: assignment.participantIds,
});
}
}
// Update participants
if (allocationDto.participants) {
// Clear existing participants
await this.participantRepository.delete({ splitId });
// Create new participants with calculated amounts
await this.createParticipants(splitId, allocationDto.participants);
}
return this.getSplitById(splitId);
}
/**
* Finalize a draft split - calculate and set final amounts
*/
async finalizeDraftSplit(splitId: string, finalizeDto: FinalizeDraftSplitDto): Promise<Split> {
const split = await this.getSplitById(splitId);
const items = await this.itemRepository.find({ where: { splitId } });
// Calculate split using the calculation service
const calculationResult = this.splitCalculationService.calculateSplit({
splitType: finalizeDto.splitType,
subtotal: items.reduce((sum, item) => sum + Number(item.totalPrice), 0),
tax: finalizeDto.tax || 0,
tip: finalizeDto.tip || 0,
participantIds: finalizeDto.participantIds,
items: items.map(item => ({
name: item.name,
price: Number(item.unitPrice),
participantIds: item.assignedToIds.length > 0 ? item.assignedToIds : finalizeDto.participantIds,
})),
percentages: finalizeDto.percentages,
customAmounts: finalizeDto.customAmounts,
tipDistribution: finalizeDto.tipDistribution,
});
// Update split total
await this.splitRepository.update(splitId, {
totalAmount: calculationResult.grandTotal,
});
// Update participants with calculated amounts
for (const share of calculationResult.shares) {
await this.participantRepository.update(
{ splitId, userId: share.participantId },
{ amountOwed: share.total }
);
}
return this.getSplitById(splitId);
}
/**
* Get split by ID with all relations
*/
async getSplitById(splitId: string): Promise<Split> {
const split = await this.splitRepository.findOne({
where: { id: splitId },
relations: ['items', 'participants', 'category'],
});
if (!split) {
throw new NotFoundException(`Split ${splitId} not found`);
}
return split;
}
/**
* Get all splits for a user
*/
async getSplitsByUser(userId: string): Promise<Split[]> {
return this.splitRepository.find({
where: { creatorWalletAddress: userId },
relations: ['items', 'participants'],
});
}
/**
* Update split
*/
async updateSplit(splitId: string, updateSplitDto: UpdateSplitDto): Promise<Split> {
await this.splitRepository.update(splitId, updateSplitDto);
return this.getSplitById(splitId);
}
/**
* Delete split
*/
async deleteSplit(splitId: string): Promise<void> {
const split = await this.getSplitById(splitId);
await this.splitRepository.softDelete(splitId);
}
/**
* Helper method to create participants
*/
private async createParticipants(
splitId: string,
participants: any[],
participantRepo: Repository<Participant> = this.participantRepository,
): Promise<void> {
const participantEntities = participants.map(p =>
participantRepo.create({
splitId,
userId: p.userId,
amountOwed: p.amountOwed || 0,
walletAddress: p.walletAddress,
})
);
await participantRepo.save(participantEntities);
}
/**
* Helper method to create items
*/
private async createItems(
splitId: string,
items: any[],
itemRepo: Repository<Item> = this.itemRepository,
): Promise<void> {
const itemEntities = items.map(item =>
itemRepo.create({
splitId,
name: item.name,
quantity: item.quantity,
unitPrice: item.unitPrice,
totalPrice: item.totalPrice,
category: item.category,
assignedToIds: item.assignedToIds || [],
})
);
await itemRepo.save(itemEntities);
}
}