Skip to main content

Overview

The Sales Service (jea-venta) provides comprehensive sales transaction management for Sistema de Ventas. It handles the complete sales lifecycle from order creation to invoice generation, with automatic calculations for taxes and totals.

Key Features

Automatic Series & Numbers

Auto-generates unique series (3 letters) and sequential document numbers for invoice tracking

Tax Calculation

Automatically calculates IGV (18% VAT) and totals based on line items

Customer Integration

Links sales to customer records via Feign client integration

Payment Integration

Associates sales with payment methods for complete transaction tracking

Detailed Line Items

Support for multiple product line items per sale with individual pricing

Audit Trail

Automatic timestamps for all transactions and modifications

Sale Entity Structure

Each sale in the system contains comprehensive information about the transaction:
@Entity
public class Venta {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    
    @Column(nullable = false, unique = true)
    private String serie;           // Auto-generated (e.g., "ABC")
    
    @Column(nullable = false, unique = true)
    private String numero;          // Auto-generated (e.g., "000123")
    
    private String descripcion;     // Sale description
    
    @Column(name = "cliente_id")
    private Long clienteId;         // Customer reference
    
    @Transient
    private Cliente cliente;        // Customer details (via Feign)
    
    @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinColumn(name = "venta_id")
    private List<VentaDetalle> detalle;  // Line items
    
    private LocalDateTime fechaVenta;    // Sale timestamp
    
    private Double baseImponible;   // Taxable amount
    private Double igv;             // 18% VAT
    private Double total;           // Grand total
    
    @Column(name = "formapago_id")
    private Long formapagoId;       // Payment method reference
    
    @Transient
    private FormaPago formaPago;    // Payment method details
}

Automatic Calculations

The system automatically calculates all financial amounts when a sale is created or updated. This ensures accuracy and consistency across all transactions.
@PrePersist
public void prePersist() {
    calcularTotales();
    generarSerieYNumero();
}

private void calcularTotales() {
    this.baseImponible = 0.0;
    this.igv = 0.0;
    this.total = 0.0;
    
    if (detalle != null) {
        for (VentaDetalle d : detalle) {
            d.calcularMontos();
            this.baseImponible += d.getBaseImponible();
            this.igv += d.getIgv();
            this.total += d.getTotal();
        }
    }
}
The IGV (Impuesto General a las Ventas) is Peru’s value-added tax set at 18%. The calculation automatically includes the tax in the total amount.

Sales Process Flow

1

Create Sale Request

Client sends sale data including customer ID, payment method, and line items with product details
2

Validate Customer

System fetches customer details from Customer Service using Feign client to validate the customer exists
3

Calculate Totals

Automatically calculates base amount, IGV (18%), and total for each line item and the entire sale
4

Generate Document Numbers

Creates unique series (3 random letters) and sequential number (6 digits) for invoice tracking
5

Save Transaction

Persists sale with all details to the database, creating a permanent transaction record
6

Update Inventory

Automatically reduces product quantities in Catalog Service via Feign client integration

Available Endpoints

The Sales Service provides comprehensive CRUD operations and advanced querying capabilities:
MethodEndpointDescription
POST/ventaCreate new sale
GET/ventaList all sales
GET/venta/{id}Get sale by ID
PUT/venta/{id}Update sale
DELETE/venta/{id}Delete sale
GET/venta/buscar-por-fechasSearch by date range
GET/venta/buscar/serieSearch by series
GET/venta/buscar/numeroSearch by number
GET/venta/buscar/serie-numeroFind by series and number
GET/venta/productos-mas-vendidosTop 10 best-selling products
GET/venta/ventas-por-mesSales summary by month
GET/venta/total-ventasTotal sales amount

Sales Analytics

Top Selling Products

Track your best-performing products with the built-in analytics endpoint:
GET /venta/productos-mas-vendidos
Returns the top 10 most sold products with quantities and revenue information.

Sales by Month

Monitor sales trends over time:
GET /venta/ventas-por-mes
Provides monthly aggregated sales data for reporting and forecasting.

Total Revenue

Get the cumulative sales total:
GET /venta/total-ventas

Search and Filtering

Find specific sales using multiple search criteria:
GET /venta/buscar-por-fechas?inicio=2024-01-01T00:00:00&fin=2024-12-31T23:59:59
Find sales by series or number for quick invoice lookup:
GET /venta/buscar/serie-numero?serie=ABC&numero=000123

Integration Points

The Sales Service integrates with multiple microservices:
  • Customer Service - Validates customer information and retrieves customer details
  • Catalog Service - Updates product inventory quantities after sale completion
  • Payment Service - Retrieves payment method information for transaction records
  • Category Service - Fetches product category information for reporting

Best Practices

Always include all line items in a single transaction. The service uses JPA cascade operations to ensure data consistency.
The system automatically updates inventory. Ensure products have sufficient stock before creating sales to avoid negative inventory.
Always validate that the customer exists before attempting to create a sale. The system will fail if the customer ID is invalid.
Document series and numbers are automatically generated. Do not attempt to set these values manually.

Next Steps

API Reference

Detailed API endpoint documentation

Customer Management

Learn about managing customer records

Inventory Control

Understand inventory tracking

Analytics & Reporting

Explore reporting capabilities

Build docs developers (and LLMs) love