📝 Markdown Document Manager

Upload markdown files and organize them in a tree structure

Add Document
Document Tree
Delete Document
View Document

Add New Document


Or Upload Markdown File

Max file size: 2M | Supported: .md, .txt, .markdown files | Content limit: 5MB

Document Tree Structure

🗑️ Delete Document

⚠️ Warning: This action cannot be undone!

SELLBILL_MULTI_PRODUCT_API_USAGE

Created: 2025-08-09 13:30:14 | Updated: 2025-08-09 13:30:14

▶ Sell Bill Multi-Product API Usage Guide

■ 🚀 Direct Database API Implementation

File: /api/sellbill_direct_api.php This API allows you to create sales bills with MULTIPLE PRODUCTS in a single API call. All database operations are handled directly without external dependencies.

■ 📦 Multi-Product Support

• Key Features:

  • → ✅ Multiple Products: Send unlimited products in single sale
  • → ✅ Individual Product Discounts: Each product can have its own discount
  • → ✅ Automatic Inventory Updates: Updates stock for all products
  • → ✅ Detailed Line Items: Creates separate database records for each product
  • → ✅ Bill-Level Discounts: Apply discounts to entire bill
  • → ✅ Mixed Payment Methods: Cash + Visa in single transaction
  • → ✅ Accounting Integration: Creates journal entries automatically

■ 🔧 Configuration

• Database Settings

Edit these variables at the top of the file:

$DB_HOST = 'localhost';

$DB_USER = 'root';

$DB_PASS = '';

$DB_NAME = 'erp_database';  // Change to your database name

■ 📊 API Request Format

• Endpoint


POST /api/sellbill_direct_api.php
Content-Type: application/json

• Multi-Product Request Structure


{
  "client_id": 25,
  "store_id": 1,
  "products": [
    {
      "product_id": 100,
      "quantity": 2,
      "price": 50.00,
      "discount": 5.00,
      "discount_type": 0
    },
    {
      "product_id": 101,
      "quantity": 1,
      "price": 30.00,
      "discount": 10,
      "discount_type": 1
    },
    {
      "product_id": 102,
      "quantity": 3,
      "price": 20.00,
      "discount": 0
    }
  ],
  "payment": {
    "cash": 150.00,
    "visa": 50.00
  },
  "bill_discount": 5,
  "comment": "Multi-product sale with mixed payments"
}

• Required Fields

| Field | Type | Description | |-------|------|-------------| | client_id | Integer | Customer ID from client table | | store_id | Integer | Store/Branch ID from store table | | products | Array | Array of product objects (minimum 1) |

• Product Object Fields

| Field | Type | Required | Description | |-------|------|----------|-------------| | product_id | Integer | ✅ | Product ID from product table | | quantity | Number | ✅ | Quantity to sell (must be > 0) | | price | Number | ✅ | Selling price per unit | | discount | Number | ❌ | Discount amount or percentage | | discount_type | Integer | ❌ | 0=Amount, 1=Percentage (default: 0) |

• Optional Fields

| Field | Type | Description | |-------|------|-------------| | payment.cash | Number | Cash amount received | | payment.visa | Number | Credit card amount received | | bill_discount | Number | Percentage discount for entire bill | | comment | String | Notes/comments for the sale |

■ 📋 Usage Examples

• Example 1: Simple Multi-Product Sale


curl -X POST http://localhost/erp/api/sellbill_direct_api.php \

  -H "Content-Type: application/json" \
  -d '{

    "client_id": 1,
    "store_id": 1,
    "products": [
      {"product_id": 10, "quantity": 2, "price": 25.00},
      {"product_id": 11, "quantity": 1, "price": 40.00}
    ],
    "payment": {"cash": 90.00}
  }'

• Example 2: Complex Sale with Individual Discounts


curl -X POST http://localhost/erp/api/sellbill_direct_api.php \

  -H "Content-Type: application/json" \
  -d '{

    "client_id": 25,
    "store_id": 1,
    "products": [
      {
        "product_id": 100,
        "quantity": 3,
        "price": 100.00,
        "discount": 15,
        "discount_type": 1
      },
      {
        "product_id": 101,
        "quantity": 2,
        "price": 50.00,
        "discount": 10.00,
        "discount_type": 0
      }
    ],
    "payment": {
      "cash": 200.00,
      "visa": 145.00
    },
    "bill_discount": 5,
    "comment": "VIP customer sale"
  }'

• Example 3: Large Multi-Product Order


curl -X POST http://localhost/erp/api/sellbill_direct_api.php \

  -H "Content-Type: application/json" \
  -d '{

    "client_id": 50,
    "store_id": 2,
    "products": [
      {"product_id": 201, "quantity": 5, "price": 20.00},
      {"product_id": 202, "quantity": 2, "price": 75.00},
      {"product_id": 203, "quantity": 10, "price": 5.00},
      {"product_id": 204, "quantity": 1, "price": 200.00},
      {"product_id": 205, "quantity": 3, "price": 30.00}
    ],
    "payment": {
      "cash": 500.00
    },
    "comment": "Bulk order - wholesale prices"
  }'

■ ✅ Success Response Format


{
  "success": true,
  "data": {
    "sell_bill_id": 1234,
    "bill_serial": "SB01202501091234",
    "client_id": 25,
    "client_name": "John Doe Company",
    "store_id": 1,
    "products_count": 3,
    "totals": {
      "subtotal": 400.00,
      "bill_discount": 20.00,
      "final_total": 380.00,
      "total_quantity": 6
    },
    "payment": {
      "cash_paid": 200.00,
      "visa_paid": 145.00,
      "total_paid": 345.00,
      "remaining_amount": 35.00
    },
    "client_debt": {
      "before": 500.00,
      "after": 535.00
    },
    "detail_ids": [5001, 5002, 5003],
    "created_at": "2024-01-20 14:30:00"
  },
  "message": "Sales bill created successfully with 3 products"
}

