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

InvoiceResource.php 43KB

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