You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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\Services\CompanySettingsService;
  10. use App\Utilities\Currency\CurrencyAccessor;
  11. use App\Utilities\Currency\CurrencyConverter;
  12. use Closure;
  13. use Filament\Forms;
  14. use Filament\Forms\Form;
  15. use Filament\Resources\RelationManagers\RelationManager;
  16. use Filament\Support\Colors\Color;
  17. use Filament\Support\Enums\FontWeight;
  18. use Filament\Support\Enums\MaxWidth;
  19. use Filament\Tables;
  20. use Filament\Tables\Table;
  21. use Illuminate\Database\Eloquent\Model;
  22. class PaymentsRelationManager extends RelationManager
  23. {
  24. protected static string $relationship = 'payments';
  25. protected static ?string $modelLabel = 'Payment';
  26. protected static bool $isLazy = false;
  27. protected $listeners = [
  28. 'refresh' => '$refresh',
  29. ];
  30. public function isReadOnly(): bool
  31. {
  32. return false;
  33. }
  34. public static function canViewForRecord(Model $ownerRecord, string $pageClass): bool
  35. {
  36. return $ownerRecord->status !== InvoiceStatus::Draft;
  37. }
  38. public function form(Form $form): Form
  39. {
  40. return $form
  41. ->columns(1)
  42. ->schema([
  43. Forms\Components\DatePicker::make('posted_at')
  44. ->label('Date')
  45. ->timezone(CompanySettingsService::getDefaultTimezone()),
  46. Forms\Components\Grid::make()
  47. ->schema([
  48. Forms\Components\Select::make('bank_account_id')
  49. ->label('Account')
  50. ->required()
  51. ->live()
  52. ->options(function () {
  53. return BankAccount::query()
  54. ->join('accounts', 'bank_accounts.account_id', '=', 'accounts.id')
  55. ->select(['bank_accounts.id', 'accounts.name', 'accounts.currency_code'])
  56. ->get()
  57. ->mapWithKeys(function ($account) {
  58. $label = $account->name;
  59. if ($account->currency_code) {
  60. $label .= " ({$account->currency_code})";
  61. }
  62. return [$account->id => $label];
  63. })
  64. ->toArray();
  65. })
  66. ->searchable(),
  67. Forms\Components\TextInput::make('amount')
  68. ->label('Amount')
  69. ->required()
  70. ->money(function (RelationManager $livewire) {
  71. /** @var Invoice $invoice */
  72. $invoice = $livewire->getOwnerRecord();
  73. return $invoice->currency_code;
  74. })
  75. ->live(onBlur: true)
  76. ->helperText(function (RelationManager $livewire, $state, ?Transaction $record) {
  77. /** @var Invoice $ownerRecord */
  78. $ownerRecord = $livewire->getOwnerRecord();
  79. $invoiceCurrency = $ownerRecord->currency_code;
  80. if (! CurrencyConverter::isValidAmount($state, 'USD')) {
  81. return null;
  82. }
  83. $amountDue = $ownerRecord->amount_due;
  84. $amount = CurrencyConverter::convertToCents($state, 'USD');
  85. if ($amount <= 0) {
  86. return 'Please enter a valid positive amount';
  87. }
  88. $currentPaymentAmount = $record?->amount ?? 0;
  89. if ($ownerRecord->status === InvoiceStatus::Overpaid) {
  90. $newAmountDue = $amountDue + $amount - $currentPaymentAmount;
  91. } else {
  92. $newAmountDue = $amountDue - $amount + $currentPaymentAmount;
  93. }
  94. return match (true) {
  95. $newAmountDue > 0 => 'Amount due after payment will be ' . CurrencyConverter::formatCentsToMoney($newAmountDue, $invoiceCurrency),
  96. $newAmountDue === 0 => 'Invoice will be fully paid',
  97. default => 'Invoice will be overpaid by ' . CurrencyConverter::formatCentsToMoney(abs($newAmountDue), $invoiceCurrency),
  98. };
  99. })
  100. ->rules([
  101. static fn (): Closure => static function (string $attribute, $value, Closure $fail) {
  102. if (! CurrencyConverter::isValidAmount($value, 'USD')) {
  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. ->slideOver()
  203. ->modalWidth(MaxWidth::TwoExtraLarge)
  204. ->visible(function () {
  205. return $this->getOwnerRecord()->canRecordPayment();
  206. })
  207. ->mountUsing(function (Form $form) {
  208. $record = $this->getOwnerRecord();
  209. $form->fill([
  210. 'posted_at' => now(),
  211. 'amount' => abs($record->amount_due),
  212. ]);
  213. })
  214. ->databaseTransaction()
  215. ->successNotificationTitle('Payment recorded')
  216. ->action(function (Tables\Actions\CreateAction $action, array $data) {
  217. /** @var Invoice $record */
  218. $record = $this->getOwnerRecord();
  219. $record->recordPayment($data);
  220. $action->success();
  221. $this->dispatch('refresh');
  222. }),
  223. ])
  224. ->actions([
  225. Tables\Actions\DeleteAction::make()
  226. ->after(fn () => $this->dispatch('refresh')),
  227. ])
  228. ->bulkActions([
  229. Tables\Actions\BulkActionGroup::make([
  230. Tables\Actions\DeleteBulkAction::make(),
  231. ]),
  232. ]);
  233. }
  234. }