Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
177 changes: 172 additions & 5 deletions app/Http/Controllers/Admin/ProductController.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use App\Http\Controllers\Controller;
use App\Models\Currency;
use App\Models\InvoiceItemGroup;
use App\Models\InvoiceProduct;
use App\Models\Pricing;
use App\Models\Product;
Expand All @@ -17,19 +18,88 @@
use App\Support\ContentTranslations;
use App\Support\UniqueSlug;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;

class ProductController extends Controller
{
public function index()
{
$groups = ProductGroup::with('products')->orderBy('sort_order')->get();

$invoiceProducts = InvoiceProduct::orderBy('name')->get();
return view('admin.products.index', compact('groups'));
}

/**
* Invoice items are separate from sellable products: they are ready-made
* lines for invoices written by hand. They get their own page, groups and
* pagination so the product catalogue stays about products.
*/
public function invoiceItems(Request $request)
{
$validated = $request->validate([
'sort' => ['nullable', Rule::in(['name', 'group', 'price'])],
'direction' => ['nullable', Rule::in(['asc', 'desc'])],
'per_page' => ['nullable', 'integer', Rule::in([25, 50, 100])],
'group' => ['nullable', 'integer', 'exists:invoice_item_groups,id'],
'subgroup' => ['nullable', 'integer', 'exists:invoice_item_groups,id'],
]);

$sort = $validated['sort'] ?? 'group';
$direction = $validated['direction'] ?? 'asc';
$perPage = (int) ($validated['per_page'] ?? 25);

$query = InvoiceProduct::query()
->select('invoice_products.*')
->with(['group.parent']);

if (! empty($validated['group'])) {
$groupId = (int) $validated['group'];
$query->whereHas('group', fn ($groupQuery) => $groupQuery
->where('id', $groupId)
->orWhere('parent_id', $groupId));
}

if (! empty($validated['subgroup'])) {
$query->where('invoice_item_group_id', (int) $validated['subgroup']);
}

if ($sort === 'group') {
$query->leftJoin('invoice_item_groups as item_groups', 'item_groups.id', '=', 'invoice_products.invoice_item_group_id')
->leftJoin('invoice_item_groups as parent_groups', 'parent_groups.id', '=', 'item_groups.parent_id')
->orderByRaw('CASE WHEN item_groups.id IS NULL THEN 1 ELSE 0 END')
->orderByRaw('COALESCE(parent_groups.name, item_groups.name) '.$direction)
->orderByRaw('CASE WHEN item_groups.parent_id IS NULL THEN 0 ELSE 1 END')
->orderBy('item_groups.name', $direction)
->orderBy('invoice_products.name');
} elseif ($sort === 'price') {
$query->orderBy('invoice_products.price', $direction)
->orderBy('invoice_products.name');
} else {
$query->orderBy('invoice_products.name', $direction);
}

$invoiceProducts = $query->paginate($perPage)->withQueryString();

$groups = InvoiceItemGroup::whereNull('parent_id')
->with(['children' => fn ($children) => $children->withCount('items')])
->withCount('items')
->orderBy('name')
->get();

$taxRateOptions = $this->taxRateOptions();
$defaultTaxLabel = $taxRateOptions->first()?->name ?? '';

return view('admin.products.index', compact('groups', 'invoiceProducts', 'taxRateOptions', 'defaultTaxLabel'));
return view('admin.products.invoice-items', compact(
'invoiceProducts',
'groups',
'taxRateOptions',
'defaultTaxLabel',
'sort',
'direction',
'perPage'
));
}

/**
Expand Down Expand Up @@ -108,7 +178,7 @@ public function destroyGroup(ProductGroup $group)
return back()->with('error', __('admin.messages.product_group_has_history'));
}

\Illuminate\Support\Facades\DB::transaction(function () use ($group, $deleted) {
DB::transaction(function () use ($group, $deleted) {
$deleted->each->forceDelete();
$group->delete();
});
Expand Down Expand Up @@ -685,6 +755,101 @@ public function copy(Product $product)
->with('success', __('admin.messages.product_copied', ['name' => $copy->name]));
}

public function storeInvoiceItemGroup(Request $request)
{
InvoiceItemGroup::create($this->validateInvoiceItemGroup($request));

return back()->with('success', __('admin.products.invoice_item_group_created'));
}

public function updateInvoiceItemGroup(Request $request, InvoiceItemGroup $invoiceItemGroup)
{
$invoiceItemGroup->update($this->validateInvoiceItemGroup($request, $invoiceItemGroup));

return back()->with('success', __('admin.products.invoice_item_group_updated'));
}

public function destroyInvoiceItemGroup(InvoiceItemGroup $invoiceItemGroup)
{
if ($invoiceItemGroup->children()->exists()) {
return back()->with('error', __('admin.products.invoice_item_group_has_children'));
}

DB::transaction(function () use ($invoiceItemGroup) {
InvoiceProduct::where('invoice_item_group_id', $invoiceItemGroup->id)
->update(['invoice_item_group_id' => null]);
$invoiceItemGroup->delete();
});

return back()->with('success', __('admin.products.invoice_item_group_deleted'));
}

/**
* A group has no parent; a subgroup points at a group. There is no third
* level, and names are unique inside the chosen parent.
*/
private function validateInvoiceItemGroup(Request $request, ?InvoiceItemGroup $group = null): array
{
$validated = $request->validate([
'name' => ['required', 'string', 'max:255'],
'parent_id' => ['nullable', 'integer', 'exists:invoice_item_groups,id'],
'type' => ['nullable', Rule::in(['group', 'subgroup'])],
]);

$name = trim($validated['name']);
$parentId = empty($validated['parent_id']) ? null : (int) $validated['parent_id'];
$type = $validated['type'] ?? ($parentId === null ? 'group' : 'subgroup');

if ($type === 'subgroup' && $parentId === null) {
throw ValidationException::withMessages([
'parent_id' => __('admin.products.invoice_item_group_parent_invalid'),
]);
}

if ($type === 'group') {
$parentId = null;
}

if ($parentId !== null) {
if ($group && $parentId === $group->id) {
throw ValidationException::withMessages([
'parent_id' => __('admin.products.invoice_item_group_parent_invalid'),
]);
}

$parent = InvoiceItemGroup::findOrFail($parentId);
if ($parent->parent_id !== null) {
throw ValidationException::withMessages([
'parent_id' => __('admin.products.invoice_item_group_parent_invalid'),
]);
}

if ($group && $group->children()->exists()) {
throw ValidationException::withMessages([
'parent_id' => __('admin.products.invoice_item_group_has_children'),
]);
}
}

$duplicate = InvoiceItemGroup::query()
->where('name', $name)
->when(
$parentId === null,
fn ($query) => $query->whereNull('parent_id'),
fn ($query) => $query->where('parent_id', $parentId)
)
->when($group, fn ($query) => $query->whereKeyNot($group->id))
->exists();

if ($duplicate) {
throw ValidationException::withMessages([
'name' => __('admin.products.invoice_item_group_name_taken'),
]);
}

return ['name' => $name, 'parent_id' => $parentId];
}

/**
* Store a catalog product/service (goods or services for invoicing).
*/
Expand Down Expand Up @@ -712,7 +877,7 @@ public function destroyInvoiceProduct(InvoiceProduct $invoiceProduct)
}

