您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

BillResource.php 37KB

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