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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. <?php
  2. namespace App\Filament\Company\Resources\Purchases\BillResource\Pages;
  3. use App\Enums\Accounting\BillStatus;
  4. use App\Enums\Accounting\PaymentMethod;
  5. use App\Filament\Company\Resources\Purchases\BillResource;
  6. use App\Models\Accounting\Bill;
  7. use App\Models\Accounting\Transaction;
  8. use App\Models\Banking\BankAccount;
  9. use App\Utilities\Currency\CurrencyConverter;
  10. use Filament\Actions;
  11. use Filament\Forms;
  12. use Filament\Forms\Form;
  13. use Filament\Notifications\Notification;
  14. use Filament\Resources\Pages\ListRecords;
  15. use Filament\Support\RawJs;
  16. use Filament\Tables;
  17. use Filament\Tables\Columns\TextColumn;
  18. use Filament\Tables\Columns\TextInputColumn;
  19. use Filament\Tables\Table;
  20. use Illuminate\Database\Eloquent\Collection;
  21. use Livewire\Attributes\Computed;
  22. class PayBills extends ListRecords
  23. {
  24. protected static string $resource = BillResource::class;
  25. protected static ?string $title = 'Pay Bills';
  26. protected static ?string $navigationLabel = 'Pay Bills';
  27. protected static string $view = 'filament.company.resources.purchases.bill-resource.pages.pay-bills';
  28. public array $paymentAmounts = [];
  29. public ?array $data = [];
  30. public function getTitle(): string
  31. {
  32. return 'Pay Bills';
  33. }
  34. public function getBreadcrumb(): string
  35. {
  36. return 'Pay Bills';
  37. }
  38. public function mount(): void
  39. {
  40. parent::mount();
  41. $this->form->fill([
  42. 'bank_account_id' => BankAccount::where('enabled', true)->first()?->id,
  43. 'payment_date' => now(),
  44. 'payment_method' => PaymentMethod::Check->value,
  45. ]);
  46. }
  47. protected function getHeaderActions(): array
  48. {
  49. return [
  50. Actions\Action::make('paySelected')
  51. ->label('Pay Selected Bills')
  52. ->icon('heroicon-o-credit-card')
  53. ->color('primary')
  54. ->action(function () {
  55. $data = $this->data;
  56. $selectedRecords = $this->getTableRecords();
  57. $paidCount = 0;
  58. $totalPaid = 0;
  59. foreach ($selectedRecords as $bill) {
  60. if (! $bill->canRecordPayment()) {
  61. continue;
  62. }
  63. // Get the payment amount from our component state
  64. $paymentAmount = $this->getPaymentAmount($bill);
  65. if ($paymentAmount <= 0) {
  66. continue;
  67. }
  68. $paymentData = [
  69. 'posted_at' => $data['payment_date'],
  70. 'payment_method' => $data['payment_method'],
  71. 'bank_account_id' => $data['bank_account_id'],
  72. 'amount' => $paymentAmount,
  73. ];
  74. $bill->recordPayment($paymentData);
  75. $paidCount++;
  76. $totalPaid += $paymentAmount;
  77. }
  78. $totalFormatted = CurrencyConverter::formatCentsToMoney($totalPaid);
  79. Notification::make()
  80. ->title('Bills paid successfully')
  81. ->body("Paid {$paidCount} bill(s) for a total of {$totalFormatted}")
  82. ->success()
  83. ->send();
  84. // Clear payment amounts after successful payment
  85. foreach ($selectedRecords as $bill) {
  86. $this->paymentAmounts[$bill->id] = 0;
  87. }
  88. $this->resetTable();
  89. }),
  90. ];
  91. }
  92. /**
  93. * @return array<int | string, string | Form>
  94. */
  95. protected function getForms(): array
  96. {
  97. return [
  98. 'form',
  99. ];
  100. }
  101. public function form(Form $form): Form
  102. {
  103. return $form
  104. ->schema([
  105. Forms\Components\Grid::make(3)
  106. ->schema([
  107. Forms\Components\Select::make('bank_account_id')
  108. ->label('Bank Account')
  109. ->options(function () {
  110. return Transaction::getBankAccountOptionsFlat();
  111. })
  112. ->selectablePlaceholder(false)
  113. ->searchable()
  114. ->softRequired(),
  115. Forms\Components\DatePicker::make('payment_date')
  116. ->label('Payment Date')
  117. ->default(now())
  118. ->softRequired(),
  119. Forms\Components\Select::make('payment_method')
  120. ->label('Payment Method')
  121. ->selectablePlaceholder(false)
  122. ->options(PaymentMethod::class)
  123. ->default(PaymentMethod::Check)
  124. ->softRequired()
  125. ->live(),
  126. ]),
  127. ])->statePath('data');
  128. }
  129. public function table(Table $table): Table
  130. {
  131. return $table
  132. ->query(
  133. Bill::query()
  134. ->with(['vendor'])
  135. ->whereIn('status', [
  136. BillStatus::Open,
  137. BillStatus::Partial,
  138. BillStatus::Overdue,
  139. ])
  140. )
  141. ->selectable()
  142. ->columns([
  143. TextColumn::make('vendor.name')
  144. ->label('Vendor')
  145. ->searchable()
  146. ->sortable(),
  147. TextColumn::make('bill_number')
  148. ->label('Bill #')
  149. ->searchable()
  150. ->sortable(),
  151. TextColumn::make('due_date')
  152. ->label('Due Date')
  153. ->date('M j, Y')
  154. ->sortable(),
  155. TextColumn::make('amount_due')
  156. ->label('Amount Due')
  157. ->currencyWithConversion(fn (Bill $record) => $record->currency_code)
  158. ->alignEnd()
  159. ->sortable(),
  160. TextInputColumn::make('payment_amount')
  161. ->label('Payment Amount')
  162. ->alignEnd()
  163. ->mask(RawJs::make('$money($input)'))
  164. ->updateStateUsing(function (Bill $record, $state) {
  165. if (empty($state) || $state === '0.00') {
  166. $this->paymentAmounts[$record->id] = 0;
  167. return '0.00';
  168. }
  169. $paymentCents = CurrencyConverter::convertToCents($state, $record->currency_code);
  170. // Validate payment doesn't exceed amount due
  171. if ($paymentCents > $record->amount_due) {
  172. Notification::make()
  173. ->title('Invalid payment amount')
  174. ->body('Payment cannot exceed amount due')
  175. ->warning()
  176. ->send();
  177. $maxAmount = CurrencyConverter::convertCentsToFormatSimple($record->amount_due, $record->currency_code);
  178. $this->paymentAmounts[$record->id] = $record->amount_due;
  179. return $maxAmount;
  180. }
  181. $this->paymentAmounts[$record->id] = $paymentCents;
  182. return $state;
  183. })
  184. ->getStateUsing(function (Bill $record) {
  185. $paymentAmount = $this->paymentAmounts[$record->id] ?? 0;
  186. return CurrencyConverter::convertCentsToFormatSimple($paymentAmount, $record->currency_code);
  187. }),
  188. ])
  189. ->actions([
  190. Tables\Actions\Action::make('setFullAmount')
  191. ->label('Pay Full')
  192. ->icon('heroicon-o-banknotes')
  193. ->color('primary')
  194. ->action(function (Bill $record) {
  195. $this->paymentAmounts[$record->id] = $record->amount_due;
  196. }),
  197. Tables\Actions\Action::make('clearAmount')
  198. ->label('Clear')
  199. ->icon('heroicon-o-x-mark')
  200. ->color('gray')
  201. ->action(function (Bill $record) {
  202. $this->paymentAmounts[$record->id] = 0;
  203. }),
  204. ])
  205. ->bulkActions([
  206. Tables\Actions\BulkAction::make('setFullAmounts')
  207. ->label('Set Full Amounts')
  208. ->icon('heroicon-o-banknotes')
  209. ->color('primary')
  210. ->deselectRecordsAfterCompletion()
  211. ->action(function (Collection $records) {
  212. $records->each(function (Bill $bill) {
  213. $this->paymentAmounts[$bill->id] = $bill->amount_due;
  214. });
  215. }),
  216. Tables\Actions\BulkAction::make('clearAmounts')
  217. ->label('Clear Amounts')
  218. ->icon('heroicon-o-x-mark')
  219. ->color('gray')
  220. ->deselectRecordsAfterCompletion()
  221. ->action(function (Collection $records) {
  222. $records->each(function (Bill $bill) {
  223. $this->paymentAmounts[$bill->id] = 0;
  224. });
  225. }),
  226. ])
  227. ->filters([
  228. Tables\Filters\SelectFilter::make('vendor')
  229. ->relationship('vendor', 'name')
  230. ->searchable()
  231. ->preload(),
  232. Tables\Filters\SelectFilter::make('status')
  233. ->multiple()
  234. ->options([
  235. BillStatus::Open->value => 'Open',
  236. BillStatus::Partial->value => 'Partial',
  237. BillStatus::Overdue->value => 'Overdue',
  238. ])
  239. ->default([BillStatus::Open->value, BillStatus::Overdue->value]),
  240. ])
  241. ->defaultSort('due_date')
  242. ->striped()
  243. ->paginated(false);
  244. }
  245. protected function getPaymentAmount(Bill $record): int
  246. {
  247. return $this->paymentAmounts[$record->id] ?? 0;
  248. }
  249. #[Computed]
  250. public function totalSelectedPaymentAmount(): string
  251. {
  252. $selectedIds = array_keys($this->getSelectedTableRecords()->toArray());
  253. $total = collect($selectedIds)
  254. ->map(fn ($id) => $this->paymentAmounts[$id] ?? 0)
  255. ->sum();
  256. return CurrencyConverter::formatCentsToMoney($total);
  257. }
  258. }