Skip to main content

Overview

The sales tracking system (Ventas) manages all purchase transactions, including product sales, promotional sales, payment processing, and comprehensive reporting for both vendors and administrators.

Sales Record Structure

Venta (Sale) Fields

FieldTypeDescription
id_ventaintUnique transaction identifier
register_idregistrointCustomer ID (buyer)
galeria_id_galeriaintProduct ID (if product sale)
promocion_id_promointPromotion ID (if promo sale)
locale_id_localintStore/vendor ID
fechavarchar(45)Transaction date
cantidadintQuantity purchased
cuantosintOrder number/counter
statusintOrder status (3=completed)
forma_pagovarchar(255)Payment method
numero_pagovarchar(255)Payment reference number

Model Relationships

Venta belongsTo:
  - Locale (store)
  - Register (customer)
  - Gallery (product)
  - Promo (promotion)

Purchase Flow

Product Purchase Process

1

Customer Selects Product

Customer browses products and clicks to purchaseValidation: System checks if product is available (cantidad_existente > 0)
2

Consultation Check

AJAX call to /ventas/consulta/{product}/{customer}/{store}Returns:
  • 2 - Product out of stock
  • 3 - Product available, can purchase
  • 4 - Customer already has pending order for this product
3

Add to Cart

If available, customer specifies quantity and adds to cartAJAX Endpoint: /ventas/add/{product}/{customer}/{store}/{quantity}/{order_count}
4

Process Transaction

System creates sale record and updates inventory:
// Decrement stock
$cantidad_existente = $cantidad_existente - $cantidad

// Increment sold counter
$prod_vendidos = $prod_vendidos + $cantidad
5

Complete Purchase

Customer finalizes payment details via /ventas/finalizar_compra

Cart System

Yoneily uses a simplified cart system where sales are recorded immediately but marked with a status. The cuantos field tracks the order sequence.
Cart Endpoint: /ventas/carrito/{store_id}/{customer_id}/{order_count} Displays:
  • All products from the selected store
  • All promotions from the store
  • Pagination (8 items per page)
  • Store information

Promotional Sales

Promotions follow a similar flow to products: Key Differences:
  • Uses promocion_id_promo instead of galeria_id_galeria
  • Updates promotion stock instead of product stock
  • Separate consultation endpoint: /ventas/consulta_promocion
  • Add endpoint: /ventas/add_promo

Payment Processing

Finalizing Purchase

Endpoint: /ventas/finalizar_compra/{payment_method}/{payment_number}/{sale_id} Process:
  1. Customer selects payment method
  2. Enters payment reference number
  3. System updates sale record:
    Venta.forma_pago = payment_method
    Venta.numero_pago = payment_number
    Venta.status = 3 (completed)
    
  4. Returns status code 6 on success

Payment Methods

The system supports multiple payment options configured per store:

Bank Transfer

Customer transfers to vendor’s bank account

Credit Card

Online card processing (if enabled)

Cash on Delivery

Payment upon product delivery

Customer Purchase History

My Purchases (Mis Compras)

Endpoint: /ventas/miscompras Features:
  • Displays customer’s purchase history
  • Pagination (6 transactions per page)
  • Ordered by date (newest first)
  • Shows:
    • Product/promo details
    • Store information
    • Quantity and price
    • Purchase date
    • Payment status
Session Integration:
$usuario = $this->Session->read('keyus'); // Customer ID
$conditions = array('Venta.register_idregistro' => $usuario);

My Messages (Mis Mensajes)

Endpoint: /ventas/mismensajes Displays customer communications with vendors:
  • Product inquiries
  • Store responses
  • Status indicators
  • Pagination (8 messages per page)

My Complaints (Mis Reclamos)

Endpoint: /ventas/misreclamos Shows customer’s submitted complaints and responses:
  • Complaint details
  • Vendor responses (resp != 0)
  • Store information
  • Status tracking
  • Pagination (8 items per page)
These views use complex JOIN queries to combine data from Denuncia, Gallery, Promo, and Locale tables.

Sales Reporting

Administrator Sales List

Endpoint: /ventas/index Features:
  • View all sales across all stores
  • Pagination (10 records per page)
  • Ordered by date (DESC)
  • Related data loaded automatically
Data Includes:
  • Customer information
  • Product/promotion details
  • Store information
  • Payment details
  • Transaction dates

PDF Generation

