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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  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. $set('description', $offeringRecord->description);
  139. $set('unit_price', $offeringRecord->price);
  140. $set('purchaseTaxes', $offeringRecord->purchaseTaxes->pluck('id')->toArray());
  141. $discountMethod = DocumentDiscountMethod::parse($get('../../discount_method'));
  142. if ($discountMethod->isPerLineItem()) {
  143. $set('purchaseDiscounts', $offeringRecord->purchaseDiscounts->pluck('id')->toArray());
  144. }
  145. }
  146. }),
  147. Forms\Components\TextInput::make('description'),
  148. Forms\Components\TextInput::make('quantity')
  149. ->required()
  150. ->numeric()
  151. ->live()
  152. ->maxValue(9999999999.99)
  153. ->default(1),
  154. Forms\Components\TextInput::make('unit_price')
  155. ->label('Price')
  156. ->hiddenLabel()
  157. ->numeric()
  158. ->live()
  159. ->maxValue(9999999999.99)
  160. ->default(0),
  161. Forms\Components\Select::make('purchaseTaxes')
  162. ->label('Taxes')
  163. ->relationship('purchaseTaxes', 'name')
  164. ->saveRelationshipsUsing(null)
  165. ->dehydrated(true)
  166. ->preload()
  167. ->multiple()
  168. ->live()
  169. ->searchable(),
  170. Forms\Components\Select::make('purchaseDiscounts')
  171. ->label('Discounts')
  172. ->relationship('purchaseDiscounts', 'name')
  173. ->saveRelationshipsUsing(null)
  174. ->dehydrated(true)
  175. ->preload()
  176. ->multiple()
  177. ->live()
  178. ->hidden(function (Forms\Get $get) {
  179. $discountMethod = DocumentDiscountMethod::parse($get('../../discount_method'));
  180. return $discountMethod->isPerDocument();
  181. })
  182. ->searchable(),
  183. Forms\Components\Placeholder::make('total')
  184. ->hiddenLabel()
  185. ->extraAttributes(['class' => 'text-left sm:text-right'])
  186. ->content(function (Forms\Get $get) {
  187. $quantity = max((float) ($get('quantity') ?? 0), 0);
  188. $unitPrice = max((float) ($get('unit_price') ?? 0), 0);
  189. $purchaseTaxes = $get('purchaseTaxes') ?? [];
  190. $purchaseDiscounts = $get('purchaseDiscounts') ?? [];
  191. $currencyCode = $get('../../currency_code') ?? CurrencyAccessor::getDefaultCurrency();
  192. $subtotal = $quantity * $unitPrice;
  193. $subtotalInCents = CurrencyConverter::convertToCents($subtotal, $currencyCode);
  194. $taxAmountInCents = Adjustment::whereIn('id', $purchaseTaxes)
  195. ->get()
  196. ->sum(function (Adjustment $adjustment) use ($subtotalInCents) {
  197. if ($adjustment->computation->isPercentage()) {
  198. return RateCalculator::calculatePercentage($subtotalInCents, $adjustment->getRawOriginal('rate'));
  199. } else {
  200. return $adjustment->getRawOriginal('rate');
  201. }
  202. });
  203. $discountAmountInCents = Adjustment::whereIn('id', $purchaseDiscounts)
  204. ->get()
  205. ->sum(function (Adjustment $adjustment) use ($subtotalInCents) {
  206. if ($adjustment->computation->isPercentage()) {
  207. return RateCalculator::calculatePercentage($subtotalInCents, $adjustment->getRawOriginal('rate'));
  208. } else {
  209. return $adjustment->getRawOriginal('rate');
  210. }
  211. });
  212. // Final total
  213. $totalInCents = $subtotalInCents + ($taxAmountInCents - $discountAmountInCents);
  214. return CurrencyConverter::formatCentsToMoney($totalInCents, $currencyCode);
  215. }),
  216. ]),
  217. DocumentTotals::make()
  218. ->type(DocumentType::Bill),
  219. ]),
  220. ]);
  221. }
  222. public static function table(Table $table): Table
  223. {
  224. return $table
  225. ->defaultSort('due_date')
  226. ->columns([
  227. Columns::id(),
  228. Tables\Columns\TextColumn::make('status')
  229. ->badge()
  230. ->searchable(),
  231. Tables\Columns\TextColumn::make('due_date')
  232. ->label('Due')
  233. ->asRelativeDay()
  234. ->sortable(),
  235. Tables\Columns\TextColumn::make('date')
  236. ->date()
  237. ->sortable(),
  238. Tables\Columns\TextColumn::make('bill_number')
  239. ->label('Number')
  240. ->searchable()
  241. ->sortable(),
  242. Tables\Columns\TextColumn::make('vendor.name')
  243. ->sortable()
  244. ->searchable()
  245. ->hiddenOn(BillsRelationManager::class),
  246. Tables\Columns\TextColumn::make('total')
  247. ->currencyWithConversion(static fn (Bill $record) => $record->currency_code)
  248. ->sortable()
  249. ->toggleable(),
  250. Tables\Columns\TextColumn::make('amount_paid')
  251. ->label('Amount paid')
  252. ->currencyWithConversion(static fn (Bill $record) => $record->currency_code)
  253. ->sortable()
  254. ->toggleable(),
  255. Tables\Columns\TextColumn::make('amount_due')
  256. ->label('Amount due')
  257. ->currencyWithConversion(static fn (Bill $record) => $record->currency_code)
  258. ->sortable(),
  259. ])
  260. ->filters([
  261. Tables\Filters\SelectFilter::make('vendor')
  262. ->relationship('vendor', 'name')
  263. ->searchable()
  264. ->preload(),
  265. Tables\Filters\SelectFilter::make('status')
  266. ->options(BillStatus::class)
  267. ->native(false),
  268. Tables\Filters\TernaryFilter::make('has_payments')
  269. ->label('Has payments')
  270. ->queries(
  271. true: fn (Builder $query) => $query->whereHas('payments'),
  272. false: fn (Builder $query) => $query->whereDoesntHave('payments'),
  273. ),
  274. DateRangeFilter::make('date')
  275. ->fromLabel('From date')
  276. ->untilLabel('To date')
  277. ->indicatorLabel('Date'),
  278. DateRangeFilter::make('due_date')
  279. ->fromLabel('From due date')
  280. ->untilLabel('To due date')
  281. ->indicatorLabel('Due'),
  282. ])
  283. ->actions([
  284. Tables\Actions\ActionGroup::make([
  285. Tables\Actions\ActionGroup::make([
  286. Tables\Actions\EditAction::make(),
  287. Tables\Actions\ViewAction::make(),
  288. Bill::getReplicateAction(Tables\Actions\ReplicateAction::class),
  289. Tables\Actions\Action::make('recordPayment')
  290. ->label('Record payment')
  291. ->stickyModalHeader()
  292. ->stickyModalFooter()
  293. ->modalFooterActionsAlignment(Alignment::End)
  294. ->modalWidth(MaxWidth::TwoExtraLarge)
  295. ->icon('heroicon-o-credit-card')
  296. ->visible(function (Bill $record) {
  297. return $record->canRecordPayment();
  298. })
  299. ->mountUsing(function (Bill $record, Form $form) {
  300. $form->fill([
  301. 'posted_at' => now(),
  302. 'amount' => $record->amount_due,
  303. ]);
  304. })
  305. ->databaseTransaction()
  306. ->successNotificationTitle('Payment recorded')
  307. ->form([
  308. Forms\Components\DatePicker::make('posted_at')
  309. ->label('Date'),
  310. Forms\Components\TextInput::make('amount')
  311. ->label('Amount')
  312. ->required()
  313. ->money(fn (Bill $record) => $record->currency_code)
  314. ->live(onBlur: true)
  315. ->helperText(function (Bill $record, $state) {
  316. $billCurrency = $record->currency_code;
  317. if (! CurrencyConverter::isValidAmount($state, $billCurrency)) {
  318. return null;
  319. }
  320. $amountDue = $record->getRawOriginal('amount_due');
  321. $amount = CurrencyConverter::convertToCents($state, $billCurrency);
  322. if ($amount <= 0) {
  323. return 'Please enter a valid positive amount';
  324. }
  325. $newAmountDue = $amountDue - $amount;
  326. return match (true) {
  327. $newAmountDue > 0 => 'Amount due after payment will be ' . CurrencyConverter::formatCentsToMoney($newAmountDue, $billCurrency),
  328. $newAmountDue === 0 => 'Bill will be fully paid',
  329. default => 'Amount exceeds bill total by ' . CurrencyConverter::formatCentsToMoney(abs($newAmountDue), $billCurrency),
  330. };
  331. })
  332. ->rules([
  333. static fn (Bill $record): Closure => static function (string $attribute, $value, Closure $fail) use ($record) {
  334. if (! CurrencyConverter::isValidAmount($value, $record->currency_code)) {
  335. $fail('Please enter a valid amount');
  336. }
  337. },
  338. ]),
  339. Forms\Components\Select::make('payment_method')
  340. ->label('Payment method')
  341. ->required()
  342. ->options(PaymentMethod::class),
  343. Forms\Components\Select::make('bank_account_id')
  344. ->label('Account')
  345. ->required()
  346. ->options(BankAccount::query()
  347. ->get()
  348. ->pluck('account.name', 'id'))
  349. ->searchable(),
  350. Forms\Components\Textarea::make('notes')
  351. ->label('Notes'),
  352. ])
  353. ->action(function (Bill $record, Tables\Actions\Action $action, array $data) {
  354. $record->recordPayment($data);
  355. $action->success();
  356. }),
  357. ])->dropdown(false),
  358. Tables\Actions\DeleteAction::make(),
  359. ]),
  360. ])
  361. ->bulkActions([
  362. Tables\Actions\BulkActionGroup::make([
  363. Tables\Actions\DeleteBulkAction::make(),
  364. ReplicateBulkAction::make()
  365. ->label('Replicate')
  366. ->modalWidth(MaxWidth::Large)
  367. ->modalDescription('Replicating bills will also replicate their line items. Are you sure you want to proceed?')
  368. ->successNotificationTitle('Bills replicated successfully')
  369. ->failureNotificationTitle('Failed to replicate bills')
  370. ->databaseTransaction()
  371. ->deselectRecordsAfterCompletion()
  372. ->excludeAttributes([
  373. 'status',
  374. 'amount_paid',
  375. 'amount_due',
  376. 'created_by',
  377. 'updated_by',
  378. 'created_at',
  379. 'updated_at',
  380. 'bill_number',
  381. 'date',
  382. 'due_date',
  383. 'paid_at',
  384. ])
  385. ->beforeReplicaSaved(function (Bill $replica) {
  386. $replica->status = BillStatus::Open;
  387. $replica->bill_number = Bill::getNextDocumentNumber();
  388. $replica->date = now();
  389. $replica->due_date = now()->addDays($replica->company->defaultBill->payment_terms->getDays());
  390. })
  391. ->withReplicatedRelationships(['lineItems'])
  392. ->withExcludedRelationshipAttributes('lineItems', [
  393. 'subtotal',
  394. 'total',
  395. 'created_by',
  396. 'updated_by',
  397. 'created_at',
  398. 'updated_at',
  399. ]),
  400. Tables\Actions\BulkAction::make('recordPayments')
  401. ->label('Record payments')
  402. ->icon('heroicon-o-credit-card')
  403. ->stickyModalHeader()
  404. ->stickyModalFooter()
  405. ->modalFooterActionsAlignment(Alignment::End)
  406. ->modalWidth(MaxWidth::TwoExtraLarge)
  407. ->databaseTransaction()
  408. ->successNotificationTitle('Payments recorded')
  409. ->failureNotificationTitle('Failed to record payments')
  410. ->deselectRecordsAfterCompletion()
  411. ->beforeFormFilled(function (Collection $records, Tables\Actions\BulkAction $action) {
  412. $isInvalid = $records->contains(fn (Bill $bill) => ! $bill->canRecordPayment());
  413. if ($isInvalid) {
  414. Notification::make()
  415. ->title('Payment recording failed')
  416. ->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.')
  417. ->persistent()
  418. ->danger()
  419. ->send();
  420. $action->cancel(true);
  421. }
  422. })
  423. ->mountUsing(function (Collection $records, Form $form) {
  424. $totalAmountDue = $records->sum(fn (Bill $bill) => $bill->getRawOriginal('amount_due'));
  425. $form->fill([
  426. 'posted_at' => now(),
  427. 'amount' => CurrencyConverter::convertCentsToFormatSimple($totalAmountDue),
  428. ]);
  429. })
  430. ->form([
  431. Forms\Components\DatePicker::make('posted_at')
  432. ->label('Date'),
  433. Forms\Components\TextInput::make('amount')
  434. ->label('Amount')
  435. ->required()
  436. ->money()
  437. ->rules([
  438. static fn (): Closure => static function (string $attribute, $value, Closure $fail) {
  439. if (! CurrencyConverter::isValidAmount($value)) {
  440. $fail('Please enter a valid amount');
  441. }
  442. },
  443. ]),
  444. Forms\Components\Select::make('payment_method')
  445. ->label('Payment method')
  446. ->required()
  447. ->options(PaymentMethod::class),
  448. Forms\Components\Select::make('bank_account_id')
  449. ->label('Account')
  450. ->required()
  451. ->options(BankAccount::query()
  452. ->get()
  453. ->pluck('account.name', 'id'))
  454. ->searchable(),
  455. Forms\Components\Textarea::make('notes')
  456. ->label('Notes'),
  457. ])
  458. ->before(function (Collection $records, Tables\Actions\BulkAction $action, array $data) {
  459. $totalPaymentAmount = CurrencyConverter::convertToCents($data['amount']);
  460. $totalAmountDue = $records->sum(fn (Bill $bill) => $bill->getRawOriginal('amount_due'));
  461. if ($totalPaymentAmount > $totalAmountDue) {
  462. $formattedTotalAmountDue = CurrencyConverter::formatCentsToMoney($totalAmountDue);
  463. Notification::make()
  464. ->title('Excess payment amount')
  465. ->body("The payment amount exceeds the total amount due of {$formattedTotalAmountDue}. Please adjust the payment amount and try again.")
  466. ->persistent()
  467. ->warning()
  468. ->send();
  469. $action->halt(true);
  470. }
  471. })
  472. ->action(function (Collection $records, Tables\Actions\BulkAction $action, array $data) {
  473. $totalPaymentAmount = CurrencyConverter::convertToCents($data['amount']);
  474. $remainingAmount = $totalPaymentAmount;
  475. $records->each(function (Bill $record) use (&$remainingAmount, $data) {
  476. $amountDue = $record->getRawOriginal('amount_due');
  477. if ($amountDue <= 0 || $remainingAmount <= 0) {
  478. return;
  479. }
  480. $paymentAmount = min($amountDue, $remainingAmount);
  481. $data['amount'] = CurrencyConverter::convertCentsToFormatSimple($paymentAmount);
  482. $record->recordPayment($data);
  483. $remainingAmount -= $paymentAmount;
  484. });
  485. $action->success();
  486. }),
  487. ]),
  488. ]);
  489. }
  490. public static function getRelations(): array
  491. {
  492. return [
  493. BillResource\RelationManagers\PaymentsRelationManager::class,
  494. ];
  495. }
  496. public static function getPages(): array
  497. {
  498. return [
  499. 'index' => Pages\ListBills::route('/'),
  500. 'create' => Pages\CreateBill::route('/create'),
  501. 'view' => Pages\ViewBill::route('/{record}'),
  502. 'edit' => Pages\EditBill::route('/{record}/edit'),
  503. ];
  504. }
  505. public static function getWidgets(): array
  506. {
  507. return [
  508. BillResource\Widgets\BillOverview::class,
  509. ];
  510. }
  511. }