Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

TransactionService.php 12KB

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