■ ❌ Error Response Format


{
  "success": false,
  "error": "Error message describing what went wrong",
  "inventory_errors": [
    {
      "product_index": 0,
      "product_id": 100,
      "error": "Insufficient inventory. Available: 1, Requested: 2"
    }
  ]
}

■ 🗄️ Database Operations

The API performs these operations for each multi-product sale:

• 1. Validation

  • → ✅ Validates all products exist and have sufficient inventory
  • → ✅ Checks client and store exist
  • → ✅ Validates quantities and prices

• 2. Main Transaction

  • → 📝 Creates 1 record in sellbill table
  • → 📝 Creates N records in sellbilldetail (one per product)
  • → 🔄 Updates N records in storedetail (inventory deduction)
  • → 🔄 Updates 1 record in client table (debt balance)

• 3. Accounting Entries

  • → 📝 Creates 1 record in dailyentry
  • → 📝 Creates records in dailyentrydebtor (cash/visa/credit)
  • → 📝 Creates 1 record in dailyentrycreditor (sales revenue)

■ 🔍 Multi-Product Processing Logic

• Inventory Management


For each product in products array:
1. Check current inventory in store
2. Validate requested quantity ≤ available quantity
3. Calculate new inventory = current - requested
4. Update storedetail table with new quantity

• Total Calculations


For each product:
1. Line Total = price × quantity
2. Line Discount = individual product discount
3. Line Final = Line Total - Line Discount

Bill Subtotal = Sum of all Line Finals
Bill Discount = Subtotal × bill_discount_percentage
Final Total = Bill Subtotal - Bill Discount

• Payment Processing


Total Paid = cash_paid + visa_paid
Remaining Amount = Final Total - Total Paid
Client New Debt = Old Debt + Remaining Amount

■ 🚨 Common Error Scenarios

• 1. Inventory Insufficient


{
  "success": false,
  "error": "Inventory validation failed",
  "inventory_errors": [
    {
      "product_index": 1,
      "product_id": 101,
      "error": "Insufficient inventory. Available: 5, Requested: 10"
    }
  ]
}

• 2. Invalid Product


{
  "success": false,
  "error": "Product at index 0 missing required fields (product_id, quantity, price)"
}

• 3. Database Connection


{
  "success": false,
  "error": "Database connection failed: Access denied for user"
}

■ 📈 Performance Notes

  • Transaction Safety: All operations wrapped in MySQL transaction
  • Rollback Support: Any failure rolls back all changes
  • Optimized Queries: Prepared statements prevent SQL injection
  • Batch Processing: Handles multiple products efficiently
  • Connection Management: Automatic connection cleanup

■ 🔐 Security Features

  • → ✅ SQL Injection Protection: All queries use prepared statements
  • → ✅ Input Validation: Comprehensive validation of all inputs
  • → ✅ Type Casting: Proper data type enforcement
  • → ✅ Transaction Integrity: Atomic operations with rollback
  • → ✅ Error Handling: Detailed error reporting without exposing sensitive data

■ 🎯 Integration Tips

• Frontend Integration


// JavaScript/React example

const createSale = async (saleData) => {
  const response = await fetch('/api/sellbill_direct_api.php', {

    method: 'POST',

    headers: {
      'Content-Type': 'application/json'

    },
    body: JSON.stringify(saleData)
  });
  
  const result = await response.json();
  
  if (result.success) {
    console.log(Sale created: ${result.data.bill_serial});
    console.log(Products processed: ${result.data.products_count});
  } else {
    console.error('Sale failed:', result.error);

  }
};

• Mobile App Integration


// Flutter/Dart example

Future<Map<String, dynamic>> createSale(Map<String, dynamic> saleData) async {
  final response = await http.post(
    Uri.parse(&#039;https://yourserver.com/erp/api/sellbill_direct_api.php&#039;),

    headers: {&#039;Content-Type&#039;: &#039;application/json&#039;},

    body: jsonEncode(saleData),
  );
  
  return jsonDecode(response.body);
}

■ 🔧 Customization Options

• Account Mapping

Edit these account IDs in the createAccountingEntries() function:

// Account IDs (customize based on your chart of accounts)

$cashAccountId = 40;    // Cash/Safe account

$bankAccountId = 38;    // Bank/Visa account  

$clientAccountId = 57;  // Client receivables

$salesAccountId = 151;  // Sales revenue

• Serial Number Format

Customize in generateBillSerial() function:

// Current format: SB01202401091234

// Customize prefix, date format, and numbering

$prefix = "SB" . str_pad($storeId, 2, "0", STR_PAD_LEFT);
$date = date(&#039;Ymd&#039;);    // Change format as needed

■ 📞 Support & Troubleshooting

• Common Issues:

  1. Database Connection: Check credentials in file header
  2. Missing Tables: Ensure all ERP tables exist
  3. Permissions: Verify database user has INSERT/UPDATE privileges
  4. Inventory: Check products have inventory records in storedetail table

• Debug Mode:

Uncomment this line for detailed error reporting:

// At top of file, uncomment:

// error_reporting(E_ALL);

// ini_set(&#039;display_errors&#039;, 1);

--- 📌 Summary: This API provides a complete, single-file solution for creating multi-product sales bills with direct database operations, full inventory management, and integrated accounting entries.