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

InvoiceResource.php 44KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800
  1. <?php
  2. namespace App\Filament\Company\Resources\Sales;
  3. use App\Collections\Accounting\DocumentCollection;
  4. use App\Enums\Accounting\AdjustmentCategory;
  5. use App\Enums\Accounting\AdjustmentStatus;
  6. use App\Enums\Accounting\AdjustmentType;
  7. use App\Enums\Accounting\DocumentDiscountMethod;
  8. use App\Enums\Accounting\DocumentType;
  9. use App\Enums\Accounting\InvoiceStatus;
  10. use App\Enums\Accounting\PaymentMethod;
  11. use App\Enums\Setting\PaymentTerms;
  12. use App\Filament\Company\Resources\Sales\ClientResource\RelationManagers\InvoicesRelationManager;
  13. use App\Filament\Company\Resources\Sales\InvoiceResource\Pages;
  14. use App\Filament\Company\Resources\Sales\InvoiceResource\Widgets;
  15. use App\Filament\Forms\Components\CreateAdjustmentSelect;
  16. use App\Filament\Forms\Components\CreateClientSelect;
  17. use App\Filament\Forms\Components\CreateCurrencySelect;
  18. use App\Filament\Forms\Components\CreateOfferingSelect;
  19. use App\Filament\Forms\Components\CustomTableRepeater;
  20. use App\Filament\Forms\Components\DocumentFooterSection;
  21. use App\Filament\Forms\Components\DocumentHeaderSection;
  22. use App\Filament\Forms\Components\DocumentTotals;
  23. use App\Filament\Tables\Actions\ReplicateBulkAction;
  24. use App\Filament\Tables\Columns;
  25. use App\Filament\Tables\Filters\DateRangeFilter;
  26. use App\Models\Accounting\Adjustment;
  27. use App\Models\Accounting\DocumentLineItem;
  28. use App\Models\Accounting\Invoice;
  29. use App\Models\Banking\BankAccount;
  30. use App\Models\Common\Client;
  31. use App\Models\Common\Offering;
  32. use App\Utilities\Currency\CurrencyAccessor;
  33. use App\Utilities\Currency\CurrencyConverter;
  34. use App\Utilities\RateCalculator;
  35. use Awcodes\TableRepeater\Header;
  36. use Closure;
  37. use Filament\Forms;
  38. use Filament\Forms\Form;
  39. use Filament\Notifications\Notification;
  40. use Filament\Resources\Resource;
  41. use Filament\Support\Enums\Alignment;
  42. use Filament\Support\Enums\MaxWidth;
  43. use Filament\Tables;
  44. use Filament\Tables\Table;
  45. use Guava\FilamentClusters\Forms\Cluster;
  46. use Illuminate\Database\Eloquent\Builder;
  47. use Illuminate\Database\Eloquent\Collection;
  48. use Illuminate\Support\Carbon;
  49. use Illuminate\Support\Facades\Auth;
  50. class InvoiceResource extends Resource
  51. {
  52. protected static ?string $model = Invoice::class;
  53. public static function form(Form $form): Form
  54. {
  55. $company = Auth::user()->currentCompany;
  56. $settings = $company->defaultInvoice;
  57. return $form
  58. ->schema([
  59. DocumentHeaderSection::make('Invoice Header')
  60. ->defaultHeader($settings->header)
  61. ->defaultSubheader($settings->subheader),
  62. Forms\Components\Section::make('Invoice Details')
  63. ->schema([
  64. Forms\Components\Split::make([
  65. Forms\Components\Group::make([
  66. CreateClientSelect::make('client_id')
  67. ->label('Client')
  68. ->required()
  69. ->live()
  70. ->afterStateUpdated(function (Forms\Set $set, Forms\Get $get, $state) {
  71. if (! $state) {
  72. return;
  73. }
  74. $currencyCode = Client::find($state)?->currency_code;
  75. if ($currencyCode) {
  76. $set('currency_code', $currencyCode);
  77. }
  78. }),
  79. CreateCurrencySelect::make('currency_code')
  80. ->disabled(function (?Invoice $record) {
  81. return $record?->hasPayments();
  82. }),
  83. ]),
  84. Forms\Components\Group::make([
  85. Forms\Components\TextInput::make('invoice_number')
  86. ->label('Invoice number')
  87. ->default(static fn () => Invoice::getNextDocumentNumber()),
  88. Forms\Components\TextInput::make('order_number')
  89. ->label('P.O/S.O Number'),
  90. Cluster::make([
  91. Forms\Components\DatePicker::make('date')
  92. ->label('Invoice date')
  93. ->live()
  94. ->default(now())
  95. ->disabled(function (?Invoice $record) {
  96. return $record?->hasPayments();
  97. })
  98. ->columnSpan(2)
  99. ->afterStateUpdated(function (Forms\Set $set, Forms\Get $get, $state) {
  100. $date = $state;
  101. $dueDate = $get('due_date');
  102. if ($date && $dueDate && $date > $dueDate) {
  103. $set('due_date', $date);
  104. }
  105. // Update due date based on payment terms if selected
  106. $paymentTerms = $get('payment_terms');
  107. if ($date && $paymentTerms && $paymentTerms !== 'custom') {
  108. $terms = PaymentTerms::parse($paymentTerms);
  109. $set('due_date', Carbon::parse($date)->addDays($terms->getDays())->toDateString());
  110. }
  111. }),
  112. Forms\Components\Select::make('payment_terms')
  113. ->label('Payment terms')
  114. ->options(function () {
  115. return collect(PaymentTerms::cases())
  116. ->mapWithKeys(function (PaymentTerms $paymentTerm) {
  117. return [$paymentTerm->value => $paymentTerm->getLabel()];
  118. })
  119. ->put('custom', 'Custom')
  120. ->toArray();
  121. })
  122. ->selectablePlaceholder(false)
  123. ->default($settings->payment_terms->value)
  124. ->live()
  125. ->afterStateUpdated(function (Forms\Set $set, Forms\Get $get, $state) {
  126. if (! $state || $state === 'custom') {
  127. return;
  128. }
  129. $date = $get('date');
  130. if ($date) {
  131. $terms = PaymentTerms::parse($state);
  132. $set('due_date', Carbon::parse($date)->addDays($terms->getDays())->toDateString());
  133. }
  134. }),
  135. ])
  136. ->label('Invoice date')
  137. ->columns(3),
  138. Forms\Components\DatePicker::make('due_date')
  139. ->label('Payment due')
  140. ->default(function () use ($settings) {
  141. return now()->addDays($settings->payment_terms->getDays());
  142. })
  143. ->minDate(static function (Forms\Get $get) {
  144. return $get('date') ?? now();
  145. })
  146. ->live()
  147. ->afterStateUpdated(function (Forms\Set $set, Forms\Get $get, $state) {
  148. if (! $state) {
  149. return;
  150. }
  151. $invoiceDate = $get('date');
  152. $paymentTerms = $get('payment_terms');
  153. if (! $invoiceDate || $paymentTerms === 'custom') {
  154. return;
  155. }
  156. $term = PaymentTerms::parse($paymentTerms);
  157. $expectedDueDate = Carbon::parse($invoiceDate)->addDays($term->getDays());
  158. if (! Carbon::parse($state)->isSameDay($expectedDueDate)) {
  159. $set('payment_terms', 'custom');
  160. }
  161. }),
  162. Forms\Components\Select::make('discount_method')
  163. ->label('Discount method')
  164. ->options(DocumentDiscountMethod::class)
  165. ->softRequired()
  166. ->default($settings->discount_method)
  167. ->afterStateUpdated(function ($state, Forms\Set $set) {
  168. $discountMethod = DocumentDiscountMethod::parse($state);
  169. if ($discountMethod->isPerDocument()) {
  170. $set('lineItems.*.salesDiscounts', []);
  171. }
  172. })
  173. ->live(),
  174. ])->grow(true),
  175. ])->from('md'),
  176. CustomTableRepeater::make('lineItems')
  177. ->hiddenLabel()
  178. ->relationship()
  179. ->saveRelationshipsUsing(null)
  180. ->dehydrated(true)
  181. ->reorderable()
  182. ->orderColumn('line_number')
  183. ->reorderAtStart()
  184. ->cloneable()
  185. ->addActionLabel('Add an item')
  186. ->headers(function (Forms\Get $get) use ($settings) {
  187. $hasDiscounts = DocumentDiscountMethod::parse($get('discount_method'))->isPerLineItem();
  188. $headers = [
  189. Header::make($settings->resolveColumnLabel('item_name', 'Items'))
  190. ->width('30%'),
  191. Header::make($settings->resolveColumnLabel('unit_name', 'Quantity'))
  192. ->width('10%'),
  193. Header::make($settings->resolveColumnLabel('price_name', 'Price'))
  194. ->width('10%'),
  195. ];
  196. if ($hasDiscounts) {
  197. $headers[] = Header::make('Adjustments')->width('30%');
  198. } else {
  199. $headers[] = Header::make('Taxes')->width('30%');
  200. }
  201. $headers[] = Header::make($settings->resolveColumnLabel('amount_name', 'Amount'))
  202. ->width('10%')
  203. ->align('right');
  204. return $headers;
  205. })
  206. ->schema([
  207. Forms\Components\Group::make([
  208. CreateOfferingSelect::make('offering_id')
  209. ->label('Item')
  210. ->hiddenLabel()
  211. ->placeholder('Select item')
  212. ->required()
  213. ->live()
  214. ->inlineSuffix()
  215. ->sellable()
  216. ->afterStateUpdated(function (Forms\Set $set, Forms\Get $get, $state, ?DocumentLineItem $record) {
  217. $offeringId = $state;
  218. $discountMethod = DocumentDiscountMethod::parse($get('../../discount_method'));
  219. $isPerLineItem = $discountMethod->isPerLineItem();
  220. $existingTaxIds = [];
  221. $existingDiscountIds = [];
  222. if ($record) {
  223. $existingTaxIds = $record->salesTaxes()->pluck('adjustments.id')->toArray();
  224. if ($isPerLineItem) {
  225. $existingDiscountIds = $record->salesDiscounts()->pluck('adjustments.id')->toArray();
  226. }
  227. }
  228. $with = [
  229. 'salesTaxes' => static function ($query) use ($existingTaxIds) {
  230. $query->where(static function ($query) use ($existingTaxIds) {
  231. $query->where('status', AdjustmentStatus::Active)
  232. ->orWhereIn('adjustments.id', $existingTaxIds);
  233. });
  234. },
  235. ];
  236. if ($isPerLineItem) {
  237. $with['salesDiscounts'] = static function ($query) use ($existingDiscountIds) {
  238. $query->where(static function ($query) use ($existingDiscountIds) {
  239. $query->where('status', AdjustmentStatus::Active)
  240. ->orWhereIn('adjustments.id', $existingDiscountIds);
  241. });
  242. };
  243. }
  244. $offeringRecord = Offering::with($with)->find($offeringId);
  245. if (! $offeringRecord) {
  246. return;
  247. }
  248. $unitPrice = CurrencyConverter::convertCentsToFormatSimple($offeringRecord->price, 'USD');
  249. $set('description', $offeringRecord->description);
  250. $set('unit_price', $unitPrice);
  251. $set('salesTaxes', $offeringRecord->salesTaxes->pluck('id')->toArray());
  252. if ($isPerLineItem) {
  253. $set('salesDiscounts', $offeringRecord->salesDiscounts->pluck('id')->toArray());
  254. }
  255. }),
  256. Forms\Components\TextInput::make('description')
  257. ->placeholder('Enter item description')
  258. ->hiddenLabel(),
  259. ])->columnSpan(1),
  260. Forms\Components\TextInput::make('quantity')
  261. ->required()
  262. ->numeric()
  263. ->live()
  264. ->maxValue(9999999999.99)
  265. ->default(1),
  266. Forms\Components\TextInput::make('unit_price')
  267. ->hiddenLabel()
  268. ->money(useAffix: false)
  269. ->live()
  270. ->default(0),
  271. Forms\Components\Group::make([
  272. CreateAdjustmentSelect::make('salesTaxes')
  273. ->label('Taxes')
  274. ->hiddenLabel()
  275. ->placeholder('Select taxes')
  276. ->category(AdjustmentCategory::Tax)
  277. ->type(AdjustmentType::Sales)
  278. ->adjustmentsRelationship('salesTaxes')
  279. ->saveRelationshipsUsing(null)
  280. ->dehydrated(true)
  281. ->inlineSuffix()
  282. ->preload()
  283. ->multiple()
  284. ->live()
  285. ->searchable(),
  286. CreateAdjustmentSelect::make('salesDiscounts')
  287. ->label('Discounts')
  288. ->hiddenLabel()
  289. ->placeholder('Select discounts')
  290. ->category(AdjustmentCategory::Discount)
  291. ->type(AdjustmentType::Sales)
  292. ->adjustmentsRelationship('salesDiscounts')
  293. ->saveRelationshipsUsing(null)
  294. ->dehydrated(true)
  295. ->inlineSuffix()
  296. ->multiple()
  297. ->live()
  298. ->hidden(function (Forms\Get $get) {
  299. $discountMethod = DocumentDiscountMethod::parse($get('../../discount_method'));
  300. return $discountMethod->isPerDocument();
  301. })
  302. ->searchable(),
  303. ])->columnSpan(1),
  304. Forms\Components\Placeholder::make('total')
  305. ->hiddenLabel()
  306. ->extraAttributes(['class' => 'text-left sm:text-right'])
  307. ->content(function (Forms\Get $get) {
  308. $quantity = max((float) ($get('quantity') ?? 0), 0);
  309. $unitPrice = CurrencyConverter::isValidAmount($get('unit_price'), 'USD')
  310. ? CurrencyConverter::convertToFloat($get('unit_price'), 'USD')
  311. : 0;
  312. $salesTaxes = $get('salesTaxes') ?? [];
  313. $salesDiscounts = $get('salesDiscounts') ?? [];
  314. $currencyCode = $get('../../currency_code') ?? CurrencyAccessor::getDefaultCurrency();
  315. $subtotal = $quantity * $unitPrice;
  316. $subtotalInCents = CurrencyConverter::convertToCents($subtotal, $currencyCode);
  317. $taxAmountInCents = Adjustment::whereIn('id', $salesTaxes)
  318. ->get()
  319. ->sum(function (Adjustment $adjustment) use ($subtotalInCents) {
  320. if ($adjustment->computation->isPercentage()) {
  321. return RateCalculator::calculatePercentage($subtotalInCents, $adjustment->getRawOriginal('rate'));
  322. } else {
  323. return $adjustment->getRawOriginal('rate');
  324. }
  325. });
  326. $discountAmountInCents = Adjustment::whereIn('id', $salesDiscounts)
  327. ->get()
  328. ->sum(function (Adjustment $adjustment) use ($subtotalInCents) {
  329. if ($adjustment->computation->isPercentage()) {
  330. return RateCalculator::calculatePercentage($subtotalInCents, $adjustment->getRawOriginal('rate'));
  331. } else {
  332. return $adjustment->getRawOriginal('rate');
  333. }
  334. });
  335. // Final total
  336. $totalInCents = $subtotalInCents + ($taxAmountInCents - $discountAmountInCents);
  337. return CurrencyConverter::formatCentsToMoney($totalInCents, $currencyCode);
  338. }),
  339. ]),
  340. DocumentTotals::make()
  341. ->type(DocumentType::Invoice),
  342. Forms\Components\Textarea::make('terms')
  343. ->default($settings->terms)
  344. ->columnSpanFull(),
  345. ]),
  346. DocumentFooterSection::make('Invoice Footer')
  347. ->defaultFooter($settings->footer),
  348. ]);
  349. }
  350. public static function table(Table $table): Table
  351. {
  352. return $table
  353. ->defaultSort('due_date')
  354. ->modifyQueryUsing(function (Builder $query, Tables\Contracts\HasTable $livewire) {
  355. if (property_exists($livewire, 'recurringInvoice')) {
  356. $recurringInvoiceId = $livewire->recurringInvoice;
  357. if (! empty($recurringInvoiceId)) {
  358. $query->where('recurring_invoice_id', $recurringInvoiceId);
  359. }
  360. }
  361. return $query;
  362. })
  363. ->columns([
  364. Columns::id(),
  365. Tables\Columns\TextColumn::make('status')
  366. ->badge()
  367. ->searchable(),
  368. Tables\Columns\TextColumn::make('due_date')
  369. ->label('Due')
  370. ->asRelativeDay()
  371. ->sortable()
  372. ->hideOnTabs(['draft']),
  373. Tables\Columns\TextColumn::make('date')
  374. ->date()
  375. ->sortable(),
  376. Tables\Columns\TextColumn::make('invoice_number')
  377. ->label('Number')
  378. ->searchable()
  379. ->description(function (Invoice $record) {
  380. return $record->source_type?->getLabel();
  381. })
  382. ->sortable(),
  383. Tables\Columns\TextColumn::make('client.name')
  384. ->sortable()
  385. ->searchable()
  386. ->hiddenOn(InvoicesRelationManager::class),
  387. Tables\Columns\TextColumn::make('total')
  388. ->currencyWithConversion(static fn (Invoice $record) => $record->currency_code)
  389. ->sortable()
  390. ->toggleable()
  391. ->alignEnd(),
  392. Tables\Columns\TextColumn::make('amount_paid')
  393. ->label('Amount paid')
  394. ->currencyWithConversion(static fn (Invoice $record) => $record->currency_code)
  395. ->sortable()
  396. ->alignEnd()
  397. ->showOnTabs(['unpaid']),
  398. Tables\Columns\TextColumn::make('amount_due')
  399. ->label('Amount due')
  400. ->currencyWithConversion(static fn (Invoice $record) => $record->currency_code)
  401. ->sortable()
  402. ->alignEnd()
  403. ->hideOnTabs(['draft']),
  404. ])
  405. ->filters([
  406. Tables\Filters\SelectFilter::make('client')
  407. ->relationship('client', 'name')
  408. ->searchable()
  409. ->preload()
  410. ->hiddenOn(InvoicesRelationManager::class),
  411. Tables\Filters\SelectFilter::make('status')
  412. ->options(InvoiceStatus::class)
  413. ->multiple(),
  414. Tables\Filters\TernaryFilter::make('has_payments')
  415. ->label('Has payments')
  416. ->queries(
  417. true: fn (Builder $query) => $query->whereHas('payments'),
  418. false: fn (Builder $query) => $query->whereDoesntHave('payments'),
  419. ),
  420. Tables\Filters\SelectFilter::make('source_type')
  421. ->label('Source type')
  422. ->options([
  423. DocumentType::Estimate->value => DocumentType::Estimate->getLabel(),
  424. DocumentType::RecurringInvoice->value => DocumentType::RecurringInvoice->getLabel(),
  425. ])
  426. ->native(false)
  427. ->query(function (Builder $query, array $data) {
  428. $sourceType = $data['value'] ?? null;
  429. return match ($sourceType) {
  430. DocumentType::Estimate->value => $query->whereNotNull('estimate_id'),
  431. DocumentType::RecurringInvoice->value => $query->whereNotNull('recurring_invoice_id'),
  432. default => $query,
  433. };
  434. }),
  435. DateRangeFilter::make('date')
  436. ->fromLabel('From date')
  437. ->untilLabel('To date')
  438. ->indicatorLabel('Date'),
  439. DateRangeFilter::make('due_date')
  440. ->fromLabel('From due date')
  441. ->untilLabel('To due date')
  442. ->indicatorLabel('Due'),
  443. ])
  444. ->actions([
  445. Tables\Actions\ActionGroup::make([
  446. Tables\Actions\ActionGroup::make([
  447. Tables\Actions\EditAction::make()
  448. ->url(static fn (Invoice $record) => Pages\EditInvoice::getUrl(['record' => $record])),
  449. Tables\Actions\ViewAction::make()
  450. ->url(static fn (Invoice $record) => Pages\ViewInvoice::getUrl(['record' => $record])),
  451. Invoice::getReplicateAction(Tables\Actions\ReplicateAction::class),
  452. Invoice::getApproveDraftAction(Tables\Actions\Action::class),
  453. Invoice::getMarkAsSentAction(Tables\Actions\Action::class),
  454. Tables\Actions\Action::make('recordPayment')
  455. ->label(fn (Invoice $record) => $record->status === InvoiceStatus::Overpaid ? 'Refund Overpayment' : 'Record Payment')
  456. ->stickyModalHeader()
  457. ->stickyModalFooter()
  458. ->modalFooterActionsAlignment(Alignment::End)
  459. ->modalWidth(MaxWidth::TwoExtraLarge)
  460. ->icon('heroicon-o-credit-card')
  461. ->visible(function (Invoice $record) {
  462. return $record->canRecordPayment();
  463. })
  464. ->mountUsing(function (Invoice $record, Form $form) {
  465. $form->fill([
  466. 'posted_at' => now(),
  467. 'amount' => $record->status === InvoiceStatus::Overpaid ? ltrim($record->amount_due, '-') : $record->amount_due,
  468. ]);
  469. })
  470. ->databaseTransaction()
  471. ->successNotificationTitle('Payment recorded')
  472. ->form([
  473. Forms\Components\DatePicker::make('posted_at')
  474. ->label('Date'),
  475. Forms\Components\TextInput::make('amount')
  476. ->label('Amount')
  477. ->required()
  478. ->money(fn (Invoice $record) => $record->currency_code)
  479. ->live(onBlur: true)
  480. ->helperText(function (Invoice $record, $state) {
  481. $invoiceCurrency = $record->currency_code;
  482. if (! CurrencyConverter::isValidAmount($state, 'USD')) {
  483. return null;
  484. }
  485. $amountDue = $record->amount_due;
  486. $amount = CurrencyConverter::convertToCents($state, 'USD');
  487. if ($amount <= 0) {
  488. return 'Please enter a valid positive amount';
  489. }
  490. if ($record->status === InvoiceStatus::Overpaid) {
  491. $newAmountDue = $amountDue + $amount;
  492. } else {
  493. $newAmountDue = $amountDue - $amount;
  494. }
  495. return match (true) {
  496. $newAmountDue > 0 => 'Amount due after payment will be ' . CurrencyConverter::formatCentsToMoney($newAmountDue, $invoiceCurrency),
  497. $newAmountDue === 0 => 'Invoice will be fully paid',
  498. default => 'Invoice will be overpaid by ' . CurrencyConverter::formatCentsToMoney(abs($newAmountDue), $invoiceCurrency),
  499. };
  500. })
  501. ->rules([
  502. static fn (): Closure => static function (string $attribute, $value, Closure $fail) {
  503. if (! CurrencyConverter::isValidAmount($value, 'USD')) {
  504. $fail('Please enter a valid amount');
  505. }
  506. },
  507. ]),
  508. Forms\Components\Select::make('payment_method')
  509. ->label('Payment method')
  510. ->required()
  511. ->options(PaymentMethod::class),
  512. Forms\Components\Select::make('bank_account_id')
  513. ->label('Account')
  514. ->required()
  515. ->options(function () {
  516. return BankAccount::query()
  517. ->join('accounts', 'bank_accounts.account_id', '=', 'accounts.id')
  518. ->select(['bank_accounts.id', 'accounts.name'])
  519. ->pluck('accounts.name', 'bank_accounts.id')
  520. ->toArray();
  521. })
  522. ->searchable(),
  523. Forms\Components\Textarea::make('notes')
  524. ->label('Notes'),
  525. ])
  526. ->action(function (Invoice $record, Tables\Actions\Action $action, array $data) {
  527. $record->recordPayment($data);
  528. $action->success();
  529. }),
  530. ])->dropdown(false),
  531. Tables\Actions\DeleteAction::make(),
  532. ]),
  533. ])
  534. ->bulkActions([
  535. Tables\Actions\BulkActionGroup::make([
  536. Tables\Actions\DeleteBulkAction::make(),
  537. ReplicateBulkAction::make()
  538. ->label('Replicate')
  539. ->modalWidth(MaxWidth::Large)
  540. ->modalDescription('Replicating invoices will also replicate their line items. Are you sure you want to proceed?')
  541. ->successNotificationTitle('Invoices replicated successfully')
  542. ->failureNotificationTitle('Failed to replicate invoices')
  543. ->databaseTransaction()
  544. ->excludeAttributes([
  545. 'status',
  546. 'amount_paid',
  547. 'amount_due',
  548. 'created_by',
  549. 'updated_by',
  550. 'created_at',
  551. 'updated_at',
  552. 'invoice_number',
  553. 'date',
  554. 'due_date',
  555. 'approved_at',
  556. 'paid_at',
  557. 'last_sent_at',
  558. 'last_viewed_at',
  559. ])
  560. ->beforeReplicaSaved(function (Invoice $replica) {
  561. $replica->status = InvoiceStatus::Draft;
  562. $replica->invoice_number = Invoice::getNextDocumentNumber();
  563. $replica->date = now();
  564. $replica->due_date = now()->addDays($replica->company->defaultInvoice->payment_terms->getDays());
  565. })
  566. ->withReplicatedRelationships(['lineItems'])
  567. ->withExcludedRelationshipAttributes('lineItems', [
  568. 'subtotal',
  569. 'total',
  570. 'created_by',
  571. 'updated_by',
  572. 'created_at',
  573. 'updated_at',
  574. ]),
  575. Tables\Actions\BulkAction::make('approveDrafts')
  576. ->label('Approve')
  577. ->icon('heroicon-o-check-circle')
  578. ->databaseTransaction()
  579. ->successNotificationTitle('Invoices approved')
  580. ->failureNotificationTitle('Failed to Approve Invoices')
  581. ->before(function (Collection $records, Tables\Actions\BulkAction $action) {
  582. $isInvalid = $records->contains(fn (Invoice $record) => ! $record->canBeApproved());
  583. if ($isInvalid) {
  584. Notification::make()
  585. ->title('Approval failed')
  586. ->body('Only draft invoices can be approved. Please adjust your selection and try again.')
  587. ->persistent()
  588. ->danger()
  589. ->send();
  590. $action->cancel(true);
  591. }
  592. })
  593. ->action(function (Collection $records, Tables\Actions\BulkAction $action) {
  594. $records->each(function (Invoice $record) {
  595. $record->approveDraft();
  596. });
  597. $action->success();
  598. }),
  599. Tables\Actions\BulkAction::make('markAsSent')
  600. ->label('Mark as sent')
  601. ->icon('heroicon-o-paper-airplane')
  602. ->databaseTransaction()
  603. ->successNotificationTitle('Invoices sent')
  604. ->failureNotificationTitle('Failed to Mark Invoices as Sent')
  605. ->before(function (Collection $records, Tables\Actions\BulkAction $action) {
  606. $isInvalid = $records->contains(fn (Invoice $record) => ! $record->canBeMarkedAsSent());
  607. if ($isInvalid) {
  608. Notification::make()
  609. ->title('Sending failed')
  610. ->body('Only unsent invoices can be marked as sent. Please adjust your selection and try again.')
  611. ->persistent()
  612. ->danger()
  613. ->send();
  614. $action->cancel(true);
  615. }
  616. })
  617. ->action(function (Collection $records, Tables\Actions\BulkAction $action) {
  618. $records->each(function (Invoice $record) {
  619. $record->markAsSent();
  620. });
  621. $action->success();
  622. }),
  623. Tables\Actions\BulkAction::make('recordPayments')
  624. ->label('Record payments')
  625. ->icon('heroicon-o-credit-card')
  626. ->stickyModalHeader()
  627. ->stickyModalFooter()
  628. ->modalFooterActionsAlignment(Alignment::End)
  629. ->modalWidth(MaxWidth::TwoExtraLarge)
  630. ->databaseTransaction()
  631. ->successNotificationTitle('Payments recorded')
  632. ->failureNotificationTitle('Failed to Record Payments')
  633. ->deselectRecordsAfterCompletion()
  634. ->beforeFormFilled(function (Collection $records, Tables\Actions\BulkAction $action) {
  635. $isInvalid = $records->contains(fn (Invoice $record) => ! $record->canBulkRecordPayment());
  636. if ($isInvalid) {
  637. Notification::make()
  638. ->title('Payment recording failed')
  639. ->body('Invoices that are either draft, paid, overpaid, voided, or are in a foreign currency cannot be processed through bulk payments. Please adjust your selection and try again.')
  640. ->persistent()
  641. ->danger()
  642. ->send();
  643. $action->cancel(true);
  644. }
  645. })
  646. ->mountUsing(function (DocumentCollection $records, Form $form) {
  647. $totalAmountDue = $records->sum('amount_due');
  648. $form->fill([
  649. 'posted_at' => now(),
  650. 'amount' => $totalAmountDue,
  651. ]);
  652. })
  653. ->form([
  654. Forms\Components\DatePicker::make('posted_at')
  655. ->label('Date'),
  656. Forms\Components\TextInput::make('amount')
  657. ->label('Amount')
  658. ->required()
  659. ->money()
  660. ->rules([
  661. static fn (): Closure => static function (string $attribute, $value, Closure $fail) {
  662. if (! CurrencyConverter::isValidAmount($value)) {
  663. $fail('Please enter a valid amount');
  664. }
  665. },
  666. ]),
  667. Forms\Components\Select::make('payment_method')
  668. ->label('Payment method')
  669. ->required()
  670. ->options(PaymentMethod::class),
  671. Forms\Components\Select::make('bank_account_id')
  672. ->label('Account')
  673. ->required()
  674. ->options(function () {
  675. return BankAccount::query()
  676. ->join('accounts', 'bank_accounts.account_id', '=', 'accounts.id')
  677. ->select(['bank_accounts.id', 'accounts.name'])
  678. ->pluck('accounts.name', 'bank_accounts.id')
  679. ->toArray();
  680. })
  681. ->searchable(),
  682. Forms\Components\Textarea::make('notes')
  683. ->label('Notes'),
  684. ])
  685. ->before(function (DocumentCollection $records, Tables\Actions\BulkAction $action, array $data) {
  686. $totalPaymentAmount = $data['amount'] ?? 0;
  687. $totalAmountDue = $records->sum('amount_due');
  688. if ($totalPaymentAmount > $totalAmountDue) {
  689. $formattedTotalAmountDue = CurrencyConverter::formatCentsToMoney($totalAmountDue);
  690. Notification::make()
  691. ->title('Excess payment amount')
  692. ->body("The payment amount exceeds the total amount due of {$formattedTotalAmountDue}. Please adjust the payment amount and try again.")
  693. ->persistent()
  694. ->warning()
  695. ->send();
  696. $action->halt(true);
  697. }
  698. })
  699. ->action(function (DocumentCollection $records, Tables\Actions\BulkAction $action, array $data) {
  700. $totalPaymentAmount = $data['amount'] ?? 0;
  701. $remainingAmount = $totalPaymentAmount;
  702. $records->each(function (Invoice $record) use (&$remainingAmount, $data) {
  703. $amountDue = $record->amount_due;
  704. if ($amountDue <= 0 || $remainingAmount <= 0) {
  705. return;
  706. }
  707. $paymentAmount = min($amountDue, $remainingAmount);
  708. $data['amount'] = $paymentAmount;
  709. $record->recordPayment($data);
  710. $remainingAmount -= $paymentAmount;
  711. });
  712. $action->success();
  713. }),
  714. ]),
  715. ]);
  716. }
  717. public static function getPages(): array
  718. {
  719. return [
  720. 'index' => Pages\ListInvoices::route('/'),
  721. 'create' => Pages\CreateInvoice::route('/create'),
  722. 'view' => Pages\ViewInvoice::route('/{record}'),
  723. 'edit' => Pages\EditInvoice::route('/{record}/edit'),
  724. ];
  725. }
  726. public static function getWidgets(): array
  727. {
  728. return [
  729. Widgets\InvoiceOverview::class,
  730. ];
  731. }
  732. }