Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

Transaction.php 9.6KB

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