/// <summary>
 /// Ajoute un article depuis une ligne de doc dans processDocument
 /// TODO Conditionnement
 /// </summary>
 /// <param name="doc"></param>
 /// <param name="ligne"></param>
 /// <param name="qte"></param>
 /// <returns></returns>
 private IBODocumentLigne3 addArticleFromLigne(IPMDocument doc, IBODocumentLigne3 ligne, double qte)
 {
     if (ligne.ArticleGammeEnum2 != null)
     {
         return(doc.AddArticleDoubleGamme(ligne.ArticleGammeEnum1, ligne.ArticleGammeEnum2, qte));
     }
     if (ligne.ArticleGammeEnum1 != null)
     {
         return(doc.AddArticleMonoGamme(ligne.ArticleGammeEnum1, qte));
     }
     return(doc.AddArticle(ligne.Article, qte));
 }
Ejemplo n.º 2
0
        private IBODocumentLigne3 addArticleToLigne(IPMDocument doc, string arRef, string gamme1, string gamme2, double qt, string unite)
        {
            IBOArticle3 article;

            if (GetInstance().FactoryArticle.ExistReference(arRef))
            {
                article = GetInstance().FactoryArticle.ReadReference(arRef);
            }
            else if (DiversRepository.UniqueRegex.IsMatch(arRef))
            {
                article       = new DiversRepository().getUniqueArticle(arRef);
                article.Unite = GetInstance().FactoryUnite.ReadIntitule(unite);
                article.Write();
            }
            else
            {
                throw new Exception($"Article '{arRef}' non trouvé");
            }

            if (gamme2 != "")
            {
                return(doc.AddArticleDoubleGamme(
                           article.FactoryArticleGammeEnum1.ReadEnumere(gamme1),
                           article.FactoryArticleGammeEnum2.ReadEnumere(gamme2),
                           qt
                           ));
            }
            if (gamme1 != "")
            {
                return(doc.AddArticleMonoGamme(
                           article.FactoryArticleGammeEnum1.ReadEnumere(gamme1),
                           qt
                           ));
            }
            return(doc.AddArticle(article, qt));
        }
