Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

PaymentsRelationManager.php 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. <?php
  2. namespace App\Filament\Company\Resources\Sales\InvoiceResource\RelationManagers;
  3. use App\Enums\Accounting\InvoiceStatus;
  4. use App\Enums\Accounting\PaymentMethod;
  5. use App\Enums\Accounting\TransactionType;
  6. use App\Models\Accounting\Invoice;
  7. use App\Models\Accounting\Transaction;
  8. use App\Models\Banking\BankAccount;
  9. use App\Utilities\Currency\CurrencyAccessor;
  10. use App\Utilities\Currency\CurrencyConverter;
  11. use Closure;
  12. use Filament\Forms;
  13. use Filament\Forms\Form;
  14. use Filament\Resources\RelationManagers\RelationManager;
  15. use Filament\Support\Colors\Color;
  16. use Filament\Support\Enums\FontWeight;
  17. use Filament\Support\Enums\MaxWidth;
  18. use Filament\Tables;
  19. use Filament\Tables\Table;
  20. use Illuminate\Database\Eloquent\Model;
  21. class PaymentsRelationManager extends RelationManager
  22. {
  23. protected static string $relationship = 'payments';
  24. protected static ?string $modelLabel = 'Payment';
  25. protected static bool $isLazy = false;
  26. protected $listeners = [
  27. 'refresh' => '$refresh',
  28. ];
  29. public function isReadOnly(): bool
  30. {
  31. return false;
  32. }
  33. public static function canViewForRecord(Model $ownerRecord, string $pageClass): bool
  34. {
  35. return $ownerRecord->status !== InvoiceStatus::Draft;
  36. }
  37. public function form(Form $form): Form
  38. {
  39. return $form
  40. ->columns(1)
  41. ->schema([
  42. Forms\Components\DatePicker::make('posted_at')
  43. ->label('Date'),
  44. Forms\Components\Grid::make()
  45. ->schema([
  46. Forms\Components\Select::make('bank_account_id')
  47. ->label('Account')
  48. ->required()
  49. ->live()
  50. ->options(function () {
  51. return BankAccount::query()
  52. ->join('accounts', 'bank_accounts.account_id', '=', 'accounts.id')
  53. ->select(['bank_accounts.id', 'accounts.name', 'accounts.currency_code'])
  54. ->get()
  55. ->mapWithKeys(function ($account) {
  56. $label = $account->name;
  57. if ($account->currency_code) {
  58. $label .= " ({$account->currency_code})";
  59. }
  60. return [$account->id => $label];
  61. })
  62. ->toArray();
  63. })
  64. ->searchable(),
  65. Forms\Components\TextInput::make('amount')
  66. ->label('Amount')
  67. ->required()
  68. ->money(function (RelationManager $livewire) {
  69. /** @var Invoice $invoice */
  70. $invoice = $livewire->getOwnerRecord();
  71. return $invoice->currency_code;
  72. })
  73. ->live(onBlur: true)
  74. ->helperText(function (RelationManager $livewire, $state, ?Transaction $record) {
  75. /** @var Invoice $ownerRecord */
  76. $ownerRecord = $livewire->getOwnerRecord();
  77. $invoiceCurrency = $ownerRecord->currency_code;
  78. if (! CurrencyConverter::isValidAmount($state, 'USD')) {
  79. return null;
  80. }
  81. $amountDue = $ownerRecord->amount_due;
  82. $amount = CurrencyConverter::convertToCents($state, 'USD');
  83. if ($amount <= 0) {
  84. return 'Please enter a valid positive amount';
  85. }
  86. $currentPaymentAmount = $record?->amount ?? 0;
  87. if ($ownerRecord->status === InvoiceStatus::Overpaid) {
  88. $newAmountDue = $amountDue + $amount - $currentPaymentAmount;
  89. } else {
  90. $newAmountDue = $amountDue - $amount + $currentPaymentAmount;
  91. }
  92. return match (true) {
  93. $newAmountDue > 0 => 'Amount due after payment will be ' . CurrencyConverter::formatCentsToMoney($newAmountDue, $invoiceCurrency),
  94. $newAmountDue === 0 => 'Invoice will be fully paid',
  95. default => 'Invoice will be overpaid by ' . CurrencyConverter::formatCentsToMoney(abs($newAmountDue), $invoiceCurrency),
  96. };
  97. })
  98. ->rules([
  99. static fn (RelationManager $livewire): Closure => static function (string $attribute, $value, Closure $fail) use ($livewire) {
  100. /** @var Invoice $invoice */
  101. $invoice = $livewire->getOwnerRecord();
  102. if (! CurrencyConverter::isValidAmount($value, $invoice->currency_code)) {
  103. $fail('Please enter a valid amount');
  104. }
  105. },
  106. ]),
  107. ])->columns(2),
  108. Forms\Components\Placeholder::make('currency_conversion')
  109. ->label('Currency Conversion')
  110. ->content(function (Forms\Get $get, RelationManager $livewire) {
  111. $amount = $get('amount');
  112. $bankAccountId = $get('bank_account_id');
  113. /** @var Invoice $invoice */
  114. $invoice = $livewire->getOwnerRecord();
  115. $invoiceCurrency = $invoice->currency_code;
  116. if (empty($amount) || empty($bankAccountId) || ! CurrencyConverter::isValidAmount($amount, 'USD')) {
  117. return null;
  118. }
  119. $bankAccount = BankAccount::with('account')->find($bankAccountId);
  120. if (! $bankAccount) {
  121. return null;
  122. }
  123. $bankCurrency = $bankAccount->account->currency_code ?? CurrencyAccessor::getDefaultCurrency();
  124. // If currencies are the same, no conversion needed
  125. if ($invoiceCurrency === $bankCurrency) {
  126. return null;
  127. }
  128. // Convert amount from invoice currency to bank currency
  129. $amountInInvoiceCurrencyCents = CurrencyConverter::convertToCents($amount, 'USD');
  130. $amountInBankCurrencyCents = CurrencyConverter::convertBalance(
  131. $amountInInvoiceCurrencyCents,
  132. $invoiceCurrency,
  133. $bankCurrency
  134. );
  135. $formattedBankAmount = CurrencyConverter::formatCentsToMoney($amountInBankCurrencyCents, $bankCurrency);
  136. return "Payment will be recorded as {$formattedBankAmount} in the bank account's currency ({$bankCurrency}).";
  137. })
  138. ->hidden(function (Forms\Get $get, RelationManager $livewire) {
  139. $bankAccountId = $get('bank_account_id');
  140. if (empty($bankAccountId)) {
  141. return true;
  142. }
  143. /** @var Invoice $invoice */
  144. $invoice = $livewire->getOwnerRecord();
  145. $invoiceCurrency = $invoice->currency_code;
  146. $bankAccount = BankAccount::with('account')->find($bankAccountId);
  147. if (! $bankAccount) {
  148. return true;
  149. }
  150. $bankCurrency = $bankAccount->account->currency_code ?? CurrencyAccessor::getDefaultCurrency();
  151. // Hide if currencies are the same
  152. return $invoiceCurrency === $bankCurrency;
  153. }),
  154. Forms\Components\Select::make('payment_method')
  155. ->label('Payment method')
  156. ->required()
  157. ->options(PaymentMethod::class),
  158. Forms\Components\Textarea::make('notes')
  159. ->label('Notes'),
  160. ]);
  161. }
  162. public function table(Table $table): Table
  163. {
  164. return $table
  165. ->recordTitleAttribute('description')
  166. ->columns([
  167. Tables\Columns\TextColumn::make('posted_at')
  168. ->label('Date')
  169. ->sortable()
  170. ->defaultDateFormat(),
  171. Tables\Columns\TextColumn::make('type')
  172. ->label('Type')
  173. ->sortable()
  174. ->toggleable(isToggledHiddenByDefault: true),
  175. Tables\Columns\TextColumn::make('description')
  176. ->label('Description')
  177. ->limit(30)
  178. ->toggleable(),
  179. Tables\Columns\TextColumn::make('bankAccount.account.name')
  180. ->label('Account')
  181. ->toggleable(),
  182. Tables\Columns\TextColumn::make('amount')
  183. ->label('Amount')
  184. ->weight(static fn (Transaction $transaction) => $transaction->reviewed ? null : FontWeight::SemiBold)
  185. ->color(
  186. static fn (Transaction $transaction) => match ($transaction->type) {
  187. TransactionType::Deposit => Color::rgb('rgb(' . Color::Green[700] . ')'),
  188. TransactionType::Journal => 'primary',
  189. default => null,
  190. }
  191. )
  192. ->sortable()
  193. ->currency(static fn (Transaction $transaction) => $transaction->bankAccount?->account->currency_code ?? CurrencyAccessor::getDefaultCurrency()),
  194. ])
  195. ->filters([
  196. //
  197. ])
  198. ->headerActions([
  199. Tables\Actions\CreateAction::make()
  200. ->label(fn () => $this->getOwnerRecord()->status === InvoiceStatus::Overpaid ? 'Refund Overpayment' : 'Record Payment')
  201. ->modalHeading(fn (Tables\Actions\CreateAction $action) => $action->getLabel())
  202. ->modalWidth(MaxWidth::TwoExtraLarge)
  203. ->visible(function () {
  204. return $this->getOwnerRecord()->canRecordPayment();
  205. })
  206. ->mountUsing(function (Form $form) {
  207. $record = $this->getOwnerRecord();
  208. $form->fill([
  209. 'posted_at' => now(),
  210. 'amount' => $record->status === InvoiceStatus::Overpaid ? ltrim($record->amount_due, '-') : $record->amount_due,
  211. ]);
  212. })
  213. ->databaseTransaction()
  214. ->successNotificationTitle('Payment recorded')
  215. ->action(function (Tables\Actions\CreateAction $action, array $data) {
  216. /** @var Invoice $record */
  217. $record = $this->getOwnerRecord();
  218. $record->recordPayment($data);
  219. $action->success();
  220. $this->dispatch('refresh');
  221. }),
  222. ])
  223. ->actions([
  224. Tables\Actions\DeleteAction::make()
  225. ->after(fn () => $this->dispatch('refresh')),
  226. ])
  227. ->bulkActions([
  228. Tables\Actions\BulkActionGroup::make([
  229. Tables\Actions\DeleteBulkAction::make(),
  230. ]),
  231. ]);
  232. }
  233. }