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

InvoiceResource.php 26KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  1. <?php
  2. namespace App\Filament\Company\Resources\Sales;
  3. use App\Filament\Company\Resources\Sales\InvoiceResource\Pages;
  4. use App\Models\Accounting\Adjustment;
  5. use App\Models\Accounting\DocumentLineItem;
  6. use App\Models\Accounting\Invoice;
  7. use App\Models\Common\Offering;
  8. use App\Utilities\Currency\CurrencyAccessor;
  9. use Awcodes\TableRepeater\Components\TableRepeater;
  10. use Awcodes\TableRepeater\Header;
  11. use Carbon\CarbonInterface;
  12. use Filament\Forms;
  13. use Filament\Forms\Components\FileUpload;
  14. use Filament\Forms\Form;
  15. use Filament\Resources\Resource;
  16. use Filament\Support\Enums\MaxWidth;
  17. use Filament\Tables;
  18. use Filament\Tables\Table;
  19. use Illuminate\Database\Eloquent\Model;
  20. use Illuminate\Support\Carbon;
  21. use Illuminate\Support\Facades\Auth;
  22. use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;
  23. class InvoiceResource extends Resource
  24. {
  25. protected static ?string $model = Invoice::class;
  26. protected static ?string $navigationIcon = 'heroicon-o-rectangle-stack';
  27. public static function form(Form $form): Form
  28. {
  29. $company = Auth::user()->currentCompany;
  30. return $form
  31. ->schema([
  32. Forms\Components\Section::make('Invoice Header')
  33. ->collapsible()
  34. ->schema([
  35. Forms\Components\Split::make([
  36. Forms\Components\Group::make([
  37. FileUpload::make('logo')
  38. ->openable()
  39. ->maxSize(1024)
  40. ->localizeLabel()
  41. ->visibility('public')
  42. ->disk('public')
  43. ->directory('logos/document')
  44. ->imageResizeMode('contain')
  45. ->imageCropAspectRatio('3:2')
  46. ->panelAspectRatio('3:2')
  47. ->maxWidth(MaxWidth::ExtraSmall)
  48. ->panelLayout('integrated')
  49. ->removeUploadedFileButtonPosition('center bottom')
  50. ->uploadButtonPosition('center bottom')
  51. ->uploadProgressIndicatorPosition('center bottom')
  52. ->getUploadedFileNameForStorageUsing(
  53. static fn (TemporaryUploadedFile $file): string => (string) str($file->getClientOriginalName())
  54. ->prepend(Auth::user()->currentCompany->id . '_'),
  55. )
  56. ->acceptedFileTypes(['image/png', 'image/jpeg', 'image/gif']),
  57. ]),
  58. Forms\Components\Group::make([
  59. Forms\Components\TextInput::make('header')
  60. ->default(fn () => $company->defaultInvoice->header),
  61. Forms\Components\TextInput::make('subheader')
  62. ->default(fn () => $company->defaultInvoice->subheader),
  63. Forms\Components\View::make('filament.forms.components.company-info')
  64. ->viewData([
  65. 'company_name' => $company->name,
  66. 'company_address' => $company->profile->address,
  67. 'company_city' => $company->profile->city?->name,
  68. 'company_state' => $company->profile->state?->name,
  69. 'company_zip' => $company->profile->zip_code,
  70. 'company_country' => $company->profile->state?->country->name,
  71. ]),
  72. ])->grow(true),
  73. ])->from('md'),
  74. ]),
  75. Forms\Components\Section::make('Invoice Details')
  76. ->schema([
  77. Forms\Components\Split::make([
  78. Forms\Components\Group::make([
  79. Forms\Components\Select::make('client_id')
  80. ->relationship('client', 'name')
  81. ->preload()
  82. ->searchable()
  83. ->required(),
  84. ]),
  85. Forms\Components\Group::make([
  86. Forms\Components\TextInput::make('invoice_number')
  87. ->label('Invoice Number')
  88. ->default(fn () => Invoice::getNextDocumentNumber()),
  89. Forms\Components\TextInput::make('order_number')
  90. ->label('P.O/S.O Number'),
  91. Forms\Components\DatePicker::make('date')
  92. ->label('Invoice Date')
  93. ->default(now()),
  94. Forms\Components\DatePicker::make('due_date')
  95. ->label('Payment Due')
  96. ->default(function () use ($company) {
  97. return now()->addDays($company->defaultInvoice->payment_terms->getDays());
  98. }),
  99. ])->grow(true),
  100. ])->from('md'),
  101. TableRepeater::make('lineItems')
  102. ->relationship()
  103. ->saveRelationshipsUsing(function (TableRepeater $component, Forms\Contracts\HasForms $livewire, ?array $state) {
  104. if (! is_array($state)) {
  105. $state = [];
  106. }
  107. $relationship = $component->getRelationship();
  108. $existingRecords = $component->getCachedExistingRecords();
  109. $recordsToDelete = [];
  110. foreach ($existingRecords->pluck($relationship->getRelated()->getKeyName()) as $keyToCheckForDeletion) {
  111. if (array_key_exists("record-{$keyToCheckForDeletion}", $state)) {
  112. continue;
  113. }
  114. $recordsToDelete[] = $keyToCheckForDeletion;
  115. $existingRecords->forget("record-{$keyToCheckForDeletion}");
  116. }
  117. $relationship
  118. ->whereKey($recordsToDelete)
  119. ->get()
  120. ->each(static fn (Model $record) => $record->delete());
  121. $childComponentContainers = $component->getChildComponentContainers(
  122. withHidden: $component->shouldSaveRelationshipsWhenHidden(),
  123. );
  124. $itemOrder = 1;
  125. $orderColumn = $component->getOrderColumn();
  126. $translatableContentDriver = $livewire->makeFilamentTranslatableContentDriver();
  127. foreach ($childComponentContainers as $itemKey => $item) {
  128. $itemData = $item->getState(shouldCallHooksBefore: false);
  129. if ($orderColumn) {
  130. $itemData[$orderColumn] = $itemOrder;
  131. $itemOrder++;
  132. }
  133. if ($record = ($existingRecords[$itemKey] ?? null)) {
  134. $itemData = $component->mutateRelationshipDataBeforeSave($itemData, record: $record);
  135. if ($itemData === null) {
  136. continue;
  137. }
  138. $translatableContentDriver ?
  139. $translatableContentDriver->updateRecord($record, $itemData) :
  140. $record->fill($itemData)->save();
  141. continue;
  142. }
  143. $relatedModel = $component->getRelatedModel();
  144. $itemData = $component->mutateRelationshipDataBeforeCreate($itemData);
  145. if ($itemData === null) {
  146. continue;
  147. }
  148. if ($translatableContentDriver) {
  149. $record = $translatableContentDriver->makeRecord($relatedModel, $itemData);
  150. } else {
  151. $record = new $relatedModel;
  152. $record->fill($itemData);
  153. }
  154. $record = $relationship->save($record);
  155. $item->model($record)->saveRelationships();
  156. $existingRecords->push($record);
  157. }
  158. $component->getRecord()->setRelation($component->getRelationshipName(), $existingRecords);
  159. /** @var Invoice $invoice */
  160. $invoice = $component->getRecord();
  161. // Recalculate totals for line items
  162. $invoice->lineItems()->each(function (DocumentLineItem $lineItem) {
  163. $lineItem->updateQuietly([
  164. 'tax_total' => $lineItem->calculateTaxTotal()->getAmount(),
  165. 'discount_total' => $lineItem->calculateDiscountTotal()->getAmount(),
  166. ]);
  167. });
  168. $subtotal = $invoice->lineItems()->sum('subtotal') / 100;
  169. $taxTotal = $invoice->lineItems()->sum('tax_total') / 100;
  170. $discountTotal = $invoice->lineItems()->sum('discount_total') / 100;
  171. $grandTotal = $subtotal + $taxTotal - $discountTotal;
  172. $invoice->updateQuietly([
  173. 'subtotal' => $subtotal,
  174. 'tax_total' => $taxTotal,
  175. 'discount_total' => $discountTotal,
  176. 'total' => $grandTotal,
  177. ]);
  178. })
  179. ->headers([
  180. Header::make('Items')->width('15%'),
  181. Header::make('Description')->width('25%'),
  182. Header::make('Quantity')->width('10%'),
  183. Header::make('Price')->width('10%'),
  184. Header::make('Taxes')->width('15%'),
  185. Header::make('Discounts')->width('15%'),
  186. Header::make('Amount')->width('10%')->align('right'),
  187. ])
  188. ->schema([
  189. Forms\Components\Select::make('offering_id')
  190. ->relationship('offering', 'name')
  191. ->preload()
  192. ->searchable()
  193. ->required()
  194. ->live()
  195. ->afterStateUpdated(function (Forms\Set $set, Forms\Get $get, $state) {
  196. $offeringId = $state;
  197. $offeringRecord = Offering::with('salesTaxes')->find($offeringId);
  198. if ($offeringRecord) {
  199. $set('description', $offeringRecord->description);
  200. $set('unit_price', $offeringRecord->price);
  201. $set('salesTaxes', $offeringRecord->salesTaxes->pluck('id')->toArray());
  202. $set('salesDiscounts', $offeringRecord->salesDiscounts->pluck('id')->toArray());
  203. }
  204. }),
  205. Forms\Components\TextInput::make('description'),
  206. Forms\Components\TextInput::make('quantity')
  207. ->required()
  208. ->numeric()
  209. ->live()
  210. ->default(1),
  211. Forms\Components\TextInput::make('unit_price')
  212. ->hiddenLabel()
  213. ->numeric()
  214. ->live()
  215. ->default(0),
  216. Forms\Components\Select::make('salesTaxes')
  217. ->relationship('salesTaxes', 'name')
  218. ->preload()
  219. ->multiple()
  220. ->live()
  221. ->searchable(),
  222. Forms\Components\Select::make('salesDiscounts')
  223. ->relationship('salesDiscounts', 'name')
  224. ->preload()
  225. ->multiple()
  226. ->live()
  227. ->searchable(),
  228. Forms\Components\Placeholder::make('total')
  229. ->hiddenLabel()
  230. ->content(function (Forms\Get $get) {
  231. $quantity = max((float) ($get('quantity') ?? 0), 0);
  232. $unitPrice = max((float) ($get('unit_price') ?? 0), 0);
  233. $salesTaxes = $get('salesTaxes') ?? [];
  234. $salesDiscounts = $get('salesDiscounts') ?? [];
  235. $subtotal = $quantity * $unitPrice;
  236. // Calculate tax amount based on subtotal
  237. $taxAmount = 0;
  238. if (! empty($salesTaxes)) {
  239. $taxRates = Adjustment::whereIn('id', $salesTaxes)->pluck('rate');
  240. $taxAmount = collect($taxRates)->sum(fn ($rate) => $subtotal * ($rate / 100));
  241. }
  242. // Calculate discount amount based on subtotal
  243. $discountAmount = 0;
  244. if (! empty($salesDiscounts)) {
  245. $discountRates = Adjustment::whereIn('id', $salesDiscounts)->pluck('rate');
  246. $discountAmount = collect($discountRates)->sum(fn ($rate) => $subtotal * ($rate / 100));
  247. }
  248. // Final total
  249. $total = $subtotal + ($taxAmount - $discountAmount);
  250. return money($total, CurrencyAccessor::getDefaultCurrency(), true)->format();
  251. }),
  252. ]),
  253. Forms\Components\Grid::make(6)
  254. ->schema([
  255. Forms\Components\ViewField::make('totals')
  256. ->columnStart(5)
  257. ->columnSpan(2)
  258. ->view('filament.forms.components.invoice-totals'),
  259. ]),
  260. // Forms\Components\Repeater::make('lineItems')
  261. // ->relationship()
  262. // ->columns(8)
  263. // ->schema([
  264. // Forms\Components\Select::make('offering_id')
  265. // ->relationship('offering', 'name')
  266. // ->preload()
  267. // ->columnSpan(2)
  268. // ->searchable()
  269. // ->required()
  270. // ->live()
  271. // ->afterStateUpdated(function (Forms\Set $set, $state) {
  272. // $offeringId = $state;
  273. // $offeringRecord = Offering::with('salesTaxes')->find($offeringId);
  274. //
  275. // if ($offeringRecord) {
  276. // $set('description', $offeringRecord->description);
  277. // $set('unit_price', $offeringRecord->price);
  278. // $set('total', $offeringRecord->price);
  279. //
  280. // $salesTaxes = $offeringRecord->salesTaxes->map(function ($tax) {
  281. // return [
  282. // 'id' => $tax->id,
  283. // 'amount' => null, // Amount will be calculated dynamically
  284. // ];
  285. // })->toArray();
  286. //
  287. // $set('taxes', $salesTaxes);
  288. // }
  289. // }),
  290. // Forms\Components\TextInput::make('description')
  291. // ->columnSpan(3)
  292. // ->required(),
  293. // Forms\Components\TextInput::make('quantity')
  294. // ->required()
  295. // ->numeric()
  296. // ->live()
  297. // ->default(1),
  298. // Forms\Components\TextInput::make('unit_price')
  299. // ->live()
  300. // ->numeric()
  301. // ->default(0),
  302. // Forms\Components\Placeholder::make('total')
  303. // ->content(function (Forms\Get $get) {
  304. // $quantity = $get('quantity');
  305. // $unitPrice = $get('unit_price');
  306. //
  307. // if ($quantity && $unitPrice) {
  308. // return $quantity * $unitPrice;
  309. // }
  310. // }),
  311. // TableRepeater::make('taxes')
  312. // ->relationship()
  313. // ->columnSpanFull()
  314. // ->columnStart(6)
  315. // ->headers([
  316. // Header::make('')->width('200px'),
  317. // Header::make('')->width('50px')->align('right'),
  318. // ])
  319. // ->defaultItems(0)
  320. // ->schema([
  321. // Forms\Components\Select::make('id') // The ID of the adjustment being attached.
  322. // ->label('Tax Adjustment')
  323. // ->options(
  324. // Adjustment::query()
  325. // ->where('category', AdjustmentCategory::Tax)
  326. // ->pluck('name', 'id')
  327. // )
  328. // ->preload()
  329. // ->searchable()
  330. // ->required()
  331. // ->live(),
  332. // Forms\Components\Placeholder::make('amount')
  333. // ->hiddenLabel()
  334. // ->content(function (Forms\Get $get) {
  335. // $quantity = $get('../../quantity') ?? 0; // Get parent quantity
  336. // $unitPrice = $get('../../unit_price') ?? 0; // Get parent unit price
  337. // $rate = Adjustment::find($get('id'))->rate ?? 0;
  338. //
  339. // $total = $quantity * $unitPrice;
  340. //
  341. // return $total * ($rate / 100);
  342. // }),
  343. // ]),
  344. // ]),
  345. Forms\Components\Textarea::make('terms')
  346. ->columnSpanFull(),
  347. ]),
  348. Forms\Components\Section::make('Invoice Footer')
  349. ->collapsible()
  350. ->schema([
  351. Forms\Components\Textarea::make('footer')
  352. ->columnSpanFull(),
  353. ]),
  354. ]);
  355. }
  356. public static function table(Table $table): Table
  357. {
  358. return $table
  359. ->columns([
  360. Tables\Columns\TextColumn::make('status')
  361. ->badge()
  362. ->searchable(),
  363. Tables\Columns\TextColumn::make('due_date')
  364. ->label('Due')
  365. ->formatStateUsing(function (Tables\Columns\TextColumn $column, mixed $state) {
  366. if (blank($state)) {
  367. return null;
  368. }
  369. $date = Carbon::parse($state)
  370. ->setTimezone($timezone ?? $column->getTimezone());
  371. if ($date->isToday()) {
  372. return 'Today';
  373. }
  374. return $date->diffForHumans([
  375. 'options' => CarbonInterface::ONE_DAY_WORDS,
  376. ]);
  377. })
  378. ->sortable(),
  379. Tables\Columns\TextColumn::make('date')
  380. ->date()
  381. ->sortable(),
  382. Tables\Columns\TextColumn::make('invoice_number')
  383. ->label('Number')
  384. ->searchable(),
  385. Tables\Columns\TextColumn::make('client.name')
  386. ->numeric()
  387. ->sortable(),
  388. Tables\Columns\TextColumn::make('total')
  389. ->currency(),
  390. Tables\Columns\TextColumn::make('amount_paid')
  391. ->label('Amount Paid')
  392. ->currency(),
  393. Tables\Columns\TextColumn::make('amount_due')
  394. ->label('Amount Due')
  395. ->currency(),
  396. ])
  397. ->filters([
  398. //
  399. ])
  400. ->actions([
  401. Tables\Actions\EditAction::make(),
  402. ])
  403. ->bulkActions([
  404. Tables\Actions\BulkActionGroup::make([
  405. Tables\Actions\DeleteBulkAction::make(),
  406. ]),
  407. ]);
  408. }
  409. public static function getRelations(): array
  410. {
  411. return [
  412. //
  413. ];
  414. }
  415. public static function getPages(): array
  416. {
  417. return [
  418. 'index' => Pages\ListInvoices::route('/'),
  419. 'create' => Pages\CreateInvoice::route('/create'),
  420. 'edit' => Pages\EditInvoice::route('/{record}/edit'),
  421. ];
  422. }
  423. }