objets_metier_rs 1.0.2

Bibliothèque Rust moderne et sûre pour l'API COM Objets Métier Sage 100c - Production Ready
//! CIAL Document Workflows - Document creation and management examples
//!
//! ⚠️ **WORK IN PROGRESS** - This example needs API corrections
//! See `cial_complete_demo.rs` for a working example.
//!
//! This example demonstrates:
//! - Creating sales documents (quotes, orders, invoices)
//! - Working with document lines
//! - Document status and properties
//! - Relationship between documents and articles
//!
//! Run with: cargo run --example cial_document_workflows

use objets_metier_rs::errors::SageResult;
use objets_metier_rs::wrappers::cial::*;
use objets_metier_rs::wrappers::cpta::*;

const BSCPTA_CLSID: &str = "309DE0FB-9FB8-4F4E-8295-CC60C60DAA33";
const BSCIAL_CLSID: &str = "ED0EC116-16B8-44CC-A68A-41BF6E15EB3F";

fn main() -> SageResult<()> {
    println!("=======================================");
    println!("CIAL Document Workflows Demo");
    println!("=======================================\n");

    // ========================================================================
    // ÉTAPE 1 : Connexion à la base comptable BIJOU (CPTA)
    // ========================================================================
    println!("📂 ÉTAPE 1 : Connexion à la base comptable BIJOU");
    println!("─────────────────────────────────────────────────────────");

    let cpta = CptaApplication::new(BSCPTA_CLSID)?;
    println!("✓ Application CPTA créée");

    cpta.set_name(r"D:\TMP\BIJOU.MAE")?;
    println!("✓ Base comptable définie : D:\\TMP\\BIJOU.MAE");

    let loggable_cpta = cpta.loggable()?;
    loggable_cpta.set_user_name("<Administrateur>")?;
    loggable_cpta.set_user_pwd("")?;
    println!("✓ Authentification CPTA configurée");

    cpta.open()?;
    println!("✓ Base comptable ouverte avec succès");

    if !cpta.is_open()? {
        eprintln!("❌ ERREUR : La base comptable n'est pas ouverte !");
        return Ok(());
    }
    println!("✓ Connexion CPTA vérifiée\n");

    // ========================================================================
    // ÉTAPE 1bis : Connexion à la base commerciale BIJOU (CIAL)
    // ========================================================================
    println!("📂 ÉTAPE 1bis : Connexion à la base commerciale BIJOU");
    println!("─────────────────────────────────────────────────────────");

    let cial = CialApplication::new(BSCIAL_CLSID)?;
    println!("✓ Application CIAL créée");

    // ⚠️ CRUCIAL : Lier CIAL à CPTA AVANT d'ouvrir la base commerciale
    cial.set_cpta_application(cpta.instance())?;
    println!("✓ Application CIAL liée à l'application CPTA");

    cial.set_name(r"D:\TMP\BIJOU.GCM")?;
    println!("✓ Base commerciale définie : D:\\TMP\\BIJOU.GCM");

    let loggable_cial = cial.loggable()?;
    loggable_cial.set_user_name("<Administrateur>")?;
    loggable_cial.set_user_pwd("")?;
    println!("✓ Authentification CIAL configurée");

    cial.open()?;
    println!("✓ Base commerciale ouverte avec succès");

    if !cial.is_open()? {
        eprintln!("❌ ERREUR : La base commerciale n'est pas ouverte !");
        return Ok(());
    }
    println!("✓ Connexion CIAL vérifiée\n");

    // Demonstrate various document workflows
    workflow_sales_documents(&cial)?;
    workflow_purchase_documents(&cial)?;
    workflow_stock_documents(&cial)?;
    workflow_document_properties(&cial)?;

    println!("\n✅ Document workflows completed!");

    cial.close()?;
    println!("✓ CIAL Connection closed");
    cpta.close()?;
    println!("✓ CPTA Connection closed");

    Ok(())
}

