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.

BillResource.php 28KB

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