@hasna/microservices 0.0.4 → 0.0.6

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.
Files changed (57) hide show
  1. package/bin/index.js +9 -1
  2. package/bin/mcp.js +9 -1
  3. package/dist/index.js +9 -1
  4. package/microservices/microservice-ads/src/cli/index.ts +198 -0
  5. package/microservices/microservice-ads/src/db/campaigns.ts +304 -0
  6. package/microservices/microservice-ads/src/mcp/index.ts +160 -0
  7. package/microservices/microservice-company/package.json +27 -0
  8. package/microservices/microservice-company/src/cli/index.ts +1126 -0
  9. package/microservices/microservice-company/src/db/company.ts +854 -0
  10. package/microservices/microservice-company/src/db/database.ts +93 -0
  11. package/microservices/microservice-company/src/db/migrations.ts +214 -0
  12. package/microservices/microservice-company/src/db/workflow-migrations.ts +44 -0
  13. package/microservices/microservice-company/src/index.ts +60 -0
  14. package/microservices/microservice-company/src/lib/audit.ts +168 -0
  15. package/microservices/microservice-company/src/lib/finance.ts +299 -0
  16. package/microservices/microservice-company/src/lib/settings.ts +85 -0
  17. package/microservices/microservice-company/src/lib/workflows.ts +698 -0
  18. package/microservices/microservice-company/src/mcp/index.ts +991 -0
  19. package/microservices/microservice-contracts/src/cli/index.ts +410 -23
  20. package/microservices/microservice-contracts/src/db/contracts.ts +430 -1
  21. package/microservices/microservice-contracts/src/db/migrations.ts +83 -0
  22. package/microservices/microservice-contracts/src/mcp/index.ts +312 -3
  23. package/microservices/microservice-domains/src/cli/index.ts +673 -0
  24. package/microservices/microservice-domains/src/db/domains.ts +613 -0
  25. package/microservices/microservice-domains/src/index.ts +21 -0
  26. package/microservices/microservice-domains/src/lib/brandsight.ts +285 -0
  27. package/microservices/microservice-domains/src/lib/godaddy.ts +328 -0
  28. package/microservices/microservice-domains/src/lib/namecheap.ts +474 -0
  29. package/microservices/microservice-domains/src/lib/registrar.ts +355 -0
  30. package/microservices/microservice-domains/src/mcp/index.ts +413 -0
  31. package/microservices/microservice-hiring/src/cli/index.ts +318 -8
  32. package/microservices/microservice-hiring/src/db/hiring.ts +503 -0
  33. package/microservices/microservice-hiring/src/db/migrations.ts +21 -0
  34. package/microservices/microservice-hiring/src/index.ts +29 -0
  35. package/microservices/microservice-hiring/src/lib/scoring.ts +206 -0
  36. package/microservices/microservice-hiring/src/mcp/index.ts +245 -0
  37. package/microservices/microservice-payments/src/cli/index.ts +255 -3
  38. package/microservices/microservice-payments/src/db/migrations.ts +18 -0
  39. package/microservices/microservice-payments/src/db/payments.ts +552 -0
  40. package/microservices/microservice-payments/src/mcp/index.ts +223 -0
  41. package/microservices/microservice-payroll/src/cli/index.ts +269 -0
  42. package/microservices/microservice-payroll/src/db/migrations.ts +26 -0
  43. package/microservices/microservice-payroll/src/db/payroll.ts +636 -0
  44. package/microservices/microservice-payroll/src/mcp/index.ts +246 -0
  45. package/microservices/microservice-shipping/src/cli/index.ts +211 -3
  46. package/microservices/microservice-shipping/src/db/migrations.ts +8 -0
  47. package/microservices/microservice-shipping/src/db/shipping.ts +453 -3
  48. package/microservices/microservice-shipping/src/mcp/index.ts +149 -1
  49. package/microservices/microservice-social/src/cli/index.ts +244 -2
  50. package/microservices/microservice-social/src/db/migrations.ts +33 -0
  51. package/microservices/microservice-social/src/db/social.ts +378 -4
  52. package/microservices/microservice-social/src/mcp/index.ts +221 -1
  53. package/microservices/microservice-subscriptions/src/cli/index.ts +315 -0
  54. package/microservices/microservice-subscriptions/src/db/migrations.ts +68 -0
  55. package/microservices/microservice-subscriptions/src/db/subscriptions.ts +567 -3
  56. package/microservices/microservice-subscriptions/src/mcp/index.ts +267 -1
  57. package/package.json +1 -1
@@ -650,3 +650,555 @@ export function deletePayout(id: string): boolean {
650
650
  const result = db.prepare("DELETE FROM payouts WHERE id = ?").run(id);
651
651
  return result.changes > 0;
652
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
+ }