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 9.7KB

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