Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

PayBills.php 11KB

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