You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

InvoiceResource.php 46KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830
  1. <?php
  2. namespace App\Filament\Company\Resources\Sales;
  3. use App\Collections\Accounting\InvoiceCollection;
  4. use App\Enums\Accounting\InvoiceStatus;
  5. use App\Enums\Accounting\PaymentMethod;
  6. use App\Filament\Company\Resources\Sales\InvoiceResource\Pages;
  7. use App\Filament\Company\Resources\Sales\InvoiceResource\RelationManagers;
  8. use App\Filament\Tables\Actions\ReplicateBulkAction;
  9. use App\Filament\Tables\Filters\DateRangeFilter;
  10. use App\Models\Accounting\Adjustment;
  11. use App\Models\Accounting\DocumentLineItem;
  12. use App\Models\Accounting\Invoice;
  13. use App\Models\Banking\BankAccount;
  14. use App\Models\Common\Offering;
  15. use App\Utilities\Currency\CurrencyAccessor;
  16. use App\Utilities\Currency\CurrencyConverter;
  17. use Awcodes\TableRepeater\Components\TableRepeater;
  18. use Awcodes\TableRepeater\Header;
  19. use Carbon\CarbonInterface;
  20. use Closure;
  21. use Filament\Forms;
  22. use Filament\Forms\Components\FileUpload;
  23. use Filament\Forms\Form;
  24. use Filament\Notifications\Notification;
  25. use Filament\Resources\Resource;
  26. use Filament\Support\Enums\Alignment;
  27. use Filament\Support\Enums\MaxWidth;
  28. use Filament\Tables;
  29. use Filament\Tables\Table;
  30. use Illuminate\Database\Eloquent\Collection;
  31. use Illuminate\Database\Eloquent\Model;
  32. use Illuminate\Support\Carbon;
  33. use Illuminate\Support\Facades\Auth;
  34. use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;
  35. class InvoiceResource extends Resource
  36. {
  37. protected static ?string $model = Invoice::class;
  38. protected static ?string $navigationIcon = 'heroicon-o-rectangle-stack';
  39. public static function form(Form $form): Form
  40. {
  41. $company = Auth::user()->currentCompany;
  42. return $form
  43. ->schema([
  44. Forms\Components\Section::make('Invoice Header')
  45. ->collapsible()
  46. ->schema([
  47. Forms\Components\Split::make([
  48. Forms\Components\Group::make([
  49. FileUpload::make('logo')
  50. ->openable()
  51. ->maxSize(1024)
  52. ->localizeLabel()
  53. ->visibility('public')
  54. ->disk('public')
  55. ->directory('logos/document')
  56. ->imageResizeMode('contain')
  57. ->imageCropAspectRatio('3:2')
  58. ->panelAspectRatio('3:2')
  59. ->maxWidth(MaxWidth::ExtraSmall)
  60. ->panelLayout('integrated')
  61. ->removeUploadedFileButtonPosition('center bottom')
  62. ->uploadButtonPosition('center bottom')
  63. ->uploadProgressIndicatorPosition('center bottom')
  64. ->getUploadedFileNameForStorageUsing(
  65. static fn (TemporaryUploadedFile $file): string => (string) str($file->getClientOriginalName())
  66. ->prepend(Auth::user()->currentCompany->id . '_'),
  67. )
  68. ->acceptedFileTypes(['image/png', 'image/jpeg', 'image/gif']),
  69. ]),
  70. Forms\Components\Group::make([
  71. Forms\Components\TextInput::make('header')
  72. ->default(fn () => $company->defaultInvoice->header),
  73. Forms\Components\TextInput::make('subheader')
  74. ->default(fn () => $company->defaultInvoice->subheader),
  75. Forms\Components\View::make('filament.forms.components.company-info')
  76. ->viewData([
  77. 'company_name' => $company->name,
  78. 'company_address' => $company->profile->address,
  79. 'company_city' => $company->profile->city?->name,
  80. 'company_state' => $company->profile->state?->name,
  81. 'company_zip' => $company->profile->zip_code,
  82. 'company_country' => $company->profile->state?->country->name,
  83. ]),
  84. ])->grow(true),
  85. ])->from('md'),
  86. ]),
  87. Forms\Components\Section::make('Invoice Details')
  88. ->schema([
  89. Forms\Components\Split::make([
  90. Forms\Components\Group::make([
  91. Forms\Components\Select::make('client_id')
  92. ->relationship('client', 'name')
  93. ->preload()
  94. ->searchable()
  95. ->required(),
  96. ]),
  97. Forms\Components\Group::make([
  98. Forms\Components\TextInput::make('invoice_number')
  99. ->label('Invoice Number')
  100. ->default(fn () => Invoice::getNextDocumentNumber()),
  101. Forms\Components\TextInput::make('order_number')
  102. ->label('P.O/S.O Number'),
  103. Forms\Components\DatePicker::make('date')
  104. ->label('Invoice Date')
  105. ->default(now()),
  106. Forms\Components\DatePicker::make('due_date')
  107. ->label('Payment Due')
  108. ->default(function () use ($company) {
  109. return now()->addDays($company->defaultInvoice->payment_terms->getDays());
  110. }),
  111. ])->grow(true),
  112. ])->from('md'),
  113. TableRepeater::make('lineItems')
  114. ->relationship()
  115. ->saveRelationshipsUsing(function (TableRepeater $component, Forms\Contracts\HasForms $livewire, ?array $state) {
  116. if (! is_array($state)) {
  117. $state = [];
  118. }
  119. $relationship = $component->getRelationship();
  120. $existingRecords = $component->getCachedExistingRecords();
  121. $recordsToDelete = [];
  122. foreach ($existingRecords->pluck($relationship->getRelated()->getKeyName()) as $keyToCheckForDeletion) {
  123. if (array_key_exists("record-{$keyToCheckForDeletion}", $state)) {
  124. continue;
  125. }
  126. $recordsToDelete[] = $keyToCheckForDeletion;
  127. $existingRecords->forget("record-{$keyToCheckForDeletion}");
  128. }
  129. $relationship
  130. ->whereKey($recordsToDelete)
  131. ->get()
  132. ->each(static fn (Model $record) => $record->delete());
  133. $childComponentContainers = $component->getChildComponentContainers(
  134. withHidden: $component->shouldSaveRelationshipsWhenHidden(),
  135. );
  136. $itemOrder = 1;
  137. $orderColumn = $component->getOrderColumn();
  138. $translatableContentDriver = $livewire->makeFilamentTranslatableContentDriver();
  139. foreach ($childComponentContainers as $itemKey => $item) {
  140. $itemData = $item->getState(shouldCallHooksBefore: false);
  141. if ($orderColumn) {
  142. $itemData[$orderColumn] = $itemOrder;
  143. $itemOrder++;
  144. }
  145. if ($record = ($existingRecords[$itemKey] ?? null)) {
  146. $itemData = $component->mutateRelationshipDataBeforeSave($itemData, record: $record);
  147. if ($itemData === null) {
  148. continue;
  149. }
  150. $translatableContentDriver ?
  151. $translatableContentDriver->updateRecord($record, $itemData) :
  152. $record->fill($itemData)->save();
  153. continue;
  154. }
  155. $relatedModel = $component->getRelatedModel();
  156. $itemData = $component->mutateRelationshipDataBeforeCreate($itemData);
  157. if ($itemData === null) {
  158. continue;
  159. }
  160. if ($translatableContentDriver) {
  161. $record = $translatableContentDriver->makeRecord($relatedModel, $itemData);
  162. } else {
  163. $record = new $relatedModel;
  164. $record->fill($itemData);
  165. }
  166. $record = $relationship->save($record);
  167. $item->model($record)->saveRelationships();
  168. $existingRecords->push($record);
  169. }
  170. $component->getRecord()->setRelation($component->getRelationshipName(), $existingRecords);
  171. /** @var Invoice $invoice */
  172. $invoice = $component->getRecord();
  173. // Recalculate totals for line items
  174. $invoice->lineItems()->each(function (DocumentLineItem $lineItem) {
  175. $lineItem->updateQuietly([
  176. 'tax_total' => $lineItem->calculateTaxTotal()->getAmount(),
  177. 'discount_total' => $lineItem->calculateDiscountTotal()->getAmount(),
  178. ]);
  179. });
  180. $subtotal = $invoice->lineItems()->sum('subtotal') / 100;
  181. $taxTotal = $invoice->lineItems()->sum('tax_total') / 100;
  182. $discountTotal = $invoice->lineItems()->sum('discount_total') / 100;
  183. $grandTotal = $subtotal + $taxTotal - $discountTotal;
  184. $invoice->updateQuietly([
  185. 'subtotal' => $subtotal,
  186. 'tax_total' => $taxTotal,
  187. 'discount_total' => $discountTotal,
  188. 'total' => $grandTotal,
  189. ]);
  190. })
  191. ->headers([
  192. Header::make('Items')->width('15%'),
  193. Header::make('Description')->width('25%'),
  194. Header::make('Quantity')->width('10%'),
  195. Header::make('Price')->width('10%'),
  196. Header::make('Taxes')->width('15%'),
  197. Header::make('Discounts')->width('15%'),
  198. Header::make('Amount')->width('10%')->align('right'),
  199. ])
  200. ->schema([
  201. Forms\Components\Select::make('offering_id')
  202. ->relationship('sellableOffering', 'name')
  203. ->preload()
  204. ->searchable()
  205. ->required()
  206. ->live()
  207. ->afterStateUpdated(function (Forms\Set $set, Forms\Get $get, $state) {
  208. $offeringId = $state;
  209. $offeringRecord = Offering::with(['salesTaxes', 'salesDiscounts'])->find($offeringId);
  210. if ($offeringRecord) {
  211. $set('description', $offeringRecord->description);
  212. $set('unit_price', $offeringRecord->price);
  213. $set('salesTaxes', $offeringRecord->salesTaxes->pluck('id')->toArray());
  214. $set('salesDiscounts', $offeringRecord->salesDiscounts->pluck('id')->toArray());
  215. }
  216. }),
  217. Forms\Components\TextInput::make('description'),
  218. Forms\Components\TextInput::make('quantity')
  219. ->required()
  220. ->numeric()
  221. ->live()
  222. ->default(1),
  223. Forms\Components\TextInput::make('unit_price')
  224. ->hiddenLabel()
  225. ->numeric()
  226. ->live()
  227. ->default(0),
  228. Forms\Components\Select::make('salesTaxes')
  229. ->relationship('salesTaxes', 'name')
  230. ->preload()
  231. ->multiple()
  232. ->live()
  233. ->searchable(),
  234. Forms\Components\Select::make('salesDiscounts')
  235. ->relationship('salesDiscounts', 'name')
  236. ->preload()
  237. ->multiple()
  238. ->live()
  239. ->searchable(),
  240. Forms\Components\Placeholder::make('total')
  241. ->hiddenLabel()
  242. ->content(function (Forms\Get $get) {
  243. $quantity = max((float) ($get('quantity') ?? 0), 0);
  244. $unitPrice = max((float) ($get('unit_price') ?? 0), 0);
  245. $salesTaxes = $get('salesTaxes') ?? [];
  246. $salesDiscounts = $get('salesDiscounts') ?? [];
  247. $subtotal = $quantity * $unitPrice;
  248. // Calculate tax amount based on subtotal
  249. $taxAmount = 0;
  250. if (! empty($salesTaxes)) {
  251. $taxRates = Adjustment::whereIn('id', $salesTaxes)->pluck('rate');
  252. $taxAmount = collect($taxRates)->sum(fn ($rate) => $subtotal * ($rate / 100));
  253. }
  254. // Calculate discount amount based on subtotal
  255. $discountAmount = 0;
  256. if (! empty($salesDiscounts)) {
  257. $discountRates = Adjustment::whereIn('id', $salesDiscounts)->pluck('rate');
  258. $discountAmount = collect($discountRates)->sum(fn ($rate) => $subtotal * ($rate / 100));
  259. }
  260. // Final total
  261. $total = $subtotal + ($taxAmount - $discountAmount);
  262. return money($total, CurrencyAccessor::getDefaultCurrency(), true)->format();
  263. }),
  264. ]),
  265. Forms\Components\Grid::make(6)
  266. ->schema([
  267. Forms\Components\ViewField::make('totals')
  268. ->columnStart(5)
  269. ->columnSpan(2)
  270. ->view('filament.forms.components.invoice-totals'),
  271. ]),
  272. // Forms\Components\Repeater::make('lineItems')
  273. // ->relationship()
  274. // ->columns(8)
  275. // ->schema([
  276. // Forms\Components\Select::make('offering_id')
  277. // ->relationship('offering', 'name')
  278. // ->preload()
  279. // ->columnSpan(2)
  280. // ->searchable()
  281. // ->required()
  282. // ->live()
  283. // ->afterStateUpdated(function (Forms\Set $set, $state) {
  284. // $offeringId = $state;
  285. // $offeringRecord = Offering::with('salesTaxes')->find($offeringId);
  286. //
  287. // if ($offeringRecord) {
  288. // $set('description', $offeringRecord->description);
  289. // $set('unit_price', $offeringRecord->price);
  290. // $set('total', $offeringRecord->price);
  291. //
  292. // $salesTaxes = $offeringRecord->salesTaxes->map(function ($tax) {
  293. // return [
  294. // 'id' => $tax->id,
  295. // 'amount' => null, // Amount will be calculated dynamically
  296. // ];
  297. // })->toArray();
  298. //
  299. // $set('taxes', $salesTaxes);
  300. // }
  301. // }),
  302. // Forms\Components\TextInput::make('description')
  303. // ->columnSpan(3)
  304. // ->required(),
  305. // Forms\Components\TextInput::make('quantity')
  306. // ->required()
  307. // ->numeric()
  308. // ->live()
  309. // ->default(1),
  310. // Forms\Components\TextInput::make('unit_price')
  311. // ->live()
  312. // ->numeric()
  313. // ->default(0),
  314. // Forms\Components\Placeholder::make('total')
  315. // ->content(function (Forms\Get $get) {
  316. // $quantity = $get('quantity');
  317. // $unitPrice = $get('unit_price');
  318. //
  319. // if ($quantity && $unitPrice) {
  320. // return $quantity * $unitPrice;
  321. // }
  322. // }),
  323. // TableRepeater::make('taxes')
  324. // ->relationship()
  325. // ->columnSpanFull()
  326. // ->columnStart(6)
  327. // ->headers([
  328. // Header::make('')->width('200px'),
  329. // Header::make('')->width('50px')->align('right'),
  330. // ])
  331. // ->defaultItems(0)
  332. // ->schema([
  333. // Forms\Components\Select::make('id') // The ID of the adjustment being attached.
  334. // ->label('Tax Adjustment')
  335. // ->options(
  336. // Adjustment::query()
  337. // ->where('category', AdjustmentCategory::Tax)
  338. // ->pluck('name', 'id')
  339. // )
  340. // ->preload()
  341. // ->searchable()
  342. // ->required()
  343. // ->live(),
  344. // Forms\Components\Placeholder::make('amount')
  345. // ->hiddenLabel()
  346. // ->content(function (Forms\Get $get) {
  347. // $quantity = $get('../../quantity') ?? 0; // Get parent quantity
  348. // $unitPrice = $get('../../unit_price') ?? 0; // Get parent unit price
  349. // $rate = Adjustment::find($get('id'))->rate ?? 0;
  350. //
  351. // $total = $quantity * $unitPrice;
  352. //
  353. // return $total * ($rate / 100);
  354. // }),
  355. // ]),
  356. // ]),
  357. Forms\Components\Textarea::make('terms')
  358. ->columnSpanFull(),
  359. ]),
  360. Forms\Components\Section::make('Invoice Footer')
  361. ->collapsible()
  362. ->schema([
  363. Forms\Components\Textarea::make('footer')
  364. ->columnSpanFull(),
  365. ]),
  366. ]);
  367. }
  368. public static function table(Table $table): Table
  369. {
  370. return $table
  371. ->columns([
  372. Tables\Columns\TextColumn::make('status')
  373. ->badge()
  374. ->searchable(),
  375. Tables\Columns\TextColumn::make('due_date')
  376. ->label('Due')
  377. ->formatStateUsing(function (Tables\Columns\TextColumn $column, mixed $state) {
  378. if (blank($state)) {
  379. return null;
  380. }
  381. $date = Carbon::parse($state)
  382. ->setTimezone($timezone ?? $column->getTimezone());
  383. if ($date->isToday()) {
  384. return 'Today';
  385. }
  386. return $date->diffForHumans([
  387. 'options' => CarbonInterface::ONE_DAY_WORDS,
  388. ]);
  389. })
  390. ->sortable(),
  391. Tables\Columns\TextColumn::make('date')
  392. ->date()
  393. ->sortable(),
  394. Tables\Columns\TextColumn::make('invoice_number')
  395. ->label('Number')
  396. ->searchable(),
  397. Tables\Columns\TextColumn::make('client.name')
  398. ->sortable(),
  399. Tables\Columns\TextColumn::make('total')
  400. ->currency(),
  401. Tables\Columns\TextColumn::make('amount_paid')
  402. ->label('Amount Paid')
  403. ->currency(),
  404. Tables\Columns\TextColumn::make('amount_due')
  405. ->label('Amount Due')
  406. ->currency(),
  407. ])
  408. ->filters([
  409. Tables\Filters\SelectFilter::make('status')
  410. ->options(InvoiceStatus::class)
  411. ->native(false),
  412. Tables\Filters\SelectFilter::make('client')
  413. ->relationship('client', 'name')
  414. ->searchable()
  415. ->preload(),
  416. DateRangeFilter::make('date')
  417. ->fromLabel('From Date')
  418. ->untilLabel('Until Date')
  419. ->indicatorLabel('Date Range'),
  420. ], layout: Tables\Enums\FiltersLayout::Modal)
  421. ->filtersFormWidth(MaxWidth::Small)
  422. ->filtersTriggerAction(
  423. fn (Tables\Actions\Action $action) => $action
  424. ->label('Filter')
  425. ->slideOver(),
  426. )
  427. ->actions([
  428. Tables\Actions\ActionGroup::make([
  429. Tables\Actions\EditAction::make(),
  430. Tables\Actions\ViewAction::make(),
  431. Tables\Actions\DeleteAction::make(),
  432. Tables\Actions\ReplicateAction::make()
  433. ->label('Duplicate')
  434. ->excludeAttributes(['status', 'amount_paid', 'amount_due', 'created_by', 'updated_by', 'created_at', 'updated_at', 'invoice_number', 'date', 'due_date'])
  435. ->modal(false)
  436. ->beforeReplicaSaved(function (Invoice $original, Invoice $replica) {
  437. $replica->status = InvoiceStatus::Draft;
  438. $replica->invoice_number = Invoice::getNextDocumentNumber();
  439. $replica->date = now();
  440. $replica->due_date = now()->addDays($original->company->defaultInvoice->payment_terms->getDays());
  441. })
  442. ->databaseTransaction()
  443. ->after(function (Invoice $original, Invoice $replica) {
  444. $original->lineItems->each(function (DocumentLineItem $lineItem) use ($replica) {
  445. $replicaLineItem = $lineItem->replicate([
  446. 'documentable_id',
  447. 'documentable_type',
  448. 'subtotal',
  449. 'total',
  450. 'created_by',
  451. 'updated_by',
  452. 'created_at',
  453. 'updated_at',
  454. ]);
  455. $replicaLineItem->documentable_id = $replica->id;
  456. $replicaLineItem->documentable_type = $replica->getMorphClass();
  457. $replicaLineItem->save();
  458. $replicaLineItem->adjustments()->sync($lineItem->adjustments->pluck('id'));
  459. });
  460. })
  461. ->successRedirectUrl(function (Invoice $replica) {
  462. return InvoiceResource::getUrl('edit', ['record' => $replica]);
  463. }),
  464. Tables\Actions\Action::make('approveDraft')
  465. ->label('Approve')
  466. ->icon('heroicon-o-check-circle')
  467. ->visible(function (Invoice $record) {
  468. return $record->isDraft();
  469. })
  470. ->databaseTransaction()
  471. ->successNotificationTitle('Invoice Approved')
  472. ->action(function (Invoice $record, Tables\Actions\Action $action) {
  473. $record->approveDraft();
  474. $action->success();
  475. }),
  476. Tables\Actions\Action::make('markAsSent')
  477. ->label('Mark as Sent')
  478. ->icon('heroicon-o-paper-airplane')
  479. ->visible(function (Invoice $record) {
  480. return $record->status === InvoiceStatus::Unsent;
  481. })
  482. ->successNotificationTitle('Invoice Sent')
  483. ->action(function (Invoice $record, Tables\Actions\Action $action) {
  484. $record->updateQuietly([
  485. 'status' => InvoiceStatus::Sent,
  486. ]);
  487. $action->success();
  488. }),
  489. Tables\Actions\Action::make('recordPayment')
  490. ->label(fn (Invoice $record) => $record->status === InvoiceStatus::Overpaid ? 'Refund Overpayment' : 'Record Payment')
  491. ->stickyModalHeader()
  492. ->stickyModalFooter()
  493. ->modalFooterActionsAlignment(Alignment::End)
  494. ->modalWidth(MaxWidth::TwoExtraLarge)
  495. ->icon('heroicon-o-credit-card')
  496. ->visible(function (Invoice $record) {
  497. return $record->canRecordPayment();
  498. })
  499. ->mountUsing(function (Invoice $record, Form $form) {
  500. $form->fill([
  501. 'posted_at' => now(),
  502. 'amount' => $record->status === InvoiceStatus::Overpaid ? ltrim($record->amount_due, '-') : $record->amount_due,
  503. ]);
  504. })
  505. ->databaseTransaction()
  506. ->successNotificationTitle('Payment Recorded')
  507. ->form([
  508. Forms\Components\DatePicker::make('posted_at')
  509. ->label('Date'),
  510. Forms\Components\TextInput::make('amount')
  511. ->label('Amount')
  512. ->required()
  513. ->money()
  514. ->live(onBlur: true)
  515. ->helperText(function (Invoice $record, $state) {
  516. if (! CurrencyConverter::isValidAmount($state)) {
  517. return null;
  518. }
  519. $amountDue = $record->getRawOriginal('amount_due');
  520. $amount = CurrencyConverter::convertToCents($state);
  521. if ($amount <= 0) {
  522. return 'Please enter a valid positive amount';
  523. }
  524. if ($record->status === InvoiceStatus::Overpaid) {
  525. $newAmountDue = $amountDue + $amount;
  526. } else {
  527. $newAmountDue = $amountDue - $amount;
  528. }
  529. return match (true) {
  530. $newAmountDue > 0 => 'Amount due after payment will be ' . CurrencyConverter::formatCentsToMoney($newAmountDue),
  531. $newAmountDue === 0 => 'Invoice will be fully paid',
  532. default => 'Invoice will be overpaid by ' . CurrencyConverter::formatCentsToMoney(abs($newAmountDue)),
  533. };
  534. })
  535. ->rules([
  536. static fn (): Closure => static function (string $attribute, $value, Closure $fail) {
  537. if (! CurrencyConverter::isValidAmount($value)) {
  538. $fail('Please enter a valid amount');
  539. }
  540. },
  541. ]),
  542. Forms\Components\Select::make('payment_method')
  543. ->label('Payment Method')
  544. ->required()
  545. ->options(PaymentMethod::class),
  546. Forms\Components\Select::make('bank_account_id')
  547. ->label('Account')
  548. ->required()
  549. ->options(BankAccount::query()
  550. ->get()
  551. ->pluck('account.name', 'id'))
  552. ->searchable(),
  553. Forms\Components\Textarea::make('notes')
  554. ->label('Notes'),
  555. ])
  556. ->action(function (Invoice $record, Tables\Actions\Action $action, array $data) {
  557. $record->recordPayment($data);
  558. $action->success();
  559. }),
  560. ]),
  561. ])
  562. ->bulkActions([
  563. Tables\Actions\BulkActionGroup::make([
  564. Tables\Actions\DeleteBulkAction::make(),
  565. ReplicateBulkAction::make()
  566. ->label('Replicate')
  567. ->modalWidth(MaxWidth::Large)
  568. ->modalDescription('Replicating invoices will also replicate their line items. Are you sure you want to proceed?')
  569. ->successNotificationTitle('Invoices Replicated Successfully')
  570. ->failureNotificationTitle('Failed to Replicate Invoices')
  571. ->databaseTransaction()
  572. ->deselectRecordsAfterCompletion()
  573. ->excludeAttributes([
  574. 'status',
  575. 'amount_paid',
  576. 'amount_due',
  577. 'created_by',
  578. 'updated_by',
  579. 'created_at',
  580. 'updated_at',
  581. 'invoice_number',
  582. 'date',
  583. 'due_date',
  584. ])
  585. ->beforeReplicaSaved(function (Invoice $replica) {
  586. $replica->status = InvoiceStatus::Draft;
  587. $replica->invoice_number = Invoice::getNextDocumentNumber();
  588. $replica->date = now();
  589. $replica->due_date = now()->addDays($replica->company->defaultInvoice->payment_terms->getDays());
  590. })
  591. ->withReplicatedRelationships(['lineItems'])
  592. ->withExcludedRelationshipAttributes('lineItems', [
  593. 'subtotal',
  594. 'total',
  595. 'created_by',
  596. 'updated_by',
  597. 'created_at',
  598. 'updated_at',
  599. ]),
  600. Tables\Actions\BulkAction::make('approveDrafts')
  601. ->label('Approve')
  602. ->icon('heroicon-o-check-circle')
  603. ->databaseTransaction()
  604. ->successNotificationTitle('Invoices Approved')
  605. ->failureNotificationTitle('Failed to Approve Invoices')
  606. ->before(function (Collection $records, Tables\Actions\BulkAction $action) {
  607. $containsNonDrafts = $records->contains(fn (Invoice $record) => ! $record->isDraft());
  608. if ($containsNonDrafts) {
  609. Notification::make()
  610. ->title('Approval Failed')
  611. ->body('Only draft invoices can be approved. Please adjust your selection and try again.')
  612. ->persistent()
  613. ->danger()
  614. ->send();
  615. $action->cancel(true);
  616. }
  617. })
  618. ->action(function (Collection $records, Tables\Actions\BulkAction $action) {
  619. $records->each(function (Invoice $record) {
  620. $record->approveDraft();
  621. });
  622. $action->success();
  623. }),
  624. Tables\Actions\BulkAction::make('markAsSent')
  625. ->label('Mark as Sent')
  626. ->icon('heroicon-o-paper-airplane')
  627. ->databaseTransaction()
  628. ->successNotificationTitle('Invoices Sent')
  629. ->failureNotificationTitle('Failed to Mark Invoices as Sent')
  630. ->before(function (Collection $records, Tables\Actions\BulkAction $action) {
  631. $doesntContainUnsent = $records->contains(fn (Invoice $record) => $record->status !== InvoiceStatus::Unsent);
  632. if ($doesntContainUnsent) {
  633. Notification::make()
  634. ->title('Sending Failed')
  635. ->body('Only unsent invoices can be marked as sent. Please adjust your selection and try again.')
  636. ->persistent()
  637. ->danger()
  638. ->send();
  639. $action->cancel(true);
  640. }
  641. })
  642. ->action(function (Collection $records, Tables\Actions\BulkAction $action) {
  643. $records->each(function (Invoice $record) {
  644. $record->updateQuietly([
  645. 'status' => InvoiceStatus::Sent,
  646. ]);
  647. });
  648. $action->success();
  649. }),
  650. Tables\Actions\BulkAction::make('recordPayments')
  651. ->label('Record Payments')
  652. ->icon('heroicon-o-credit-card')
  653. ->stickyModalHeader()
  654. ->stickyModalFooter()
  655. ->modalFooterActionsAlignment(Alignment::End)
  656. ->modalWidth(MaxWidth::TwoExtraLarge)
  657. ->databaseTransaction()
  658. ->successNotificationTitle('Payments Recorded')
  659. ->failureNotificationTitle('Failed to Record Payments')
  660. ->deselectRecordsAfterCompletion()
  661. ->beforeFormFilled(function (Collection $records, Tables\Actions\BulkAction $action) {
  662. $cantRecordPayments = $records->contains(fn (Invoice $record) => ! $record->canBulkRecordPayment());
  663. if ($cantRecordPayments) {
  664. Notification::make()
  665. ->title('Payment Recording Failed')
  666. ->body('Invoices that are either draft, paid, overpaid, or voided cannot be processed through bulk payments. Please adjust your selection and try again.')
  667. ->persistent()
  668. ->danger()
  669. ->send();
  670. $action->cancel(true);
  671. }
  672. })
  673. ->mountUsing(function (InvoiceCollection $records, Form $form) {
  674. $totalAmountDue = $records->sumMoneyFormattedSimple('amount_due');
  675. $form->fill([
  676. 'posted_at' => now(),
  677. 'amount' => $totalAmountDue,
  678. ]);
  679. })
  680. ->form([
  681. Forms\Components\DatePicker::make('posted_at')
  682. ->label('Date'),
  683. Forms\Components\TextInput::make('amount')
  684. ->label('Amount')
  685. ->required()
  686. ->money()
  687. ->rules([
  688. static fn (): Closure => static function (string $attribute, $value, Closure $fail) {
  689. if (! CurrencyConverter::isValidAmount($value)) {
  690. $fail('Please enter a valid amount');
  691. }
  692. },
  693. ]),
  694. Forms\Components\Select::make('payment_method')
  695. ->label('Payment Method')
  696. ->required()
  697. ->options(PaymentMethod::class),
  698. Forms\Components\Select::make('bank_account_id')
  699. ->label('Account')
  700. ->required()
  701. ->options(BankAccount::query()
  702. ->get()
  703. ->pluck('account.name', 'id'))
  704. ->searchable(),
  705. Forms\Components\Textarea::make('notes')
  706. ->label('Notes'),
  707. ])
  708. ->before(function (InvoiceCollection $records, Tables\Actions\BulkAction $action, array $data) {
  709. $totalPaymentAmount = CurrencyConverter::convertToCents($data['amount']);
  710. $totalAmountDue = $records->sumMoneyInCents('amount_due');
  711. if ($totalPaymentAmount > $totalAmountDue) {
  712. $formattedTotalAmountDue = CurrencyConverter::formatCentsToMoney($totalAmountDue);
  713. Notification::make()
  714. ->title('Excess Payment Amount')
  715. ->body("The payment amount exceeds the total amount due of {$formattedTotalAmountDue}. Please adjust the payment amount and try again.")
  716. ->persistent()
  717. ->warning()
  718. ->send();
  719. $action->halt(true);
  720. }
  721. })
  722. ->action(function (InvoiceCollection $records, Tables\Actions\BulkAction $action, array $data) {
  723. $totalPaymentAmount = CurrencyConverter::convertToCents($data['amount']);
  724. $remainingAmount = $totalPaymentAmount;
  725. $records->each(function (Invoice $record) use (&$remainingAmount, $data) {
  726. $amountDue = $record->getRawOriginal('amount_due');
  727. if ($amountDue <= 0 || $remainingAmount <= 0) {
  728. return;
  729. }
  730. $paymentAmount = min($amountDue, $remainingAmount);
  731. $data['amount'] = CurrencyConverter::convertCentsToFormatSimple($paymentAmount);
  732. $record->recordPayment($data);
  733. $remainingAmount -= $paymentAmount;
  734. });
  735. $action->success();
  736. }),
  737. ]),
  738. ]);
  739. }
  740. public static function getRelations(): array
  741. {
  742. return [
  743. RelationManagers\PaymentsRelationManager::class,
  744. ];
  745. }
  746. public static function getPages(): array
  747. {
  748. return [
  749. 'index' => Pages\ListInvoices::route('/'),
  750. 'create' => Pages\CreateInvoice::route('/create'),
  751. 'view' => Pages\ViewInvoice::route('/{record}'),
  752. 'edit' => Pages\EditInvoice::route('/{record}/edit'),
  753. ];
  754. }
  755. }