where('is_active', true); if ($request->has('q') && $request->q) { $products->where(function($query) use ($request) { $query->where('name', 'like', "%{$request->q}%") ->orWhere('sku', 'like', "%{$request->q}%"); }); } $products = $products->orderBy('name') ->paginate(config('app.pagination')); return ApiResponse::OK->response([ 'products' => $products ]); } public function show(Inventory $inventario) { return ApiResponse::OK->response([ 'model' => $inventario->load(['category', 'price']) ]); } public function store(InventoryStoreRequest $request) { $product = $this->productService->createProduct($request->validated()); return ApiResponse::OK->response([ 'model' => $product ]); } public function update(InventoryUpdateRequest $request, Inventory $inventario) { $product = $this->productService->updateProduct($inventario, $request->validated()); return ApiResponse::OK->response([ 'model' => $product ]); } public function destroy(Inventory $inventario) { $inventario->delete(); return ApiResponse::OK->response(); } /** * Importar productos desde Excel */ public function import(InventoryImportRequest $request) { try { $import = new ProductsImport(); Excel::import($import, $request->file('file')); $stats = $import->getStats(); return ApiResponse::OK->response([ 'message' => 'Importación completada exitosamente.', 'imported' => $stats['imported'], 'skipped' => $stats['skipped'], 'errors' => $stats['errors'], ]); } catch (ValidationException $e) { $failures = $e->failures(); $errors = []; foreach ($failures as $failure) { $errors[] = [ 'row' => $failure->row(), 'attribute' => $failure->attribute(), 'errors' => $failure->errors(), 'values' => $failure->values(), ]; } return ApiResponse::BAD_REQUEST->response([ 'message' => 'Error de validación en el archivo.', 'errors' => $errors, ]); } catch (\Exception $e) { return ApiResponse::INTERNAL_ERROR->response([ 'message' => 'Error al importar productos: ' . $e->getMessage(), ]); } } /** * Descargar plantilla de Excel para importación */ public function downloadTemplate() { $headers = [ 'nombre', 'sku', 'categoria', 'stock', 'costo', 'precio_venta', 'impuesto' ]; $exampleData = [ [ 'nombre' => 'Samsung Galaxy A55', 'sku' => 'SAM-A55-BLK', 'categoria' => 'Electrónica', 'stock' => 15, 'costo' => 5000.00, 'precio_venta' => 7500.00, 'impuesto' => 16 ], [ 'nombre' => 'Coca Cola 600ml', 'sku' => 'COCA-600', 'categoria' => 'Bebidas', 'stock' => 100, 'costo' => 12.50, 'precio_venta' => 18.00, 'impuesto' => 8 ], [ 'nombre' => 'Laptop HP Pavilion 15', 'sku' => 'HP-LAP-15', 'categoria' => 'Computadoras', 'stock' => 5, 'costo' => 8500.00, 'precio_venta' => 12000.00, 'impuesto' => 16 ], ]; return Excel::download( new class($headers, $exampleData) implements FromArray, WithHeadings { use Exportable; public function __construct(private array $headers, private array $data) {} public function array(): array { return $this->data; } public function headings(): array { return $this->headers; } }, 'plantilla_productos.xlsx' ); } }