### Install and Start Local PostgreSQL (macOS) Source: https://github.com/makebyjordan/stock-verifactu/blob/main/DATABASE_SETUP.md Installs PostgreSQL using Homebrew on macOS and starts the service. It also includes a command to create the initial database named 'inventory_db'. ```bash brew install postgresql brew services start postgresql createdb inventory_db ``` -------------------------------- ### Run Docker PostgreSQL Container Source: https://github.com/makebyjordan/stock-verifactu/blob/main/DATABASE_SETUP.md Starts a PostgreSQL version 15 container using Docker, naming it 'inventory-postgres'. It sets a password, designates the database name, and maps the default PostgreSQL port. ```bash docker run --name inventory-postgres -e POSTGRES_PASSWORD=password -e POSTGRES_DB=inventory_db -p 5432:5432 -d postgres:15 ``` -------------------------------- ### Run Prisma Database Migrations Source: https://github.com/makebyjordan/stock-verifactu/blob/main/DATABASE_SETUP.md Executes Prisma database migrations to initialize or update the database schema. This command should be run after setting up the database connection. ```bash npx prisma migrate dev --name init ``` -------------------------------- ### Configure Environment Variables and Run Prisma Commands Source: https://context7.com/makebyjordan/stock-verifactu/llms.txt This section shows how to set up the `.env.local` file for database connections and application settings. It also includes essential Prisma commands for database initialization and generation, as well as for starting the development server and building/running the production application. ```bash # .env.local configuration DATABASE_URL="postgresql://username:password@localhost:5432/inventory_db" NEXT_PUBLIC_APP_NAME="Sistema de Inventario" NEXT_PUBLIC_BASE_URL="http://localhost:3000" # For Vercel Postgres (production): # DATABASE_URL="postgres://default:xxx@xxx-pooler.xxx.vercel-storage.com:5432/verceldb" # Initialize database: npx prisma migrate dev --name init npx prisma generate # Start development server: npm run dev # Build for production: npm run build npm run start ``` -------------------------------- ### Configure Docker PostgreSQL Connection String Source: https://github.com/makebyjordan/stock-verifactu/blob/main/DATABASE_SETUP.md Provides the `DATABASE_URL` format for connecting to a PostgreSQL database running inside a Docker container. This is typically configured in a `.env.local` file. ```env DATABASE_URL="postgresql://postgres:password@localhost:5432/inventory_db" ``` -------------------------------- ### Configure Local PostgreSQL Connection String Source: https://github.com/makebyjordan/stock-verifactu/blob/main/DATABASE_SETUP.md Specifies the format for the `DATABASE_URL` environment variable required for connecting to a local PostgreSQL database. This is typically used in a `.env.local` file. ```env DATABASE_URL="postgresql://username:password@localhost:5432/inventory_db" ``` -------------------------------- ### Products API - Get Single Product Source: https://context7.com/makebyjordan/stock-verifactu/llms.txt Retrieves the details of a specific product using its unique identifier. ```APIDOC ## GET /api/products/{id} ### Description Retrieve detailed information for a specific product by ID, including related category and supplier data. ### Method GET ### Endpoint /api/products/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the product. ### Request Example ```bash curl -X GET "http://localhost:3000/api/products/clx789ghi" ``` ### Response #### Success Response (200) - **id** (string) - Unique identifier for the product. - **barcode** (string) - Barcode of the product. - **title** (string) - Title of the product. - **name** (string) - Name of the product. - **description** (string) - Description of the product. - **costPrice** (number) - Cost price of the product. - **salePrice** (number) - Sale price of the product. - **taxRate** (number) - Tax rate applied to the product. - **currentStock** (integer) - Current stock level. - **minStock** (integer) - Minimum stock level. - **categoryId** (string) - ID of the product's category. - **supplierId** (string) - ID of the product's supplier. - **category** (object) - Related category information. - **id** (string) - Category ID. - **name** (string) - Category name. - **supplier** (object) - Related supplier information. - **id** (string) - Supplier ID. - **name** (string) - Supplier name. - **createdAt** (string) - Timestamp of creation. - **updatedAt** (string) - Timestamp of last update. #### Error Response (404) - **error** (string) - Error message indicating the product was not found. #### Response Example (Success) ```json { "id": "clx789ghi", "barcode": "7501234567890", "title": "Laptop Dell XPS 13", "name": "Dell XPS 13", "description": "13-inch ultrabook", "costPrice": 850.00, "salePrice": 1200.00, "taxRate": 16.00, "currentStock": 15, "minStock": 5, "categoryId": "clx123abc", "supplierId": "clx456def", "category": { "id": "clx123abc", "name": "Laptops" }, "supplier": { "id": "clx456def", "name": "Dell Inc." }, "createdAt": "2024-01-15T10:30:00Z", "updatedAt": "2024-01-20T14:45:00Z" } ``` #### Response Example (Not Found) ```json { "error": "Product not found" } ``` ``` -------------------------------- ### Products API - Get Single Product Source: https://context7.com/makebyjordan/stock-verifactu/llms.txt Retrieves detailed information for a specific product using its unique identifier. This API endpoint returns comprehensive product data, including its associated category and supplier details. It is useful for displaying individual product information or for further processing. ```bash curl -X GET "http://localhost:3000/api/products/clx789ghi" ``` -------------------------------- ### Sales API - Get Sales History Source: https://context7.com/makebyjordan/stock-verifactu/llms.txt Retrieve paginated sales history with optional date filtering and product details. ```APIDOC ## GET /api/sales ### Description Retrieve paginated sales history with optional date filtering and product details. ### Method GET ### Endpoint `/api/sales` ### Query Parameters - **page** (integer) - Optional - The page number for pagination. - **limit** (integer) - Optional - The number of items per page. - **startDate** (string) - Optional - The start date for filtering sales (YYYY-MM-DD). - **endDate** (string) - Optional - The end date for filtering sales (YYYY-MM-DD). ### Response #### Success Response (200) - **sales** (array) - An array of sale objects. - **id** (string) - The unique identifier for the sale. - **productId** (string) - The ID of the product sold. - **quantity** (integer) - The quantity of the product sold. - **unitPrice** (number) - The price per unit. - **subtotal** (number) - The subtotal for the sale item. - **taxAmount** (number) - The amount of tax applied. - **total** (number) - The total amount for the sale item. - **createdAt** (string) - The timestamp when the sale was created (ISO 8601 format). - **product** (object) - Details of the product sold. - **barcode** (string) - The product barcode. - **title** (string) - The product title. - **name** (string) - The product name. - **total** (integer) - The total number of sales records. - **page** (integer) - The current page number. - **limit** (integer) - The number of items per page. - **totalPages** (integer) - The total number of pages available. #### Response Example ```json { "sales": [ { "id": "clxsale003", "productId": "clx789ghi", "quantity": 1, "unitPrice": 1200.00, "subtotal": 1200.00, "taxAmount": 192.00, "total": 1392.00, "createdAt": "2024-01-22T16:00:00Z", "product": { "barcode": "7501234567890", "title": "Laptop Dell XPS 13", "name": "Dell XPS 13" } } ], "total": 15, "page": 1, "limit": 10, "totalPages": 2 } ``` ``` -------------------------------- ### Dashboard Stats API - Get Real-time Statistics Source: https://context7.com/makebyjordan/stock-verifactu/llms.txt Retrieve comprehensive dashboard metrics including product count, low stock alerts, inventory value, and today's sales summary. ```APIDOC ## GET /api/stats ### Description Retrieve real-time statistics for the dashboard, including total products, low stock alerts, inventory value, and a summary of today's sales. ### Method GET ### Endpoint `/api/stats` ### Response #### Success Response (200) - **totalProducts** (integer) - The total number of products in the inventory. - **lowStockProducts** (integer) - The number of products currently at low stock levels. - **inventoryValue** (number) - The total monetary value of the current inventory. - **todaySales** (object) - A summary of sales for the current day. - **total** (number) - The total revenue from sales today. - **quantity** (integer) - The total quantity of items sold today. - **count** (integer) - The total number of sales transactions today. #### Response Example ```json { "totalProducts": 157, "lowStockProducts": 8, "inventoryValue": 245380.50, "todaySales": { "total": 15840.00, "quantity": 23, "count": 12 } } ``` ``` -------------------------------- ### Products API - Create New Product Source: https://context7.com/makebyjordan/stock-verifactu/llms.txt Creates a new product in the inventory system. Includes validation for input data and handles duplicate barcode entries. ```APIDOC ## POST /api/products ### Description Create a new product with automatic validation and initial stock movement tracking. Checks for duplicate barcodes and creates an atomic transaction for product creation and stock history. ### Method POST ### Endpoint /api/products ### Parameters #### Request Body - **barcode** (string) - Required - The barcode of the product. - **title** (string) - Required - The title of the product. - **name** (string) - Required - The name of the product. - **description** (string) - Optional - Description of the product. - **costPrice** (number) - Required - The cost price of the product. - **salePrice** (number) - Required - The sale price of the product. - **taxRate** (number) - Required - The tax rate applicable to the product. - **currentStock** (integer) - Required - The initial stock quantity. - **minStock** (integer) - Required - The minimum stock level threshold. - **categoryId** (string) - Required - The ID of the product's category. - **supplierId** (string) - Required - The ID of the product's supplier. ### Request Example ```json { "barcode": "7501234567890", "title": "Laptop Dell XPS 13", "name": "Dell XPS 13", "description": "13-inch ultrabook with Intel i7", "costPrice": 850.00, "salePrice": 1200.00, "taxRate": 16.00, "currentStock": 15, "minStock": 5, "categoryId": "clx123abc", "supplierId": "clx456def" } ``` ### Response #### Success Response (201) - **success** (boolean) - Indicates if the product creation was successful. - **product** (object) - The newly created product object. - **id** (string) - Unique identifier for the product. - **barcode** (string) - Barcode of the product. - **title** (string) - Title of the product. - **name** (string) - Name of the product. - **description** (string) - Description of the product. - **costPrice** (number) - Cost price of the product. - **salePrice** (number) - Sale price of the product. - **taxRate** (number) - Tax rate applied to the product. - **currentStock** (integer) - Current stock level. - **minStock** (integer) - Minimum stock level. - **categoryId** (string) - ID of the product's category. - **supplierId** (string) - ID of the product's supplier. - **createdAt** (string) - Timestamp of creation. - **updatedAt** (string) - Timestamp of last update. #### Error Response (400/409) - **error** (string) - Error message (e.g., "Ya existe un producto con este código de barras", "Datos inválidos"). - **details** (array) - Optional - Array of validation error details. - **path** (array) - Path to the invalid field. - **message** (string) - Description of the validation error. #### Response Example (Success) ```json { "success": true, "product": { "id": "clx789ghi", "barcode": "7501234567890", "title": "Laptop Dell XPS 13", "name": "Dell XPS 13", "description": "13-inch ultrabook with Intel i7", "costPrice": 850.00, "salePrice": 1200.00, "taxRate": 16.00, "currentStock": 15, "minStock": 5, "categoryId": "clx123abc", "supplierId": "clx456def", "createdAt": "2024-01-15T10:30:00Z", "updatedAt": "2024-01-15T10:30:00Z" } } ``` #### Response Example (Duplicate Barcode) ```json { "error": "Ya existe un producto con este código de barras" } ``` #### Response Example (Validation Error) ```json { "error": "Datos inválidos", "details": [ { "path": ["costPrice"], "message": "El precio de costo debe ser mayor a 0" } ] } ``` ``` -------------------------------- ### Products API - List Products Source: https://context7.com/makebyjordan/stock-verifactu/llms.txt Retrieves a paginated list of products with support for searching, filtering by category and supplier, and sorting. ```APIDOC ## GET /api/products ### Description Get paginated product list with search, category filter, supplier filter, and sorting capabilities. Returns products with related category and supplier information. ### Method GET ### Endpoint /api/products ### Parameters #### Query Parameters - **page** (integer) - Optional - The page number for pagination. - **limit** (integer) - Optional - The number of products per page. - **search** (string) - Optional - Search term for barcode, title, or name. - **categoryId** (string) - Optional - Filter products by category ID. - **supplierId** (string) - Optional - Filter products by supplier ID. - **sortBy** (string) - Optional - Field to sort products by (e.g., `currentStock`). - **sortOrder** (string) - Optional - Order of sorting (`asc` or `desc`). ### Request Example ```bash curl -X GET "http://localhost:3000/api/products?page=1&limit=10&search=laptop&categoryId=clx123abc" ``` ### Response #### Success Response (200) - **products** (array) - Array of product objects. - **id** (string) - Unique identifier for the product. - **barcode** (string) - Barcode of the product. - **title** (string) - Title of the product. - **name** (string) - Name of the product. - **description** (string) - Description of the product. - **costPrice** (number) - Cost price of the product. - **salePrice** (number) - Sale price of the product. - **taxRate** (number) - Tax rate applied to the product. - **currentStock** (integer) - Current stock level. - **minStock** (integer) - Minimum stock level. - **categoryId** (string) - ID of the product's category. - **supplierId** (string) - ID of the product's supplier. - **category** (object) - Related category information. - **id** (string) - Category ID. - **name** (string) - Category name. - **supplier** (object) - Related supplier information. - **id** (string) - Supplier ID. - **name** (string) - Supplier name. - **createdAt** (string) - Timestamp of creation. - **updatedAt** (string) - Timestamp of last update. - **total** (integer) - Total number of products matching the query. - **page** (integer) - Current page number. - **limit** (integer) - Number of products per page. - **totalPages** (integer) - Total number of pages. #### Response Example ```json { "products": [ { "id": "clx789ghi", "barcode": "7501234567890", "title": "Laptop Dell XPS 13", "name": "Dell XPS 13", "description": "13-inch ultrabook", "costPrice": 850.00, "salePrice": 1200.00, "taxRate": 16.00, "currentStock": 15, "minStock": 5, "categoryId": "clx123abc", "supplierId": "clx456def", "category": { "id": "clx123abc", "name": "Laptops" }, "supplier": { "id": "clx456def", "name": "Dell Inc." }, "createdAt": "2024-01-15T10:30:00Z", "updatedAt": "2024-01-20T14:45:00Z" } ], "total": 1, "page": 1, "limit": 10, "totalPages": 1 } ``` ``` -------------------------------- ### Categories API - List and Create Categories Source: https://context7.com/makebyjordan/stock-verifactu/llms.txt Manage product categories with product count tracking. ```APIDOC ## GET /api/categories ### Description Retrieve a list of all product categories along with the count of products in each category. ### Method GET ### Endpoint `/api/categories` ### Response #### Success Response (200) - **categories** (array) - An array of category objects. - **id** (string) - The unique identifier for the category. - **name** (string) - The name of the category. - **description** (string) - A description of the category. - **createdAt** (string) - The timestamp when the category was created (ISO 8601 format). - **updatedAt** (string) - The timestamp when the category was last updated (ISO 8601 format). - **_count** (object) - Contains the count of products in this category. - **products** (integer) - The number of products belonging to this category. #### Response Example ```json [ { "id": "clx123abc", "name": "Laptops", "description": "Notebook computers and ultrabooks", "createdAt": "2024-01-10T08:00:00Z", "updatedAt": "2024-01-10T08:00:00Z", "_count": { "products": 15 } }, { "id": "clx234bcd", "name": "Accessories", "description": "Computer accessories and peripherals", "createdAt": "2024-01-11T09:00:00Z", "updatedAt": "2024-01-11T09:00:00Z", "_count": { "products": 42 } } ] ``` ## POST /api/categories ### Description Create a new product category. ### Method POST ### Endpoint `/api/categories` ### Request Body - **name** (string) - Required - The name of the new category. - **description** (string) - Optional - A description for the new category. ### Request Example ```json { "name": "Monitors", "description": "Display screens and monitors" } ``` ### Response #### Success Response (201) - **id** (string) - The unique identifier for the newly created category. - **name** (string) - The name of the category. - **description** (string) - The description of the category. - **createdAt** (string) - The timestamp when the category was created (ISO 8601 format). - **updatedAt** (string) - The timestamp when the category was last updated (ISO 8601 format). #### Response Example ```json { "id": "clx345cde", "name": "Monitors", "description": "Display screens and monitors", "createdAt": "2024-01-22T17:00:00Z", "updatedAt": "2024-01-22T17:00:00Z" } ``` #### Error Response (409 Conflict) - **error** (string) - "Ya existe una categoría con este nombre" #### Response Example ```json { "error": "Ya existe una categoría con este nombre" } ``` ``` -------------------------------- ### Products API - List Products with Filtering and Pagination Source: https://context7.com/makebyjordan/stock-verifactu/llms.txt Retrieves a paginated list of products with options for searching by barcode, title, or name, filtering by category and supplier, and sorting by various fields like stock. It returns product details along with associated category and supplier information. The API supports parameters like page, limit, search, categoryId, supplierId, sortBy, and sortOrder. ```bash # Get first page of products (10 per page) curl -X GET "http://localhost:3000/api/products?page=1&limit=10" # Search products by barcode, title, or name curl -X GET "http://localhost:3000/api/products?search=7501234567890&page=1&limit=10" # Filter by category and sort by stock curl -X GET "http://localhost:3000/api/products?categoryId=clx123abc&sortBy=currentStock&sortOrder=asc" # Filter by supplier with search curl -X GET "http://localhost:3000/api/products?supplierId=clx456def&search=laptop&limit=20" ``` -------------------------------- ### Products API - Add Stock to Product Source: https://context7.com/makebyjordan/stock-verifactu/llms.txt Increases the stock quantity for a given product and records the transaction. ```APIDOC ## POST /api/products/{productId}/stock ### Description Increment product stock quantity with transaction tracking. Creates stock movement record with ENTRY type. ### Method POST ### Endpoint `/api/products/{productId}/stock` ### Parameters #### Path Parameters - **productId** (string) - Required - The ID of the product to add stock to. #### Request Body - **quantity** (integer) - Required - The quantity of stock to add. Must be greater than 0. - **unitPrice** (number) - Optional - The unit price of the stock being added. - **notes** (string) - Optional - Additional notes for the stock movement. ### Request Example ```json { "quantity": 10, "unitPrice": 875.00, "notes": "Restock from supplier" } ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message of successful stock addition. - **product** (object) - Updated product information. - **id** (string) - Product ID. - **barcode** (string) - Product barcode. - **title** (string) - Product title. - **currentStock** (integer) - The new current stock quantity. - **updatedAt** (string) - The timestamp of the last update (ISO 8601 format). #### Response Example ```json { "message": "Stock agregado exitosamente", "product": { "id": "clx789ghi", "barcode": "7501234567890", "title": "Laptop Dell XPS 13", "currentStock": 25, "updatedAt": "2024-01-22T11:00:00Z" } } ``` #### Error Response (400) - **error** (string) - Indicates invalid data was provided. - **details** (array) - Specific validation errors. - **path** (array) - Path to the invalid field. - **message** (string) - Description of the validation error. #### Error Response Example ```json { "error": "Datos inválidos", "details": [ { "path": ["quantity"], "message": "La cantidad debe ser mayor a 0" } ] } ``` ``` -------------------------------- ### Products API - Check Product by Barcode Source: https://context7.com/makebyjordan/stock-verifactu/llms.txt Verifies the existence of a product using its barcode and retrieves recent stock movements and sales history. ```APIDOC ## GET /api/products/check ### Description Check if a product exists by barcode and retrieve recent stock movements and sales history. Used for scanning operations. ### Method GET ### Endpoint `/api/products/check` ### Parameters #### Query Parameters - **barcode** (string) - Required - The barcode of the product to check. ### Response #### Success Response (200) - **exists** (boolean) - Indicates if the product was found. - **product** (object or null) - Contains product details if found, otherwise null. - **id** (string) - The unique identifier of the product. - **barcode** (string) - The barcode of the product. - **title** (string) - The title of the product. - **name** (string) - The name of the product. - **currentStock** (integer) - The current stock quantity. - **salePrice** (number) - The sale price of the product. - **stockMovements** (array) - A list of recent stock movements. - **id** (string) - Stock movement ID. - **type** (string) - Type of movement (e.g., ENTRY, EXIT). - **quantity** (integer) - Quantity moved. - **unitPrice** (number) - Unit price at the time of movement. - **totalValue** (number) - Total value of the movement. - **notes** (string) - Notes about the movement. - **createdAt** (string) - Date and time of the movement (ISO 8601 format). - **sales** (array) - A list of recent sales. - **id** (string) - Sale ID. - **quantity** (integer) - Quantity sold. - **unitPrice** (number) - Unit price at the time of sale. - **total** (number) - Total value of the sale. - **createdAt** (string) - Date and time of the sale (ISO 8601 format). #### Response Example (Product Found) ```json { "exists": true, "product": { "id": "clx789ghi", "barcode": "7501234567890", "title": "Laptop Dell XPS 13", "name": "Dell XPS 13", "currentStock": 15, "salePrice": 1200.00, "stockMovements": [ { "id": "clxmov001", "type": "ENTRY", "quantity": 15, "unitPrice": 850.00, "totalValue": 12750.00, "notes": "Stock inicial", "createdAt": "2024-01-15T10:30:00Z" } ], "sales": [ { "id": "clxsale001", "quantity": 2, "unitPrice": 1200.00, "total": 2784.00, "createdAt": "2024-01-20T14:30:00Z" } ] } } ``` #### Response Example (Product Not Found) ```json { "exists": false, "product": null } ``` ``` -------------------------------- ### Add Stock to Product - API Source: https://context7.com/makebyjordan/stock-verifactu/llms.txt Increments the stock quantity for a given product and records the transaction as an 'ENTRY' type stock movement. Requires product ID and transaction details. ```bash curl -X POST "http://localhost:3000/api/products/clx789ghi/stock" \ -H "Content-Type: application/json" \ -d '{ \ "quantity": 10, \ "unitPrice": 875.00, \ "notes": "Restock from supplier" \ }' ``` -------------------------------- ### Products API - Create New Product Source: https://context7.com/makebyjordan/stock-verifactu/llms.txt Creates a new product entry in the inventory system. This API endpoint handles input validation using Zod and ensures data integrity through atomic transactions for product creation and initial stock record. It also checks for duplicate barcodes to prevent conflicts. The endpoint accepts product details as a JSON payload. ```bash curl -X POST "http://localhost:3000/api/products" \ -H "Content-Type: application/json" \ -d '{ "barcode": "7501234567890", "title": "Laptop Dell XPS 13", "name": "Dell XPS 13", "description": "13-inch ultrabook with Intel i7", "costPrice": 850.00, "salePrice": 1200.00, "taxRate": 16.00, "currentStock": 15, "minStock": 5, "categoryId": "clx123abc", "supplierId": "clx456def" }' ``` -------------------------------- ### Sales API - Process Sale by Product ID Source: https://context7.com/makebyjordan/stock-verifactu/llms.txt Records a sale transaction for a specified product, updating inventory and creating necessary records. ```APIDOC ## POST /api/products/{productId}/sell ### Description Execute a sale transaction for a specific product, validates stock availability, updates inventory, and creates sale and stock movement records atomically. ### Method POST ### Endpoint `/api/products/{productId}/sell` ### Parameters #### Path Parameters - **productId** (string) - Required - The ID of the product being sold. #### Request Body - **quantity** (integer) - Required - The quantity of the product sold. - **salePrice** (number) - Required - The price per unit at which the product was sold. ### Request Example ```json { "quantity": 2, "salePrice": 1200.00 } ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message of a successful sale. - **product** (object) - Details of the product after the sale. - **id** (string) - Product ID. - **barcode** (string) - Product barcode. - **title** (string) - Product title. - **currentStock** (integer) - The updated stock quantity. - **sale** (object) - Details of the recorded sale. - **id** (string) - Sale ID. - **productId** (string) - ID of the product sold. - **quantity** (integer) - Quantity sold. - **unitPrice** (number) - Unit price of the sale. - **subtotal** (number) - Subtotal of the sale (quantity * unitPrice). - **taxAmount** (number) - Calculated tax amount for the sale. - **total** (number) - Total amount of the sale (including tax). - **createdAt** (string) - Date and time of the sale (ISO 8601 format). #### Response Example ```json { "message": "Venta registrada exitosamente", "product": { "id": "clx789ghi", "barcode": "7501234567890", "title": "Laptop Dell XPS 13", "currentStock": 23 }, "sale": { "id": "clxsale002", "productId": "clx789ghi", "quantity": 2, "unitPrice": 1200.00, "subtotal": 2400.00, "taxAmount": 384.00, "total": 2784.00, "createdAt": "2024-01-22T15:30:00Z" } } ``` #### Error Response (400) - **error** (string) - Message indicating insufficient stock. - **Disponible**: Available stock quantity. #### Error Response Example ```json { "error": "Stock insuficiente. Disponible: 1" } ``` ``` -------------------------------- ### Update Product Details - API Source: https://context7.com/makebyjordan/stock-verifactu/llms.txt Updates product information such as title, description, pricing, and supplier details. Stock quantity is managed separately. Lookup can be done by product ID. ```bash curl -X PUT "http://localhost:3000/api/products/clx789ghi" \ -H "Content-Type: application/json" \ -d '{ \ "title": "Laptop Dell XPS 13 Plus", \ "name": "Dell XPS 13 Plus", \ "description": "Updated 13-inch ultrabook", \ "costPrice": 900.00, \ "salePrice": 1300.00, \ "taxRate": 16.00, \ "minStock": 8, \ "categoryId": "clx123abc", \ "supplierId": "clx456def" \ }' ``` -------------------------------- ### React Products List Component with API Integration (TypeScript) Source: https://context7.com/makebyjordan/stock-verifactu/llms.txt A React component that fetches a list of products from an API, displays them with stock and price information, and allows users to initiate sales. It includes loading and error states, pagination, and search functionality. The component uses TypeScript for type safety and relies on `fetch` for API communication. ```typescript 'use client' import { useState, useEffect } from 'react' interface Product { id: string barcode: string title: string name: string currentStock: number salePrice: number categoryId?: string category?: { id: string; name: string } } interface ProductsResponse { products: Product[] total: number page: number totalPages: number } export default function ProductsList() { const [products, setProducts] = useState([]) const [loading, setLoading] = useState(true) const [error, setError] = useState(null) const [search, setSearch] = useState('') const [page, setPage] = useState(1) useEffect(() => { async function fetchProducts() { try { setLoading(true) const params = new URLSearchParams({ page: page.toString(), limit: '10', ...(search && { search }), }) const response = await fetch(`/api/products?${params}`) if (!response.ok) { throw new Error('Failed to fetch products') } const data: ProductsResponse = await response.json() setProducts(data.products) setError(null) } catch (err) { setError(err instanceof Error ? err.message : 'An error occurred') } finally { setLoading(false) } } fetchProducts() }, [page, search]) async function handleSell(productId: string, quantity: number, price: number) { try { const response = await fetch(`/api/products/${productId}/sell`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ quantity, salePrice: price }), }) if (!response.ok) { const error = await response.json() throw new Error(error.error) } const result = await response.json() alert(`Sale successful! New stock: ${result.product.currentStock}`) // Refresh products list setPage(p => p) } catch (err) { alert(err instanceof Error ? err.message : 'Sale failed') } } if (loading) return
Loading products...
if (error) return
Error: {error}
return (
setSearch(e.target.value)} className="border p-2 mb-4" />
{products.map((product) => (

{product.title}

Stock: {product.currentStock}

Price: ${product.salePrice}

Category: {product.category?.name || 'N/A'}

))}
Page {page}
) } ``` -------------------------------- ### Reports API - Generate Inventory and Sales Reports Source: https://context7.com/makebyjordan/stock-verifactu/llms.txt Generate detailed reports with sales analysis, top products, low stock alerts, and inventory summary for specified time periods. ```APIDOC ## GET /api/reports ### Description Generate detailed reports including sales analysis, top products, low stock alerts, and an inventory summary for a specified time period. ### Method GET ### Endpoint `/api/reports` ### Query Parameters - **period** (string) - Required - The time period for the report. Accepts `24h`, `7d`, `30d`, or `all`. ### Response #### Success Response (200) - **period** (string) - The time period the report covers. - **sales** (object) - Sales analysis for the period. - **total** (number) - Total sales revenue. - **count** (integer) - Total number of sales transactions. - **average** (number) - Average sale value. - **items** (array) - Details of individual sales items. - **id** (string) - Sale ID. - **productTitle** (string) - Title of the product sold. - **quantity** (integer) - Quantity sold in this transaction. - **total** (number) - Total amount for this sale item. - **createdAt** (string) - Timestamp of the sale (ISO 8601 format). - **topProducts** (array) - List of top-selling products. - **productId** (string) - ID of the product. - **productTitle** (string) - Title of the product. - **totalQuantity** (integer) - Total quantity sold. - **totalRevenue** (number) - Total revenue generated by the product. - **lowStock** (array) - List of products currently at low stock. - **id** (string) - Product ID. - **title** (string) - Product title. - **currentStock** (integer) - Current stock level. - **minStock** (integer) - Minimum stock threshold. - **summary** (object) - Overall inventory summary. - **totalProducts** (integer) - Total number of distinct products. - **totalStock** (integer) - Total quantity of all products in stock. - **totalValue** (number) - Total monetary value of the inventory. #### Response Example ```json { "period": "7d", "sales": { "total": 45680.00, "count": 67, "average": 681.79, "items": [ { "id": "clxsale003", "productTitle": "Laptop Dell XPS 13", "quantity": 1, "total": 1392.00, "createdAt": "2024-01-22T16:00:00Z" } ] }, "topProducts": [ { "productId": "clx789ghi", "productTitle": "Laptop Dell XPS 13", "totalQuantity": 15, "totalRevenue": 20880.00 } ], "lowStock": [ { "id": "clxprod123", "title": "Wireless Mouse", "currentStock": 3, "minStock": 10 } ], "summary": { "totalProducts": 157, "totalStock": 3842, "totalValue": 245380.50 } } ``` ``` -------------------------------- ### Sales API - Process Sale by Barcode Source: https://context7.com/makebyjordan/stock-verifactu/llms.txt Processes a sale transaction by scanning a product's barcode, automatically handling product lookup and inventory updates. ```APIDOC ## POST /api/sales ### Description Process sale using barcode scanning, automatically looks up product and executes transaction with tax calculations. ### Method POST ### Endpoint `/api/sales` ### Parameters #### Request Body - **barcode** (string) - Required - The barcode of the product being sold. - **quantity** (integer) - Required - The quantity of the product sold. ### Request Example ```json { "barcode": "7501234567890", "quantity": 1 } ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the sale was processed successfully. - **sale** (object) - Details of the recorded sale. - **id** (string) - Sale ID. - **productId** (string) - ID of the product sold. - **quantity** (integer) - Quantity sold. - **unitPrice** (number) - Unit price of the sale. - **subtotal** (number) - Subtotal of the sale. - **taxAmount** (number) - Calculated tax amount. - **total** (number) - Total amount of the sale. - **createdAt** (string) - Date and time of the sale (ISO 8601 format). - **newStock** (integer) - The updated stock quantity for the product. #### Response Example ```json { "success": true, "sale": { "id": "clxsale003", "productId": "clx789ghi", "quantity": 1, "unitPrice": 1200.00, "subtotal": 1200.00, "taxAmount": 192.00, "total": 1392.00, "createdAt": "2024-01-22T16:00:00Z" }, "newStock": 22 } ``` #### Error Response (400) - **error** (string) - Message indicating insufficient stock or product not found. #### Error Response Example ```json { "error": "Stock insuficiente" } ``` ``` -------------------------------- ### Process Sale by Product ID - API Source: https://context7.com/makebyjordan/stock-verifactu/llms.txt Executes a sale for a specified product by its ID, ensuring stock availability. This operation atomically updates inventory and creates sale and stock movement records. ```bash curl -X POST "http://localhost:3000/api/products/clx789ghi/sell" \ -H "Content-Type: application/json" \ -d '{ \ "quantity": 2, \ "salePrice": 1200.00 \ }' ``` -------------------------------- ### Process Sale by Barcode - API Source: https://context7.com/makebyjordan/stock-verifactu/llms.txt Processes a sale transaction by scanning a product's barcode. The system automatically looks up the product, calculates taxes, and updates inventory atomically. ```bash curl -X POST "http://localhost:3000/api/sales" \ -H "Content-Type: application/json" \ -d '{ \ "barcode": "7501234567890", \ "quantity": 1 \ }' ```