您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

BillResource.php 30KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  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(function () {
  350. return BankAccount::query()
  351. ->join('accounts', 'bank_accounts.account_id', '=', 'accounts.id')
  352. ->select(['bank_accounts.id', 'accounts.name'])
  353. ->pluck('accounts.name', 'bank_accounts.id')
  354. ->toArray();
  355. })
  356. ->searchable(),
  357. Forms\Components\Textarea::make('notes')
  358. ->label('Notes'),
  359. ])
  360. ->action(function (Bill $record, Tables\Actions\Action $action, array $data) {
  361. $record->recordPayment($data);
  362. $action->success();
  363. }),
  364. ])->dropdown(false),
  365. Tables\Actions\DeleteAction::make(),
  366. ]),
  367. ])
  368. ->bulkActions([
  369. Tables\Actions\BulkActionGroup::make([
  370. Tables\Actions\DeleteBulkAction::make(),
  371. ReplicateBulkAction::make()
  372. ->label('Replicate')
  373. ->modalWidth(MaxWidth::Large)
  374. ->modalDescription('Replicating bills will also replicate their line items. Are you sure you want to proceed?')
  375. ->successNotificationTitle('Bills replicated successfully')
  376. ->failureNotificationTitle('Failed to replicate bills')
  377. ->databaseTransaction()
  378. ->deselectRecordsAfterCompletion()
  379. ->excludeAttributes([
  380. 'status',
  381. 'amount_paid',
  382. 'amount_due',
  383. 'created_by',
  384. 'updated_by',
  385. 'created_at',
  386. 'updated_at',
  387. 'bill_number',
  388. 'date',
  389. 'due_date',
  390. 'paid_at',
  391. ])
  392. ->beforeReplicaSaved(function (Bill $replica) {
  393. $replica->status = BillStatus::Open;
  394. $replica->bill_number = Bill::getNextDocumentNumber();
  395. $replica->date = now();
  396. $replica->due_date = now()->addDays($replica->company->defaultBill->payment_terms->getDays());
  397. })
  398. ->withReplicatedRelationships(['lineItems'])
  399. ->withExcludedRelationshipAttributes('lineItems', [
  400. 'subtotal',
  401. 'total',
  402. 'created_by',
  403. 'updated_by',
  404. 'created_at',
  405. 'updated_at',
  406. ]),
  407. Tables\Actions\BulkAction::make('recordPayments')
  408. ->label('Record payments')
  409. ->icon('heroicon-o-credit-card')
  410. ->stickyModalHeader()
  411. ->stickyModalFooter()
  412. ->modalFooterActionsAlignment(Alignment::End)
  413. ->modalWidth(MaxWidth::TwoExtraLarge)
  414. ->databaseTransaction()
  415. ->successNotificationTitle('Payments recorded')
  416. ->failureNotificationTitle('Failed to record payments')
  417. ->deselectRecordsAfterCompletion()
  418. ->beforeFormFilled(function (Collection $records, Tables\Actions\BulkAction $action) {
  419. $isInvalid = $records->contains(fn (Bill $bill) => ! $bill->canRecordPayment());
  420. if ($isInvalid) {
  421. Notification::make()
  422. ->title('Payment recording failed')
  423. ->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.')
  424. ->persistent()
  425. ->danger()
  426. ->send();
  427. $action->cancel(true);
  428. }
  429. })
  430. ->mountUsing(function (Collection $records, Form $form) {
  431. $totalAmountDue = $records->sum(fn (Bill $bill) => $bill->getRawOriginal('amount_due'));
  432. $form->fill([
  433. 'posted_at' => now(),
  434. 'amount' => CurrencyConverter::convertCentsToFormatSimple($totalAmountDue),
  435. ]);
  436. })
  437. ->form([
  438. Forms\Components\DatePicker::make('posted_at')
  439. ->label('Date'),
  440. Forms\Components\TextInput::make('amount')
  441. ->label('Amount')
  442. ->required()
  443. ->money()
  444. ->rules([
  445. static fn (): Closure => static function (string $attribute, $value, Closure $fail) {
  446. if (! CurrencyConverter::isValidAmount($value)) {
  447. $fail('Please enter a valid amount');
  448. }
  449. },
  450. ]),
  451. Forms\Components\Select::make('payment_method')
  452. ->label('Payment method')
  453. ->required()
  454. ->options(PaymentMethod::class),
  455. Forms\Components\Select::make('bank_account_id')
  456. ->label('Account')
  457. ->required()
  458. ->options(function () {
  459. return BankAccount::query()
  460. ->join('accounts', 'bank_accounts.account_id', '=', 'accounts.id')
  461. ->select(['bank_accounts.id', 'accounts.name'])
  462. ->pluck('accounts.name', 'bank_accounts.id')
  463. ->toArray();
  464. })
  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. BillResource\RelationManagers\PaymentsRelationManager::class,
  505. ];
  506. }
  507. public static function getPages(): array
  508. {
  509. return [
  510. 'index' => Pages\ListBills::route('/'),
  511. 'create' => Pages\CreateBill::route('/create'),
  512. 'view' => Pages\ViewBill::route('/{record}'),
  513. 'edit' => Pages\EditBill::route('/{record}/edit'),
  514. ];
  515. }
  516. public static function getWidgets(): array
  517. {
  518. return [
  519. BillResource\Widgets\BillOverview::class,
  520. ];
  521. }
  522. }