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
use crate::com::{SafeDispatch, SafeVariant};
use crate::errors::{SageError, SageResult};
use crate::wrappers::cial::objects::{Depot, Famille, Gamme};
use crate::wrappers::cpta::objects::{CompteG, Taxe};
use windows::Win32::System::Com::IDispatch;

/// Wrapper pour un article (IBOArticle3)
///
/// Représente un article du catalogue commercial avec sa référence,
/// sa désignation, ses prix, gammes, tarifs, stock, etc.
///
/// ✅ IMPLÉMENTATION ENRICHIE - Version Phase 6
/// Propriétés complètes pour gestion commerciale et comptable.
///
/// # Exemple
/// ```no_run
/// use objets_metier_rs::wrappers::cial::CialApplication;
///
/// let cial_app = CialApplication::new("Objets100c.CIAL")?;
/// let factory = cial_app.factory_article()?;
/// let article = factory.read_reference("BAAR01")?;
/// println!("Article: {}", article.ar_ref()?);
/// println!("Prix vente HT: {}", article.ar_prix_ven()?);
/// println!("Stock disponible: {}", article.get_stock_disponible()?);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub struct Article {
    pub(crate) dispatch: IDispatch,
}

impl Article {
    /// Crée un SafeDispatch temporaire pour les appels
    fn dispatch(&self) -> SafeDispatch<'_> {
        SafeDispatch::new(&self.dispatch)
    }

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

    /// Référence de l'article
    pub fn ar_ref(&self) -> SageResult<String> {
        self.dispatch()
            .call_method_by_name("AR_Ref", &[])?
            .to_string()
    }

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

    /// Désignation de l'article
    pub fn ar_design(&self) -> SageResult<String> {
        self.dispatch()
            .call_method_by_name("AR_Design", &[])?
            .to_string()
    }

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

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

    // ==================== PROPRIÉTÉS ESSENTIELLES ====================

    /// Code-barres de l'article
    pub fn ar_code_barre(&self) -> SageResult<String> {
        self.dispatch()
            .call_method_by_name("AR_CodeBarre", &[])?
            .to_string()
    }

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

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

    pub fn set_ar_famille(&self, famille: &Famille) -> SageResult<()> {
        let param = SafeVariant::from_dispatch(famille.dispatch.clone());
        self.dispatch().call_property_put("AR_Famille", &[param])?;
        Ok(())
    }

    /// Unité de vente
    pub fn ar_unite_ven(&self) -> SageResult<String> {
        self.dispatch()
            .call_method_by_name("AR_UniteVen", &[])?
            .to_string()
    }

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

    /// Unité pour les prix
    pub fn ar_unite_pri(&self) -> SageResult<String> {
        self.dispatch()
            .call_method_by_name("AR_UnitePri", &[])?
            .to_string()
    }

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

    /// Conditionnement
    pub fn ar_condition(&self) -> SageResult<String> {
        self.dispatch()
            .call_method_by_name("AR_Condition", &[])?
            .to_string()
    }

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

    // ==================== PROPRIÉTÉS DE PRIX ====================

    /// Prix de vente HT
    pub fn ar_prix_ven(&self) -> SageResult<f64> {
        self.dispatch()
            .call_method_by_name("AR_PrixVen", &[])?
            .to_f64()
    }

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

    /// Prix d'achat HT
    pub fn ar_prix_ach(&self) -> SageResult<f64> {
        self.dispatch()
            .call_method_by_name("AR_PrixAch", &[])?
            .to_f64()
    }

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

    /// Coefficient multiplicateur
    pub fn ar_coef(&self) -> SageResult<f64> {
        self.dispatch()
            .call_method_by_name("AR_Coef", &[])?
            .to_f64()
    }

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

    /// Prix de vente TTC
    pub fn ar_prix_ttc(&self) -> SageResult<f64> {
        self.dispatch()
            .call_method_by_name("AR_PrixTTC", &[])?
            .to_f64()
    }

    // ==================== GAMMES ====================

    /// Première gamme de l'article
    pub fn ar_gamme1(&self) -> SageResult<Option<Gamme>> {
        let variant = self.dispatch().call_method_by_name("AR_Gamme1", &[])?;
        if variant.is_empty_or_null() {
            return Ok(None);
        }
        if variant.is_object() {
            Ok(Some(Gamme {
                dispatch: variant.to_dispatch()?,
            }))
        } else {
            Err(SageError::ConversionError {
                from_type: "VARIANT".to_string(),
                to_type: "Gamme".to_string(),
                value: "AR_Gamme1 n'est pas un objet".to_string(),
            })
        }
    }

    pub fn set_ar_gamme1(&self, gamme: &Gamme) -> SageResult<()> {
        let param = SafeVariant::from_dispatch(gamme.dispatch.clone());
        self.dispatch().call_property_put("AR_Gamme1", &[param])?;
        Ok(())
    }

    /// Deuxième gamme de l'article
    pub fn ar_gamme2(&self) -> SageResult<Option<Gamme>> {
        let variant = self.dispatch().call_method_by_name("AR_Gamme2", &[])?;
        if variant.is_empty_or_null() {
            return Ok(None);
        }
        if variant.is_object() {
            Ok(Some(Gamme {
                dispatch: variant.to_dispatch()?,
            }))
        } else {
            Err(SageError::ConversionError {
                from_type: "VARIANT".to_string(),
                to_type: "Gamme".to_string(),
                value: "AR_Gamme2 n'est pas un objet".to_string(),
            })
        }
    }

    pub fn set_ar_gamme2(&self, gamme: &Gamme) -> SageResult<()> {
        let param = SafeVariant::from_dispatch(gamme.dispatch.clone());
        self.dispatch().call_property_put("AR_Gamme2", &[param])?;
        Ok(())
    }

    // ==================== GESTION ====================

    /// Indique si l'article est géré en stock
    pub fn ar_suivi_stock(&self) -> SageResult<bool> {
        self.dispatch()
            .call_method_by_name("AR_SuiviStock", &[])?
            .to_bool()
    }

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

    /// Indique si l'article est en sommeil (inactif)
    pub fn ar_sommeil(&self) -> SageResult<bool> {
        self.dispatch()
            .call_method_by_name("AR_Sommeil", &[])?
            .to_bool()
    }

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

    /// Statistique article 1
    pub fn ar_stat01(&self) -> SageResult<String> {
        self.dispatch()
            .call_method_by_name("AR_Stat01", &[])?
            .to_string()
    }

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

    // ==================== PROPRIÉTÉS COMPTABLES ====================

    /// Catégorie comptable
    pub fn ar_categorie(&self) -> SageResult<String> {
        self.dispatch()
            .call_method_by_name("AR_Categorie", &[])?
            .to_string()
    }

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

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

    pub fn set_ar_compte_cpt_g(&self, compte: &CompteG) -> SageResult<()> {
        let param = SafeVariant::from_dispatch(compte.dispatch.clone());
        self.dispatch()
            .call_property_put("AR_CompteCPT_G", &[param])?;
        Ok(())
    }

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

    pub fn set_ar_compte_cpt_a(&self, compte: &CompteG) -> SageResult<()> {
        let param = SafeVariant::from_dispatch(compte.dispatch.clone());
        self.dispatch()
            .call_property_put("AR_CompteCPT_A", &[param])?;
        Ok(())
    }

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

    pub fn set_ar_compte_cpt_s(&self, compte: &CompteG) -> SageResult<()> {
        let param = SafeVariant::from_dispatch(compte.dispatch.clone());
        self.dispatch()
            .call_property_put("AR_CompteCPT_S", &[param])?;
        Ok(())
    }

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

    pub fn set_ar_compte_tva(&self, taxe: &Taxe) -> SageResult<()> {
        let param = SafeVariant::from_dispatch(taxe.dispatch.clone());
        self.dispatch()
            .call_property_put("AR_CompteTVA", &[param])?;
        Ok(())
    }

    // ==================== PROPRIÉTÉS DE STOCK ====================

    /// Quantité en stock
    pub fn ar_qte_sto(&self) -> SageResult<f64> {
        self.dispatch()
            .call_method_by_name("AR_QteSto", &[])?
            .to_f64()
    }

    /// Quantité réservée
    pub fn ar_qte_res(&self) -> SageResult<f64> {
        self.dispatch()
            .call_method_by_name("AR_QteRes", &[])?
            .to_f64()
    }

    /// Quantité en commande
    pub fn ar_qte_cde(&self) -> SageResult<f64> {
        self.dispatch()
            .call_method_by_name("AR_QteCde", &[])?
            .to_f64()
    }

    /// Stock minimum
    pub fn ar_qte_min(&self) -> SageResult<f64> {
        self.dispatch()
            .call_method_by_name("AR_QteMin", &[])?
            .to_f64()
    }

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

    /// Stock maximum
    pub fn ar_qte_max(&self) -> SageResult<f64> {
        self.dispatch()
            .call_method_by_name("AR_QteMax", &[])?
            .to_f64()
    }

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

    /// Quantité de réapprovisionnement
    pub fn ar_qte_reap(&self) -> SageResult<f64> {
        self.dispatch()
            .call_method_by_name("AR_QteReap", &[])?
            .to_f64()
    }

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

    /// Dépôt principal
    pub fn ar_depot(&self) -> SageResult<Option<Depot>> {
        let variant = self.dispatch().call_method_by_name("AR_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: "AR_Depot n'est pas un objet".to_string(),
            })
        }
    }

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

    /// Dernier prix d'achat
    pub fn ar_dernier_pa(&self) -> SageResult<f64> {
        self.dispatch()
            .call_method_by_name("AR_DernierPA", &[])?
            .to_f64()
    }

    // ==================== MÉTHODES DE CALCUL ====================

    /// Calcule le prix TTC à partir du prix HT et de la TVA
    ///
    /// # Exemple
    /// ```no_run
    /// # use objets_metier_rs::wrappers::cial::objects::Article;
    /// # fn example(article: Article) -> Result<(), Box<dyn std::error::Error>> {
    /// let prix_ttc = article.calculate_prix_ttc()?;
    /// println!("Prix TTC calculé: {}", prix_ttc);
    /// # Ok(())
    /// # }
    /// ```
    pub fn calculate_prix_ttc(&self) -> SageResult<f64> {
        // Le prix TTC est déjà calculé par Sage
        self.ar_prix_ttc()
    }

    /// Calcule le prix HT à partir du prix TTC et de la TVA
    pub fn calculate_prix_ht(&self) -> SageResult<f64> {
        self.ar_prix_ven()
    }

    /// Retourne le stock disponible (stock - réservé)
    ///
    /// # Exemple
    /// ```no_run
    /// # use objets_metier_rs::wrappers::cial::objects::Article;
    /// # fn example(article: Article) -> Result<(), Box<dyn std::error::Error>> {
    /// let dispo = article.get_stock_disponible()?;
    /// if dispo < 0.0 {
    ///     println!("⚠️ Stock négatif: rupture!");
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn get_stock_disponible(&self) -> SageResult<f64> {
        let qte_sto = self.ar_qte_sto()?;
        let qte_res = self.ar_qte_res()?;
        Ok(qte_sto - qte_res)
    }

    /// Vérifie si l'article nécessite un réapprovisionnement
    ///
    /// Retourne true si le stock disponible est inférieur au stock minimum
    pub fn need_reappro(&self) -> SageResult<bool> {
        let dispo = self.get_stock_disponible()?;
        let min = self.ar_qte_min()?;
        Ok(dispo < min)
    }

    /// Initialise l'article avec des valeurs par défaut
    ///
    /// Cette méthode doit être appelée après create() pour initialiser
    /// les valeurs par défaut automatiquement
    pub fn set_default_article(&self) -> SageResult<()> {
        self.dispatch().call_method_by_name("SetDefault", &[])?;
        Ok(())
    }

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

    /// Écrit l'article dans la base de données
    ///
    /// # Exemple
    /// ```no_run
    /// # use objets_metier_rs::wrappers::cial::objects::Article;
    /// # fn example(article: Article) -> Result<(), Box<dyn std::error::Error>> {
    /// article.set_ar_design("Nouvelle désignation")?;
    /// article.set_ar_prix_ven(19.99)?;
    /// article.write()?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn write(&self) -> SageResult<()> {
        self.dispatch().call_method_by_name("Write", &[])?;
        Ok(())
    }

    /// Écrit l'article avec initialisation des valeurs par défaut
    ///
    /// Recommandé pour la création de nouveaux articles
    pub fn write_default(&self) -> SageResult<()> {
        self.dispatch().call_method_by_name("WriteDefault", &[])?;
        Ok(())
    }

    /// Supprime l'article de la base de données
    ///
    /// ⚠️ ATTENTION : Cette opération est irréversible
    pub fn remove(&self) -> SageResult<()> {
        self.dispatch().call_method_by_name("Remove", &[])?;
        Ok(())
    }
}

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

    #[test]
    fn test_article_creation_needs_factory() {
        // Les articles sont créés via FactoryArticle
        // Ce test documente le pattern d'utilisation
    }

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