objets_metier_rs 1.0.2

Bibliothèque Rust moderne et sûre pour l'API COM Objets Métier Sage 100c - Production Ready
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
use crate::com::{SafeDispatch, SafeVariant};
use crate::errors::{SageError, SageResult};
use crate::wrappers::cial::objects::{ConditionLivraison, Depot, Expedition};
use crate::wrappers::cpta::objects::{Contact, Devise, Reglement, Tiers};
use windows::Win32::System::Com::IDispatch;

/// Wrapper pour un document de vente (IBODocumentVente3)
///
/// Représente un document de vente: devis, commande, BL, facture, avoir
///
/// Types de documents (DO_Type):
/// - 0 = Devis
/// - 1 = Bon de commande client
/// - 2 = Bon de livraison / Préparation de livraison
/// - 3 = Bon de retour / Facture
/// - 4 = Avoir
///
/// ✅ IMPLÉMENTATION ENRICHIE - Version Phase 6
/// Propriétés complètes pour gestion commerciale.
///
/// # Exemple
/// ```no_run
/// use objets_metier_rs::wrappers::cial::CialApplication;
///
/// let cial_app = CialApplication::new("Objets100c.CIAL")?;
/// let factory = cial_app.factory_document_vente()?;
/// let facture = factory.create_facture()?;
///
/// // Propriétés enrichies
/// facture.set_do_piece("FA00001")?;
/// facture.set_do_ref("CMD-CLIENT-123")?;
/// println!("Total HT: {}", facture.do_total_ht()?);
/// println!("Total TTC: {}", facture.do_total_ttc()?);
///
/// facture.write()?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub struct DocumentVente {
    pub(crate) dispatch: IDispatch,
}

