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.

Transaction.php 8.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. <?php
  2. namespace App\Models\Accounting;
  3. use App\Casts\TransactionAmountCast;
  4. use App\Concerns\Blamable;
  5. use App\Concerns\CompanyOwned;
  6. use App\Enums\Accounting\AccountCategory;
  7. use App\Enums\Accounting\AccountType;
  8. use App\Enums\Accounting\PaymentMethod;
  9. use App\Enums\Accounting\TransactionType;
  10. use App\Models\Banking\BankAccount;
  11. use App\Models\Common\Client;
  12. use App\Models\Common\Contact;
  13. use App\Models\Common\Vendor;
  14. use App\Observers\TransactionObserver;
  15. use Database\Factories\Accounting\TransactionFactory;
  16. use Illuminate\Database\Eloquent\Attributes\ObservedBy;
  17. use Illuminate\Database\Eloquent\Builder;
  18. use Illuminate\Database\Eloquent\Factories\Factory;
  19. use Illuminate\Database\Eloquent\Factories\HasFactory;
  20. use Illuminate\Database\Eloquent\Model;
  21. use Illuminate\Database\Eloquent\Relations\BelongsTo;
  22. use Illuminate\Database\Eloquent\Relations\HasMany;
  23. use Illuminate\Database\Eloquent\Relations\MorphTo;
  24. use Illuminate\Support\Collection;
  25. #[ObservedBy(TransactionObserver::class)]
  26. class Transaction extends Model
  27. {
  28. use Blamable;
  29. use CompanyOwned;
  30. use HasFactory;
  31. protected $fillable = [
  32. 'company_id',
  33. 'account_id', // Account from Chart of Accounts (Income/Expense accounts)
  34. 'bank_account_id', // Cash/Bank Account
  35. 'plaid_transaction_id',
  36. 'contact_id',
  37. 'type', // 'deposit', 'withdrawal', 'journal'
  38. 'payment_channel',
  39. 'payment_method',
  40. 'is_payment',
  41. 'description',
  42. 'notes',
  43. 'reference',
  44. 'amount',
  45. 'pending',
  46. 'reviewed',
  47. 'posted_at',
  48. 'created_by',
  49. 'updated_by',
  50. 'meta',
  51. ];
  52. protected $casts = [
  53. 'type' => TransactionType::class,
  54. 'payment_method' => PaymentMethod::class,
  55. 'amount' => TransactionAmountCast::class,
  56. 'pending' => 'boolean',
  57. 'reviewed' => 'boolean',
  58. 'posted_at' => 'date',
  59. 'meta' => 'array',
  60. ];
  61. public function account(): BelongsTo
  62. {
  63. return $this->belongsTo(Account::class, 'account_id');
  64. }
  65. public function bankAccount(): BelongsTo
  66. {
  67. return $this->belongsTo(BankAccount::class, 'bank_account_id');
  68. }
  69. public function contact(): BelongsTo
  70. {
  71. return $this->belongsTo(Contact::class, 'contact_id');
  72. }
  73. public function journalEntries(): HasMany
  74. {
  75. return $this->hasMany(JournalEntry::class, 'transaction_id');
  76. }
  77. public function transactionable(): MorphTo
  78. {
  79. return $this->morphTo();
  80. }
  81. public function payeeable(): MorphTo
  82. {
  83. return $this->morphTo();
  84. }
  85. public function isUncategorized(): bool
  86. {
  87. return $this->journalEntries->contains(fn (JournalEntry $entry) => $entry->account->isUncategorized());
  88. }
  89. public function isPayment(): bool
  90. {
  91. return $this->is_payment;
  92. }
  93. public function updateAmountIfBalanced(): void
  94. {
  95. if ($this->journalEntries->areBalanced() && $this->journalEntries->sumDebits()->formatSimple() !== $this->getAttributeValue('amount')) {
  96. $this->setAttribute('amount', $this->journalEntries->sumDebits()->formatSimple());
  97. $this->save();
  98. }
  99. }
  100. public static function getBankAccountOptions(?int $excludedAccountId = null, ?int $currentBankAccountId = null): array
  101. {
  102. return BankAccount::query()
  103. ->whereHas('account', function (Builder $query) {
  104. $query->where('archived', false);
  105. })
  106. ->with(['account' => function ($query) {
  107. $query->where('archived', false);
  108. }, 'account.subtype' => function ($query) {
  109. $query->select(['id', 'name']);
  110. }])
  111. ->when($excludedAccountId, fn (Builder $query) => $query->where('account_id', '!=', $excludedAccountId))
  112. ->when($currentBankAccountId, fn (Builder $query) => $query->orWhere('id', $currentBankAccountId))
  113. ->get()
  114. ->groupBy('account.subtype.name')
  115. ->map(fn (Collection $bankAccounts, string $subtype) => $bankAccounts->pluck('account.name', 'id'))
  116. ->toArray();
  117. }
  118. public static function getBankAccountAccountOptions(?int $excludedBankAccountId = null, ?int $currentAccountId = null): array
  119. {
  120. return Account::query()
  121. ->whereHas('bankAccount', function (Builder $query) use ($excludedBankAccountId) {
  122. // Exclude the specific bank account if provided
  123. if ($excludedBankAccountId) {
  124. $query->whereNot('id', $excludedBankAccountId);
  125. }
  126. })
  127. ->where(function (Builder $query) use ($currentAccountId) {
  128. $query->where('archived', false)
  129. ->orWhere('id', $currentAccountId);
  130. })
  131. ->get()
  132. ->groupBy(fn (Account $account) => $account->category->getPluralLabel())
  133. ->map(fn (Collection $accounts, string $category) => $accounts->pluck('name', 'id'))
  134. ->toArray();
  135. }
  136. public static function getChartAccountOptions(): array
  137. {
  138. return Account::query()
  139. ->select(['id', 'name', 'category'])
  140. ->get()
  141. ->groupBy(fn (Account $account) => $account->category->getPluralLabel())
  142. ->map(fn (Collection $accounts, string $category) => $accounts->pluck('name', 'id'))
  143. ->toArray();
  144. }
  145. public static function getTransactionAccountOptions(
  146. TransactionType $type,
  147. ?int $currentAccountId = null
  148. ): array {
  149. $associatedAccountTypes = match ($type) {
  150. TransactionType::Deposit => [
  151. AccountType::OperatingRevenue, // Sales, service income
  152. AccountType::NonOperatingRevenue, // Interest, dividends received
  153. AccountType::CurrentLiability, // Loans received
  154. AccountType::NonCurrentLiability, // Long-term financing
  155. AccountType::Equity, // Owner contributions
  156. AccountType::ContraExpense, // Refunds of expenses
  157. AccountType::UncategorizedRevenue,
  158. ],
  159. TransactionType::Withdrawal => [
  160. AccountType::OperatingExpense, // Regular business expenses
  161. AccountType::NonOperatingExpense, // Interest paid, etc.
  162. AccountType::CurrentLiability, // Loan payments
  163. AccountType::NonCurrentLiability, // Long-term debt payments
  164. AccountType::Equity, // Owner withdrawals
  165. AccountType::ContraRevenue, // Customer refunds, discounts
  166. AccountType::UncategorizedExpense,
  167. ],
  168. default => null,
  169. };
  170. return Account::query()
  171. ->doesntHave('adjustment')
  172. ->doesntHave('bankAccount')
  173. ->when($associatedAccountTypes, fn (Builder $query) => $query->whereIn('type', $associatedAccountTypes))
  174. ->where(function (Builder $query) use ($currentAccountId) {
  175. $query->where('archived', false)
  176. ->orWhere('id', $currentAccountId);
  177. })
  178. ->get()
  179. ->groupBy(fn (Account $account) => $account->category->getPluralLabel())
  180. ->map(fn (Collection $accounts, string $category) => $accounts->pluck('name', 'id'))
  181. ->toArray();
  182. }
  183. public static function getJournalAccountOptions(
  184. ?int $currentAccountId = null
  185. ): array {
  186. return Account::query()
  187. ->where(function (Builder $query) use ($currentAccountId) {
  188. $query->where('archived', false)
  189. ->orWhere('id', $currentAccountId);
  190. })
  191. ->get()
  192. ->groupBy(fn (Account $account) => $account->category->getPluralLabel())
  193. ->map(fn (Collection $accounts, string $category) => $accounts->pluck('name', 'id'))
  194. ->toArray();
  195. }
  196. public static function getUncategorizedAccountByType(TransactionType $type): ?Account
  197. {
  198. [$category, $accountName] = match ($type) {
  199. TransactionType::Deposit => [AccountCategory::Revenue, 'Uncategorized Income'],
  200. TransactionType::Withdrawal => [AccountCategory::Expense, 'Uncategorized Expense'],
  201. default => [null, null],
  202. };
  203. return Account::where('category', $category)
  204. ->where('name', $accountName)
  205. ->first();
  206. }
  207. public static function getPayeeOptions(): array
  208. {
  209. $clients = Client::query()
  210. ->orderBy('name')
  211. ->pluck('name', 'id')
  212. ->toArray();
  213. $vendors = Vendor::query()
  214. ->orderBy('name')
  215. ->pluck('name', 'id')
  216. ->mapWithKeys(fn ($name, $id) => [-$id => $name])
  217. ->toArray();
  218. return [
  219. 'Clients' => $clients,
  220. 'Vendors' => $vendors,
  221. ];
  222. }
  223. protected static function newFactory(): Factory
  224. {
  225. return TransactionFactory::new();
  226. }
  227. }