/**
* @return array{name: string, price: string, unit: ?string, tax_rate: float, tax_label: ?string}
* @return array{name: string, price: string, unit: ?string, tax_rate: float, tax_label: ?string, invoice_item_group_id: ?int}
*/
private function validateInvoiceProduct(Request $request): array
{
Expand All @@ -721,9 +886,10 @@ private function validateInvoiceProduct(Request $request): array
'price' => 'required|numeric|min:0',
'unit' => 'nullable|string|max:50',
'tax_label' => 'nullable|string|max:255',
'invoice_item_group_id' => ['nullable', 'integer', 'exists:invoice_item_groups,id'],
]);

$taxLabel = $v['tax_label'] ?: null;
$taxLabel = $v['tax_label'] ?? null;
$rule = $taxLabel ? TaxRule::where('name', $taxLabel)->orderBy('id')->first() : null;
$taxRate = $rule ? (float) $rule->tax_rate : 0.0;

Expand All @@ -734,6 +900,7 @@ private function validateInvoiceProduct(Request $request): array
'tax_rate' => $taxRate,
'tax_label' => $taxLabel,
'tax_rule_id' => $rule?->id,
'invoice_item_group_id' => $v['invoice_item_group_id'] ?? null,
];
}
}
30 changes: 30 additions & 0 deletions app/Models/InvoiceItemGroup.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class InvoiceItemGroup extends Model
{
protected $fillable = ['parent_id', 'name'];

protected function casts(): array
{
return ['parent_id' => 'integer'];
}

public function parent()
{
return $this->belongsTo(self::class, 'parent_id');
}

public function children()
{
return $this->hasMany(self::class, 'parent_id')->orderBy('name');
}

public function items()
{
return $this->hasMany(InvoiceProduct::class, 'invoice_item_group_id');
}
}
4 changes: 3 additions & 1 deletion app/Models/InvoiceProduct.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@
class InvoiceProduct extends Model {
use HasFactory;

protected $fillable = ["name", "price", "unit", "tax_rate", "tax_label", "tax_rule_id"];
protected $fillable = ["name", "price", "unit", "tax_rate", "tax_label", "tax_rule_id", "invoice_item_group_id"];
protected function casts(): array { return ["price" => "decimal:2", "tax_rate" => "decimal:2", "tax_rule_id" => "integer"]; }

public function taxRule() { return $this->belongsTo(TaxRule::class); }

public function group() { return $this->belongsTo(InvoiceItemGroup::class, 'invoice_item_group_id'); }
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
public function up(): void
{
Schema::create('invoice_item_groups', function (Blueprint $table) {
$table->id();
$table->foreignId('parent_id')->nullable()->constrained('invoice_item_groups')->nullOnDelete();
$table->string('name');
$table->timestamps();

$table->index(['parent_id', 'name']);
});

Schema::table('invoice_products', function (Blueprint $table) {
$table->foreignId('invoice_item_group_id')
->nullable()
->after('tax_rule_id')
->constrained('invoice_item_groups')
->nullOnDelete();
});
}

public function down(): void
{
Schema::table('invoice_products', function (Blueprint $table) {
$table->dropConstrainedForeignId('invoice_item_group_id');
});

Schema::dropIfExists('invoice_item_groups');
}
};
33 changes: 33 additions & 0 deletions lang/de/admin.php
Original file line number Diff line number Diff line change
Expand Up @@ -2016,6 +2016,7 @@
'nav.product_addons' => 'Produkt-Add-ons',
'nav.product_bundles' => 'Produktpakete',
'nav.products_services' => 'Produkte/Dienstleistungen',
'nav.invoice_items' => 'Rechnungspositionen',
'nav.promotions' => 'Werbeaktionen',
'nav.quotes' => 'Zitate',
'nav.reports' => 'Berichte',
Expand Down Expand Up @@ -2461,6 +2462,38 @@
'products.no_products_services' => 'Noch keine Rechnungsposten.',
'products.products_services' => 'Rechnungsposten',
'products.invoice_items_hint' => 'Vorgefertigte Positionen für Rechnungen, die Sie von Hand erstellen. Um eine Dienstleistung mit eigenem Abrechnungszeitraum zu verkaufen, legen Sie mit „Neues Produkt“ ein Produkt an.',
'products.invoice_items_title' => 'Rechnungspositionen',
'products.invoice_items_added' => 'Bereits hinzugefügte Rechnungspositionen',
'products.new_invoice_item_group' => 'Neue Gruppe',
'products.edit_invoice_item_group' => 'Gruppe bearbeiten',
'products.invoice_item_group' => 'Gruppe',
'products.invoice_item_subgroup' => 'Untergruppe',
'products.invoice_item_group_type' => 'Typ',
'products.invoice_item_group_root' => 'Gruppe',
'products.invoice_item_group_parent' => 'Übergeordnete Gruppe',
'products.invoice_item_groups' => 'Gruppen und Untergruppen',
'products.invoice_item_group_name' => 'Gruppenname',
'products.invoice_item_group_name_placeholder' => 'z. B. Leistungen',
'products.invoice_item_name_placeholder' => 'z. B. IT-Dienstleistung',
'products.invoice_item_unit_placeholder' => 'Stk. / Std.',
'products.invoice_item_price_placeholder' => '0.00',
'products.invoice_item_group_has_children' => 'Diese Gruppe hat Untergruppen. Löschen Sie zuerst die Untergruppen.',
'products.invoice_item_group_parent_invalid' => 'Eine Untergruppe kann nur zu einer Gruppe der obersten Ebene gehören.',
'products.invoice_item_group_name_taken' => 'Dieser Name wird in dieser Gruppe bereits verwendet.',
'products.invoice_item_group_created' => 'Gruppe erstellt.',
'products.invoice_item_group_updated' => 'Gruppe aktualisiert.',
'products.invoice_item_group_deleted' => 'Gruppe gelöscht.',
'products.confirm_delete_invoice_item_group' => 'Diese Gruppe löschen? Ihre Positionen bleiben ohne Gruppe.',
'products.filter_by_group' => 'Gruppe',
'products.all_groups' => 'Alle Gruppen',
'products.items_per_page' => 'Pro Seite',
'products.sort_by_name' => 'Bezeichnung',
'products.sort_by_group' => 'Gruppe / Untergruppe',
'products.sort_by_price' => 'Preis',
'products.apply_filters' => 'Filtern',
'products.no_invoice_item_groups' => 'Noch keine Gruppen.',
'products.no_invoice_item_group' => 'Keine Gruppe',
'products.zero_tax' => '0%',
'products.unit' => 'Einheit',
'projects' => [
'actions' => 'Aktionen',
Expand Down
Loading
Loading