Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

Transaction.php 9.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  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, bool $excludeArchived = true): array
  104. {
  105. return BankAccount::query()
  106. ->whereHas('account', function (Builder $query) use ($excludeArchived) {
  107. if ($excludeArchived) {
  108. $query->where('archived', false);
  109. }
  110. })
  111. ->with(['account' => function ($query) use ($excludeArchived) {
  112. if ($excludeArchived) {
  113. $query->where('archived', false);
  114. }
  115. }, 'account.subtype' => function ($query) {
  116. $query->select(['id', 'name']);
  117. }])
  118. ->when($excludedAccountId, fn (Builder $query) => $query->where('account_id', '!=', $excludedAccountId))
  119. ->when($currentBankAccountId, fn (Builder $query) => $query->orWhere('id', $currentBankAccountId))
  120. ->get()
  121. ->groupBy('account.subtype.name')
  122. ->map(fn (Collection $bankAccounts, string $subtype) => $bankAccounts->pluck('account.name', 'id'))
  123. ->toArray();
  124. }
  125. public static function getBankAccountAccountOptions(?int $excludedBankAccountId = null, ?int $currentAccountId = null): array
  126. {
  127. return Account::query()
  128. ->whereHas('bankAccount', function (Builder $query) use ($excludedBankAccountId) {
  129. // Exclude the specific bank account if provided
  130. if ($excludedBankAccountId) {
  131. $query->whereNot('id', $excludedBankAccountId);
  132. }
  133. })
  134. ->where(function (Builder $query) use ($currentAccountId) {
  135. $query->where('archived', false)
  136. ->orWhere('id', $currentAccountId);
  137. })
  138. ->get()
  139. ->groupBy(fn (Account $account) => $account->category->getPluralLabel())
  140. ->map(fn (Collection $accounts, string $category) => $accounts->pluck('name', 'id'))
  141. ->toArray();
  142. }
  143. public static function getChartAccountOptions(): array
  144. {
  145. return Account::query()
  146. ->select(['id', 'name', 'category'])
  147. ->get()
  148. ->groupBy(fn (Account $account) => $account->category->getPluralLabel())
  149. ->map(fn (Collection $accounts, string $category) => $accounts->pluck('name', 'id'))
  150. ->toArray();
  151. }
  152. public static function getTransactionAccountOptions(
  153. TransactionType $type,
  154. ?int $currentAccountId = null
  155. ): array {
  156. $associatedAccountTypes = match ($type) {
  157. TransactionType::Deposit => [
  158. AccountType::OperatingRevenue, // Sales, service income
  159. AccountType::NonOperatingRevenue, // Interest, dividends received
  160. AccountType::CurrentLiability, // Loans received
  161. AccountType::NonCurrentLiability, // Long-term financing
  162. AccountType::Equity, // Owner contributions
  163. AccountType::ContraExpense, // Refunds of expenses
  164. AccountType::UncategorizedRevenue,
  165. ],
  166. TransactionType::Withdrawal => [
  167. AccountType::OperatingExpense, // Regular business expenses
  168. AccountType::NonOperatingExpense, // Interest paid, etc.
  169. AccountType::CurrentLiability, // Loan payments
  170. AccountType::NonCurrentLiability, // Long-term debt payments
  171. AccountType::Equity, // Owner withdrawals
  172. AccountType::ContraRevenue, // Customer refunds, discounts
  173. AccountType::UncategorizedExpense,
  174. ],
  175. default => null,
  176. };
  177. return Account::query()
  178. ->doesntHave('adjustment')
  179. ->doesntHave('bankAccount')
  180. ->when($associatedAccountTypes, fn (Builder $query) => $query->whereIn('type', $associatedAccountTypes))
  181. ->where(function (Builder $query) use ($currentAccountId) {
  182. $query->where('archived', false)
  183. ->orWhere('id', $currentAccountId);
  184. })
  185. ->get()
  186. ->groupBy(fn (Account $account) => $account->category->getPluralLabel())
  187. ->map(fn (Collection $accounts, string $category) => $accounts->pluck('name', 'id'))
  188. ->toArray();
  189. }
  190. public static function getJournalAccountOptions(
  191. ?int $currentAccountId = null
  192. ): array {
  193. return Account::query()
  194. ->where(function (Builder $query) use ($currentAccountId) {
  195. $query->where('archived', false)
  196. ->orWhere('id', $currentAccountId);
  197. })
  198. ->get()
  199. ->groupBy(fn (Account $account) => $account->category->getPluralLabel())
  200. ->map(fn (Collection $accounts, string $category) => $accounts->pluck('name', 'id'))
  201. ->toArray();
  202. }
  203. public static function getUncategorizedAccountByType(TransactionType $type): ?Account
  204. {
  205. [$category, $accountName] = match ($type) {
  206. TransactionType::Deposit => [AccountCategory::Revenue, 'Uncategorized Income'],
  207. TransactionType::Withdrawal => [AccountCategory::Expense, 'Uncategorized Expense'],
  208. default => [null, null],
  209. };
  210. return Account::where('category', $category)
  211. ->where('name', $accountName)
  212. ->first();
  213. }
  214. public static function getPayeeOptions(): array
  215. {
  216. $clients = Client::query()
  217. ->orderBy('name')
  218. ->pluck('name', 'id')
  219. ->toArray();
  220. $vendors = Vendor::query()
  221. ->orderBy('name')
  222. ->pluck('name', 'id')
  223. ->mapWithKeys(fn ($name, $id) => [-$id => $name])
  224. ->toArray();
  225. return [
  226. 'Clients' => $clients,
  227. 'Vendors' => $vendors,
  228. ];
  229. }
  230. public function getReportTableUrl(): string
  231. {
  232. if ($this->transactionable_type && ! $this->is_payment) {
  233. return match ($this->transactionable_type) {
  234. Bill::class => ViewBill::getUrl(['record' => $this->transactionable_id]),
  235. default => ViewInvoice::getUrl(['record' => $this->transactionable_id]),
  236. };
  237. }
  238. return ViewTransaction::getUrl(['record' => $this->id]);
  239. }
  240. protected static function newFactory(): Factory
  241. {
  242. return TransactionFactory::new();
  243. }
  244. }