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

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