Route: /ventas/pdf_compra/{id}Generates:
  • Individual transaction receipt
  • Product/promo details
  • Customer information
  • Payment method and reference
  • Store contact details
Use Case: Customer receipt or invoice

PDF Configuration

Configure::write('debug', 0); // Disable debug for clean PDF
$this->layout = 'pdf'; // Use PDF layout template

Inventory Integration

Stock Updates

Every sale automatically triggers inventory updates:
// Check availability
$galeria = $this->Gallery->find('all', array(
    'conditions' => array(
        'id_galeria' => $producto,
        'cantidad_existente >' => 0
    )
));

// Calculate new stock
$cantidad_existente = $current - $cantidad_vendida;
$prod_vendidos = $current_sold + $cantidad_vendida;

// Update gallery
$this->Gallery->updateAll(
    array(
        'Gallery.cantidad_existente' => $cantidad_existente,
        'Gallery.prod_vendidos' => $prod_vendidos
    ),
    array('Gallery.id_galeria' => $producto)
);

Out of Stock Handling

When a product’s cantidad_existente reaches 0, the system returns error code 2, preventing further purchases.
Response Codes:
  • 0 - Database error
  • 1 - Success
  • 2 - Out of stock
  • 4 - Duplicate order (customer already has pending order)

Sales Statistics

Transaction Counter

Endpoint: /ventas/cuantos Returns total number of sales in the system (all time). Usage: Display dashboard statistics or track order numbers.

Sales Analysis

Query sales data for business intelligence:
SELECT 
  locale_id_local,
  COUNT(*) as total_sales,
  SUM(cantidad) as total_units,
  DATE(fecha) as sale_date
FROM ventas
GROUP BY locale_id_local, DATE(fecha)
ORDER BY sale_date DESC

Customer Interaction

Complaint Filing

Customers can file complaints about purchases: Endpoint: /ventas/denunciar/{product}/{customer}/{store} Process:
  1. Customer selects product to complain about
  2. Form opens with pre-filled details
  3. Customer enters complaint text
  4. Submitted to /ventas/finalizar_denunciar
  5. Complaint record created in denuncias table
Complaints are covered in detail in the Complaints System documentation.

AJAX Endpoints

Consultation System

All purchase validation happens via AJAX for instant feedback:
Route: /ventas/consulta/{product}/{customer}/{store}Returns:
  • 2 - Out of stock
  • 3 - Available
  • 4 - Pending order exists
Route: /ventas/consulta_promocion/{product}/{customer}/{store}Returns: Same codes as product consultation
Route: /ventas/add_carrito/{product}/{customer}/{store}/{quantity}/{order}Returns:
  • 0 - Database error
  • 1 - Success
  • 2 - Out of stock

Access Control

Public Endpoints

The following actions are accessible without login:
$this->Auth->allowedActions = array(
    'add',
    'consulta',
    'denunciar',
    'finalizar_denunciar',
    'add_promo',
    'consulta_promocion',
    'denunciar_promo',
    'miscompras',
    'mismensajes',
    'misreclamos',
    'finalizar_compra',
    'pdf_compra',
    'carrito',
    'cuantos',
    'add_carrito'
);

Protected Actions

Administrator-only endpoints:
  • index - View all sales
  • view - View sale details
  • pdf_completo_venta - Generate comprehensive reports
  • delete operations

Best Practices

  • Always validate stock before sale
  • Use database transactions for multi-step operations
  • Update inventory atomically with sale creation
  • Log all transaction changes
  • Provide immediate feedback on stock availability
  • Clear error messages for out-of-stock items
  • Prevent duplicate orders for same product
  • Send confirmation after payment
  • Generate PDFs on-demand, not pre-cached
  • Include all relevant transaction details
  • Provide date-range filtering for reports
  • Export options for accounting integration

Inventory Management

Product stock and pricing

Promotions

Promotional campaigns

Complaints System

Customer feedback handling

Technical Notes

Date Format

Sales dates are stored as strings in d-m-Y format:
$fecha = date('d-m-Y'); // Example: 26-10-2012

Sale Status Codes

StatusDescription
NULLIncomplete/pending
3Completed with payment

Session Variables

// Customer session (public site)
$this->Session->read('keyus'); // Customer ID

// Admin session
$this->Session->read('Auth.User.id_usuario');
$this->Session->read('Auth.User.locale_id_local');

Build docs developers (and LLMs) love