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

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