You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

TransactionService.php 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. <?php
  2. namespace App\Services;
  3. use App\Enums\Accounting\AccountCategory;
  4. use App\Enums\Accounting\AccountType;
  5. use App\Enums\Accounting\JournalEntryType;
  6. use App\Enums\Accounting\TransactionType;
  7. use App\Models\Accounting\Account;
  8. use App\Models\Accounting\JournalEntry;
  9. use App\Models\Accounting\Transaction;
  10. use App\Models\Banking\BankAccount;
  11. use App\Models\Company;
  12. use App\Utilities\Currency\CurrencyAccessor;
  13. use App\Utilities\Currency\CurrencyConverter;
  14. use Illuminate\Support\Carbon;
  15. use Illuminate\Support\Facades\DB;
  16. class TransactionService
  17. {
  18. public function createStartingBalanceIfNeeded(Company $company, Account $account, BankAccount $bankAccount, array $transactions, float $currentBalance, string $startDate): void
  19. {
  20. if ($account->transactions()->doesntExist()) {
  21. $accountSign = $account->category === AccountCategory::Asset ? 1 : -1;
  22. $sumOfTransactions = collect($transactions)->reduce(static function ($carry, $transaction) {
  23. return bcadd($carry, (string) -$transaction->amount, 2);
  24. }, '0.00');
  25. $adjustedBalance = (string) ($currentBalance * $accountSign);
  26. $startingBalance = bcsub($adjustedBalance, $sumOfTransactions, 2);
  27. $this->createStartingBalanceTransaction($company, $account, $bankAccount, (float) $startingBalance, $startDate);
  28. }
  29. }
  30. public function storeTransactions(Company $company, BankAccount $bankAccount, array $transactions): void
  31. {
  32. foreach ($transactions as $transaction) {
  33. $this->storeTransaction($company, $bankAccount, $transaction);
  34. }
  35. }
  36. public function createStartingBalanceTransaction(Company $company, Account $account, BankAccount $bankAccount, float $startingBalance, string $startDate): void
  37. {
  38. $transactionType = $startingBalance >= 0 ? TransactionType::Deposit : TransactionType::Withdrawal;
  39. $accountName = $startingBalance >= 0 ? "Owner's Investment" : "Owner's Drawings";
  40. $chartAccount = $account->where('category', AccountCategory::Equity)->where('name', $accountName)->first();
  41. $postedAt = Carbon::parse($startDate)->subDay()->toDateTimeString();
  42. Transaction::create([
  43. 'company_id' => $company->id,
  44. 'account_id' => $chartAccount->id,
  45. 'bank_account_id' => $bankAccount->id,
  46. 'type' => $transactionType,
  47. 'amount' => abs($startingBalance),
  48. 'payment_channel' => 'other',
  49. 'posted_at' => $postedAt,
  50. 'description' => 'Starting Balance',
  51. 'pending' => false,
  52. 'reviewed' => false,
  53. ]);
  54. }
  55. public function storeTransaction(Company $company, BankAccount $bankAccount, object $transaction): void
  56. {
  57. $transactionType = $transaction->amount < 0 ? TransactionType::Deposit : TransactionType::Withdrawal;
  58. $paymentChannel = $transaction->payment_channel;
  59. $chartAccount = $this->getAccountFromTransaction($company, $transaction, $transactionType);
  60. $postedAt = $transaction->datetime ?? Carbon::parse($transaction->date)->toDateTimeString();
  61. $description = $transaction->name;
  62. Transaction::create([
  63. 'company_id' => $company->id,
  64. 'account_id' => $chartAccount->id,
  65. 'bank_account_id' => $bankAccount->id,
  66. 'plaid_transaction_id' => $transaction->transaction_id,
  67. 'type' => $transactionType,
  68. 'amount' => abs($transaction->amount),
  69. 'payment_channel' => $paymentChannel,
  70. 'posted_at' => $postedAt,
  71. 'description' => $description,
  72. 'pending' => false,
  73. 'reviewed' => false,
  74. ]);
  75. }
  76. public function getAccountFromTransaction(Company $company, object $transaction, TransactionType $transactionType): Account
  77. {
  78. $accountCategory = match ($transactionType) {
  79. TransactionType::Deposit => AccountCategory::Revenue,
  80. TransactionType::Withdrawal => AccountCategory::Expense,
  81. default => null,
  82. };
  83. $accounts = $company->accounts()
  84. ->where('category', $accountCategory)
  85. ->whereNotIn('type', [AccountType::UncategorizedRevenue, AccountType::UncategorizedExpense])
  86. ->get();
  87. $bestMatchName = $this->findBestAccountMatch($transaction, $accounts->pluck('name')->toArray());
  88. if ($bestMatchName === null) {
  89. return $this->getUncategorizedAccount($company, $transactionType);
  90. }
  91. return $accounts->firstWhere('name', $bestMatchName) ?: $this->getUncategorizedAccount($company, $transactionType);
  92. }
  93. private function findBestAccountMatch(object $transaction, array $accountNames): ?string
  94. {
  95. $acceptableConfidenceLevels = ['VERY_HIGH', 'HIGH'];
  96. $similarityThreshold = 70.0;
  97. $plaidDetail = $transaction->personal_finance_category->detailed ?? null;
  98. $plaidPrimary = $transaction->personal_finance_category->primary ?? null;
  99. $bestMatchName = null;
  100. $bestMatchPercent = 0.0;
  101. foreach ([$plaidDetail, $plaidPrimary] as $plaidCategory) {
  102. if ($plaidCategory !== null && in_array($transaction->personal_finance_category->confidence_level, $acceptableConfidenceLevels, true)) {
  103. foreach ($accountNames as $accountName) {
  104. $normalizedPlaidCategory = strtolower(str_replace('_', ' ', $plaidCategory));
  105. $normalizedAccountName = strtolower(str_replace('_', ' ', $accountName));
  106. $currentMatchPercent = 0.0;
  107. similar_text($normalizedPlaidCategory, $normalizedAccountName, $currentMatchPercent);
  108. if ($currentMatchPercent >= $similarityThreshold && $currentMatchPercent > $bestMatchPercent) {
  109. $bestMatchPercent = $currentMatchPercent;
  110. $bestMatchName = $accountName; // Use and return the original account name for the best match, not the normalized one
  111. }
  112. }
  113. }
  114. }
  115. return $bestMatchName;
  116. }
  117. public function getUncategorizedAccount(Company $company, TransactionType $transactionType): Account
  118. {
  119. [$type, $name] = match ($transactionType) {
  120. TransactionType::Deposit => [AccountType::UncategorizedRevenue, 'Uncategorized Income'],
  121. TransactionType::Withdrawal => [AccountType::UncategorizedExpense, 'Uncategorized Expense'],
  122. default => [null, null],
  123. };
  124. return $company->accounts()
  125. ->where('type', $type)
  126. ->where('name', $name)
  127. ->firstOrFail();
  128. }
  129. public function createJournalEntries(Transaction $transaction): void
  130. {
  131. // Additional check to avoid duplication during replication
  132. if ($transaction->journalEntries()->exists() || $transaction->type->isJournal() || str_starts_with($transaction->description, '(Copy of)')) {
  133. return;
  134. }
  135. [$debitAccount, $creditAccount] = $this->determineAccounts($transaction);
  136. if ($debitAccount === null || $creditAccount === null) {
  137. return;
  138. }
  139. $this->createJournalEntriesForTransaction($transaction, $debitAccount, $creditAccount);
  140. }
  141. public function updateJournalEntries(Transaction $transaction): void
  142. {
  143. if ($transaction->type->isJournal() || $this->hasRelevantChanges($transaction) === false) {
  144. return;
  145. }
  146. $journalEntries = $transaction->journalEntries;
  147. $debitEntry = $journalEntries->where('type', JournalEntryType::Debit)->first();
  148. $creditEntry = $journalEntries->where('type', JournalEntryType::Credit)->first();
  149. if ($debitEntry === null || $creditEntry === null) {
  150. return;
  151. }
  152. [$debitAccount, $creditAccount] = $this->determineAccounts($transaction);
  153. if ($debitAccount === null || $creditAccount === null) {
  154. return;
  155. }
  156. $convertedTransactionAmount = $this->getConvertedTransactionAmount($transaction);
  157. DB::transaction(function () use ($debitEntry, $debitAccount, $convertedTransactionAmount, $creditEntry, $creditAccount) {
  158. $this->updateJournalEntryForTransaction($debitEntry, $debitAccount, $convertedTransactionAmount);
  159. $this->updateJournalEntryForTransaction($creditEntry, $creditAccount, $convertedTransactionAmount);
  160. });
  161. }
  162. public function deleteJournalEntries(Transaction $transaction): void
  163. {
  164. DB::transaction(static function () use ($transaction) {
  165. $transaction->journalEntries()->each(fn (JournalEntry $entry) => $entry->delete());
  166. });
  167. }
  168. private function determineAccounts(Transaction $transaction): array
  169. {
  170. $chartAccount = $transaction->account;
  171. $bankAccount = $transaction->bankAccount?->account;
  172. if ($transaction->type->isTransfer()) {
  173. // Essentially a withdrawal from the bank account and a deposit to the chart account (which is a bank account)
  174. // Credit: bankAccount (source of funds, money is being withdrawn)
  175. // Debit: chartAccount (destination of funds, money is being deposited)
  176. return [$chartAccount, $bankAccount];
  177. }
  178. $debitAccount = $transaction->type->isWithdrawal() ? $chartAccount : $bankAccount;
  179. $creditAccount = $transaction->type->isWithdrawal() ? $bankAccount : $chartAccount;
  180. return [$debitAccount, $creditAccount];
  181. }
  182. private function createJournalEntriesForTransaction(Transaction $transaction, Account $debitAccount, Account $creditAccount): void
  183. {
  184. $convertedTransactionAmount = $this->getConvertedTransactionAmount($transaction);
  185. DB::transaction(function () use ($debitAccount, $transaction, $convertedTransactionAmount, $creditAccount) {
  186. $debitAccount->journalEntries()->create([
  187. 'company_id' => $transaction->company_id,
  188. 'transaction_id' => $transaction->id,
  189. 'type' => JournalEntryType::Debit,
  190. 'amount' => $convertedTransactionAmount,
  191. 'description' => $transaction->description,
  192. 'created_by' => $transaction->created_by,
  193. 'updated_by' => $transaction->updated_by,
  194. ]);
  195. $creditAccount->journalEntries()->create([
  196. 'company_id' => $transaction->company_id,
  197. 'transaction_id' => $transaction->id,
  198. 'type' => JournalEntryType::Credit,
  199. 'amount' => $convertedTransactionAmount,
  200. 'description' => $transaction->description,
  201. 'created_by' => $transaction->created_by,
  202. 'updated_by' => $transaction->updated_by,
  203. ]);
  204. });
  205. }
  206. private function getConvertedTransactionAmount(Transaction $transaction): string
  207. {
  208. $defaultCurrency = CurrencyAccessor::getDefaultCurrency();
  209. $bankAccountCurrency = $transaction->bankAccount->account->currency_code;
  210. if ($bankAccountCurrency !== $defaultCurrency) {
  211. return $this->convertToDefaultCurrency($transaction->amount, $bankAccountCurrency, $defaultCurrency);
  212. }
  213. return $transaction->amount;
  214. }
  215. private function convertToDefaultCurrency(string $amount, string $fromCurrency, string $toCurrency): string
  216. {
  217. $amountInCents = CurrencyConverter::prepareForAccessor($amount, $fromCurrency);
  218. $convertedAmountInCents = CurrencyConverter::convertBalance($amountInCents, $fromCurrency, $toCurrency);
  219. return CurrencyConverter::prepareForMutator($convertedAmountInCents, $toCurrency);
  220. }
  221. private function hasRelevantChanges(Transaction $transaction): bool
  222. {
  223. return $transaction->wasChanged(['amount', 'account_id', 'bank_account_id', 'type']);
  224. }
  225. private function updateJournalEntryForTransaction(JournalEntry $journalEntry, Account $account, string $convertedTransactionAmount): void
  226. {
  227. DB::transaction(static function () use ($journalEntry, $account, $convertedTransactionAmount) {
  228. $journalEntry->update([
  229. 'account_id' => $account->id,
  230. 'amount' => $convertedTransactionAmount,
  231. ]);
  232. });
  233. }
  234. }