-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathreconciliation.go
1867 lines (1669 loc) · 71.3 KB
/
reconciliation.go
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
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright 2024 Blnk Finance Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package blnk
import (
"bufio"
"bytes"
"context"
"encoding/csv"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"math"
"mime"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
"github.com/jerry-enebeli/blnk/config"
"github.com/jerry-enebeli/blnk/database"
"github.com/jerry-enebeli/blnk/internal/notification"
"github.com/jerry-enebeli/blnk/model"
"github.com/texttheater/golang-levenshtein/levenshtein"
"github.com/wacul/ptr"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/trace"
)
// Status constants representing the various states a process can be in.
const (
StatusStarted = "started" // Indicates the process has started.
StatusInProgress = "in_progress" // Indicates the process is ongoing.
StatusCompleted = "completed" // Indicates the process is finished successfully.
StatusFailed = "failed" // Indicates the process has failed.
)
// transactionProcessor represents the processor for handling reconciliation-related transactions.
// Fields:
// - reconciliation: The reconciliation object that holds transaction data to be processed.
// - progress: Tracks the progress of the reconciliation process.
// - reconciler: A function that handles the reconciliation logic for a batch of transactions.
// - matches: Counter for transactions that have been successfully matched.
// - unmatched: Counter for transactions that couldn't be matched.
// - datasource: The interface for database operations, enabling interaction with the data source.
// - progressSaveCount: The number of transactions processed before saving progress.
type transactionProcessor struct {
reconciliation model.Reconciliation
progress model.ReconciliationProgress
reconciler reconciler
matches int
unmatched int
datasource database.IDataSource
progressSaveCount int
blnk *Blnk
}
// reconciler defines the function type for reconciling a batch of transactions.
// It accepts a context, and a slice of transactions, and returns the matched transactions and unmatched ones.
type reconciler func(ctx context.Context, txns []*model.Transaction) ([]model.Match, []string)
// detectFileType attempts to detect the file type based on its extension or content.
// If the file extension can identify the type, it returns that, otherwise, it inspects the content of the file.
// Parameters:
// - data: The file content as a byte slice.
// - filename: The name of the file to detect by extension.
// Returns:
// - string: The detected file type (MIME type).
// - error: If content detection fails.
func detectFileType(data []byte, filename string) (string, error) {
// Attempt to detect file type by its extension first.
if mimeType := detectByExtension(filename); mimeType != "" {
return mimeType, nil
}
// If detection by extension fails, analyze the content.
return detectByContent(data)
}
// detectByExtension detects the MIME type by the file extension.
// Parameters:
// - filename: The name of the file to detect by extension.
// Returns:
// - string: The MIME type corresponding to the file extension.
func detectByExtension(filename string) string {
ext := strings.ToLower(filepath.Ext(filename)) // Extract and lower the file extension.
return mime.TypeByExtension(ext) // Use the standard library to get MIME type.
}
// detectByContent detects the MIME type based on the content of the file.
// Parameters:
// - data: The file content as a byte slice.
// Returns:
// - string: The detected MIME type.
// - error: If content analysis fails.
func detectByContent(data []byte) (string, error) {
mimeType := http.DetectContentType(data) // Detect content type by analyzing the first 512 bytes.
switch mimeType {
case "application/octet-stream", "text/plain":
// If detected as binary or plain text, analyze the content further.
return analyzeTextContent(data)
case "text/csv; charset=utf-8":
// Directly return if CSV is detected.
return "text/csv", nil
default:
return mimeType, nil // Return detected MIME type.
}
}
// analyzeTextContent further inspects text-based content to differentiate between CSV, JSON, or plain text.
// Parameters:
// - data: The file content as a byte slice.
// Returns:
// - string: The detected MIME type (either CSV, JSON, or plain text).
// - error: If content analysis fails.
func analyzeTextContent(data []byte) (string, error) {
if looksLikeCSV(data) {
return "text/csv", nil
}
if json.Valid(data) {
return "application/json", nil
}
return "text/plain", nil // Default to plain text if no other format matches.
}
// looksLikeCSV checks whether the provided data looks like a CSV file.
// It checks for multiple lines and ensures they have the same number of fields (based on commas).
// Parameters:
// - data: The file content as a byte slice.
// Returns:
// - bool: True if the content seems like a CSV file, otherwise false.
func looksLikeCSV(data []byte) bool {
lines := bytes.Split(data, []byte("\n")) // Split the content into lines.
if len(lines) < 2 {
return false // Require at least two lines for CSV.
}
// Count the number of fields (columns) in the first line.
fields := bytes.Count(lines[0], []byte(",")) + 1
// Ensure all subsequent lines have the same number of fields.
for _, line := range lines[1:] {
if len(line) == 0 {
continue // Skip empty lines.
}
if bytes.Count(line, []byte(","))+1 != fields {
return false // Return false if field count doesn't match.
}
}
return fields > 1 // Return true if there are at least two fields.
}
// parseFloat parses a string into a float64 value.
// If the string is not a valid float, it returns 0.
// Parameters:
// - s: The string to parse.
// Returns:
// - float64: The parsed float value or 0 if parsing fails.
func parseFloat(s string) float64 {
f, err := strconv.ParseFloat(s, 64)
if err != nil {
return 0 // Return 0 if parsing fails.
}
return f
}
// parseTime parses a string into a time.Time object in RFC3339 format.
// If parsing fails, it returns a zero-value time.Time object.
// Parameters:
// - s: The string to parse into a timestamp.
// Returns:
// - time.Time: The parsed time object or zero time if parsing fails.
func parseTime(s string) time.Time {
t, err := time.Parse(time.RFC3339, s)
if err != nil {
return time.Time{} // Return zero time if parsing fails.
}
return t
}
// contains checks whether a slice contains a specific string.
// Parameters:
// - slice: The slice to check.
// - item: The item to look for in the slice.
// Returns:
// - bool: True if the item is found in the slice, otherwise false.
func contains(slice []string, item string) bool {
for _, a := range slice {
if a == item {
return true
}
}
return false
}
// parseAndStoreCSV reads and processes a CSV file from an io.Reader, parsing each row and storing the corresponding transactions.
// Parameters:
// - ctx: The context for controlling execution.
// - uploadID: The unique ID of the current upload.
// - source: The source of the external data.
// - reader: An io.Reader for reading the CSV data.
// Returns:
// - error: If parsing or storing fails.
func (s *Blnk) parseAndStoreCSV(ctx context.Context, uploadID, source string, reader io.Reader) error {
csvReader := csv.NewReader(bufio.NewReader(reader))
// Read the header row to determine column mapping.
headers, err := csvReader.Read()
if err != nil {
return fmt.Errorf("error reading CSV headers: %w", err)
}
// Create a column map to associate column names with their indices.
columnMap, err := createColumnMap(headers)
if err != nil {
return err
}
// Process the CSV rows based on the column map.
return s.processCSVRows(ctx, uploadID, source, csvReader, columnMap)
}
// processCSVRows reads and processes each row in the CSV file, parsing the fields and storing the transactions.
// Parameters:
// - ctx: The context for controlling execution.
// - uploadID: The unique ID of the current upload.
// - source: The source of the external data.
// - csvReader: The CSV reader for reading rows.
// - columnMap: The map associating column names with their indices.
// Returns:
// - error: If parsing or storing any row fails.
func (s *Blnk) processCSVRows(ctx context.Context, uploadID, source string, csvReader *csv.Reader, columnMap map[string]int) error {
var errs []error // To accumulate any errors encountered during processing.
rowNum := 1 // Row number starts at 1 to account for the header row.
for {
record, err := csvReader.Read() // Read the next row.
if err == io.EOF {
break // Stop processing if end of file is reached.
}
if err != nil {
errs = append(errs, fmt.Errorf("error reading row %d: %w", rowNum, err))
continue // Continue processing other rows even if this row fails.
}
rowNum++ // Increment row number.
// Parse the row into an ExternalTransaction object.
externalTxn, err := parseExternalTransaction(record, columnMap, source)
if err != nil {
errs = append(errs, fmt.Errorf("error parsing row %d: %w", rowNum, err))
continue // Skip this row if parsing fails.
}
// Store the parsed transaction.
if err := s.storeExternalTransaction(ctx, uploadID, externalTxn); err != nil {
errs = append(errs, fmt.Errorf("error storing transaction from row %d: %w", rowNum, err))
}
// Check for context cancellation every 1000 rows.
if rowNum%1000 == 0 {
select {
case <-ctx.Done():
return ctx.Err() // Return if the context is cancelled.
default:
}
}
}
if len(errs) > 0 {
// If there were errors, return a summary of them.
return fmt.Errorf("encountered %d errors while processing CSV: %v", len(errs), errs)
}
return nil
}
// createColumnMap creates a map of column names to their indices based on the headers row of a CSV file.
// Ensures that required columns (ID, Amount, Date) are present.
// Parameters:
// - headers: The slice of column headers from the CSV file.
// Returns:
// - map[string]int: A map of column names to their respective indices.
// - error: If any required column is missing.
func createColumnMap(headers []string) (map[string]int, error) {
requiredColumns := []string{"ID", "Amount", "Date"} // Columns that must be present in the CSV.
columnMap := make(map[string]int)
// Map each column name to its index.
for i, header := range headers {
columnMap[strings.ToLower(strings.TrimSpace(header))] = i
}
// Ensure all required columns are present.
for _, col := range requiredColumns {
if _, exists := columnMap[strings.ToLower(col)]; !exists {
return nil, fmt.Errorf("required column '%s' not found in CSV", col)
}
}
return columnMap, nil
}
// parseExternalTransaction parses a row of the CSV file into an ExternalTransaction object.
// Parameters:
// - record: The slice of strings representing the row's fields.
// - columnMap: A map of column names to their indices.
// - source: The source of the external data.
// Returns:
// - model.ExternalTransaction: The parsed ExternalTransaction object.
// - error: If parsing fails due to missing or invalid data.
func parseExternalTransaction(record []string, columnMap map[string]int, source string) (model.ExternalTransaction, error) {
if len(record) != len(columnMap) {
// Return an error if the number of fields in the row doesn't match the column map.
return model.ExternalTransaction{}, fmt.Errorf("incorrect number of fields in record")
}
// Get required fields from the record and parse them into appropriate types.
id, err := getRequiredField(record, columnMap, "id")
if err != nil {
return model.ExternalTransaction{}, err
}
amountStr, err := getRequiredField(record, columnMap, "amount")
if err != nil {
return model.ExternalTransaction{}, err
}
currency, err := getRequiredField(record, columnMap, "currency")
if err != nil {
return model.ExternalTransaction{}, err
}
amount := parseFloat(amountStr)
if err != nil {
return model.ExternalTransaction{}, fmt.Errorf("invalid amount: %w", err)
}
reference, err := getRequiredField(record, columnMap, "reference")
if err != nil {
return model.ExternalTransaction{}, err
}
description, err := getRequiredField(record, columnMap, "description")
if err != nil {
return model.ExternalTransaction{}, err
}
dateStr, err := getRequiredField(record, columnMap, "date")
if err != nil {
return model.ExternalTransaction{}, err
}
date := parseTime(dateStr)
if err != nil {
return model.ExternalTransaction{}, fmt.Errorf("invalid date: %w", err)
}
// Return the parsed ExternalTransaction object.
return model.ExternalTransaction{
ID: id,
Amount: amount,
Currency: currency,
Reference: reference,
Description: description,
Date: date,
Source: source,
}, nil
}
// getRequiredField retrieves a field from a CSV record, ensuring it is not empty.
// Parameters:
// - record: The slice of strings representing the row's fields.
// - columnMap: A map of column names to their indices.
// - field: The name of the field to retrieve.
// Returns:
// - string: The value of the field.
// - error: If the field is missing or empty.
func getRequiredField(record []string, columnMap map[string]int, field string) (string, error) {
if index, exists := columnMap[field]; exists && index < len(record) {
value := strings.TrimSpace(record[index])
if value == "" {
return "", fmt.Errorf("required field '%s' is empty", field)
}
return value, nil
}
return "", fmt.Errorf("required field '%s' not found in record", field)
}
// parseAndStoreJSON parses and stores transactions from a JSON file.
// Parameters:
// - ctx: The context for controlling execution.
// - uploadID: The unique ID of the current upload.
// - source: The source of the external data.
// - reader: An io.Reader for reading the JSON data.
// Returns:
// - int: The number of parsed transactions.
// - error: If parsing or storing fails.
func (s *Blnk) parseAndStoreJSON(ctx context.Context, uploadID, source string, reader io.Reader) (int, error) {
decoder := json.NewDecoder(reader)
var transactions []model.ExternalTransaction
// Decode the JSON data into a slice of ExternalTransaction objects.
if err := decoder.Decode(&transactions); err != nil {
return 0, err
}
// Store each parsed transaction.
for _, txn := range transactions {
txn.Source = source
if err := s.storeExternalTransaction(ctx, uploadID, txn); err != nil {
return 0, err
}
}
return len(transactions), nil
}
// UploadExternalData handles the process of uploading external data by detecting file type, parsing, and storing it.
// Parameters:
// - ctx: The context for controlling execution.
// - source: The source of the external data.
// - reader: An io.Reader for reading the data.
// - filename: The name of the file being uploaded.
// Returns:
// - string: The ID of the upload.
// - int: The total number of records processed.
// - error: If any step of the process fails.
func (s *Blnk) UploadExternalData(ctx context.Context, source string, reader io.Reader, filename string) (string, int, error) {
uploadID := model.GenerateUUIDWithSuffix("upload") // Generate a unique ID for the upload.
// Create a temporary file and populate it with the uploaded data.
tempFile, err := s.createAndPopulateTempFile(filename, reader)
if err != nil {
return "", 0, err
}
defer s.cleanupTempFile(tempFile) // Ensure the temp file is cleaned up after processing.
// Detect the file type (CSV or JSON) based on the content.
fileType, err := s.detectFileTypeFromTempFile(tempFile, filename)
if err != nil {
return "", 0, err
}
// Parse and store the data based on its file type.
total, err := s.parseAndStoreData(ctx, uploadID, source, tempFile, fileType)
if err != nil {
return "", 0, err
}
return uploadID, total, nil
}
// createAndPopulateTempFile creates a temporary file and writes the uploaded data to it.
// Parameters:
// - filename: The original filename of the upload.
// - reader: An io.Reader for reading the upload data.
// Returns:
// - *os.File: The created temporary file.
// - error: If file creation or data writing fails.
func (s *Blnk) createAndPopulateTempFile(filename string, reader io.Reader) (*os.File, error) {
// Create a new temporary file with a name based on the original filename.
tempFile, err := s.createTempFile(filename)
if err != nil {
return nil, fmt.Errorf("error creating temporary file: %w", err)
}
// Copy the uploaded data into the temporary file.
if _, err := io.Copy(tempFile, reader); err != nil {
return nil, fmt.Errorf("error copying upload data: %w", err)
}
// Reset the file pointer to the beginning for subsequent reading.
if _, err := tempFile.Seek(0, 0); err != nil {
return nil, fmt.Errorf("error seeking temporary file: %w", err)
}
return tempFile, nil
}
// detectFileTypeFromTempFile detects the file type by reading the first 512 bytes from the temporary file.
// Parameters:
// - tempFile: The temporary file containing the uploaded data.
// - filename: The original filename of the upload.
// Returns:
// - string: The detected file type (MIME type).
// - error: If file type detection fails.
func (s *Blnk) detectFileTypeFromTempFile(tempFile *os.File, filename string) (string, error) {
header := make([]byte, 512)
// Read the first 512 bytes of the file (enough for MIME type detection).
if _, err := tempFile.Read(header); err != nil && err != io.EOF {
return "", fmt.Errorf("error reading file header: %w", err)
}
// Detect the file type based on the content.
fileType, err := detectFileType(header, filename)
if err != nil {
return "", fmt.Errorf("error detecting file type: %w", err)
}
// Reset the file pointer to the beginning for subsequent reading.
if _, err := tempFile.Seek(0, 0); err != nil {
return "", fmt.Errorf("error seeking temporary file: %w", err)
}
return fileType, nil
}
// parseAndStoreData parses and stores data based on the file type (either CSV or JSON).
// Parameters:
// - ctx: The context for controlling execution.
// - uploadID: The unique ID of the current upload.
// - source: The source of the external data.
// - reader: An io.Reader for reading the data.
// - fileType: The detected MIME type of the file.
// Returns:
// - int: The total number of records processed.
// - error: If parsing or storing fails.
func (s *Blnk) parseAndStoreData(ctx context.Context, uploadID, source string, reader io.Reader, fileType string) (int, error) {
switch fileType {
case "text/csv", "text/csv; charset=utf-8":
// Handle CSV files.
err := s.parseAndStoreCSV(ctx, uploadID, source, reader)
return 0, err // CSV parsing doesn't return a count.
case "application/json":
// Handle JSON files.
return s.parseAndStoreJSON(ctx, uploadID, source, reader)
default:
// Return an error if the file type is unsupported.
return 0, fmt.Errorf("unsupported file type: %s", fileType)
}
}
// createTempFile creates a new temporary file for storing the uploaded data.
// Parameters:
// - originalFilename: The original filename of the upload.
// Returns:
// - *os.File: The created temporary file.
// - error: If the temporary file cannot be created.
func (s *Blnk) createTempFile(originalFilename string) (*os.File, error) {
// Create the directory for temporary files if it doesn't exist.
tempDir := filepath.Join(os.TempDir(), "blnk_uploads")
if err := os.MkdirAll(tempDir, 0755); err != nil {
return nil, fmt.Errorf("error creating temporary directory: %w", err)
}
// Create a temporary file with a prefix based on the original filename.
prefix := fmt.Sprintf("%s_", filepath.Base(originalFilename))
tempFile, err := os.CreateTemp(tempDir, prefix)
if err != nil {
return nil, fmt.Errorf("error creating temporary file: %w", err)
}
return tempFile, nil
}
// cleanupTempFile removes the specified temporary file from the filesystem.
// Parameters:
// - file: The temporary file to remove.
func (s *Blnk) cleanupTempFile(file *os.File) {
if file != nil {
filename := file.Name() // Get the file name.
file.Close() // Close the file before removing it.
if err := os.Remove(filename); err != nil {
// Log any errors encountered during file removal.
log.Printf("Error removing temporary file %s: %v", filename, err)
}
}
}
// storeExternalTransaction stores an external transaction in the datasource.
// Parameters:
// - ctx: The context for controlling execution.
// - uploadID: The unique ID of the current upload.
// - txn: The external transaction to store.
// Returns:
// - error: If storing the transaction fails.
func (s *Blnk) storeExternalTransaction(ctx context.Context, uploadID string, txn model.ExternalTransaction) error {
return s.datasource.RecordExternalTransaction(ctx, &txn, uploadID)
}
// postReconciliationActions queues the indexing of reconciliation data in the background.
// This allows the reconciliation to be indexed without blocking the main process.
// Parameters:
// - ctx: The context for controlling execution.
// - reconciliation: The reconciliation object to be indexed.
func (l *Blnk) postReconciliationActions(_ context.Context, reconciliation model.Reconciliation) {
go func() {
// Queue the reconciliation data for indexing.
err := l.queue.queueIndexData(reconciliation.ReconciliationID, "reconciliations", reconciliation)
if err != nil {
// If there is an error, notify through the notification system.
notification.NotifyError(err)
}
}()
}
// StartReconciliation initiates the reconciliation process by creating a new reconciliation entry and starting the
// process asynchronously. The process is detached to run in the background.
// Parameters:
// - ctx: The context controlling the reconciliation process.
// - uploadID: The ID of the uploaded transaction file to reconcile.
// - strategy: The reconciliation strategy to be used (e.g., "one_to_one").
// - groupCriteria: Criteria to group transactions (optional).
// - matchingRuleIDs: The IDs of the rules used for matching transactions.
// - isDryRun: If true, the reconciliation will not commit changes (useful for testing).
// Returns:
// - string: The ID of the reconciliation process.
// - error: If the reconciliation fails to start.
func (s *Blnk) StartReconciliation(ctx context.Context, uploadID string, strategy string, groupCriteria string, matchingRuleIDs []string, isDryRun bool) (string, error) {
// Generate a unique ID for the reconciliation.
reconciliationID := model.GenerateUUIDWithSuffix("recon")
// Initialize a new reconciliation object with the provided parameters.
reconciliation := model.Reconciliation{
ReconciliationID: reconciliationID,
UploadID: uploadID,
Status: StatusStarted,
StartedAt: time.Now(),
IsDryRun: isDryRun,
}
// Record the reconciliation in the data source (e.g., database).
if err := s.datasource.RecordReconciliation(ctx, &reconciliation); err != nil {
return "", err
}
// Detach the context to allow the reconciliation process to run in the background.
detachedCtx := context.Background()
ctxWithTrace := trace.ContextWithSpan(detachedCtx, trace.SpanFromContext(ctx))
// Start the reconciliation process asynchronously.
go func() {
err := s.processReconciliation(ctxWithTrace, reconciliation, strategy, groupCriteria, matchingRuleIDs)
if err != nil {
// If an error occurs during the reconciliation, log it and update the reconciliation status to "failed".
log.Printf("Error in reconciliation process: %v", err)
err := s.datasource.UpdateReconciliationStatus(ctxWithTrace, reconciliationID, StatusFailed, 0, 0)
if err != nil {
log.Printf("Error updating reconciliation status: %v", err)
}
}
}()
return reconciliationID, nil
}
// StartInstantReconciliation initiates a reconciliation process directly with provided transactions
// instead of loading them from an uploaded file.
// Parameters:
// - ctx: The context controlling the reconciliation process.
// - externalTransactions: The array of external transactions to reconcile.
// - strategy: The reconciliation strategy to be used (e.g., "one_to_one").
// - groupCriteria: Criteria to group transactions (optional).
// - matchingRuleIDs: The IDs of the rules used for matching transactions.
// - isDryRun: If true, the reconciliation will not commit changes (useful for testing).
// Returns:
// - string: The ID of the reconciliation process.
// - error: If the reconciliation fails to start.
func (s *Blnk) StartInstantReconciliation(ctx context.Context, externalTransactions []model.ExternalTransaction,
strategy string, groupCriteria string, matchingRuleIDs []string, isDryRun bool) (string, error) {
// Generate a unique ID for the reconciliation
reconciliationID := model.GenerateUUIDWithSuffix("recon")
// Use a temporary ID for the transactions
tempID := model.GenerateUUIDWithSuffix("instant")
// Initialize a new reconciliation object with the provided parameters
reconciliation := model.Reconciliation{
ReconciliationID: reconciliationID,
UploadID: tempID,
Status: StatusStarted,
StartedAt: time.Now(),
IsDryRun: isDryRun,
}
// Record the reconciliation in the data source
if err := s.datasource.RecordReconciliation(ctx, &reconciliation); err != nil {
return "", err
}
// Store the provided transactions in the database with the temporary ID
for _, txn := range externalTransactions {
if err := s.storeExternalTransaction(ctx, tempID, txn); err != nil {
// Log error and update reconciliation status
log.Printf("Error storing transaction: %v", err)
err := s.datasource.UpdateReconciliationStatus(ctx, reconciliationID, StatusFailed, 0, 0)
if err != nil {
log.Printf("Error updating reconciliation status: %v", err)
return "", fmt.Errorf("failed to store external transaction: %w", err)
}
return "", fmt.Errorf("failed to store external transaction: %w", err)
}
}
// Detach the context to allow the reconciliation process to run in the background
detachedCtx := context.Background()
ctxWithTrace := trace.ContextWithSpan(detachedCtx, trace.SpanFromContext(ctx))
// Start the reconciliation process asynchronously
go func() {
err := s.processReconciliation(ctxWithTrace, reconciliation, strategy, groupCriteria, matchingRuleIDs)
if err != nil {
// If an error occurs during the reconciliation, log it and update the reconciliation status to "failed"
log.Printf("Error in instant reconciliation process: %v", err)
err := s.datasource.UpdateReconciliationStatus(ctxWithTrace, reconciliationID, StatusFailed, 0, 0)
if err != nil {
log.Printf("Error updating reconciliation status: %v", err)
}
}
}()
return reconciliationID, nil
}
// GetReconciliation retrieves a reconciliation by its ID.
// Parameters:
// - ctx: The context controlling the request.
// - reconciliationID: The ID of the reconciliation to retrieve.
// Returns:
// - *model.Reconciliation: The retrieved reconciliation object.
// - error: If the reconciliation cannot be found or if retrieval fails.
func (s *Blnk) GetReconciliation(ctx context.Context, reconciliationID string) (*model.Reconciliation, error) {
reconciliation, err := s.datasource.GetReconciliation(ctx, reconciliationID)
if err != nil {
return nil, fmt.Errorf("failed to retrieve reconciliation: %w", err)
}
return reconciliation, nil
}
// matchesRules checks whether an external transaction matches a group transaction based on specified matching rules.
// It iterates through the rules and criteria, evaluating whether the transactions meet the conditions for a match.
// Parameters:
// - externalTxn: The external transaction to match.
// - groupTxn: The internal or group transaction to compare against.
// - rules: A list of matching rules containing criteria to apply.
// Returns:
// - bool: True if the transactions match based on the rules, otherwise false.
func (s *Blnk) matchesRules(externalTxn *model.Transaction, groupTxn model.Transaction, rules []model.MatchingRule) bool {
for _, rule := range rules {
allCriteriaMet := true
// Iterate through each rule's criteria to check if all conditions are satisfied.
for _, criteria := range rule.Criteria {
var criterionMet bool
// Check each field specified in the criteria.
switch criteria.Field {
case "amount":
// Compare amounts between the external and group transactions.
criterionMet = s.matchesGroupAmount(externalTxn.Amount, groupTxn.Amount, criteria)
case "date":
// Compare the dates of the transactions.
criterionMet = s.matchesGroupDate(externalTxn.CreatedAt, groupTxn.CreatedAt, criteria)
case "description":
// Compare the description fields for a match.
criterionMet = s.matchesString(externalTxn.Description, groupTxn.Description, criteria)
case "reference":
// Compare the transaction references for a match.
criterionMet = s.matchesString(externalTxn.Reference, groupTxn.Reference, criteria)
case "currency":
// Compare the currencies of the transactions.
criterionMet = s.matchesCurrency(externalTxn.Currency, groupTxn.Currency, criteria)
}
// If any criterion is not met, mark the rule as not satisfied.
if !criterionMet {
allCriteriaMet = false
break
}
}
// If all criteria are satisfied, return true (the transactions match).
if allCriteriaMet {
return true
}
}
return false
}
// loadReconciliationProgress retrieves the progress of a reconciliation process.
// Parameters:
// - ctx: The context controlling the request.
// - reconciliationID: The ID of the reconciliation to load progress for.
// Returns:
// - model.ReconciliationProgress: The current progress of the reconciliation.
// - error: If the progress cannot be retrieved.
func (s *Blnk) loadReconciliationProgress(ctx context.Context, reconciliationID string) (model.ReconciliationProgress, error) {
return s.datasource.LoadReconciliationProgress(ctx, reconciliationID)
}
// processReconciliation manages the full reconciliation process by executing each step: updating the status,
// fetching rules, processing transactions, and finalizing the reconciliation.
// Parameters:
// - ctx: The context controlling the process.
// - reconciliation: The reconciliation object representing the current reconciliation.
// - strategy: The reconciliation strategy (e.g., one-to-one, one-to-many).
// - groupCriteria: Criteria for grouping transactions (optional).
// - matchingRuleIDs: A list of matching rule IDs to apply during the process.
// Returns:
// - error: If any step in the reconciliation process fails.
func (s *Blnk) processReconciliation(ctx context.Context, reconciliation model.Reconciliation, strategy string, groupCriteria string, matchingRuleIDs []string) error {
// Update the reconciliation status to "in progress".
if err := s.updateReconciliationStatus(ctx, reconciliation.ReconciliationID, StatusInProgress); err != nil {
return fmt.Errorf("failed to update reconciliation status: %w", err)
}
// Retrieve the matching rules that apply to the reconciliation.
matchingRules, err := s.getMatchingRules(ctx, matchingRuleIDs)
if err != nil {
return fmt.Errorf("failed to get matching rules: %w", err)
}
// Initialize the reconciliation progress.
progress, err := s.initializeReconciliationProgress(ctx, reconciliation.ReconciliationID)
if err != nil {
return fmt.Errorf("failed to initialize reconciliation progress: %w", err)
}
// Create the reconciler function based on the strategy and rules.
reconciler := s.createReconciler(strategy, groupCriteria, matchingRules)
// Create a transaction processor to handle the reconciliation logic.
processor := s.createTransactionProcessor(reconciliation, progress, reconciler)
// Process the transactions for reconciliation based on the chosen strategy.
err = s.processTransactions(ctx, reconciliation.UploadID, processor, strategy)
if err != nil {
return fmt.Errorf("failed to process transactions: %w", err)
}
// After processing, retrieve the results (matched and unmatched counts).
matched, unmatched := processor.getResults()
// Finalize the reconciliation by updating the status and recording the results.
return s.finalizeReconciliation(ctx, reconciliation, matched, unmatched)
}
// updateReconciliationStatus updates the status of a reconciliation process in the database.
// Parameters:
// - ctx: The context controlling the request.
// - reconciliationID: The ID of the reconciliation.
// - status: The new status to set.
// Returns:
// - error: If the status update fails.
func (s *Blnk) updateReconciliationStatus(ctx context.Context, reconciliationID, status string) error {
return s.datasource.UpdateReconciliationStatus(ctx, reconciliationID, status, 0, 0)
}
// initializeReconciliationProgress initializes or retrieves the progress of a reconciliation.
// If no progress exists, it creates a new progress entry.
// Parameters:
// - ctx: The context controlling the request.
// - reconciliationID: The ID of the reconciliation.
// Returns:
// - model.ReconciliationProgress: The current or newly initialized progress.
// - error: If the initialization or retrieval fails.
func (s *Blnk) initializeReconciliationProgress(ctx context.Context, reconciliationID string) (model.ReconciliationProgress, error) {
progress, err := s.loadReconciliationProgress(ctx, reconciliationID)
if err != nil {
log.Printf("Error loading reconciliation progress: %v", err)
return model.ReconciliationProgress{}, nil
}
return progress, nil
}
// createReconciler creates a reconciler function based on the specified strategy, group criteria, and matching rules.
// Parameters:
// - strategy: The reconciliation strategy (e.g., one-to-one, one-to-many).
// - groupCriteria: Criteria for grouping transactions (optional).
// - matchingRules: A list of matching rules to apply during reconciliation.
// Returns:
// - reconciler: A function that performs reconciliation according to the specified strategy.
func (s *Blnk) createReconciler(strategy string, groupCriteria string, matchingRules []model.MatchingRule) reconciler {
return func(ctx context.Context, txns []*model.Transaction) ([]model.Match, []string) {
switch strategy {
case "one_to_one":
// Perform one-to-one reconciliation.
return s.oneToOneReconciliation(ctx, txns, matchingRules)
case "one_to_many":
// Perform one-to-many reconciliation.
return s.oneToManyReconciliation(ctx, txns, groupCriteria, matchingRules, false)
case "many_to_one":
// Perform many-to-one reconciliation.
return s.manyToOneReconciliation(ctx, txns, groupCriteria, matchingRules, true)
default:
// Log unsupported strategies.
log.Printf("Unsupported reconciliation strategy: %s", strategy)
return nil, nil
}
}
}
// createTransactionProcessor creates a new transaction processor for the reconciliation.
// Parameters:
// - reconciliation: The reconciliation object representing the current process.
// - progress: The current progress of the reconciliation.
// - reconciler: The reconciler function to apply.
// Returns:
// - *transactionProcessor: The created transaction processor.
func (s *Blnk) createTransactionProcessor(reconciliation model.Reconciliation, progress model.ReconciliationProgress, reconciler func(ctx context.Context, txns []*model.Transaction) ([]model.Match, []string)) *transactionProcessor {
conf, err := config.Fetch()
if err != nil {
log.Printf("Error fetching configuration: %v", err)
}
return &transactionProcessor{
reconciliation: reconciliation,
progress: progress,
reconciler: reconciler,
datasource: s.datasource,
progressSaveCount: conf.Reconciliation.ProgressInterval,
blnk: s,
}
}
// process handles individual transaction processing, applying the reconciliation logic and recording results.
// It also updates internal transaction metadata asynchronously when matches are found.
// Parameters:
// - ctx: The context controlling the request.
// - txn: The transaction to process.
// Returns:
// - error: If processing or recording results fails.
func (tp *transactionProcessor) process(ctx context.Context, txn *model.Transaction) error {
// Reconcile the batch of transactions and get matches and unmatched transactions.
batchMatches, batchUnmatched := tp.reconciler(ctx, []*model.Transaction{txn})
// Increment the counters for matched and unmatched transactions.
tp.matches += len(batchMatches)
tp.unmatched += len(batchUnmatched)
// If the reconciliation is not a dry run, record the matches and unmatched transactions.
if !tp.reconciliation.IsDryRun {
if len(batchMatches) > 0 {
// Record the matched transactions.
if err := tp.datasource.RecordMatches(ctx, tp.reconciliation.ReconciliationID, batchMatches); err != nil {
return err
}
// Asynchronously update the metadata for each matched internal transaction
go tp.updateMatchedTransactionsMetadata(context.Background(), batchMatches)
}
if len(batchUnmatched) > 0 {
// Record the unmatched transactions.
if err := tp.datasource.RecordUnmatched(ctx, tp.reconciliation.ReconciliationID, batchUnmatched); err != nil {
return err
}
}
}
// Update the progress with the last processed transaction ID and increment the processed count.
tp.progress.LastProcessedExternalTxnID = txn.TransactionID
tp.progress.ProcessedCount++
// Periodically save the reconciliation progress.
if tp.progress.ProcessedCount%tp.progressSaveCount == 0 {
if err := tp.datasource.SaveReconciliationProgress(ctx, tp.reconciliation.ReconciliationID, tp.progress); err != nil {
log.Printf("Error saving reconciliation progress: %v", err)
}
}
return nil
}
// updateMatchedTransactionsMetadata updates the metadata for internal transactions that were matched.
// This function adds reconciliation information to the internal transaction's metadata.
// Parameters:
// - ctx: The context controlling the operation.
// - matches: The list of matches to process.
func (tp *transactionProcessor) updateMatchedTransactionsMetadata(ctx context.Context, matches []model.Match) {
for _, match := range matches {
// Prepare metadata with reconciliation information
metadata := map[string]interface{}{
"reconciled": true,
"reconciliation_id": tp.reconciliation.ReconciliationID,
"reconciled_at": time.Now().Format(time.RFC3339),
"external_txn_id": match.ExternalTransactionID,
"reconciliation_amount": match.Amount,
}
// Update the internal transaction's metadata
err := tp.blnk.updateEntityMetadata(ctx, "transactions", match.InternalTransactionID, metadata)
if err != nil {
log.Printf("Error updating metadata for transaction %s: %v", match.InternalTransactionID, err)
}
}