Ejemplo n.º 3
0
        public Article DeclareStock(double noteStock, Article article)
        {
            IBOArticle3  OMArticle = GetInstance().FactoryArticle.ReadReference(article.ArRef);
            double       stockReel;
            double       mouvQt;
            IBODocument3 dayDocIn = null, dayDocOut = null;

            using (SqlConnection cnx = new SqlConnection(cnxString))
            {
                cnx.Open();
                using (SqlCommand cmd = cnx.CreateCommand())
                {
                    cmd.CommandText = @"SELECT DO_Piece, DO_Type FROM F_DOCENTETE 
                        WHERE DO_Date = CAST(CURRENT_TIMESTAMP AS DATE) AND DO_Ref = 'REGUL STOCK' AND DO_Type IN (20,21)";
                    using (SqlDataReader reader = cmd.ExecuteReader())
                    {
                        if (reader.HasRows)
                        {
                            while (reader.Read())
                            {
                                short  doType  = (short)reader["DO_Type"];
                                string doPiece = (string)reader["DO_Piece"];

                                switch (doType)
                                {
                                case 20:
                                    dayDocIn = GetInstance().FactoryDocumentStock.ReadPiece(DocumentType.DocumentTypeStockMouvIn, doPiece);
                                    dayDocIn.CouldModified();
                                    removeLigneFromDoc(dayDocIn, OMArticle, article.Gamme1, article.Gamme2);
                                    break;

                                case 21:
                                    dayDocOut = GetInstance().FactoryDocumentStock.ReadPiece(DocumentType.DocumentTypeStockMouvOut, doPiece);
                                    dayDocOut.CouldModified();
                                    removeLigneFromDoc(dayDocOut, OMArticle, article.Gamme1, article.Gamme2);
                                    break;

                                default:
                                    throw new Exception($"Type {doType} non pris en charge");
                                }
                            }
                        }
                    }
                }

                stockReel = getStockReel(OMArticle, article.Gamme1, article.Gamme2);

                // Mouvement d'entrée
                if (noteStock > stockReel)
                {
                    mouvQt = noteStock - stockReel;
                    if (dayDocIn == null)
                    {
                        IPMDocument procDocIn = GetInstance().CreateProcess_Document(DocumentType.DocumentTypeStockMouvIn);
                        dayDocIn = procDocIn.Document;
                        procDocIn.Document.DO_Ref = "REGUL STOCK";
                        addArticleToLigne((IBODocumentLigne3)dayDocIn.FactoryDocumentLigne.Create(), OMArticle, article.Gamme1, article.Gamme2, mouvQt).WriteDefault();
                        procDocIn.Process();
                    }
                    addArticleToLigne((IBODocumentLigne3)dayDocIn.FactoryDocumentLigne.Create(), OMArticle, article.Gamme1, article.Gamme2, mouvQt).WriteDefault();
                }

                // Mouvement de sortie
                if (noteStock < stockReel)
                {
                    mouvQt = stockReel - noteStock;
                    if (dayDocOut == null)
                    {
                        IPMDocument procDocOut = GetInstance().CreateProcess_Document(DocumentType.DocumentTypeStockMouvOut);
                        dayDocOut = procDocOut.Document;
                        procDocOut.Document.DO_Ref = "REGUL STOCK";
                        addArticleToLigne((IBODocumentLigne3)dayDocOut.FactoryDocumentLigne.Create(), OMArticle, article.Gamme1, article.Gamme2, mouvQt).WriteDefault();
                        procDocOut.Process();
                    }
                    addArticleToLigne((IBODocumentLigne3)dayDocOut.FactoryDocumentLigne.Create(), OMArticle, article.Gamme1, article.Gamme2, mouvQt).WriteDefault();
                }
            }

            article.Stock = getStockReel(OMArticle, article.Gamme1, article.Gamme2);
            return(article);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Crée une commande dépot
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="targetDb"></param>
        /// <returns></returns>
        public string createCommandeDepot(DataTable dt, string targetDb)
        {
            BSCIALApplication100c bsc = GetInstance();

            try
            {
                bsc.Open();
                IBOClient3 client = getClient(bsc, dt.Rows[0]["DBCLIENT"].ToString() + " DEPOT");

                string doRef = dt.Rows[0]["DO_Piece"].ToString();

                CheckCommandeClientExiste(client.CT_Num, doRef, targetDb);

                // Crée le bon de commande client
                IPMDocument       procDocV   = bsc.CreateProcess_Document(DocumentType.DocumentTypeVenteCommande);
                IBODocumentVente3 docVEntete = (IBODocumentVente3)procDocV.Document;

                docVEntete.DO_Ref = doRef;

                // Affecte le numéro de pièce
                docVEntete.SetDefaultDO_Piece();

                docVEntete.SetDefaultClient(client);
                docVEntete.CategorieTarif = bsc.FactoryCategorieTarif.ReadIntitule("Tarif Article N° 6");

                IBODocumentVenteLigne3 docVLigne;
                foreach (DataRow row in dt.Rows)
                {
                    string arRef             = row["AR_Ref"].ToString();
                    string gamme1            = row["Gamme1"].ToString();
                    string gamme2            = row["Gamme2"].ToString();
                    double qt                = double.Parse(row["DL_Qte"].ToString(), System.Globalization.CultureInfo.InvariantCulture);
                    string refFourn          = row["AF_RefFourniss"].ToString();
                    string design            = row["DL_Design"].ToString();
                    string txtComplementaire = row["DT_Text"].ToString();
                    string unite             = row["EU_Enumere"].ToString();

                    if (arRef != "")
                    {
                        docVLigne = (IBODocumentVenteLigne3)addArticleToLigne(procDocV, arRef, gamme1, gamme2, qt, unite);
                        // Si pas de ref fourn, on essaie de recup la ref fourn principal
                        if (refFourn == "" && docVLigne.Article.FournisseurPrincipal != null)
                        {
                            refFourn = docVLigne.Article.FournisseurPrincipal.Reference;
                        }
                        docVLigne.AF_RefFourniss = refFourn;
                        docVLigne.SetDefaultRemise();
                        docVLigne.DO_Ref            = doRef;
                        docVLigne.DL_Design         = design;
                        docVLigne.TxtComplementaire = txtComplementaire;
                        docVLigne.Write();
                    }
                    else
                    {
                        // Sinon c'est une ligne de commentaire
                        docVLigne           = (IBODocumentVenteLigne3)docVEntete.FactoryDocumentLigne.Create();
                        docVLigne.DL_Design = design;
                        docVLigne.Write();
                    }
                }

                if (procDocV.CanProcess)
                {
                    procDocV.Process();
                    // Cherche les divers pour forcer la maj du texte complémentaire
                    // Ne peut pas être effectué pendant le process car les info libres n'existent pas encore

                    foreach (IBODocumentVenteLigne3 ligne in GetDocument(docVEntete.DO_Piece).FactoryDocumentLigne.List)
                    {
                        if (ligne.Article != null && (ligne.Article.AR_Ref == "DIVERS" || ligne.Article.Famille.FA_CodeFamille == "UNIQUE"))
                        {
                            new DiversRepository().saveLigneVente(ligne);
                        }
                    }
                }
                else
                {
                    throw new Exception(GetProcessError(procDocV));
                }

                string subject = $"[INTERMAG] Commande Dépôt {client.CT_Classement} {docVEntete.DO_Piece}";
                string body    = $@"<p>Le magasin {client.CT_Classement} vous a passé une commande dépôt n° <b>{docVEntete.DO_Piece}</b></p>
                                 <p>Collaborateur : {dt.Rows[0]["Collaborateur"].ToString()}</p>
                                 <p>Merci de vous référer à Sage pour en connaître le contenu.</p>";
                sendMail(dt.Rows[0]["DBCLIENT"].ToString(), bsc.DatabaseInfo.DatabaseName, subject, body);

                EventLog.WriteEntry(log, subject, EventLogEntryType.Information, 100);

                return(string.Format(
                           "[OK];{0};{1}: Commande client {2} créée",
                           docVEntete.DO_Piece,
                           bsc.DatabaseInfo.DatabaseName,
                           docVEntete.DO_Piece
                           ));
            }
            catch (Exception e)
            {
                EventLog.WriteEntry(log, e.ToString(), EventLogEntryType.Error, 100);
                throw new Exception(e.Message);
            }
            finally
            {
                if (bsc != null)
                {
                    bsc.Close();
                }
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Crée une commande Retro
        /// TODO utiliser le programme Contremarque pour générer l'APC? eg crée le document de vente en premier puis ajoute une contremarque sur toute les lignes
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public string createCommandeRetro(DataTable dt, string targetDb)
        {
            BSCIALApplication100c bsc = GetInstance();

            try
            {
                bsc.Open();
                IBOClient3 client = getClient(bsc, dt.Rows[0]["DBCLIENT"].ToString() + " RETRO");
                string     doRef  = dt.Rows[0]["DO_Piece"].ToString();
                CheckCommandeClientExiste(client.CT_Num, doRef, targetDb);

                // Crée le bon de commande client
                IPMDocument       procDocV   = bsc.CreateProcess_Document(DocumentType.DocumentTypeVenteCommande);
                IBODocumentVente3 docVEntete = (IBODocumentVente3)procDocV.Document;

                // Affecte le numéro de pièce
                docVEntete.SetDefaultDO_Piece();

                docVEntete.SetDefaultClient(client);
                docVEntete.CategorieTarif = bsc.FactoryCategorieTarif.ReadIntitule("Tarif Article N° 13");

                IBODocumentVenteLigne3 docVLigne;
                foreach (DataRow row in dt.Rows)
                {
                    string arRef             = row["AR_Ref"].ToString();
                    string gamme1            = row["Gamme1"].ToString();
                    string gamme2            = row["Gamme2"].ToString();
                    double montantHT         = double.Parse(row["DL_MontantHT"].ToString(), System.Globalization.CultureInfo.InvariantCulture);
                    double qt                = double.Parse(row["DL_Qte"].ToString(), System.Globalization.CultureInfo.InvariantCulture);
                    double prixUNet          = montantHT / qt;
                    string refFourn          = row["AF_RefFourniss"].ToString();
                    string design            = row["DL_Design"].ToString();
                    string txtComplementaire = row["DT_Text"].ToString();
                    string unite             = row["EU_Enumere"].ToString();

                    docVLigne = null;

                    if (arRef != "")
                    {
                        docVLigne = (IBODocumentVenteLigne3)addArticleToLigne(procDocV, arRef, gamme1, gamme2, qt, unite);
                        docVLigne.DL_PrixUnitaire   = prixUNet;
                        docVLigne.DL_Design         = design;
                        docVLigne.TxtComplementaire = txtComplementaire;
                        docVLigne.Write();
                    }
                    else
                    {
                        // Sinon c'est une ligne de commentaire
                        docVLigne           = (IBODocumentVenteLigne3)docVEntete.FactoryDocumentLigne.Create();
                        docVLigne.DL_Design = design;
                        docVLigne.Write();
                    }
                }

                if (procDocV.CanProcess)
                {
                    procDocV.Process();

                    // Cherche les divers pour forcer la maj du texte complémentaire
                    // Ne peut pas être effectué pendant le process car les info libres n'existent pas encore
                    foreach (IBODocumentVenteLigne3 ligne in GetDocument(docVEntete.DO_Piece).FactoryDocumentLigne.List)
                    {
                        if (ligne.Article != null && (ligne.Article.AR_Ref == "DIVERS" || ligne.Article.Famille.FA_CodeFamille == "UNIQUE"))
                        {
                            new DiversRepository().saveLigneVente(ligne);
                        }
                    }

                    // Ajoute les lignes en contremarque
                    ContremarqueRepository cmRepos = new ContremarqueRepository();
                    cmRepos.Log += Log;
                    Collection <Contremarque> cms = cmRepos.getAll(docVEntete.DO_Piece);
                    cms.Select(c => {
                        c.RowChecked    = true;
                        c.SelectedFourn = "Principal";
                        // On force pour chaque ligne le fournisseur demandé
                        // Cela permet de faire du retro sur un fournisseur secondaire
                        c.FournPrinc = dt.Rows[0]["DO_Tiers"].ToString();
                        return(c);
                    }).ToList();
                    cmRepos.saveAll(cms, docVEntete.DO_Piece, true);
                }
                else
                {
                    throw new Exception(GetProcessError(procDocV));
                }

                string subject = $"[INTERMAG] Commande Retro {client.CT_Classement} {docVEntete.DO_Piece}";
                string body    = $@"<p>Le magasin {client.CT_Classement} vous a passé une commande Retro n° <b>{docVEntete.DO_Piece}</b></p>
                                 <p>Collaborateur : {dt.Rows[0]["Collaborateur"].ToString()}</p>
                                 <p>Merci de vous référer à Sage pour en connaître le contenu.</p>";
                sendMail(dt.Rows[0]["DBCLIENT"].ToString(), bsc.DatabaseInfo.DatabaseName, subject, body);
                EventLog.WriteEntry(log, subject, EventLogEntryType.Information, 100);
                return($"[OK];{docVEntete.DO_Piece};{bsc.DatabaseInfo.DatabaseName}: Commande client {docVEntete.DO_Piece} créée {Environment.NewLine}{cmLogMessage}");
            }
            catch (Exception e)
            {
                EventLog.WriteEntry(log, e.ToString(), EventLogEntryType.Error, 100);
                throw new Exception(e.Message);
            }
            finally
            {
                if (bsc != null)
                {
                    bsc.Close();
                }
            }
        }
        /// <summary>
        /// Cde Retro: Duplique le bon de commande fournisseur en cde magasin
        /// </summary>
        /// <param name="docOrigin"></param>
        /// <param name="magPieces"></param>
        /// <param name="targetDb"></param>
        private void editCommandeRetro(IBODocumentAchat3 docOrigin, string magPieces, string targetDb)
        {
            try
            {
                // Commande RETRO
                IBOFournisseur3 fourn;

                using (SqlConnection cnx = new SqlConnection(cnxString))
                {
                    cnx.Open();
                    using (SqlCommand cmd = cnx.CreateCommand())
                    {
                        cmd.CommandText =
                            "SELECT CT_Num FROM F_COMPTET WHERE CT_Classement = @ctClassement AND CT_Type = 1";
                        cmd.Parameters.AddWithValue("@ctClassement", targetDb);
                        using (SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow))
                        {
                            if (reader.HasRows)
                            {
                                reader.Read();
                                fourn = GetInstance().CptaApplication.FactoryFournisseur.ReadNumero(reader["CT_Num"].ToString());
                            }
                            else
                            {
                                throw new Exception($"Fournisseur '{targetDb}' non trouvé");
                            }
                        }
                    }
                }

                // Duplication du doc d'origine en document d'achat magasin
                IPMDocument       procDoc = GetInstance().CreateProcess_Document(DocumentType.DocumentTypeAchatCommandeConf);
                IBODocumentAchat3 docNew  = (IBODocumentAchat3)procDoc.Document;

                docNew.SetDefaultDO_Piece();
                docNew.DO_Statut = DocumentStatutType.DocumentStatutTypeConfirme;
                docNew.DO_Ref    = magPieces;
                docNew.SetDefaultFournisseur(fourn);
                docNew.Collaborateur = docOrigin.Collaborateur;

                IBODocumentAchatLigne3 docNewLigne;

                foreach (IBODocumentAchatLigne3 docOrigineLigne in docOrigin.FactoryDocumentLigne.List)
                {
                    if (docOrigineLigne.Article == null)
                    {
                        // Ligne de commentaire
                        docNewLigne           = (IBODocumentAchatLigne3)docNew.FactoryDocumentLigne.Create();
                        docNewLigne.DL_Design = docOrigineLigne.DL_Design;
                        docNewLigne.Write();
                    }
                    else
                    {
                        docNewLigne = (IBODocumentAchatLigne3)addArticleFromLigne(procDoc, docOrigineLigne, docOrigineLigne.DL_Qte);
                        docNewLigne.AF_RefFourniss  = docOrigineLigne.AF_RefFourniss;
                        docNewLigne.Taxe[0]         = GetInstance().CptaApplication.FactoryTaxe.ReadCode("8");
                        docNewLigne.DL_PrixUnitaire = docOrigineLigne.DL_MontantHT / docOrigineLigne.DL_Qte;
                        docNewLigne.SetDefaultRemise();
                        docNewLigne.DO_Ref            = docOrigineLigne.InfoLibre["DLNo"];
                        docNewLigne.TxtComplementaire = docOrigineLigne.TxtComplementaire;
                        docNewLigne.DL_Design         = docOrigineLigne.DL_Design;
                        docNewLigne.Write();
                    }
                }

                if (procDoc.CanProcess)
                {
                    procDoc.Process();

                    foreach (IBODocumentAchatLigne3 ligne in GetDocument(docNew.DO_Piece).FactoryDocumentLigne.List)
                    {
                        if (ligne.Article != null && (ligne.Article.AR_Ref == "DIVERS" || ligne.Article.Famille.FA_CodeFamille == "UNIQUE"))
                        {
                            new DiversRepository().saveLigneAchat(ligne);
                        }
                    }

                    using (SqlConnection cnx = new SqlConnection(cnxString))
                    {
                        cnx.Open();
                        // Met à jour les infos libres
                        using (SqlCommand cmd = cnx.CreateCommand())
                        {
                            cmd.CommandText = @"UPDATE F_DOCENTETE 
                                                SET [Date Statut] = GETDATE(), [RETRO_FOURN] = @retroFourn 
                                                WHERE DO_Piece = @doPiece";
                            cmd.Parameters.AddWithValue("@doPiece", docNew.DO_Piece);
                            cmd.Parameters.AddWithValue("@retroFourn", docOrigin.Fournisseur.CT_Num);
                            cmd.ExecuteNonQuery();
                        }
                    }

                    docNew.Refresh();
                }
                else
                {
                    throw new Exception(GetProcessError(procDoc));
                }

                // Met à jour la référence du doc origine
                docOrigin.DO_Ref    = $"Voir {docNew.DO_Piece}";
                docOrigin.DO_Statut = DocumentStatutType.DocumentStatutTypeConfirme;
                docOrigin.Write();

                // Contremarque
                using (SqlConnection cnx = new SqlConnection(cnxString))
                {
                    cnx.Open();
                    SqlTransaction transaction = cnx.BeginTransaction();

                    try
                    {
                        using (SqlCommand cmd = cnx.CreateCommand())
                        {
                            cmd.Transaction = transaction;
                            // Recup les lignes du doc d'origine
                            cmd.CommandText = @"SELECT CM.DL_NoIn, CM.DL_NoOut, CM_Qte
                                                FROM F_CMLIEN CM
                                                JOIN F_DOCLIGNE DL ON DL.DL_No = CM.DL_NoIn
                                                WHERE DL.DO_PIECE = @doPiece  ";
                            cmd.Parameters.AddWithValue("@doPiece", docOrigin.DO_Piece);

                            using (SqlDataReader reader = cmd.ExecuteReader())
                            {
                                if (reader.HasRows)
                                {
                                    // Y a de la contremarque sur le doc
                                    while (reader.Read())
                                    {
                                        int dlNoIn = (int)reader["DL_NoIn"];
                                        using (SqlCommand cmd3 = cnx.CreateCommand())
                                        {
                                            cmd3.Transaction = transaction;
                                            cmd3.CommandText =
                                                "UPDATE F_CMLIEN SET DL_NoIn = (SELECT DL_No FROM F_DOCLIGNE WHERE DO_Ref = @dlNoIn) WHERE DL_NoIn = @dlNoIn";
                                            cmd3.Parameters.AddWithValue("@dlNoIn", dlNoIn.ToString());
                                            cmd3.ExecuteNonQuery();
                                        }

                                        // On remplace DO_Ref par sa valeur réelle
                                        using (SqlCommand cmdUpd = cnx.CreateCommand())
                                        {
                                            cmdUpd.Transaction = transaction;
                                            cmdUpd.CommandText = "UPDATE F_DOCLIGNE SET DO_Ref = @doRef WHERE DO_Ref = @uid";
                                            cmdUpd.Parameters.AddWithValue("@doRef", magPieces);
                                            cmdUpd.Parameters.AddWithValue("@uid", docOrigin.DO_Piece + dlNoIn);
                                            cmdUpd.ExecuteNonQuery();
                                        }
                                    }
                                }
                            }

                            transaction.Commit();
                        }
                    }
                    catch (Exception e)
                    {
                        transaction.Rollback();
                        throw new Exception(e.ToString());
                    }
                }

                Log($"{dbName} :: Doc Achat {docOrigin.DO_Piece} dupliqué vers le doc achat {docNew.DO_Piece}");

                // Met à jour la commande distante
                IntermagServiceClient client = createClient(targetDb);
                client.SetDoRef(docNew.DO_Piece, targetDb, magPieces.Split('/')[0]);
                client.Close();

                // Suppression du document fournisseur d'origine
                if (MessageBox.Show(
                        "Souhaitez-vous supprimer le document fournisseur d'origine?",
                        "Suppression doc origine",
                        MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    docOrigin.Remove();
                }
                else
                {
                    Log($"Vous devrez supprimer le document d'achat n° {docOrigin.DO_Piece} manuellement.");
                    // Dévérouille le doc
                    docOrigin.Read();
                }
            }
            catch (Exception e)
            {
                throw new Exception(e.ToString());
            }
        }
        /// <summary>
        /// Cde dépot: Met à jour les prix, statut ...
        /// </summary>
        /// <param name="docAOrigin"></param>
        /// <param name="magPiece"></param>
        private void editCommandeDepot(IBODocumentAchat3 docAOrigin, string magPiece)
        {
            try
            {
                // Commande Dépôt
                docAOrigin.DO_Ref    = magPiece;
                docAOrigin.DO_Statut = DocumentStatutType.DocumentStatutTypeConfirme;
                //docAOrigin.InfoLibre["Date Statut"] = DateTime.Now;
                docAOrigin.Write();

                using (SqlConnection cnx = new SqlConnection(cnxString))
                {
                    cnx.Open();
                    using (SqlCommand cmd = cnx.CreateCommand())
                    {
                        cmd.CommandText = "UPDATE F_DOCENTETE SET [Date Statut] = GETDATE() WHERE DO_Piece = @doPiece";
                        cmd.Parameters.AddWithValue("@doPiece", docAOrigin.DO_Piece);

                        cmd.ExecuteNonQuery();
                    }
                }

                docAOrigin.Refresh();

                // Simule une commande client Tarif 6 pour recup les prix remisés
                // et les appliquer au doc d'achat
                IPMDocument       procDocV   = GetInstance().CreateProcess_Document(DocumentType.DocumentTypeVenteCommande);
                IBODocumentVente3 docVEntete = (IBODocumentVente3)procDocV.Document;

                docVEntete.SetDefaultClient(GetInstance().CptaApplication.FactoryClient.ReadNumero("DEVEL"));
                docVEntete.CategorieTarif = GetInstance().FactoryCategorieTarif.ReadIntitule("Tarif Article N° 6");

                IBODocumentVenteLigne3 docVLigne;
                foreach (IBODocumentAchatLigne3 ligneOrigin in docAOrigin.FactoryDocumentLigne.List)
                {
                    if (ligneOrigin.Article != null)
                    {
                        Debug.Print(ligneOrigin.Article.AR_Ref);
                        docVLigne = (IBODocumentVenteLigne3)docVEntete.FactoryDocumentLigne.Create();
                        IBOArticle3 a   = ligneOrigin.Article;
                        double      qte = ligneOrigin.DL_Qte;
                        docVLigne.SetDefaultArticle(a, qte);
                        docVLigne.SetDefaultRemise();

                        ligneOrigin.DL_PrixUnitaire = docVLigne.DL_PrixUnitaire;
                        ligneOrigin.Remise.FromString(docVLigne.Remise.ToString());
                        ligneOrigin.DO_Ref = magPiece;
                        ligneOrigin.Write();

                        if (ligneOrigin.Article.AR_Ref == "DIVERS" || ligneOrigin.Article.Famille.FA_CodeFamille == "UNIQUE")
                        {
                            new DiversRepository().saveLigneAchat(ligneOrigin);
                        }
                    }
                }

                // Déverrouille le doc
                docAOrigin.Read();
            }
            catch (Exception e)
            {
                throw new Exception(e.ToString());
            }
        }