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

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