選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

InvoiceResource.php 33KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  1. <?php
  2. namespace App\Filament\Company\Resources\Sales;
  3. use App\Enums\Accounting\InvoiceStatus;
  4. use App\Filament\Company\Resources\Sales\InvoiceResource\Pages;
  5. use App\Models\Accounting\Adjustment;
  6. use App\Models\Accounting\DocumentLineItem;
  7. use App\Models\Accounting\Invoice;
  8. use App\Models\Banking\BankAccount;
  9. use App\Models\Common\Offering;
  10. use App\Utilities\Currency\CurrencyAccessor;
  11. use App\Utilities\Currency\CurrencyConverter;
  12. use Awcodes\TableRepeater\Components\TableRepeater;
  13. use Awcodes\TableRepeater\Header;
  14. use Carbon\CarbonInterface;
  15. use Filament\Forms;
  16. use Filament\Forms\Components\FileUpload;
  17. use Filament\Forms\Form;
  18. use Filament\Resources\Resource;
  19. use Filament\Support\Enums\MaxWidth;
  20. use Filament\Tables;
  21. use Filament\Tables\Table;
  22. use Illuminate\Database\Eloquent\Model;
  23. use Illuminate\Support\Carbon;
  24. use Illuminate\Support\Facades\Auth;
  25. use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;
  26. class InvoiceResource extends Resource
  27. {
  28. protected static ?string $model = Invoice::class;
  29. protected static ?string $navigationIcon = 'heroicon-o-rectangle-stack';
  30. public static function form(Form $form): Form
  31. {
  32. $company = Auth::user()->currentCompany;
  33. return $form
  34. ->schema([
  35. Forms\Components\Section::make('Invoice Header')
  36. ->collapsible()
  37. ->schema([
  38. Forms\Components\Split::make([
  39. Forms\Components\Group::make([
  40. FileUpload::make('logo')
  41. ->openable()
  42. ->maxSize(1024)
  43. ->localizeLabel()
  44. ->visibility('public')
  45. ->disk('public')
  46. ->directory('logos/document')
  47. ->imageResizeMode('contain')
  48. ->imageCropAspectRatio('3:2')
  49. ->panelAspectRatio('3:2')
  50. ->maxWidth(MaxWidth::ExtraSmall)
  51. ->panelLayout('integrated')
  52. ->removeUploadedFileButtonPosition('center bottom')
  53. ->uploadButtonPosition('center bottom')
  54. ->uploadProgressIndicatorPosition('center bottom')
  55. ->getUploadedFileNameForStorageUsing(
  56. static fn (TemporaryUploadedFile $file): string => (string) str($file->getClientOriginalName())
  57. ->prepend(Auth::user()->currentCompany->id . '_'),
  58. )
  59. ->acceptedFileTypes(['image/png', 'image/jpeg', 'image/gif']),
  60. ]),
  61. Forms\Components\Group::make([
  62. Forms\Components\TextInput::make('header')
  63. ->default(fn () => $company->defaultInvoice->header),
  64. Forms\Components\TextInput::make('subheader')
  65. ->default(fn () => $company->defaultInvoice->subheader),
  66. Forms\Components\View::make('filament.forms.components.company-info')
  67. ->viewData([
  68. 'company_name' => $company->name,
  69. 'company_address' => $company->profile->address,
  70. 'company_city' => $company->profile->city?->name,
  71. 'company_state' => $company->profile->state?->name,
  72. 'company_zip' => $company->profile->zip_code,
  73. 'company_country' => $company->profile->state?->country->name,
  74. ]),
  75. ])->grow(true),
  76. ])->from('md'),
  77. ]),
  78. Forms\Components\Section::make('Invoice Details')
  79. ->schema([
  80. Forms\Components\Split::make([
  81. Forms\Components\Group::make([
  82. Forms\Components\Select::make('client_id')
  83. ->relationship('client', 'name')
  84. ->preload()
  85. ->searchable()
  86. ->required(),
  87. ]),
  88. Forms\Components\Group::make([
  89. Forms\Components\TextInput::make('invoice_number')
  90. ->label('Invoice Number')
  91. ->default(fn () => Invoice::getNextDocumentNumber()),
  92. Forms\Components\TextInput::make('order_number')
  93. ->label('P.O/S.O Number'),
  94. Forms\Components\DatePicker::make('date')
  95. ->label('Invoice Date')
  96. ->default(now()),
  97. Forms\Components\DatePicker::make('due_date')
  98. ->label('Payment Due')
  99. ->default(function () use ($company) {
  100. return now()->addDays($company->defaultInvoice->payment_terms->getDays());
  101. }),
  102. ])->grow(true),
  103. ])->from('md'),
  104. TableRepeater::make('lineItems')
  105. ->relationship()
  106. ->saveRelationshipsUsing(function (TableRepeater $component, Forms\Contracts\HasForms $livewire, ?array $state) {
  107. if (! is_array($state)) {
  108. $state = [];
  109. }
  110. $relationship = $component->getRelationship();
  111. $existingRecords = $component->getCachedExistingRecords();
  112. $recordsToDelete = [];
  113. foreach ($existingRecords->pluck($relationship->getRelated()->getKeyName()) as $keyToCheckForDeletion) {
  114. if (array_key_exists("record-{$keyToCheckForDeletion}", $state)) {
  115. continue;
  116. }
  117. $recordsToDelete[] = $keyToCheckForDeletion;
  118. $existingRecords->forget("record-{$keyToCheckForDeletion}");
  119. }
  120. $relationship
  121. ->whereKey($recordsToDelete)
  122. ->get()
  123. ->each(static fn (Model $record) => $record->delete());
  124. $childComponentContainers = $component->getChildComponentContainers(
  125. withHidden: $component->shouldSaveRelationshipsWhenHidden(),
  126. );
  127. $itemOrder = 1;
  128. $orderColumn = $component->getOrderColumn();
  129. $translatableContentDriver = $livewire->makeFilamentTranslatableContentDriver();
  130. foreach ($childComponentContainers as $itemKey => $item) {
  131. $itemData = $item->getState(shouldCallHooksBefore: false);
  132. if ($orderColumn) {
  133. $itemData[$orderColumn] = $itemOrder;
  134. $itemOrder++;
  135. }
  136. if ($record = ($existingRecords[$itemKey] ?? null)) {
  137. $itemData = $component->mutateRelationshipDataBeforeSave($itemData, record: $record);
  138. if ($itemData === null) {
  139. continue;
  140. }
  141. $translatableContentDriver ?
  142. $translatableContentDriver->updateRecord($record, $itemData) :
  143. $record->fill($itemData)->save();
  144. continue;
  145. }
  146. $relatedModel = $component->getRelatedModel();
  147. $itemData = $component->mutateRelationshipDataBeforeCreate($itemData);
  148. if ($itemData === null) {
  149. continue;
  150. }
  151. if ($translatableContentDriver) {
  152. $record = $translatableContentDriver->makeRecord($relatedModel, $itemData);
  153. } else {
  154. $record = new $relatedModel;
  155. $record->fill($itemData);
  156. }
  157. $record = $relationship->save($record);
  158. $item->model($record)->saveRelationships();
  159. $existingRecords->push($record);
  160. }
  161. $component->getRecord()->setRelation($component->getRelationshipName(), $existingRecords);
  162. /** @var Invoice $invoice */
  163. $invoice = $component->getRecord();
  164. // Recalculate totals for line items
  165. $invoice->lineItems()->each(function (DocumentLineItem $lineItem) {
  166. $lineItem->updateQuietly([
  167. 'tax_total' => $lineItem->calculateTaxTotal()->getAmount(),
  168. 'discount_total' => $lineItem->calculateDiscountTotal()->getAmount(),
  169. ]);
  170. });
  171. $subtotal = $invoice->lineItems()->sum('subtotal') / 100;
  172. $taxTotal = $invoice->lineItems()->sum('tax_total') / 100;
  173. $discountTotal = $invoice->lineItems()->sum('discount_total') / 100;
  174. $grandTotal = $subtotal + $taxTotal - $discountTotal;
  175. $invoice->updateQuietly([
  176. 'subtotal' => $subtotal,
  177. 'tax_total' => $taxTotal,
  178. 'discount_total' => $discountTotal,
  179. 'total' => $grandTotal,
  180. ]);
  181. })
  182. ->headers([
  183. Header::make('Items')->width('15%'),
  184. Header::make('Description')->width('25%'),
  185. Header::make('Quantity')->width('10%'),
  186. Header::make('Price')->width('10%'),
  187. Header::make('Taxes')->width('15%'),
  188. Header::make('Discounts')->width('15%'),
  189. Header::make('Amount')->width('10%')->align('right'),
  190. ])
  191. ->schema([
  192. Forms\Components\Select::make('offering_id')
  193. ->relationship('sellableOffering', 'name')
  194. ->preload()
  195. ->searchable()
  196. ->required()
  197. ->live()
  198. ->afterStateUpdated(function (Forms\Set $set, Forms\Get $get, $state) {
  199. $offeringId = $state;
  200. $offeringRecord = Offering::with('salesTaxes')->find($offeringId);
  201. if ($offeringRecord) {
  202. $set('description', $offeringRecord->description);
  203. $set('unit_price', $offeringRecord->price);
  204. $set('salesTaxes', $offeringRecord->salesTaxes->pluck('id')->toArray());
  205. $set('salesDiscounts', $offeringRecord->salesDiscounts->pluck('id')->toArray());
  206. }
  207. }),
  208. Forms\Components\TextInput::make('description'),
  209. Forms\Components\TextInput::make('quantity')
  210. ->required()
  211. ->numeric()
  212. ->live()
  213. ->default(1),
  214. Forms\Components\TextInput::make('unit_price')
  215. ->hiddenLabel()
  216. ->numeric()
  217. ->live()
  218. ->default(0),
  219. Forms\Components\Select::make('salesTaxes')
  220. ->relationship('salesTaxes', 'name')
  221. ->preload()
  222. ->multiple()
  223. ->live()
  224. ->searchable(),
  225. Forms\Components\Select::make('salesDiscounts')
  226. ->relationship('salesDiscounts', 'name')
  227. ->preload()
  228. ->multiple()
  229. ->live()
  230. ->searchable(),
  231. Forms\Components\Placeholder::make('total')
  232. ->hiddenLabel()
  233. ->content(function (Forms\Get $get) {
  234. $quantity = max((float) ($get('quantity') ?? 0), 0);
  235. $unitPrice = max((float) ($get('unit_price') ?? 0), 0);
  236. $salesTaxes = $get('salesTaxes') ?? [];
  237. $salesDiscounts = $get('salesDiscounts') ?? [];
  238. $subtotal = $quantity * $unitPrice;
  239. // Calculate tax amount based on subtotal
  240. $taxAmount = 0;
  241. if (! empty($salesTaxes)) {
  242. $taxRates = Adjustment::whereIn('id', $salesTaxes)->pluck('rate');
  243. $taxAmount = collect($taxRates)->sum(fn ($rate) => $subtotal * ($rate / 100));
  244. }
  245. // Calculate discount amount based on subtotal
  246. $discountAmount = 0;
  247. if (! empty($salesDiscounts)) {
  248. $discountRates = Adjustment::whereIn('id', $salesDiscounts)->pluck('rate');
  249. $discountAmount = collect($discountRates)->sum(fn ($rate) => $subtotal * ($rate / 100));
  250. }
  251. // Final total
  252. $total = $subtotal + ($taxAmount - $discountAmount);
  253. return money($total, CurrencyAccessor::getDefaultCurrency(), true)->format();
  254. }),
  255. ]),
  256. Forms\Components\Grid::make(6)
  257. ->schema([
  258. Forms\Components\ViewField::make('totals')
  259. ->columnStart(5)
  260. ->columnSpan(2)
  261. ->view('filament.forms.components.invoice-totals'),
  262. ]),
  263. // Forms\Components\Repeater::make('lineItems')
  264. // ->relationship()
  265. // ->columns(8)
  266. // ->schema([
  267. // Forms\Components\Select::make('offering_id')
  268. // ->relationship('offering', 'name')
  269. // ->preload()
  270. // ->columnSpan(2)
  271. // ->searchable()
  272. // ->required()
  273. // ->live()
  274. // ->afterStateUpdated(function (Forms\Set $set, $state) {
  275. // $offeringId = $state;
  276. // $offeringRecord = Offering::with('salesTaxes')->find($offeringId);
  277. //
  278. // if ($offeringRecord) {
  279. // $set('description', $offeringRecord->description);
  280. // $set('unit_price', $offeringRecord->price);
  281. // $set('total', $offeringRecord->price);
  282. //
  283. // $salesTaxes = $offeringRecord->salesTaxes->map(function ($tax) {
  284. // return [
  285. // 'id' => $tax->id,
  286. // 'amount' => null, // Amount will be calculated dynamically
  287. // ];
  288. // })->toArray();
  289. //
  290. // $set('taxes', $salesTaxes);
  291. // }
  292. // }),
  293. // Forms\Components\TextInput::make('description')
  294. // ->columnSpan(3)
  295. // ->required(),
  296. // Forms\Components\TextInput::make('quantity')
  297. // ->required()
  298. // ->numeric()
  299. // ->live()
  300. // ->default(1),
  301. // Forms\Components\TextInput::make('unit_price')
  302. // ->live()
  303. // ->numeric()
  304. // ->default(0),
  305. // Forms\Components\Placeholder::make('total')
  306. // ->content(function (Forms\Get $get) {
  307. // $quantity = $get('quantity');
  308. // $unitPrice = $get('unit_price');
  309. //
  310. // if ($quantity && $unitPrice) {
  311. // return $quantity * $unitPrice;
  312. // }
  313. // }),
  314. // TableRepeater::make('taxes')
  315. // ->relationship()
  316. // ->columnSpanFull()
  317. // ->columnStart(6)
  318. // ->headers([
  319. // Header::make('')->width('200px'),
  320. // Header::make('')->width('50px')->align('right'),
  321. // ])
  322. // ->defaultItems(0)
  323. // ->schema([
  324. // Forms\Components\Select::make('id') // The ID of the adjustment being attached.
  325. // ->label('Tax Adjustment')
  326. // ->options(
  327. // Adjustment::query()
  328. // ->where('category', AdjustmentCategory::Tax)
  329. // ->pluck('name', 'id')
  330. // )
  331. // ->preload()
  332. // ->searchable()
  333. // ->required()
  334. // ->live(),
  335. // Forms\Components\Placeholder::make('amount')
  336. // ->hiddenLabel()
  337. // ->content(function (Forms\Get $get) {
  338. // $quantity = $get('../../quantity') ?? 0; // Get parent quantity
  339. // $unitPrice = $get('../../unit_price') ?? 0; // Get parent unit price
  340. // $rate = Adjustment::find($get('id'))->rate ?? 0;
  341. //
  342. // $total = $quantity * $unitPrice;
  343. //
  344. // return $total * ($rate / 100);
  345. // }),
  346. // ]),
  347. // ]),
  348. Forms\Components\Textarea::make('terms')
  349. ->columnSpanFull(),
  350. ]),
  351. Forms\Components\Section::make('Invoice Footer')
  352. ->collapsible()
  353. ->schema([
  354. Forms\Components\Textarea::make('footer')
  355. ->columnSpanFull(),
  356. ]),
  357. ]);
  358. }
  359. public static function table(Table $table): Table
  360. {
  361. return $table
  362. ->columns([
  363. Tables\Columns\TextColumn::make('status')
  364. ->badge()
  365. ->searchable(),
  366. Tables\Columns\TextColumn::make('due_date')
  367. ->label('Due')
  368. ->formatStateUsing(function (Tables\Columns\TextColumn $column, mixed $state) {
  369. if (blank($state)) {
  370. return null;
  371. }
  372. $date = Carbon::parse($state)
  373. ->setTimezone($timezone ?? $column->getTimezone());
  374. if ($date->isToday()) {
  375. return 'Today';
  376. }
  377. return $date->diffForHumans([
  378. 'options' => CarbonInterface::ONE_DAY_WORDS,
  379. ]);
  380. })
  381. ->sortable(),
  382. Tables\Columns\TextColumn::make('date')
  383. ->date()
  384. ->sortable(),
  385. Tables\Columns\TextColumn::make('invoice_number')
  386. ->label('Number')
  387. ->searchable(),
  388. Tables\Columns\TextColumn::make('client.name')
  389. ->sortable(),
  390. Tables\Columns\TextColumn::make('total')
  391. ->currency(),
  392. Tables\Columns\TextColumn::make('amount_paid')
  393. ->label('Amount Paid')
  394. ->currency(),
  395. Tables\Columns\TextColumn::make('amount_due')
  396. ->label('Amount Due')
  397. ->currency(),
  398. ])
  399. ->filters([
  400. //
  401. ])
  402. ->actions([
  403. Tables\Actions\ActionGroup::make([
  404. Tables\Actions\EditAction::make(),
  405. Tables\Actions\ViewAction::make(),
  406. Tables\Actions\DeleteAction::make(),
  407. Tables\Actions\ReplicateAction::make()
  408. ->label('Duplicate')
  409. ->excludeAttributes(['status', 'amount_paid', 'amount_due', 'created_by', 'updated_by', 'created_at', 'updated_at', 'invoice_number', 'date', 'due_date'])
  410. ->modal(false)
  411. ->beforeReplicaSaved(function (Invoice $original, Invoice $replica) {
  412. $replica->status = InvoiceStatus::Draft;
  413. $replica->invoice_number = Invoice::getNextDocumentNumber();
  414. $replica->date = now();
  415. $replica->due_date = now()->addDays($original->company->defaultInvoice->payment_terms->getDays());
  416. })
  417. ->after(function (Invoice $original, Invoice $replica) {
  418. $original->lineItems->each(function (DocumentLineItem $lineItem) use ($replica) {
  419. $replicaLineItem = $lineItem->replicate([
  420. 'documentable_id',
  421. 'documentable_type',
  422. 'subtotal',
  423. 'total',
  424. 'created_by',
  425. 'updated_by',
  426. 'created_at',
  427. 'updated_at',
  428. ]);
  429. $replicaLineItem->documentable_id = $replica->id;
  430. $replicaLineItem->documentable_type = $replica->getMorphClass();
  431. $replicaLineItem->save();
  432. $replicaLineItem->adjustments()->sync($lineItem->adjustments->pluck('id'));
  433. });
  434. })
  435. ->successRedirectUrl(function (Invoice $replica) {
  436. return InvoiceResource::getUrl('edit', ['record' => $replica]);
  437. }),
  438. Tables\Actions\Action::make('approveDraft')
  439. ->label('Approve')
  440. ->icon('heroicon-o-check-circle')
  441. ->visible(function (Invoice $record) {
  442. return $record->isDraft();
  443. })
  444. ->action(function (Invoice $record) {
  445. $record->updateQuietly([
  446. 'status' => InvoiceStatus::Unsent,
  447. ]);
  448. }),
  449. Tables\Actions\Action::make('markAsSent')
  450. ->label('Mark as Sent')
  451. ->icon('heroicon-o-paper-airplane')
  452. ->visible(function (Invoice $record) {
  453. return $record->status === InvoiceStatus::Unsent;
  454. })
  455. ->action(function (Invoice $record) {
  456. $record->updateQuietly([
  457. 'status' => InvoiceStatus::Sent,
  458. ]);
  459. }),
  460. Tables\Actions\Action::make('recordPayment')
  461. ->label('Record Payment')
  462. ->modalWidth(MaxWidth::TwoExtraLarge)
  463. ->icon('heroicon-o-credit-card')
  464. ->visible(function (Invoice $record) {
  465. return $record->canRecordPayment();
  466. })
  467. ->mountUsing(function (Invoice $record, Form $form) {
  468. $form->fill([
  469. 'date' => now(),
  470. 'amount' => $record->amount_due,
  471. ]);
  472. })
  473. ->form([
  474. Forms\Components\DatePicker::make('date')
  475. ->label('Payment Date'),
  476. Forms\Components\TextInput::make('amount')
  477. ->label('Amount')
  478. ->required()
  479. ->money(),
  480. Forms\Components\Select::make('payment_method')
  481. ->label('Payment Method')
  482. ->options([
  483. 'bank_payment' => 'Bank Payment',
  484. 'cash' => 'Cash',
  485. 'check' => 'Check',
  486. 'credit_card' => 'Credit Card',
  487. 'paypal' => 'PayPal',
  488. 'other' => 'Other',
  489. ]),
  490. Forms\Components\Select::make('bank_account_id')
  491. ->label('Account')
  492. ->options(BankAccount::query()
  493. ->get()
  494. ->pluck('account.name', 'id'))
  495. ->searchable(),
  496. Forms\Components\Textarea::make('notes')
  497. ->label('Notes'),
  498. ])
  499. ->action(function (Invoice $record, array $data) {
  500. $payment = $record->payments()->create([
  501. 'date' => $data['date'],
  502. 'amount' => $data['amount'],
  503. 'payment_method' => $data['payment_method'],
  504. 'bank_account_id' => $data['bank_account_id'],
  505. 'notes' => $data['notes'],
  506. ]);
  507. $amountPaid = $record->getRawOriginal('amount_paid');
  508. $paymentAmount = $payment->getRawOriginal('amount');
  509. $totalAmount = $record->getRawOriginal('total');
  510. $newAmountPaid = $amountPaid + $paymentAmount;
  511. $record->amount_paid = CurrencyConverter::convertCentsToFloat($newAmountPaid);
  512. if ($newAmountPaid > $totalAmount) {
  513. $record->status = InvoiceStatus::Overpaid;
  514. } elseif ($newAmountPaid === $totalAmount) {
  515. $record->status = InvoiceStatus::Paid;
  516. } else {
  517. $record->status = InvoiceStatus::Partial;
  518. }
  519. $record->save();
  520. }),
  521. ]),
  522. ])
  523. ->bulkActions([
  524. Tables\Actions\BulkActionGroup::make([
  525. Tables\Actions\DeleteBulkAction::make(),
  526. ]),
  527. ]);
  528. }
  529. public static function getRelations(): array
  530. {
  531. return [
  532. //
  533. ];
  534. }
  535. public static function getPages(): array
  536. {
  537. return [
  538. 'index' => Pages\ListInvoices::route('/'),
  539. 'create' => Pages\CreateInvoice::route('/create'),
  540. 'view' => Pages\ViewInvoice::route('/{record}'),
  541. 'edit' => Pages\EditInvoice::route('/{record}/edit'),
  542. ];
  543. }
  544. }