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.

BillResource.php 37KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665
  1. <?php
  2. namespace App\Filament\Company\Resources\Purchases;
  3. use App\Enums\Accounting\AdjustmentCategory;
  4. use App\Enums\Accounting\AdjustmentStatus;
  5. use App\Enums\Accounting\AdjustmentType;
  6. use App\Enums\Accounting\BillStatus;
  7. use App\Enums\Accounting\DocumentDiscountMethod;
  8. use App\Enums\Accounting\DocumentType;
  9. use App\Enums\Accounting\PaymentMethod;
  10. use App\Enums\Setting\PaymentTerms;
  11. use App\Filament\Company\Resources\Purchases\BillResource\Pages;
  12. use App\Filament\Company\Resources\Purchases\VendorResource\RelationManagers\BillsRelationManager;
  13. use App\Filament\Forms\Components\CreateAdjustmentSelect;
  14. use App\Filament\Forms\Components\CreateCurrencySelect;
  15. use App\Filament\Forms\Components\CreateVendorSelect;
  16. use App\Filament\Forms\Components\DocumentTotals;
  17. use App\Filament\Tables\Actions\ReplicateBulkAction;
  18. use App\Filament\Tables\Columns;
  19. use App\Filament\Tables\Filters\DateRangeFilter;
  20. use App\Models\Accounting\Adjustment;
  21. use App\Models\Accounting\Bill;
  22. use App\Models\Accounting\DocumentLineItem;
  23. use App\Models\Banking\BankAccount;
  24. use App\Models\Common\Offering;
  25. use App\Models\Common\Vendor;
  26. use App\Utilities\Currency\CurrencyAccessor;
  27. use App\Utilities\Currency\CurrencyConverter;
  28. use App\Utilities\RateCalculator;
  29. use Awcodes\TableRepeater\Components\TableRepeater;
  30. use Awcodes\TableRepeater\Header;
  31. use Closure;
  32. use Filament\Forms;
  33. use Filament\Forms\Form;
  34. use Filament\Notifications\Notification;
  35. use Filament\Resources\Resource;
  36. use Filament\Support\Enums\Alignment;
  37. use Filament\Support\Enums\MaxWidth;
  38. use Filament\Tables;
  39. use Filament\Tables\Table;
  40. use Guava\FilamentClusters\Forms\Cluster;
  41. use Illuminate\Database\Eloquent\Builder;
  42. use Illuminate\Database\Eloquent\Collection;
  43. use Illuminate\Support\Carbon;
  44. use Illuminate\Support\Facades\Auth;
  45. class BillResource extends Resource
  46. {
  47. protected static ?string $model = Bill::class;
  48. public static function form(Form $form): Form
  49. {
  50. $company = Auth::user()->currentCompany;
  51. $settings = $company->defaultBill;
  52. return $form
  53. ->schema([
  54. Forms\Components\Section::make('Bill Details')
  55. ->schema([
  56. Forms\Components\Split::make([
  57. Forms\Components\Group::make([
  58. CreateVendorSelect::make('vendor_id')
  59. ->label('Vendor')
  60. ->required()
  61. ->live()
  62. ->afterStateUpdated(function (Forms\Set $set, Forms\Get $get, $state) {
  63. if (! $state) {
  64. return;
  65. }
  66. $currencyCode = Vendor::find($state)?->currency_code;
  67. if ($currencyCode) {
  68. $set('currency_code', $currencyCode);
  69. }
  70. }),
  71. CreateCurrencySelect::make('currency_code'),
  72. ]),
  73. Forms\Components\Group::make([
  74. Forms\Components\TextInput::make('bill_number')
  75. ->label('Bill number')
  76. ->default(static fn () => Bill::getNextDocumentNumber())
  77. ->required(),
  78. Forms\Components\TextInput::make('order_number')
  79. ->label('P.O/S.O Number'),
  80. Cluster::make([
  81. Forms\Components\DatePicker::make('date')
  82. ->label('Bill date')
  83. ->live()
  84. ->default(now())
  85. ->disabled(function (?Bill $record) {
  86. return $record?->hasPayments();
  87. })
  88. ->columnSpan(2)
  89. ->afterStateUpdated(function (Forms\Set $set, Forms\Get $get, $state) {
  90. $date = $state;
  91. $dueDate = $get('due_date');
  92. if ($date && $dueDate && $date > $dueDate) {
  93. $set('due_date', $date);
  94. }
  95. // Update due date based on payment terms if selected
  96. $paymentTerms = $get('payment_terms');
  97. if ($date && $paymentTerms && $paymentTerms !== 'custom') {
  98. $terms = PaymentTerms::parse($paymentTerms);
  99. $set('due_date', Carbon::parse($date)->addDays($terms->getDays())->toDateString());
  100. }
  101. }),
  102. Forms\Components\Select::make('payment_terms')
  103. ->label('Payment terms')
  104. ->options(function () {
  105. return collect(PaymentTerms::cases())
  106. ->mapWithKeys(function (PaymentTerms $paymentTerm) {
  107. return [$paymentTerm->value => $paymentTerm->getLabel()];
  108. })
  109. ->put('custom', 'Custom')
  110. ->toArray();
  111. })
  112. ->selectablePlaceholder(false)
  113. ->default($settings->payment_terms->value)
  114. ->live()
  115. ->afterStateUpdated(function (Forms\Set $set, Forms\Get $get, $state) {
  116. if (! $state || $state === 'custom') {
  117. return;
  118. }
  119. $date = $get('date');
  120. if ($date) {
  121. $terms = PaymentTerms::parse($state);
  122. $set('due_date', Carbon::parse($date)->addDays($terms->getDays())->toDateString());
  123. }
  124. }),
  125. ])
  126. ->label('Bill date')
  127. ->columns(3),
  128. Forms\Components\DatePicker::make('due_date')
  129. ->label('Due date')
  130. ->default(function () use ($company) {
  131. return now()->addDays($company->defaultBill->payment_terms->getDays());
  132. })
  133. ->required()
  134. ->live()
  135. ->afterStateUpdated(function (Forms\Set $set, Forms\Get $get, $state) {
  136. if (! $state) {
  137. return;
  138. }
  139. $date = $get('date');
  140. $paymentTerms = $get('payment_terms');
  141. if (! $date || $paymentTerms === 'custom') {
  142. return;
  143. }
  144. $term = PaymentTerms::parse($paymentTerms);
  145. $expected = Carbon::parse($date)->addDays($term->getDays());
  146. if (! Carbon::parse($state)->isSameDay($expected)) {
  147. $set('payment_terms', 'custom');
  148. }
  149. }),
  150. Forms\Components\Select::make('discount_method')
  151. ->label('Discount method')
  152. ->options(DocumentDiscountMethod::class)
  153. ->selectablePlaceholder(false)
  154. ->default(DocumentDiscountMethod::PerLineItem)
  155. ->afterStateUpdated(function ($state, Forms\Set $set) {
  156. $discountMethod = DocumentDiscountMethod::parse($state);
  157. if ($discountMethod->isPerDocument()) {
  158. $set('lineItems.*.purchaseDiscounts', []);
  159. }
  160. })
  161. ->live(),
  162. ])->grow(true),
  163. ])->from('md'),
  164. TableRepeater::make('lineItems')
  165. ->relationship()
  166. ->saveRelationshipsUsing(null)
  167. ->dehydrated(true)
  168. ->headers(function (Forms\Get $get) use ($settings) {
  169. $hasDiscounts = DocumentDiscountMethod::parse($get('discount_method'))->isPerLineItem();
  170. $headers = [
  171. Header::make($settings->resolveColumnLabel('item_name', 'Items'))
  172. ->width($hasDiscounts ? '15%' : '20%'),
  173. Header::make('Description')
  174. ->width($hasDiscounts ? '15%' : '20%'),
  175. Header::make($settings->resolveColumnLabel('unit_name', 'Quantity'))
  176. ->width('10%'),
  177. Header::make($settings->resolveColumnLabel('price_name', 'Price'))
  178. ->width('10%'),
  179. Header::make('Taxes')
  180. ->width($hasDiscounts ? '20%' : '30%'),
  181. ];
  182. if ($hasDiscounts) {
  183. $headers[] = Header::make('Discounts')->width('20%');
  184. }
  185. $headers[] = Header::make($settings->resolveColumnLabel('amount_name', 'Amount'))
  186. ->width('10%')
  187. ->align('right');
  188. return $headers;
  189. })
  190. ->schema([
  191. Forms\Components\Select::make('offering_id')
  192. ->label('Item')
  193. ->relationship('purchasableOffering', 'name')
  194. ->preload()
  195. ->searchable()
  196. ->required()
  197. ->live()
  198. ->afterStateUpdated(function (Forms\Set $set, Forms\Get $get, $state, ?DocumentLineItem $record) {
  199. $offeringId = $state;
  200. $discountMethod = DocumentDiscountMethod::parse($get('../../discount_method'));
  201. $isPerLineItem = $discountMethod->isPerLineItem();
  202. $existingTaxIds = [];
  203. $existingDiscountIds = [];
  204. if ($record) {
  205. $existingTaxIds = $record->purchaseTaxes()->pluck('adjustments.id')->toArray();
  206. if ($isPerLineItem) {
  207. $existingDiscountIds = $record->purchaseDiscounts()->pluck('adjustments.id')->toArray();
  208. }
  209. }
  210. $with = [
  211. 'purchaseTaxes' => static function ($query) use ($existingTaxIds) {
  212. $query->where(static function ($query) use ($existingTaxIds) {
  213. $query->where('status', AdjustmentStatus::Active)
  214. ->orWhereIn('adjustments.id', $existingTaxIds);
  215. });
  216. },
  217. ];
  218. if ($isPerLineItem) {
  219. $with['purchaseDiscounts'] = static function ($query) use ($existingDiscountIds) {
  220. $query->where(static function ($query) use ($existingDiscountIds) {
  221. $query->where('status', AdjustmentStatus::Active)
  222. ->orWhereIn('adjustments.id', $existingDiscountIds);
  223. });
  224. };
  225. }
  226. $offeringRecord = Offering::with($with)->find($offeringId);
  227. if (! $offeringRecord) {
  228. return;
  229. }
  230. $unitPrice = CurrencyConverter::convertToFloat($offeringRecord->price, $get('../../currency_code') ?? CurrencyAccessor::getDefaultCurrency());
  231. $set('description', $offeringRecord->description);
  232. $set('unit_price', $unitPrice);
  233. $set('purchaseTaxes', $offeringRecord->purchaseTaxes->pluck('id')->toArray());
  234. if ($isPerLineItem) {
  235. $set('purchaseDiscounts', $offeringRecord->purchaseDiscounts->pluck('id')->toArray());
  236. }
  237. }),
  238. Forms\Components\TextInput::make('description'),
  239. Forms\Components\TextInput::make('quantity')
  240. ->required()
  241. ->numeric()
  242. ->live()
  243. ->maxValue(9999999999.99)
  244. ->default(1),
  245. Forms\Components\TextInput::make('unit_price')
  246. ->label('Price')
  247. ->hiddenLabel()
  248. ->numeric()
  249. ->live()
  250. ->maxValue(9999999999.99)
  251. ->default(0),
  252. CreateAdjustmentSelect::make('purchaseTaxes')
  253. ->label('Taxes')
  254. ->category(AdjustmentCategory::Tax)
  255. ->type(AdjustmentType::Purchase)
  256. ->adjustmentsRelationship('purchaseTaxes')
  257. ->saveRelationshipsUsing(null)
  258. ->dehydrated(true)
  259. ->preload()
  260. ->multiple()
  261. ->live()
  262. ->searchable(),
  263. CreateAdjustmentSelect::make('purchaseDiscounts')
  264. ->label('Discounts')
  265. ->category(AdjustmentCategory::Discount)
  266. ->type(AdjustmentType::Purchase)
  267. ->adjustmentsRelationship('purchaseDiscounts')
  268. ->saveRelationshipsUsing(null)
  269. ->dehydrated(true)
  270. ->multiple()
  271. ->live()
  272. ->hidden(function (Forms\Get $get) {
  273. $discountMethod = DocumentDiscountMethod::parse($get('../../discount_method'));
  274. return $discountMethod->isPerDocument();
  275. })
  276. ->searchable(),
  277. Forms\Components\Placeholder::make('total')
  278. ->hiddenLabel()
  279. ->extraAttributes(['class' => 'text-left sm:text-right'])
  280. ->content(function (Forms\Get $get) {
  281. $quantity = max((float) ($get('quantity') ?? 0), 0);
  282. $unitPrice = max((float) ($get('unit_price') ?? 0), 0);
  283. $purchaseTaxes = $get('purchaseTaxes') ?? [];
  284. $purchaseDiscounts = $get('purchaseDiscounts') ?? [];
  285. $currencyCode = $get('../../currency_code') ?? CurrencyAccessor::getDefaultCurrency();
  286. $subtotal = $quantity * $unitPrice;
  287. $subtotalInCents = CurrencyConverter::convertToCents($subtotal, $currencyCode);
  288. $taxAmountInCents = Adjustment::whereIn('id', $purchaseTaxes)
  289. ->get()
  290. ->sum(function (Adjustment $adjustment) use ($subtotalInCents) {
  291. if ($adjustment->computation->isPercentage()) {
  292. return RateCalculator::calculatePercentage($subtotalInCents, $adjustment->getRawOriginal('rate'));
  293. } else {
  294. return $adjustment->getRawOriginal('rate');
  295. }
  296. });
  297. $discountAmountInCents = Adjustment::whereIn('id', $purchaseDiscounts)
  298. ->get()
  299. ->sum(function (Adjustment $adjustment) use ($subtotalInCents) {
  300. if ($adjustment->computation->isPercentage()) {
  301. return RateCalculator::calculatePercentage($subtotalInCents, $adjustment->getRawOriginal('rate'));
  302. } else {
  303. return $adjustment->getRawOriginal('rate');
  304. }
  305. });
  306. // Final total
  307. $totalInCents = $subtotalInCents + ($taxAmountInCents - $discountAmountInCents);
  308. return CurrencyConverter::formatCentsToMoney($totalInCents, $currencyCode);
  309. }),
  310. ]),
  311. DocumentTotals::make()
  312. ->type(DocumentType::Bill),
  313. ]),
  314. ]);
  315. }
  316. public static function table(Table $table): Table
  317. {
  318. return $table
  319. ->defaultSort('due_date')
  320. ->columns([
  321. Columns::id(),
  322. Tables\Columns\TextColumn::make('status')
  323. ->badge()
  324. ->searchable(),
  325. Tables\Columns\TextColumn::make('due_date')
  326. ->label('Due')
  327. ->asRelativeDay()
  328. ->sortable(),
  329. Tables\Columns\TextColumn::make('date')
  330. ->date()
  331. ->sortable(),
  332. Tables\Columns\TextColumn::make('bill_number')
  333. ->label('Number')
  334. ->searchable()
  335. ->sortable(),
  336. Tables\Columns\TextColumn::make('vendor.name')
  337. ->sortable()
  338. ->searchable()
  339. ->hiddenOn(BillsRelationManager::class),
  340. Tables\Columns\TextColumn::make('total')
  341. ->currencyWithConversion(static fn (Bill $record) => $record->currency_code)
  342. ->sortable()
  343. ->toggleable(),
  344. Tables\Columns\TextColumn::make('amount_paid')
  345. ->label('Amount paid')
  346. ->currencyWithConversion(static fn (Bill $record) => $record->currency_code)
  347. ->sortable()
  348. ->toggleable(),
  349. Tables\Columns\TextColumn::make('amount_due')
  350. ->label('Amount due')
  351. ->currencyWithConversion(static fn (Bill $record) => $record->currency_code)
  352. ->sortable(),
  353. ])
  354. ->filters([
  355. Tables\Filters\SelectFilter::make('vendor')
  356. ->relationship('vendor', 'name')
  357. ->searchable()
  358. ->preload()
  359. ->hiddenOn(BillsRelationManager::class),
  360. Tables\Filters\SelectFilter::make('status')
  361. ->options(BillStatus::class)
  362. ->native(false),
  363. Tables\Filters\TernaryFilter::make('has_payments')
  364. ->label('Has payments')
  365. ->queries(
  366. true: fn (Builder $query) => $query->whereHas('payments'),
  367. false: fn (Builder $query) => $query->whereDoesntHave('payments'),
  368. ),
  369. DateRangeFilter::make('date')
  370. ->fromLabel('From date')
  371. ->untilLabel('To date')
  372. ->indicatorLabel('Date'),
  373. DateRangeFilter::make('due_date')
  374. ->fromLabel('From due date')
  375. ->untilLabel('To due date')
  376. ->indicatorLabel('Due'),
  377. ])
  378. ->actions([
  379. Tables\Actions\ActionGroup::make([
  380. Tables\Actions\ActionGroup::make([
  381. Tables\Actions\EditAction::make()
  382. ->url(static fn (Bill $record) => Pages\EditBill::getUrl(['record' => $record])),
  383. Tables\Actions\ViewAction::make()
  384. ->url(static fn (Bill $record) => Pages\ViewBill::getUrl(['record' => $record])),
  385. Bill::getReplicateAction(Tables\Actions\ReplicateAction::class),
  386. Tables\Actions\Action::make('recordPayment')
  387. ->label('Record payment')
  388. ->stickyModalHeader()
  389. ->stickyModalFooter()
  390. ->modalFooterActionsAlignment(Alignment::End)
  391. ->modalWidth(MaxWidth::TwoExtraLarge)
  392. ->icon('heroicon-o-credit-card')
  393. ->visible(function (Bill $record) {
  394. return $record->canRecordPayment();
  395. })
  396. ->mountUsing(function (Bill $record, Form $form) {
  397. $form->fill([
  398. 'posted_at' => now(),
  399. 'amount' => $record->amount_due,
  400. ]);
  401. })
  402. ->databaseTransaction()
  403. ->successNotificationTitle('Payment recorded')
  404. ->form([
  405. Forms\Components\DatePicker::make('posted_at')
  406. ->label('Date'),
  407. Forms\Components\TextInput::make('amount')
  408. ->label('Amount')
  409. ->required()
  410. ->money(fn (Bill $record) => $record->currency_code)
  411. ->live(onBlur: true)
  412. ->helperText(function (Bill $record, $state) {
  413. $billCurrency = $record->currency_code;
  414. if (! CurrencyConverter::isValidAmount($state, $billCurrency)) {
  415. return null;
  416. }
  417. $amountDue = $record->getRawOriginal('amount_due');
  418. $amount = CurrencyConverter::convertToCents($state, $billCurrency);
  419. if ($amount <= 0) {
  420. return 'Please enter a valid positive amount';
  421. }
  422. $newAmountDue = $amountDue - $amount;
  423. return match (true) {
  424. $newAmountDue > 0 => 'Amount due after payment will be ' . CurrencyConverter::formatCentsToMoney($newAmountDue, $billCurrency),
  425. $newAmountDue === 0 => 'Bill will be fully paid',
  426. default => 'Amount exceeds bill total by ' . CurrencyConverter::formatCentsToMoney(abs($newAmountDue), $billCurrency),
  427. };
  428. })
  429. ->rules([
  430. static fn (Bill $record): Closure => static function (string $attribute, $value, Closure $fail) use ($record) {
  431. if (! CurrencyConverter::isValidAmount($value, $record->currency_code)) {
  432. $fail('Please enter a valid amount');
  433. }
  434. },
  435. ]),
  436. Forms\Components\Select::make('payment_method')
  437. ->label('Payment method')
  438. ->required()
  439. ->options(PaymentMethod::class),
  440. Forms\Components\Select::make('bank_account_id')
  441. ->label('Account')
  442. ->required()
  443. ->options(function () {
  444. return BankAccount::query()
  445. ->join('accounts', 'bank_accounts.account_id', '=', 'accounts.id')
  446. ->select(['bank_accounts.id', 'accounts.name'])
  447. ->pluck('accounts.name', 'bank_accounts.id')
  448. ->toArray();
  449. })
  450. ->searchable(),
  451. Forms\Components\Textarea::make('notes')
  452. ->label('Notes'),
  453. ])
  454. ->action(function (Bill $record, Tables\Actions\Action $action, array $data) {
  455. $record->recordPayment($data);
  456. $action->success();
  457. }),
  458. ])->dropdown(false),
  459. Tables\Actions\DeleteAction::make(),
  460. ]),
  461. ])
  462. ->bulkActions([
  463. Tables\Actions\BulkActionGroup::make([
  464. Tables\Actions\DeleteBulkAction::make(),
  465. ReplicateBulkAction::make()
  466. ->label('Replicate')
  467. ->modalWidth(MaxWidth::Large)
  468. ->modalDescription('Replicating bills will also replicate their line items. Are you sure you want to proceed?')
  469. ->successNotificationTitle('Bills replicated successfully')
  470. ->failureNotificationTitle('Failed to replicate bills')
  471. ->databaseTransaction()
  472. ->deselectRecordsAfterCompletion()
  473. ->excludeAttributes([
  474. 'status',
  475. 'amount_paid',
  476. 'amount_due',
  477. 'created_by',
  478. 'updated_by',
  479. 'created_at',
  480. 'updated_at',
  481. 'bill_number',
  482. 'date',
  483. 'due_date',
  484. 'paid_at',
  485. ])
  486. ->beforeReplicaSaved(function (Bill $replica) {
  487. $replica->status = BillStatus::Open;
  488. $replica->bill_number = Bill::getNextDocumentNumber();
  489. $replica->date = now();
  490. $replica->due_date = now()->addDays($replica->company->defaultBill->payment_terms->getDays());
  491. })
  492. ->withReplicatedRelationships(['lineItems'])
  493. ->withExcludedRelationshipAttributes('lineItems', [
  494. 'subtotal',
  495. 'total',
  496. 'created_by',
  497. 'updated_by',
  498. 'created_at',
  499. 'updated_at',
  500. ]),
  501. Tables\Actions\BulkAction::make('recordPayments')
  502. ->label('Record payments')
  503. ->icon('heroicon-o-credit-card')
  504. ->stickyModalHeader()
  505. ->stickyModalFooter()
  506. ->modalFooterActionsAlignment(Alignment::End)
  507. ->modalWidth(MaxWidth::TwoExtraLarge)
  508. ->databaseTransaction()
  509. ->successNotificationTitle('Payments recorded')
  510. ->failureNotificationTitle('Failed to record payments')
  511. ->deselectRecordsAfterCompletion()
  512. ->beforeFormFilled(function (Collection $records, Tables\Actions\BulkAction $action) {
  513. $isInvalid = $records->contains(fn (Bill $bill) => ! $bill->canRecordPayment());
  514. if ($isInvalid) {
  515. Notification::make()
  516. ->title('Payment recording failed')
  517. ->body('Bills that are either paid, voided, or are in a foreign currency cannot be processed through bulk payments. Please adjust your selection and try again.')
  518. ->persistent()
  519. ->danger()
  520. ->send();
  521. $action->cancel(true);
  522. }
  523. })
  524. ->mountUsing(function (Collection $records, Form $form) {
  525. $totalAmountDue = $records->sum(fn (Bill $bill) => $bill->getRawOriginal('amount_due'));
  526. $form->fill([
  527. 'posted_at' => now(),
  528. 'amount' => CurrencyConverter::convertCentsToFormatSimple($totalAmountDue),
  529. ]);
  530. })
  531. ->form([
  532. Forms\Components\DatePicker::make('posted_at')
  533. ->label('Date'),
  534. Forms\Components\TextInput::make('amount')
  535. ->label('Amount')
  536. ->required()
  537. ->money()
  538. ->rules([
  539. static fn (): Closure => static function (string $attribute, $value, Closure $fail) {
  540. if (! CurrencyConverter::isValidAmount($value)) {
  541. $fail('Please enter a valid amount');
  542. }
  543. },
  544. ]),
  545. Forms\Components\Select::make('payment_method')
  546. ->label('Payment method')
  547. ->required()
  548. ->options(PaymentMethod::class),
  549. Forms\Components\Select::make('bank_account_id')
  550. ->label('Account')
  551. ->required()
  552. ->options(function () {
  553. return BankAccount::query()
  554. ->join('accounts', 'bank_accounts.account_id', '=', 'accounts.id')
  555. ->select(['bank_accounts.id', 'accounts.name'])
  556. ->pluck('accounts.name', 'bank_accounts.id')
  557. ->toArray();
  558. })
  559. ->searchable(),
  560. Forms\Components\Textarea::make('notes')
  561. ->label('Notes'),
  562. ])
  563. ->before(function (Collection $records, Tables\Actions\BulkAction $action, array $data) {
  564. $totalPaymentAmount = CurrencyConverter::convertToCents($data['amount']);
  565. $totalAmountDue = $records->sum(fn (Bill $bill) => $bill->getRawOriginal('amount_due'));
  566. if ($totalPaymentAmount > $totalAmountDue) {
  567. $formattedTotalAmountDue = CurrencyConverter::formatCentsToMoney($totalAmountDue);
  568. Notification::make()
  569. ->title('Excess payment amount')
  570. ->body("The payment amount exceeds the total amount due of {$formattedTotalAmountDue}. Please adjust the payment amount and try again.")
  571. ->persistent()
  572. ->warning()
  573. ->send();
  574. $action->halt(true);
  575. }
  576. })
  577. ->action(function (Collection $records, Tables\Actions\BulkAction $action, array $data) {
  578. $totalPaymentAmount = CurrencyConverter::convertToCents($data['amount']);
  579. $remainingAmount = $totalPaymentAmount;
  580. $records->each(function (Bill $record) use (&$remainingAmount, $data) {
  581. $amountDue = $record->getRawOriginal('amount_due');
  582. if ($amountDue <= 0 || $remainingAmount <= 0) {
  583. return;
  584. }
  585. $paymentAmount = min($amountDue, $remainingAmount);
  586. $data['amount'] = CurrencyConverter::convertCentsToFormatSimple($paymentAmount);
  587. $record->recordPayment($data);
  588. $remainingAmount -= $paymentAmount;
  589. });
  590. $action->success();
  591. }),
  592. ]),
  593. ]);
  594. }
  595. public static function getPages(): array
  596. {
  597. return [
  598. 'index' => Pages\ListBills::route('/'),
  599. 'create' => Pages\CreateBill::route('/create'),
  600. 'view' => Pages\ViewBill::route('/{record}'),
  601. 'edit' => Pages\EditBill::route('/{record}/edit'),
  602. ];
  603. }
  604. public static function getWidgets(): array
  605. {
  606. return [
  607. BillResource\Widgets\BillOverview::class,
  608. ];
  609. }
  610. }