-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcategorizationService.js
More file actions
489 lines (447 loc) · 12.7 KB
/
categorizationService.js
File metadata and controls
489 lines (447 loc) · 12.7 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
/**
* Transaction Categorization Service
* Handles automatic and manual categorization of transactions
*/
const Transaction = require('../../models/Transaction');
const Category = require('../../models/Category');
const CategoryRule = require('../../models/CategoryRule');
const logger = require('../../utils/logger');
const { Op } = require('sequelize');
/**
* Get all categories for a tenant
* @param {string} userId - User ID
* @param {string} tenantId - Xero tenant ID
* @returns {Array} List of categories
*/
const getCategories = async (userId, tenantId) => {
try {
const categories = await Category.findAll({
where: {
userId,
tenantId,
isActive: true
},
order: [['name', 'ASC']]
});
return categories;
} catch (error) {
logger.error('Error in getCategories:', error);
throw error;
}
};
/**
* Create a new category
* @param {string} userId - User ID
* @param {string} tenantId - Xero tenant ID
* @param {Object} categoryData - Category data
* @returns {Object} Created category
*/
const createCategory = async (userId, tenantId, categoryData) => {
try {
const category = await Category.create({
userId,
tenantId,
name: categoryData.name,
description: categoryData.description,
accountId: categoryData.accountId,
accountCode: categoryData.accountCode,
accountName: categoryData.accountName,
type: categoryData.type,
color: categoryData.color,
icon: categoryData.icon,
parentId: categoryData.parentId,
metadata: categoryData.metadata
});
return category;
} catch (error) {
logger.error('Error in createCategory:', error);
throw error;
}
};
/**
* Get all category rules for a tenant
* @param {string} userId - User ID
* @param {string} tenantId - Xero tenant ID
* @returns {Array} List of category rules
*/
const getCategoryRules = async (userId, tenantId) => {
try {
const rules = await CategoryRule.findAll({
where: {
userId,
tenantId,
isActive: true
},
order: [['priority', 'ASC']]
});
return rules;
} catch (error) {
logger.error('Error in getCategoryRules:', error);
throw error;
}
};
/**
* Create a new category rule
* @param {string} userId - User ID
* @param {string} tenantId - Xero tenant ID
* @param {Object} ruleData - Rule data
* @returns {Object} Created rule
*/
const createCategoryRule = async (userId, tenantId, ruleData) => {
try {
// Validate category exists
const category = await Category.findOne({
where: {
id: ruleData.categoryId,
userId,
tenantId,
isActive: true
}
});
if (!category) {
throw new Error('Category not found');
}
// Create rule
const rule = await CategoryRule.create({
userId,
tenantId,
categoryId: ruleData.categoryId,
name: ruleData.name,
description: ruleData.description,
conditions: ruleData.conditions,
priority: ruleData.priority || 100,
isAutomatic: ruleData.isAutomatic !== undefined ? ruleData.isAutomatic : true
});
return rule;
} catch (error) {
logger.error('Error in createCategoryRule:', error);
throw error;
}
};
/**
* Apply category rules to uncategorized transactions
* @param {string} userId - User ID
* @param {string} tenantId - Xero tenant ID
* @param {Object} options - Options for categorization
* @returns {Object} Categorization results
*/
const applyCategorizationRules = async (userId, tenantId, options = {}) => {
try {
// Get active rules
const rules = await CategoryRule.findAll({
where: {
userId,
tenantId,
isActive: true,
isAutomatic: true
},
order: [['priority', 'ASC']]
});
if (rules.length === 0) {
return { categorized: 0, total: 0 };
}
// Get uncategorized transactions
const transactions = await Transaction.findAll({
where: {
userId,
tenantId,
categoryId: null,
status: {
[Op.ne]: 'VOIDED'
}
},
limit: options.limit || 100
});
if (transactions.length === 0) {
return { categorized: 0, total: 0 };
}
// Apply rules to transactions
let categorizedCount = 0;
for (const transaction of transactions) {
// Find matching rule
const matchingRule = findMatchingRule(transaction, rules);
if (matchingRule) {
// Apply category
await transaction.update({
categoryId: matchingRule.categoryId,
status: 'CATEGORIZED',
metadata: {
...transaction.metadata,
categorization: {
ruleId: matchingRule.id,
ruleName: matchingRule.name,
categoryId: matchingRule.categoryId,
date: new Date()
}
}
});
// Update rule stats
await matchingRule.update({
matchCount: matchingRule.matchCount + 1,
lastMatchedAt: new Date()
});
categorizedCount++;
}
}
logger.info(`Applied categorization rules: ${categorizedCount}/${transactions.length} transactions categorized`);
return {
categorized: categorizedCount,
total: transactions.length
};
} catch (error) {
logger.error('Error in applyCategorizationRules:', error);
throw error;
}
};
/**
* Find matching rule for a transaction
* @param {Object} transaction - Transaction object
* @param {Array} rules - List of category rules
* @returns {Object|null} Matching rule or null
*/
const findMatchingRule = (transaction, rules) => {
for (const rule of rules) {
if (evaluateRuleConditions(transaction, rule.conditions)) {
return rule;
}
}
return null;
};
/**
* Evaluate rule conditions against a transaction
* @param {Object} transaction - Transaction object
* @param {Array} conditions - List of condition objects
* @returns {boolean} True if conditions match
*/
const evaluateRuleConditions = (transaction, conditions) => {
// If no conditions, rule doesn't match
if (!conditions || !Array.isArray(conditions) || conditions.length === 0) {
return false;
}
// All conditions must match (AND logic)
return conditions.every(condition => {
const { field, operator, value } = condition;
// Get field value from transaction
let fieldValue;
switch (field) {
case 'description':
fieldValue = transaction.description;
break;
case 'reference':
fieldValue = transaction.reference;
break;
case 'amount':
fieldValue = transaction.amount;
break;
case 'contactName':
fieldValue = transaction.contactName;
break;
case 'accountName':
fieldValue = transaction.accountName;
break;
default:
// Try to get from metadata
if (transaction.metadata && field.startsWith('metadata.')) {
const metaField = field.substring(9);
fieldValue = transaction.metadata[metaField];
} else {
fieldValue = transaction[field];
}
}
// If field doesn't exist, condition doesn't match
if (fieldValue === undefined || fieldValue === null) {
return false;
}
// Evaluate based on operator
switch (operator) {
case 'equals':
return fieldValue === value;
case 'notEquals':
return fieldValue !== value;
case 'contains':
return typeof fieldValue === 'string' && fieldValue.toLowerCase().includes(value.toLowerCase());
case 'notContains':
return typeof fieldValue === 'string' && !fieldValue.toLowerCase().includes(value.toLowerCase());
case 'startsWith':
return typeof fieldValue === 'string' && fieldValue.toLowerCase().startsWith(value.toLowerCase());
case 'endsWith':
return typeof fieldValue === 'string' && fieldValue.toLowerCase().endsWith(value.toLowerCase());
case 'greaterThan':
return typeof fieldValue === 'number' && fieldValue > value;
case 'lessThan':
return typeof fieldValue === 'number' && fieldValue < value;
case 'greaterThanOrEqual':
return typeof fieldValue === 'number' && fieldValue >= value;
case 'lessThanOrEqual':
return typeof fieldValue === 'number' && fieldValue <= value;
case 'in':
return Array.isArray(value) && value.includes(fieldValue);
case 'notIn':
return Array.isArray(value) && !value.includes(fieldValue);
default:
return false;
}
});
};
/**
* Manually categorize a transaction
* @param {string} userId - User ID
* @param {string} tenantId - Xero tenant ID
* @param {string} transactionId - Transaction ID
* @param {string} categoryId - Category ID
* @returns {Object} Updated transaction
*/
const categorizeTransaction = async (userId, tenantId, transactionId, categoryId) => {
try {
// Validate category exists
const category = await Category.findOne({
where: {
id: categoryId,
userId,
tenantId,
isActive: true
}
});
if (!category) {
throw new Error('Category not found');
}
// Get transaction
const transaction = await Transaction.findOne({
where: {
id: transactionId,
userId,
tenantId
}
});
if (!transaction) {
throw new Error('Transaction not found');
}
// Update transaction
await transaction.update({
categoryId,
status: 'CATEGORIZED',
metadata: {
...transaction.metadata,
categorization: {
categoryId,
categoryName: category.name,
date: new Date(),
method: 'MANUAL'
}
}
});
logger.info(`Manually categorized transaction ${transactionId} with category ${categoryId}`);
return transaction;
} catch (error) {
logger.error('Error in categorizeTransaction:', error);
throw error;
}
};
/**
* Get categorization statistics
* @param {string} userId - User ID
* @param {string} tenantId - Xero tenant ID
* @param {Object} options - Options for statistics
* @returns {Object} Categorization statistics
*/
const getCategorizationStats = async (userId, tenantId, options = {}) => {
try {
// Get date range
const days = options.days || 30;
const toDate = new Date();
const fromDate = new Date();
fromDate.setDate(fromDate.getDate() - days);
// Count total transactions
const totalCount = await Transaction.count({
where: {
userId,
tenantId,
status: {
[Op.ne]: 'VOIDED'
},
date: {
[Op.between]: [fromDate, toDate]
}
}
});
// Count categorized transactions
const categorizedCount = await Transaction.count({
where: {
userId,
tenantId,
categoryId: {
[Op.ne]: null
},
status: {
[Op.ne]: 'VOIDED'
},
date: {
[Op.between]: [fromDate, toDate]
}
}
});
// Calculate percentage
const categorizedPercentage = totalCount > 0
? Math.round((categorizedCount / totalCount) * 100)
: 0;
// Get top categories
const topCategories = await Transaction.findAll({
attributes: [
'categoryId',
[sequelize.fn('COUNT', sequelize.col('id')), 'count'],
[sequelize.fn('SUM', sequelize.col('amount')), 'total']
],
where: {
userId,
tenantId,
categoryId: {
[Op.ne]: null
},
status: {
[Op.ne]: 'VOIDED'
},
date: {
[Op.between]: [fromDate, toDate]
}
},
group: ['categoryId'],
order: [[sequelize.literal('count'), 'DESC']],
limit: 5,
include: [{
model: Category,
attributes: ['name', 'type', 'color']
}]
});
return {
totalTransactions: totalCount,
categorizedTransactions: categorizedCount,
uncategorizedTransactions: totalCount - categorizedCount,
categorizedPercentage,
topCategories: topCategories.map(tc => ({
categoryId: tc.categoryId,
name: tc.Category.name,
type: tc.Category.type,
color: tc.Category.color,
count: tc.get('count'),
total: tc.get('total')
})),
period: {
fromDate,
toDate,
days
}
};
} catch (error) {
logger.error('Error in getCategorizationStats:', error);
throw error;
}
};
module.exports = {
getCategories,
createCategory,
getCategoryRules,
createCategoryRule,
applyCategorizationRules,
categorizeTransaction,
getCategorizationStats
};