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 47KB

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