/// Demonstrate sales document workflow
fn workflow_sales_documents(app: &CialApplication) -> SageResult<()> {
    println!("╔═══════════════════════════════════╗");
    println!("║   Sales Document Workflow         ║");
    println!("╚═══════════════════════════════════╝\n");

    let factory = app.factory_document_vente()?;
    let _documents = factory.list()?;

    println!("✅ FactoryDocumentVente accessible");

    // Document types reference
    println!("\n📋 Document types:");
    println!("   Type 0:  Devis (Quote)");
    println!("   Type 10: Commande (Order)");
    println!("   Type 20: Préparation livraison (Prep Delivery)");
    println!("   Type 30: Bon de livraison (Delivery)");
    println!("   Type 40: Bon de reprise (Return)");
    println!("   Type 50: Avoir (Credit)");
    println!("   Type 60: Facture (Invoice)");
    println!("   Type 70: Facture comptabilisée (Accounted Invoice)");

    // Test exist_piece and read_piece
    println!("\n📄 Testing document access:");
    let test_type: i32 = 60; // Type 60 = Facture de vente
    let test_piece = "FA00001";
    match factory.exist_piece(test_type, test_piece) {
        Ok(exists) => {
            println!(
                "   ✓ ExistPiece({}, '{}') = {}",
                test_type, test_piece, exists
            );
            if exists {
                match factory.read_piece(test_type, test_piece) {
                    Ok(_doc) => println!("   ✓ ReadPiece succeeded"),
                    Err(e) => println!("   ✗ ReadPiece error: {}", e),
                }
            }
        }
        Err(e) => {
            println!("   ✗ ExistPiece error: {}", e);
        }
    }

    // Test create_type
    println!("\n🔧 Testing document creation (not persisted):");
    match factory.create_type(60) {
        // Type 60 = Facture
        Ok(_doc) => println!(
            "   ✓ create_type(60) works - Facture created - Piece {}",
            _doc.do_piece()?.as_str()
        ),
        Err(e) => println!("   ✗ create_type error: {}", e),
    }

    Ok(())
}

/// Demonstrate purchase document workflow
fn workflow_purchase_documents(app: &CialApplication) -> SageResult<()> {
    println!("\n╔═══════════════════════════════════╗");
    println!("║   Purchase Document Workflow      ║");
    println!("╚═══════════════════════════════════╝\n");

    let factory = app.factory_document_achat()?;
    let _documents = factory.list()?;

    println!("✅ FactoryDocumentAchat accessible");

    // Document types reference
    println!("\n📋 Purchase document types:");
    println!("   Type 120: Commande fournisseur (Supplier order)");
    println!("   Type 130: BL fournisseur (Supplier delivery)");
    println!("   Type 160: Facture fournisseur (Supplier invoice)");
    println!("   Type 150: Avoir fournisseur (Supplier credit)");

    // Test exist_piece with correct enum value
    println!("\n📄 Testing ExistPiece:");
    let test_type = 160; // Type 160 = Facture fournisseur
    let test_piece = "FFA00001";
    match factory.exist_piece(test_type, test_piece) {
        Ok(exists) => {
            println!(
                "   ✓ ExistPiece({}, '{}') = {}",
                test_type, test_piece, exists
            );
        }
        Err(e) => {
            println!("   ✗ ExistPiece error: {}", e);
        }
    }

    Ok(())
}

/// Demonstrate stock document workflow
fn workflow_stock_documents(app: &CialApplication) -> SageResult<()> {
    println!("\n╔═══════════════════════════════════╗");
    println!("║   Stock Document Workflow         ║");
    println!("╚═══════════════════════════════════╝\n");

    let factory = app.factory_document_stock()?;
    let _documents = factory.list()?;

    println!("✅ FactoryDocumentStock accessible");

    // Document types reference
    println!("\n📦 Stock document types:");
    println!("   Type 110: Bon de livraison stock");
    println!("   Type 120: Bon de retour stock");
    println!("   Type 130: Transfert entre dépôts");

    Ok(())
}

/// Demonstrate document property access
fn workflow_document_properties(app: &CialApplication) -> SageResult<()> {
    println!("\n╔═══════════════════════════════════╗");
    println!("║   Document Properties Demo        ║");
    println!("╚═══════════════════════════════════╝\n");

    let factory = app.factory_document_vente()?;
    let _documents = factory.list()?;

    println!("✅ FactoryDocumentVente accessible");

    println!("\n📄 Common document properties:");
    println!("   - DO_Piece: Document number");
    println!("   - DO_Type: Document type (0, 10, 20, 30, 40, 50, 60, 70...)");
    println!("   - DO_Date: Document date");
    println!("   - DO_Ref: Reference");
    println!("   - DO_Souche: Numbering sequence");
    println!("   - DO_Devise: Currency");
    println!("   - cbMarq: Internal ID");

    println!("\n💡 Use read_piece(type, piece) to access document properties");

    Ok(())
}