feat: enhance Expense model and service with media handling and receipt upload functionality
This commit is contained in:
parent
a138ffe63c
commit
e63f692478
@ -27,7 +27,7 @@ public function rules(): array
|
|||||||
return [
|
return [
|
||||||
'amount' => ['required', 'integer', 'min:1'],
|
'amount' => ['required', 'integer', 'min:1'],
|
||||||
'description' => ['required', 'string', 'max:100'],
|
'description' => ['required', 'string', 'max:100'],
|
||||||
'receipt_key' => ['nullable', 'string', 'max:500'],
|
'receipt_key' => ['required', 'string', 'max:500'],
|
||||||
'file_size' => ['nullable', 'integer', 'min:1'],
|
'file_size' => ['nullable', 'integer', 'min:1'],
|
||||||
'file_mime_type' => ['nullable', 'string', 'in:image/jpeg,image/png,image/webp,image/gif'],
|
'file_mime_type' => ['nullable', 'string', 'in:image/jpeg,image/png,image/webp,image/gif'],
|
||||||
];
|
];
|
||||||
|
|||||||
@ -7,11 +7,13 @@
|
|||||||
use Illuminate\Database\Eloquent\Model;
|
use Illuminate\Database\Eloquent\Model;
|
||||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||||
use Illuminate\Database\Eloquent\SoftDeletes;
|
use Illuminate\Database\Eloquent\SoftDeletes;
|
||||||
|
use Spatie\MediaLibrary\HasMedia;
|
||||||
|
use Spatie\MediaLibrary\InteractsWithMedia;
|
||||||
|
|
||||||
#[Guarded(['id'])]
|
#[Guarded(['id'])]
|
||||||
class Expense extends Model
|
class Expense extends Model implements HasMedia
|
||||||
{
|
{
|
||||||
use HasFactory, SoftDeletes;
|
use HasFactory, SoftDeletes, InteractsWithMedia;
|
||||||
|
|
||||||
protected function casts(): array
|
protected function casts(): array
|
||||||
{
|
{
|
||||||
|
|||||||
@ -6,17 +6,50 @@
|
|||||||
use App\Models\CashAccount;
|
use App\Models\CashAccount;
|
||||||
use App\Models\CashTransaction;
|
use App\Models\CashTransaction;
|
||||||
use App\Models\Expense;
|
use App\Models\Expense;
|
||||||
|
use App\Services\S3PresignedService;
|
||||||
use Illuminate\Support\Collection;
|
use Illuminate\Support\Collection;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
use Illuminate\Validation\ValidationException;
|
use Illuminate\Validation\ValidationException;
|
||||||
|
use Spatie\MediaLibrary\MediaCollections\Models\Media;
|
||||||
|
|
||||||
class ExpenseService
|
class ExpenseService
|
||||||
{
|
{
|
||||||
|
public function __construct(
|
||||||
|
private S3PresignedService $s3Service = new S3PresignedService,
|
||||||
|
) {}
|
||||||
|
|
||||||
public function getAll(): Collection
|
public function getAll(): Collection
|
||||||
{
|
{
|
||||||
return Expense::with('createdBy.userProfile')
|
return Expense::select('id', 'created_by_id', 'amount', 'description', 'created_at')
|
||||||
|
->with('createdBy.userProfile', 'media')
|
||||||
->latest()
|
->latest()
|
||||||
->get();
|
->get()
|
||||||
|
->map(fn (Expense $expense) => $this->formatExpense($expense));
|
||||||
|
}
|
||||||
|
|
||||||
|
private function formatExpense(Expense $expense): array
|
||||||
|
{
|
||||||
|
$media = $expense->getFirstMedia('receipts');
|
||||||
|
|
||||||
|
if (! $media) {
|
||||||
|
return $expense->toArray() + [
|
||||||
|
'receipt_key' => null,
|
||||||
|
'receipt_url' => null,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
$s3Key = $media->file_name;
|
||||||
|
|
||||||
|
// Handle old data where file_name is just the filename, not full path
|
||||||
|
if (str_starts_with($s3Key, '/') || ! str_contains($s3Key, '/')) {
|
||||||
|
$s3Key = $media->getPath();
|
||||||
|
}
|
||||||
|
|
||||||
|
return $expense->toArray() + [
|
||||||
|
'receipt_key' => $s3Key,
|
||||||
|
'receipt_url' => $this->s3Service->getTemporaryUrl($s3Key),
|
||||||
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
public function create(array $data): Expense
|
public function create(array $data): Expense
|
||||||
@ -42,12 +75,18 @@ public function create(array $data): Expense
|
|||||||
'description' => $data['description'],
|
'description' => $data['description'],
|
||||||
]);
|
]);
|
||||||
|
|
||||||
return Expense::create([
|
$expense = Expense::create([
|
||||||
'cash_transaction_id' => $cashTransaction->id,
|
'cash_transaction_id' => $cashTransaction->id,
|
||||||
'created_by_id' => auth()->id(),
|
'created_by_id' => auth()->id(),
|
||||||
'amount' => $data['amount'],
|
'amount' => $data['amount'],
|
||||||
'description' => $data['description'],
|
'description' => $data['description'],
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
if (! empty($data['receipt_key'])) {
|
||||||
|
$this->registerMedia($expense, $data['receipt_key'], $data['file_size'] ?? null, $data['file_mime_type'] ?? null);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $expense;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -81,6 +120,24 @@ public function update(Expense $expense, array $data): Expense
|
|||||||
'description' => $data['description'],
|
'description' => $data['description'],
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
if (array_key_exists('receipt_key', $data)) {
|
||||||
|
$currentMedia = $expense->getFirstMedia('receipts');
|
||||||
|
$currentKey = $currentMedia?->file_name;
|
||||||
|
|
||||||
|
// Normalize: if file_name is just a filename (old data), use getPath()
|
||||||
|
if ($currentMedia && ! str_contains($currentKey, '/')) {
|
||||||
|
$currentKey = $currentMedia->getPath();
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($data['receipt_key'] !== $currentKey) {
|
||||||
|
$expense->clearMediaCollection('receipts');
|
||||||
|
|
||||||
|
if (! empty($data['receipt_key'])) {
|
||||||
|
$this->registerMedia($expense, $data['receipt_key'], $data['file_size'] ?? null, $data['file_mime_type'] ?? null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return $expense;
|
return $expense;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@ -89,12 +146,37 @@ public function delete(Expense $expense): bool
|
|||||||
{
|
{
|
||||||
return DB::transaction(function () use ($expense) {
|
return DB::transaction(function () use ($expense) {
|
||||||
$cashAccount = CashAccount::firstOrFail();
|
$cashAccount = CashAccount::firstOrFail();
|
||||||
$cashTransaction = $expense->cashTransaction;
|
|
||||||
|
|
||||||
$newBalance = $cashAccount->balance + $expense->amount;
|
$newBalance = $cashAccount->balance + $expense->amount;
|
||||||
$cashAccount->update(['balance' => $newBalance]);
|
$cashAccount->update(['balance' => $newBalance]);
|
||||||
|
|
||||||
|
$expense->clearMediaCollection('receipts');
|
||||||
|
|
||||||
return $expense->delete();
|
return $expense->delete();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private function registerMedia(Expense $expense, string $s3Key, ?int $fileSize = null, ?string $mimeType = null): void
|
||||||
|
{
|
||||||
|
$fileName = pathinfo($s3Key, PATHINFO_BASENAME);
|
||||||
|
$name = pathinfo($s3Key, PATHINFO_FILENAME);
|
||||||
|
|
||||||
|
Media::create([
|
||||||
|
'model_type' => Expense::class,
|
||||||
|
'model_id' => $expense->id,
|
||||||
|
'uuid' => Str::uuid(),
|
||||||
|
'collection_name' => 'receipts',
|
||||||
|
'name' => $name,
|
||||||
|
'file_name' => $s3Key,
|
||||||
|
'mime_type' => $mimeType ?? 'image/jpeg',
|
||||||
|
'disk' => 's3',
|
||||||
|
'conversions_disk' => 's3',
|
||||||
|
'size' => $fileSize ?? 0,
|
||||||
|
'manipulations' => [],
|
||||||
|
'custom_properties' => [],
|
||||||
|
'generated_conversions' => ['thumb' => true],
|
||||||
|
'responsive_images' => [],
|
||||||
|
'order_column' => 1,
|
||||||
|
]);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,5 +1,4 @@
|
|||||||
import type { ColumnDef } from '@tanstack/react-table';
|
import { ImagePreviewModal } from '@/components/image-preview-modal';
|
||||||
import { ArrowUpDown, Pencil, Trash2 } from 'lucide-react';
|
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import {
|
import {
|
||||||
Tooltip,
|
Tooltip,
|
||||||
@ -8,11 +7,16 @@ import {
|
|||||||
TooltipTrigger,
|
TooltipTrigger,
|
||||||
} from '@/components/ui/tooltip';
|
} from '@/components/ui/tooltip';
|
||||||
import { formatCurrency } from '@/lib/utils';
|
import { formatCurrency } from '@/lib/utils';
|
||||||
|
import type { ColumnDef } from '@tanstack/react-table';
|
||||||
|
import { ArrowUpDown, Pencil, Trash2 } from 'lucide-react';
|
||||||
|
import { useState } from 'react';
|
||||||
|
|
||||||
export type Expense = {
|
export type Expense = {
|
||||||
id: number;
|
id: number;
|
||||||
amount: number;
|
amount: number;
|
||||||
description: string;
|
description: string;
|
||||||
|
receipt_key: string | null;
|
||||||
|
receipt_url: string | null;
|
||||||
created_at: string;
|
created_at: string;
|
||||||
created_by: {
|
created_by: {
|
||||||
user_profile: {
|
user_profile: {
|
||||||
@ -39,6 +43,31 @@ type CreateColumnsParams = {
|
|||||||
handleDeleteClick: (expense: Expense) => void;
|
handleDeleteClick: (expense: Expense) => void;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
function ReceiptPreview({ url, title }: { url: string; title: string }) {
|
||||||
|
const [open, setOpen] = useState(false);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<button
|
||||||
|
onClick={() => setOpen(true)}
|
||||||
|
className="block h-10 w-10 overflow-hidden rounded-md border bg-muted transition-opacity hover:opacity-80"
|
||||||
|
>
|
||||||
|
<img
|
||||||
|
src={url}
|
||||||
|
alt={title}
|
||||||
|
className="h-full w-full object-cover"
|
||||||
|
/>
|
||||||
|
</button>
|
||||||
|
<ImagePreviewModal
|
||||||
|
open={open}
|
||||||
|
onOpenChange={setOpen}
|
||||||
|
src={url}
|
||||||
|
title={title}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
export function createExpenseColumns(
|
export function createExpenseColumns(
|
||||||
params: CreateColumnsParams,
|
params: CreateColumnsParams,
|
||||||
): ColumnDef<Expense>[] {
|
): ColumnDef<Expense>[] {
|
||||||
@ -85,6 +114,19 @@ export function createExpenseColumns(
|
|||||||
<span className="max-w-[200px] truncate block">{row.getValue('description') as string}</span>
|
<span className="max-w-[200px] truncate block">{row.getValue('description') as string}</span>
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
id: 'receipt',
|
||||||
|
header: () => <span>Bukti</span>,
|
||||||
|
cell: ({ row }) => {
|
||||||
|
const receiptUrl = row.original.receipt_url;
|
||||||
|
|
||||||
|
if (!receiptUrl) {
|
||||||
|
return <span className="text-muted-foreground">-</span>;
|
||||||
|
}
|
||||||
|
|
||||||
|
return <ReceiptPreview url={receiptUrl} title={row.original.description} />;
|
||||||
|
},
|
||||||
|
},
|
||||||
{
|
{
|
||||||
accessorKey: 'amount',
|
accessorKey: 'amount',
|
||||||
header: ({ column }) => (
|
header: ({ column }) => (
|
||||||
@ -114,7 +156,6 @@ export function createExpenseColumns(
|
|||||||
const createdBy = row.original.created_by;
|
const createdBy = row.original.created_by;
|
||||||
|
|
||||||
return <span>{createdBy?.user_profile?.full_name ?? '-'}</span>;
|
return <span>{createdBy?.user_profile?.full_name ?? '-'}</span>;
|
||||||
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
@ -1,6 +1,9 @@
|
|||||||
import { Form, Head, router } from '@inertiajs/react';
|
import { Form, Head, router } from '@inertiajs/react';
|
||||||
import { Plus } from 'lucide-react';
|
import { Plus } from 'lucide-react';
|
||||||
import { useState } from 'react';
|
import { useState } from 'react';
|
||||||
|
import { ConfirmDialog } from '@/components/confirm-dialog';
|
||||||
|
import { DataTable } from '@/components/data-table';
|
||||||
|
import { FileUpload } from '@/components/file-upload';
|
||||||
import InputError from '@/components/input-error';
|
import InputError from '@/components/input-error';
|
||||||
import { RupiahInput } from '@/components/rupiah-input';
|
import { RupiahInput } from '@/components/rupiah-input';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
@ -16,8 +19,6 @@ import { Label } from '@/components/ui/label';
|
|||||||
import { destroy, index as expenseIndex, store, update } from '@/routes/admin/finance/expenses';
|
import { destroy, index as expenseIndex, store, update } from '@/routes/admin/finance/expenses';
|
||||||
import { createExpenseColumns } from './columns';
|
import { createExpenseColumns } from './columns';
|
||||||
import type { Expense } from './columns';
|
import type { Expense } from './columns';
|
||||||
import { ConfirmDialog } from '@/components/confirm-dialog';
|
|
||||||
import { DataTable } from '@/components/data-table';
|
|
||||||
|
|
||||||
type Props = {
|
type Props = {
|
||||||
expenses: Expense[];
|
expenses: Expense[];
|
||||||
@ -27,6 +28,12 @@ export default function ExpenseIndex({ expenses }: Props) {
|
|||||||
const [createOpen, setCreateOpen] = useState(false);
|
const [createOpen, setCreateOpen] = useState(false);
|
||||||
const [editing, setEditing] = useState<Expense | null>(null);
|
const [editing, setEditing] = useState<Expense | null>(null);
|
||||||
const [deleting, setDeleting] = useState<Expense | null>(null);
|
const [deleting, setDeleting] = useState<Expense | null>(null);
|
||||||
|
const [createReceiptKey, setCreateReceiptKey] = useState<string | null>(null);
|
||||||
|
const [editReceiptKey, setEditReceiptKey] = useState<string | null>(null);
|
||||||
|
const [createUploading, setCreateUploading] = useState(false);
|
||||||
|
const [editUploading, setEditUploading] = useState(false);
|
||||||
|
const [createFileMeta, setCreateFileMeta] = useState<{ size: number; type: string } | null>(null);
|
||||||
|
const [editFileMeta, setEditFileMeta] = useState<{ size: number; type: string } | null>(null);
|
||||||
|
|
||||||
function handleDelete() {
|
function handleDelete() {
|
||||||
if (!deleting) {
|
if (!deleting) {
|
||||||
@ -39,7 +46,10 @@ export default function ExpenseIndex({ expenses }: Props) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const columns = createExpenseColumns({
|
const columns = createExpenseColumns({
|
||||||
handleEdit: (expense) => setEditing(expense),
|
handleEdit: (expense) => {
|
||||||
|
setEditing(expense);
|
||||||
|
setEditReceiptKey(expense.receipt_key ?? null);
|
||||||
|
},
|
||||||
handleDeleteClick: (expense) => setDeleting(expense),
|
handleDeleteClick: (expense) => setDeleting(expense),
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -54,7 +64,14 @@ export default function ExpenseIndex({ expenses }: Props) {
|
|||||||
Pengeluaran
|
Pengeluaran
|
||||||
</h2>
|
</h2>
|
||||||
</div>
|
</div>
|
||||||
<Dialog open={createOpen} onOpenChange={setCreateOpen}>
|
<Dialog open={createOpen} onOpenChange={(open) => {
|
||||||
|
setCreateOpen(open);
|
||||||
|
|
||||||
|
if (!open) {
|
||||||
|
setCreateReceiptKey(null);
|
||||||
|
setCreateFileMeta(null);
|
||||||
|
}
|
||||||
|
}}>
|
||||||
<Button asChild>
|
<Button asChild>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
@ -65,7 +82,11 @@ export default function ExpenseIndex({ expenses }: Props) {
|
|||||||
</button>
|
</button>
|
||||||
</Button>
|
</Button>
|
||||||
<DialogContent>
|
<DialogContent>
|
||||||
<Form action={store()} resetOnSuccess onSuccess={() => setCreateOpen(false)}>
|
<Form action={store()} resetOnSuccess onSuccess={() => {
|
||||||
|
setCreateOpen(false);
|
||||||
|
setCreateReceiptKey(null);
|
||||||
|
setCreateFileMeta(null);
|
||||||
|
}}>
|
||||||
{({ errors, processing }) => {
|
{({ errors, processing }) => {
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@ -92,6 +113,20 @@ export default function ExpenseIndex({ expenses }: Props) {
|
|||||||
/>
|
/>
|
||||||
<InputError message={errors.description} />
|
<InputError message={errors.description} />
|
||||||
</div>
|
</div>
|
||||||
|
<div className="grid gap-2">
|
||||||
|
<Label>Bukti{' '} <span className="text-destructive">*</span></Label>
|
||||||
|
<input type="hidden" name="receipt_key" value={createReceiptKey ?? ''} />
|
||||||
|
<input type="hidden" name="file_size" value={createFileMeta?.size ?? ''} />
|
||||||
|
<input type="hidden" name="file_mime_type" value={createFileMeta?.type ?? ''} />
|
||||||
|
<FileUpload
|
||||||
|
value={createReceiptKey}
|
||||||
|
onChange={setCreateReceiptKey}
|
||||||
|
folder="expense"
|
||||||
|
onUploadingChange={setCreateUploading}
|
||||||
|
onFileMeta={setCreateFileMeta}
|
||||||
|
/>
|
||||||
|
<InputError message={errors.receipt_key} />
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<DialogFooter>
|
<DialogFooter>
|
||||||
<Button
|
<Button
|
||||||
@ -103,11 +138,13 @@ export default function ExpenseIndex({ expenses }: Props) {
|
|||||||
</Button>
|
</Button>
|
||||||
<Button
|
<Button
|
||||||
type='submit'
|
type='submit'
|
||||||
disabled={processing}
|
disabled={processing || createUploading}
|
||||||
>
|
>
|
||||||
{processing
|
{processing
|
||||||
? 'Menyimpan...'
|
? 'Menyimpan...'
|
||||||
: 'Simpan'}
|
: createUploading
|
||||||
|
? 'Mengunggah...'
|
||||||
|
: 'Simpan'}
|
||||||
</Button>
|
</Button>
|
||||||
</DialogFooter>
|
</DialogFooter>
|
||||||
</>
|
</>
|
||||||
@ -131,12 +168,18 @@ export default function ExpenseIndex({ expenses }: Props) {
|
|||||||
onOpenChange={(open) => {
|
onOpenChange={(open) => {
|
||||||
if (!open) {
|
if (!open) {
|
||||||
setEditing(null);
|
setEditing(null);
|
||||||
|
setEditReceiptKey(null);
|
||||||
|
setEditFileMeta(null);
|
||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<DialogContent>
|
<DialogContent>
|
||||||
{editing && (
|
{editing && (
|
||||||
<Form action={update(editing.id)} resetOnSuccess onSuccess={() => setEditing(null)}>
|
<Form action={update(editing.id)} resetOnSuccess onSuccess={() => {
|
||||||
|
setEditing(null);
|
||||||
|
setEditReceiptKey(null);
|
||||||
|
setEditFileMeta(null);
|
||||||
|
}}>
|
||||||
{({ errors, processing }) => {
|
{({ errors, processing }) => {
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@ -160,6 +203,21 @@ export default function ExpenseIndex({ expenses }: Props) {
|
|||||||
/>
|
/>
|
||||||
<InputError message={errors.description} />
|
<InputError message={errors.description} />
|
||||||
</div>
|
</div>
|
||||||
|
<div className="grid gap-2">
|
||||||
|
<Label>Bukti{' '} <span className="text-destructive">*</span></Label>
|
||||||
|
<input type="hidden" name="receipt_key" value={editReceiptKey ?? ''} />
|
||||||
|
<input type="hidden" name="file_size" value={editFileMeta?.size ?? ''} />
|
||||||
|
<input type="hidden" name="file_mime_type" value={editFileMeta?.type ?? ''} />
|
||||||
|
<FileUpload
|
||||||
|
value={editReceiptKey}
|
||||||
|
onChange={setEditReceiptKey}
|
||||||
|
folder="expense"
|
||||||
|
onUploadingChange={setEditUploading}
|
||||||
|
existingUrl={editing.receipt_url}
|
||||||
|
onFileMeta={setEditFileMeta}
|
||||||
|
/>
|
||||||
|
<InputError message={errors.receipt_key} />
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<DialogFooter>
|
<DialogFooter>
|
||||||
<Button
|
<Button
|
||||||
@ -173,11 +231,13 @@ export default function ExpenseIndex({ expenses }: Props) {
|
|||||||
</Button>
|
</Button>
|
||||||
<Button
|
<Button
|
||||||
type="submit"
|
type="submit"
|
||||||
disabled={processing}
|
disabled={processing || editUploading}
|
||||||
>
|
>
|
||||||
{processing
|
{processing
|
||||||
? 'Menyimpan...'
|
? 'Menyimpan...'
|
||||||
: 'Simpan'}
|
: editUploading
|
||||||
|
? 'Mengunggah...'
|
||||||
|
: 'Simpan'}
|
||||||
</Button>
|
</Button>
|
||||||
</DialogFooter>
|
</DialogFooter>
|
||||||
</>
|
</>
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user