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 30KB

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