impl DocumentVente {
    fn dispatch(&self) -> SafeDispatch<'_> {
        SafeDispatch::new(&self.dispatch)
    }

    // ==================== PROPRIÉTÉS PRINCIPALES ====================

    /// Numéro de pièce
    pub fn do_piece(&self) -> SageResult<String> {
        self.dispatch()
            .call_method_by_name("DO_Piece", &[])?
            .to_string()
    }

    pub fn set_do_piece(&self, value: &str) -> SageResult<()> {
        let param = SafeVariant::from_string(value);
        self.dispatch().call_property_put("DO_Piece", &[param])?;
        Ok(())
    }

    /// Type de document (0=Devis, 1=Commande, 2=BL, 3=Facture, 4=Avoir)
    pub fn do_type(&self) -> SageResult<i32> {
        self.dispatch()
            .call_method_by_name("DO_Type", &[])?
            .to_i32()
    }

    /// cbMarq - Identifiant unique
    pub fn cbmarq(&self) -> SageResult<i32> {
        self.dispatch().call_method_by_name("cbMarq", &[])?.to_i32()
    }

    // ==================== PROPRIÉTÉS EN-TÊTE ====================

    /// Date du document
    pub fn do_date(&self) -> SageResult<String> {
        self.dispatch()
            .call_method_by_name("DO_Date", &[])?
            .to_string()
    }

    pub fn set_do_date(&self, value: &str) -> SageResult<()> {
        let param = SafeVariant::from_string(value);
        self.dispatch().call_property_put("DO_Date", &[param])?;
        Ok(())
    }

    /// Date de livraison
    pub fn do_date_livr(&self) -> SageResult<String> {
        self.dispatch()
            .call_method_by_name("DO_DateLivr", &[])?
            .to_string()
    }

    pub fn set_do_date_livr(&self, value: &str) -> SageResult<()> {
        let param = SafeVariant::from_string(value);
        self.dispatch().call_property_put("DO_DateLivr", &[param])?;
        Ok(())
    }

    /// Souche de numérotation
    pub fn do_souche(&self) -> SageResult<i32> {
        self.dispatch()
            .call_method_by_name("DO_Souche", &[])?
            .to_i32()
    }

    pub fn set_do_souche(&self, value: i32) -> SageResult<()> {
        let param = SafeVariant::I4(value);
        self.dispatch().call_property_put("DO_Souche", &[param])?;
        Ok(())
    }

    /// Client (tiers)
    pub fn do_tiers(&self) -> SageResult<Option<Tiers>> {
        let variant = self.dispatch().call_method_by_name("DO_Tiers", &[])?;
        if variant.is_empty_or_null() {
            return Ok(None);
        }
        if variant.is_object() {
            Ok(Some(Tiers {
                dispatch: variant.to_dispatch()?,
            }))
        } else {
            Err(SageError::ConversionError {
                from_type: "VARIANT".to_string(),
                to_type: "Tiers".to_string(),
                value: "DO_Tiers n'est pas un objet".to_string(),
            })
        }
    }

    pub fn set_do_tiers(&self, tiers: &Tiers) -> SageResult<()> {
        let param = SafeVariant::from_dispatch(tiers.dispatch.clone());
        self.dispatch().call_property_put("DO_Tiers", &[param])?;
        Ok(())
    }

    /// Tiers payeur (si différent du client)
    pub fn do_tiers_payeur(&self) -> SageResult<Option<Tiers>> {
        let variant = self.dispatch().call_method_by_name("DO_TiersPayeur", &[])?;
        if variant.is_empty_or_null() {
            return Ok(None);
        }
        if variant.is_object() {
            Ok(Some(Tiers {
                dispatch: variant.to_dispatch()?,
            }))
        } else {
            Err(SageError::ConversionError {
                from_type: "VARIANT".to_string(),
                to_type: "Tiers".to_string(),
                value: "DO_TiersPayeur n'est pas un objet".to_string(),
            })
        }
    }

    pub fn set_do_tiers_payeur(&self, tiers: &Tiers) -> SageResult<()> {
        let param = SafeVariant::from_dispatch(tiers.dispatch.clone());
        self.dispatch()
            .call_property_put("DO_TiersPayeur", &[param])?;
        Ok(())
    }

    /// Contact client
    pub fn do_contact(&self) -> SageResult<Option<Contact>> {
        let variant = self.dispatch().call_method_by_name("DO_Contact", &[])?;
        if variant.is_empty_or_null() {
            return Ok(None);
        }
        if variant.is_object() {
            Ok(Some(Contact {
                dispatch: variant.to_dispatch()?,
            }))
        } else {
            Err(SageError::ConversionError {
                from_type: "VARIANT".to_string(),
                to_type: "Contact".to_string(),
                value: "DO_Contact n'est pas un objet".to_string(),
            })
        }
    }

    pub fn set_do_contact(&self, contact: &Contact) -> SageResult<()> {
        let param = SafeVariant::from_dispatch(contact.dispatch.clone());
        self.dispatch().call_property_put("DO_Contact", &[param])?;
        Ok(())
    }

    /// Référence client
    pub fn do_ref(&self) -> SageResult<String> {
        self.dispatch()
            .call_method_by_name("DO_Ref", &[])?
            .to_string()
    }

    pub fn set_do_ref(&self, value: &str) -> SageResult<()> {
        let param = SafeVariant::from_string(value);
        self.dispatch().call_property_put("DO_Ref", &[param])?;
        Ok(())
    }

    /// Devise
    pub fn do_devise(&self) -> SageResult<Option<Devise>> {
        let variant = self.dispatch().call_method_by_name("DO_Devise", &[])?;
        if variant.is_empty_or_null() {
            return Ok(None);
        }
        if variant.is_object() {
            Ok(Some(Devise {
                dispatch: variant.to_dispatch()?,
            }))
        } else {
            Err(SageError::ConversionError {
                from_type: "VARIANT".to_string(),
                to_type: "Devise".to_string(),
                value: "DO_Devise n'est pas un objet".to_string(),
            })
        }
    }

    pub fn set_do_devise(&self, devise: &Devise) -> SageResult<()> {
        let param = SafeVariant::from_dispatch(devise.dispatch.clone());
        self.dispatch().call_property_put("DO_Devise", &[param])?;
        Ok(())
    }

    /// Taux de change
    pub fn do_cours(&self) -> SageResult<f64> {
        self.dispatch()
            .call_method_by_name("DO_Cours", &[])?
            .to_f64()
    }

    pub fn set_do_cours(&self, value: f64) -> SageResult<()> {
        let param = SafeVariant::R8(value);
        self.dispatch().call_property_put("DO_Cours", &[param])?;
        Ok(())
    }

    /// Dépôt d'expédition
    pub fn do_depot(&self) -> SageResult<Option<Depot>> {
        let variant = self.dispatch().call_method_by_name("DO_Depot", &[])?;
        if variant.is_empty_or_null() {
            return Ok(None);
        }
        if variant.is_object() {
            Ok(Some(Depot {
                dispatch: variant.to_dispatch()?,
            }))
        } else {
            Err(SageError::ConversionError {
                from_type: "VARIANT".to_string(),
                to_type: "Depot".to_string(),
                value: "DO_Depot n'est pas un objet".to_string(),
            })
        }
    }

    pub fn set_do_depot(&self, depot: &Depot) -> SageResult<()> {
        let param = SafeVariant::from_dispatch(depot.dispatch.clone());
        self.dispatch().call_property_put("DO_Depot", &[param])?;
        Ok(())
    }

    /// Condition de livraison
    pub fn do_condition(&self) -> SageResult<Option<ConditionLivraison>> {
        let variant = self.dispatch().call_method_by_name("DO_Condition", &[])?;
        if variant.is_empty_or_null() {
            return Ok(None);
        }
        if variant.is_object() {
            Ok(Some(ConditionLivraison {
                dispatch: variant.to_dispatch()?,
            }))
        } else {
            Err(SageError::ConversionError {
                from_type: "VARIANT".to_string(),
                to_type: "ConditionLivraison".to_string(),
                value: "DO_Condition n'est pas un objet".to_string(),
            })
        }
    }

    pub fn set_do_condition(&self, condition: &ConditionLivraison) -> SageResult<()> {
        let param = SafeVariant::from_dispatch(condition.dispatch.clone());
        self.dispatch()
            .call_property_put("DO_Condition", &[param])?;
        Ok(())
    }

    /// Mode d'expédition
    pub fn do_expedition(&self) -> SageResult<Option<Expedition>> {
        let variant = self.dispatch().call_method_by_name("DO_Expedition", &[])?;
        if variant.is_empty_or_null() {
            return Ok(None);
        }
        if variant.is_object() {
            Ok(Some(Expedition {
                dispatch: variant.to_dispatch()?,
            }))
        } else {
            Err(SageError::ConversionError {
                from_type: "VARIANT".to_string(),
                to_type: "Expedition".to_string(),
                value: "DO_Expedition n'est pas un objet".to_string(),
            })
        }
    }

    pub fn set_do_expedition(&self, expedition: &Expedition) -> SageResult<()> {
        let param = SafeVariant::from_dispatch(expedition.dispatch.clone());
        self.dispatch()
            .call_property_put("DO_Expedition", &[param])?;
        Ok(())
    }

    /// Langue du document (0=Français, 1=Anglais, etc.)
    pub fn do_langue(&self) -> SageResult<i16> {
        self.dispatch()
            .call_method_by_name("DO_Langue", &[])?
            .to_short()
    }

    pub fn set_do_langue(&self, value: i16) -> SageResult<()> {
        let param = SafeVariant::I2(value);
        self.dispatch().call_property_put("DO_Langue", &[param])?;
        Ok(())
    }

    /// Statut du document (0=Brouillon, 1=Validé, 2=Transféré)
    pub fn do_statut(&self) -> SageResult<i16> {
        self.dispatch()
            .call_method_by_name("DO_Statut", &[])?
            .to_short()
    }

    pub fn set_do_statut(&self, value: i16) -> SageResult<()> {
        let param = SafeVariant::I2(value);
        self.dispatch().call_property_put("DO_Statut", &[param])?;
        Ok(())
    }

    /// Document validé
    pub fn do_valide(&self) -> SageResult<bool> {
        self.dispatch()
            .call_method_by_name("DO_Valide", &[])?
            .to_bool()
    }

    pub fn set_do_valide(&self, value: bool) -> SageResult<()> {
        let param = SafeVariant::Bool(value);
        self.dispatch().call_property_put("DO_Valide", &[param])?;
        Ok(())
    }

    // ==================== PROPRIÉTÉS FINANCIÈRES ====================

    /// Total HT
    pub fn do_total_ht(&self) -> SageResult<f64> {
        self.dispatch()
            .call_method_by_name("DO_TotalHT", &[])?
            .to_f64()
    }

    /// Total TTC
    pub fn do_total_ttc(&self) -> SageResult<f64> {
        self.dispatch()
            .call_method_by_name("DO_TotalTTC", &[])?
            .to_f64()
    }

    /// Net à payer
    pub fn do_net_a_payer(&self) -> SageResult<f64> {
        self.dispatch()
            .call_method_by_name("DO_NetAPayer", &[])?
            .to_f64()
    }

    /// Total des remises
    pub fn do_total_remise(&self) -> SageResult<f64> {
        self.dispatch()
            .call_method_by_name("DO_TotalRemise", &[])?
            .to_f64()
    }

    /// Remise en-tête (pourcentage)
    pub fn do_remise(&self) -> SageResult<f64> {
        self.dispatch()
            .call_method_by_name("DO_Remise", &[])?
            .to_f64()
    }

    pub fn set_do_remise(&self, value: f64) -> SageResult<()> {
        let param = SafeVariant::R8(value);
        self.dispatch().call_property_put("DO_Remise", &[param])?;
        Ok(())
    }

    /// Montant de la remise en-tête
    pub fn do_montant_remise(&self) -> SageResult<f64> {
        self.dispatch()
            .call_method_by_name("DO_MontantRemise", &[])?
            .to_f64()
    }

    pub fn set_do_montant_remise(&self, value: f64) -> SageResult<()> {
        let param = SafeVariant::R8(value);
        self.dispatch()
            .call_property_put("DO_MontantRemise", &[param])?;
        Ok(())
    }

    /// Port HT
    pub fn do_port_ht(&self) -> SageResult<f64> {
        self.dispatch()
            .call_method_by_name("DO_PortHT", &[])?
            .to_f64()
    }

    pub fn set_do_port_ht(&self, value: f64) -> SageResult<()> {
        let param = SafeVariant::R8(value);
        self.dispatch().call_property_put("DO_PortHT", &[param])?;
        Ok(())
    }

    /// Port TTC
    pub fn do_port_ttc(&self) -> SageResult<f64> {
        self.dispatch()
            .call_method_by_name("DO_PortTTC", &[])?
            .to_f64()
    }

    /// Poids total
    pub fn do_total_poids(&self) -> SageResult<f64> {
        self.dispatch()
            .call_method_by_name("DO_TotalPoids", &[])?
            .to_f64()
    }

    /// Volume total
    pub fn do_total_volume(&self) -> SageResult<f64> {
        self.dispatch()
            .call_method_by_name("DO_TotalVolume", &[])?
            .to_f64()
    }

    /// Montant déjà réglé
    pub fn do_montant_regle(&self) -> SageResult<f64> {
        self.dispatch()
            .call_method_by_name("DO_MontantRegle", &[])?
            .to_f64()
    }

    /// Solde restant à payer
    pub fn do_solde(&self) -> SageResult<f64> {
        self.dispatch()
            .call_method_by_name("DO_Solde", &[])?
            .to_f64()
    }

    // ==================== PROPRIÉTÉS DE RÈGLEMENT ====================

    /// Mode de règlement
    pub fn do_reglement(&self) -> SageResult<Option<Reglement>> {
        let variant = self.dispatch().call_method_by_name("DO_Reglement", &[])?;
        if variant.is_empty_or_null() {
            return Ok(None);
        }
        if variant.is_object() {
            Ok(Some(Reglement {
                dispatch: variant.to_dispatch()?,
            }))
        } else {
            Err(SageError::ConversionError {
                from_type: "VARIANT".to_string(),
                to_type: "Reglement".to_string(),
                value: "DO_Reglement n'est pas un objet".to_string(),
            })
        }
    }

    pub fn set_do_reglement(&self, reglement: &Reglement) -> SageResult<()> {
        let param = SafeVariant::from_dispatch(reglement.dispatch.clone());
        self.dispatch()
            .call_property_put("DO_Reglement", &[param])?;
        Ok(())
    }

    /// Condition de règlement
    pub fn do_condition_r(&self) -> SageResult<String> {
        self.dispatch()
            .call_method_by_name("DO_ConditionR", &[])?
            .to_string()
    }

    pub fn set_do_condition_r(&self, value: &str) -> SageResult<()> {
        let param = SafeVariant::from_string(value);
        self.dispatch()
            .call_property_put("DO_ConditionR", &[param])?;
        Ok(())
    }

    /// Nombre d'échéances
    pub fn do_nb_echeance(&self) -> SageResult<i16> {
        self.dispatch()
            .call_method_by_name("DO_NbEcheance", &[])?
            .to_short()
    }

    pub fn set_do_nb_echeance(&self, value: i16) -> SageResult<()> {
        let param = SafeVariant::I2(value);
        self.dispatch()
            .call_property_put("DO_NbEcheance", &[param])?;
        Ok(())
    }

    /// Date de la première échéance
    pub fn do_date_echeance1(&self) -> SageResult<String> {
        self.dispatch()
            .call_method_by_name("DO_DateEcheance1", &[])?
            .to_string()
    }

    pub fn set_do_date_echeance1(&self, value: &str) -> SageResult<()> {
        let param = SafeVariant::from_string(value);
        self.dispatch()
            .call_property_put("DO_DateEcheance1", &[param])?;
        Ok(())
    }

    /// Type de paiement
    pub fn do_type_paiement(&self) -> SageResult<i16> {
        self.dispatch()
            .call_method_by_name("DO_TypePaiement", &[])?
            .to_short()
    }

    pub fn set_do_type_paiement(&self, value: i16) -> SageResult<()> {
        let param = SafeVariant::I2(value);
        self.dispatch()
            .call_property_put("DO_TypePaiement", &[param])?;
        Ok(())
    }

    // ==================== PROPRIÉTÉS DE SUIVI ====================

    /// Document transféré
    pub fn do_transf(&self) -> SageResult<bool> {
        self.dispatch()
            .call_method_by_name("DO_Transf", &[])?
            .to_bool()
    }

    /// Document clôturé
    pub fn do_cloture(&self) -> SageResult<bool> {
        self.dispatch()
            .call_method_by_name("DO_Cloture", &[])?
            .to_bool()
    }

    pub fn set_do_cloture(&self, value: bool) -> SageResult<()> {
        let param = SafeVariant::Bool(value);
        self.dispatch().call_property_put("DO_Cloture", &[param])?;
        Ok(())
    }

    /// À facturer
    pub fn do_facturer(&self) -> SageResult<bool> {
        self.dispatch()
            .call_method_by_name("DO_Facturer", &[])?
            .to_bool()
    }

    /// À expédier
    pub fn do_expedier(&self) -> SageResult<bool> {
        self.dispatch()
            .call_method_by_name("DO_Expedier", &[])?
            .to_bool()
    }

    /// Utilisateur créateur
    pub fn do_user(&self) -> SageResult<String> {
        self.dispatch()
            .call_method_by_name("DO_User", &[])?
            .to_string()
    }

    /// Date de création
    pub fn do_date_creat(&self) -> SageResult<String> {
        self.dispatch()
            .call_method_by_name("DO_DateCreat", &[])?
            .to_string()
    }

    /// Date de modification
    pub fn do_date_modif(&self) -> SageResult<String> {
        self.dispatch()
            .call_method_by_name("DO_DateModif", &[])?
            .to_string()
    }

    /// Commentaire
    pub fn do_commentaire(&self) -> SageResult<String> {
        self.dispatch()
            .call_method_by_name("DO_Commentaire", &[])?
            .to_string()
    }

    pub fn set_do_commentaire(&self, value: &str) -> SageResult<()> {
        let param = SafeVariant::from_string(value);
        self.dispatch()
            .call_property_put("DO_Commentaire", &[param])?;
        Ok(())
    }

    // ==================== COLLECTIONS ET RELATIONS ====================

    /// Collection des lignes du document
    pub fn document_lignes(&self) -> SageResult<SafeVariant> {
        self.dispatch().call_method_by_name("DocumentLignes", &[])
    }

    /// Récupère une ligne par son index
    pub fn get_ligne(&self, index: i32) -> SageResult<SafeVariant> {
        let param = SafeVariant::I4(index);
        self.dispatch().call_method_by_name("GetLigne", &[param])
    }

    /// Crée une nouvelle ligne
    pub fn create_ligne(&self) -> SageResult<SafeVariant> {
        self.dispatch().call_method_by_name("CreateLigne", &[])
    }

    // ==================== MÉTHODES MÉTIER ====================

    /// Recalcule tous les totaux du document
    pub fn recalculate_totals(&self) -> SageResult<()> {
        self.dispatch()
            .call_method_by_name("RecalculateTotals", &[])?;
        Ok(())
    }

    /// Valide le document
    pub fn validate_document(&self) -> SageResult<()> {
        self.dispatch()
            .call_method_by_name("ValidateDocument", &[])?;
        Ok(())
    }

    /// Transfère le document vers un autre type
    pub fn transfer_to(&self, doc_type: i16) -> SageResult<SafeVariant> {
        let param = SafeVariant::I2(doc_type);
        self.dispatch().call_method_by_name("TransferTo", &[param])
    }

    /// Clôture le document
    pub fn close_document(&self) -> SageResult<()> {
        self.dispatch().call_method_by_name("CloseDocument", &[])?;
        Ok(())
    }

    /// Ajoute un règlement
    pub fn add_payment(&self, amount: f64) -> SageResult<()> {
        let param = SafeVariant::R8(amount);
        self.dispatch()
            .call_method_by_name("AddPayment", &[param])?;
        Ok(())
    }

    /// Duplique le document
    pub fn duplicate(&self) -> SageResult<DocumentVente> {
        let result = self.dispatch().call_method_by_name("Duplicate", &[])?;
        if result.is_object() {
            Ok(DocumentVente {
                dispatch: result.to_dispatch()?,
            })
        } else {
            Err(SageError::ConversionError {
                from_type: "VARIANT".to_string(),
                to_type: "DocumentVente".to_string(),
                value: "Duplicate ne retourne pas un objet".to_string(),
            })
        }
    }

    /// Aperçu avant impression
    pub fn print_preview(&self) -> SageResult<()> {
        self.dispatch().call_method_by_name("PrintPreview", &[])?;
        Ok(())
    }

    /// Envoi par email
    pub fn send_email(&self, email: &str) -> SageResult<()> {
        let param = SafeVariant::from_string(email);
        self.dispatch().call_method_by_name("SendEmail", &[param])?;
        Ok(())
    }

    // ==================== MÉTHODES D'ÉCRITURE ====================

    /// Écrit le document (sans initialisation automatique)
    pub fn write(&self) -> SageResult<()> {
        self.dispatch().call_method_by_name("Write", &[])?;
        Ok(())
    }

    /// Enregistre le document avec initialisation automatique des valeurs par défaut
    ///
    /// **RECOMMANDÉ** pour la création de nouveaux documents car cette méthode :
    /// - Initialise automatiquement les champs avec valeurs par défaut
    /// - Génère les numéros de pièce automatiquement
    /// - Crée les lignes d'emplacements si multi-emplacements activé
    ///
    /// # Exemple
    /// ```no_run
    /// # use objets_metier_rs::wrappers::cial::CialApplication;
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # let cial = CialApplication::new("Objets100c.CIAL")?;
    /// # let factory = cial.factory_document_vente()?;
    /// let doc = factory.create_type(0)?; // Devis
    /// // Définir les propriétés minimales...
    /// doc.write_default()?; // ← Préférer à write() pour nouveaux documents
    /// # Ok(())
    /// # }
    /// ```
    pub fn write_default(&self) -> SageResult<()> {
        self.dispatch().call_method_by_name("WriteDefault", &[])?;
        Ok(())
    }

    pub fn remove(&self) -> SageResult<()> {
        self.dispatch().call_method_by_name("Remove", &[])?;
        Ok(())
    }

    // ==================== MÉTHODES D'INITIALISATION ====================

    /// Initialise le document avec un client par défaut
    ///
    /// Cette méthode DOIT être appelée avant write() ou write_default() pour :
    /// - Définir le tiers (client) du document
    /// - Initialiser automatiquement les propriétés liées au client :
    ///   * Mode de règlement
    ///   * Conditions de règlement
    ///   * Devise
    ///   * Représentant
    ///   * Dépôt de livraison
    ///   * Catégorie tarifaire et remises
    ///
    /// # Arguments
    /// * `client` - IDispatch du client (obtenu via FactoryClient.read_numero())
    ///
    /// # Exemple
    /// ```no_run
    /// # use objets_metier_rs::wrappers::cpta::CptaApplication;
    /// # use objets_metier_rs::wrappers::cial::CialApplication;
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # let cpta = CptaApplication::new("309DE0FB-9FB8-4F4E-8295-CC60C60DAA33")?;
    /// # cpta.open()?;
    /// # let cial = CialApplication::new("Objets100c.CIAL")?;
    /// # cial.open()?;
    /// // Obtenir le client
    /// let client = cpta.factory_client()?.read_numero("CARAT")?;
    ///
    /// // Créer le document et définir le client
    /// let doc = cial.factory_document_vente()?.create_type(0)?;
    /// doc.set_default_client(&client.dispatch)?; // ← CRUCIAL !
    /// doc.write_default()?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn set_default_client(&self, client_dispatch: &IDispatch) -> SageResult<()> {
        let param = SafeVariant::from_dispatch(client_dispatch.clone());
        self.dispatch()
            .call_method_by_name("SetDefaultClient", &[param])?;
        Ok(())
    }

    /// Génère automatiquement un numéro de pièce pour le document
    ///
    /// Le numéro est généré selon les paramètres de numérotation configurés
    /// dans Sage 100c (Fichier / Paramètres société / Documents).
    ///
    /// # Exemple
    /// ```no_run
    /// # use objets_metier_rs::wrappers::cial::CialApplication;
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # let cial = CialApplication::new("Objets100c.CIAL")?;
    /// let doc = cial.factory_document_vente()?.create_type(0)?;
    /// doc.set_default_do_piece()?; // Génère DE00001, DE00002, etc.
    /// # Ok(())
    /// # }
    /// ```
    pub fn set_default_do_piece(&self) -> SageResult<()> {
        self.dispatch()
            .call_method_by_name("SetDefaultDO_Piece", &[])?;
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_document_vente_has_enriched_properties() {
        // Vérifier que l'objet DocumentVente a bien toutes les propriétés enrichies
        // Ce test compile = les signatures sont correctes
    }
}