Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

BillResource.php 31KB

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