protected void btn_CreateInv_Click(object sender, EventArgs e)
    {
        string   invNo    = "";
        string   mastType = "WH";
        DateTime dt       = DateTime.Today;
        bool     isNew    = false;
        int      docId    = 0;

        if (list.Count > 0)
        {
            XAArInvoice iv = null;
            for (int i = 0; i < list.Count; i++)
            {
                string  counterType = "AR-IV";
                string  partyId     = list[i].partyId;
                string  product     = list[i].doNo;
                string  doNo        = list[i].doNo;
                int     qty         = list[i].qty;
                decimal surcharge   = list[i].surcharge;
                string  sql_cost    = string.Format(@"select * from(select mast.DoNo,CONVERT(VARCHAR(10),mast.DoDate,110) as DoDate,cost.ChgCode as ChargeCode, 
ChgCodeDes as Description,CONVERT(int,CostQty) as Qty,CostPrice as Price,StatusCode,
isnull(((CostQty)*(isnull((CostPrice),0) )),0) as TotalAmt,dbo.fun_GetPartyName(mast.PartyId) AS PartyName,mast.PartyId,
0 as Surcharge,0 as SurchageAmt,JobType as DoType,CONVERT(decimal(10,6),(isnull((CostQty*CostPrice),0)*CostGst)) as GstAmt,
ISNULL((select count(SequenceId) from XAArInvoiceDet det where det.ChgCode=cost.ChgCode and det.MastRefNo=RefNo),0) as CostCnt,
isnull((select count(Id) from Wh_Costing where RefNo=mast.DoNo and JobType=mast.DoType),0) as CostDoCnt
 from Wh_Costing cost left join Wh_DO mast on RefNo=mast.DoNo and JobType=mast.DoType and StatusCode='CLS'
 ) as tab where CostCnt=0 and CostDoCnt>0 and TotalAmt>0 and DoNo='{0}'", doNo);
                string  sql         = string.Format(@"select top 1 det.DocNo from XAArInvoiceDet det inner join XAArInvoice mast on det.DocNo=mast.DocNo where det.MastRefNo='{0}' and InvType='HANDLING' and CancelInd='N' order by det.DocNo desc", doNo);
                invNo = SafeValue.SafeString(C2.Manager.ORManager.ExecuteScalar(sql));

                if (invNo.Length == 0)
                {
                    iv    = new XAArInvoice();
                    invNo = C2Setup.GetNextNo("", counterType, dt);
                    isNew = true;
                }
                else
                {
                    Wilson.ORMapper.OPathQuery query = new Wilson.ORMapper.OPathQuery(typeof(XAArInvoice), "DocNo='" + invNo + "'");
                    iv    = C2.Manager.ORManager.GetObject(query) as XAArInvoice;
                    isNew = false;
                }
                iv.DocType     = "IV";
                iv.DocDate     = dt;
                iv.DocNo       = invNo;
                iv.PartyTo     = partyId;
                iv.CurrencyId  = System.Configuration.ConfigurationManager.AppSettings["Currency"];
                iv.ExRate      = 1;
                iv.AcCode      = EzshipHelper.GetAccApCode(iv.PartyTo, iv.CurrencyId);
                iv.AcSource    = "DB";
                iv.Description = "";
                iv.Term        = "CASH";

                string[] currentPeriod = EzshipHelper.GetAccPeriod(iv.DocDate);
                iv.AcYear   = SafeValue.SafeInt(currentPeriod[1], iv.DocDate.Year);
                iv.AcPeriod = SafeValue.SafeInt(currentPeriod[0], iv.DocDate.Month);

                iv.MastRefNo   = "";
                iv.JobRefNo    = "";
                iv.MastType    = mastType;
                iv.DocAmt      = 0;
                iv.LocAmt      = 0;
                iv.BalanceAmt  = 0;
                iv.CancelDate  = new DateTime(1900, 1, 1);
                iv.CancelInd   = "N";
                iv.DocDueDate  = dt;
                iv.ExportInd   = "N";
                iv.SpecialNote = "";
                iv.UserId      = EzshipHelper.GetUserName();
                iv.EntryDate   = DateTime.Now;
                iv.InvType     = "HANDLING";
                if (isNew)
                {
                    C2.Manager.ORManager.StartTracking(iv, Wilson.ORMapper.InitialState.Inserted);
                    C2.Manager.ORManager.PersistChanges(iv);
                    C2Setup.SetNextNo(iv.DocType, counterType, invNo, iv.DocDate);
                }
                else
                {
                    Manager.ORManager.StartTracking(iv, Wilson.ORMapper.InitialState.Updated);
                    Manager.ORManager.PersistChanges(iv);
                }

                try
                {
                    DataTable tab_Cost = ConnectSql.GetTab(sql_cost);
                    for (int a = 0; a < tab_Cost.Rows.Count; a++)
                    {
                        C2.XAArInvoiceDet det = new C2.XAArInvoiceDet();
                        det.DocId     = iv.SequenceId;
                        det.DocLineNo = i + 1;
                        det.DocNo     = invNo;
                        det.DocType   = "IV";
                        det.AcCode    = SafeValue.SafeString(ConnectSql.ExecuteScalar(string.Format("select ArCode from ref_product where Code='{0}'", product)), System.Configuration.ConfigurationManager.AppSettings["ItemArCode"]);
                        det.AcSource  = "CR";
                        det.MastRefNo = doNo;
                        det.JobRefNo  = "";
                        det.MastType  = mastType;
                        det.SplitType = "";


                        det.ChgCode = SafeValue.SafeString(tab_Cost.Rows[a]["ChargeCode"]);;
                        det.ChgDes1 = SafeValue.SafeString(tab_Cost.Rows[a]["Description"]);
                        det.ChgDes2 = "";
                        det.ChgDes3 = "";

                        det.Price    = SafeValue.SafeDecimal(tab_Cost.Rows[a]["Price"]);
                        det.Qty      = SafeValue.SafeInt(tab_Cost.Rows[a]["Qty"], 0);
                        det.Unit     = "";
                        det.Currency = iv.CurrencyId;
                        det.ExRate   = 1;
                        det.Gst      = 0;
                        if (det.ExRate == 0)
                        {
                            det.ExRate = 1;
                        }
                        if (det.Gst > 0)
                        {
                            det.GstType = "S";
                        }
                        else if (det.Currency == System.Configuration.ConfigurationManager.AppSettings["Currency"])
                        {
                            det.GstType = "E";
                        }
                        else
                        {
                            det.GstType = "Z";
                        }
                        decimal amt    = SafeValue.ChinaRound(det.Qty * det.Price, 2);
                        decimal gstAmt = SafeValue.ChinaRound((amt * det.Gst), 2);
                        decimal docAmt = amt + gstAmt;
                        decimal locAmt = SafeValue.ChinaRound(docAmt * det.ExRate, 2);
                        det.GstAmt   = gstAmt;
                        det.DocAmt   = docAmt;
                        det.LocAmt   = locAmt;
                        det.OtherAmt = 0;

                        C2.Manager.ORManager.StartTracking(det, Wilson.ORMapper.InitialState.Inserted);
                        C2.Manager.ORManager.PersistChanges(det);
                        if (surcharge != 0)
                        {
                            det.ChgCode = "HANDLE";
                            det.Qty     = 1;
                            det.Price   = surcharge;
                            sql         = string.Format(@"select * from XXChgCode where ChgcodeId='{0}'", det.ChgCode);
                            DataTable tab = ConnectSql.GetTab(sql);
                            for (int j = 0; j < tab.Rows.Count; j++)
                            {
                                det.AcCode  = SafeValue.SafeString(tab.Rows[j]["ArCode"]);
                                det.ChgDes1 = SafeValue.SafeString(tab.Rows[j]["ChgcodeDes"]);
                                det.GstType = SafeValue.SafeString(tab.Rows[j]["GstTypeId"]);
                                det.Gst     = SafeValue.SafeDecimal(tab.Rows[j]["GstP"]);
                            }


                            amt    = SafeValue.ChinaRound(det.Qty * det.Price, 2);
                            gstAmt = SafeValue.ChinaRound((amt * det.Gst), 2);

                            docAmt = amt + gstAmt;

                            locAmt     = SafeValue.ChinaRound(docAmt * det.ExRate, 2);
                            det.GstAmt = gstAmt;
                            det.DocAmt = docAmt;
                            det.LocAmt = locAmt;
                            C2.Manager.ORManager.StartTracking(det, Wilson.ORMapper.InitialState.Inserted);
                            C2.Manager.ORManager.PersistChanges(det);
                        }
                        docId = iv.SequenceId;
                    }
                }
                catch
                {
                }
                UpdateMaster(docId);
            }
            // string script = string.Format('<script type="text/javascript" > parent.navTab.openTab("{0}","/opsAccount/ArInvoiceEdit.aspx?no="{0}"",{title:'', fresh:false, external:true});</script>", invNo);
            //string script = string.Format("<script type='text/javascript' >alert('{0}');</script>", refNo);
            //Response.Clear();
            //Response.Write(script);
            //<a href='javascript: parent.navTab.openTab("<%# Eval("DoNo") %>","/WareHouse/Job/DoOutEdit.aspx?no=<%# Eval("DoNo") %>",{title:"<%# Eval("DoNo") %>", fresh:false, external:true});'><%# Eval("DoNo") %></a>
            Response.Redirect("/opsAccount/ArInvoiceEdit.aspx?no=" + invNo);
        }
    }
示例#2
0
    protected void grid_SKULine_CustomDataCallback(object sender, ASPxGridViewCustomDataCallbackEventArgs e)
    {
        string s      = e.Parameters;
        string soNo   = SafeValue.SafeString(Request.QueryString["no"].ToString());
        string schId  = SafeValue.SafeString(Request.QueryString["SchId"].ToString());
        string userId = HttpContext.Current.User.Identity.Name;

        if (s == "Save")
        {
            bool      result = false;
            string    issueN = "";
            string    sql    = string.Format(@"select * from Wh_TransDet where DoNo='{0}'", soNo);
            DataTable tab    = ConnectSql.GetTab(sql);
            for (int i = 0; i < tab.Rows.Count; i++)
            {
                if (SafeValue.SafeInt(tab.Rows[i]["Qty1"], 0) == 0)
                {
                    e.Result = "Fail,Please keyin Qty ";
                    return;
                }
            }
            C2.XAArInvoice inv    = null;
            C2.XAArInvoice inv_Do = null;
            if (tab.Rows.Count > 0)
            {
                //Get SO
                #region Get So
                bool isNew = false;
                Wilson.ORMapper.OPathQuery query1 = new Wilson.ORMapper.OPathQuery(typeof(WhTrans), "DoNo='" + soNo + "'");
                WhTrans   so     = C2.Manager.ORManager.GetObject(query1) as WhTrans;
                string    sql1   = string.Format("select doNo from wh_do where DoType='Out' and PoNo='{0}'", soNo);
                DataTable tab_do = ConnectSql.GetTab(sql1);
                string where = "(1=0";
                for (int i = 0; i < tab_do.Rows.Count; i++)
                {
                    where += string.Format(" or DoNo='{0}' ", tab_do.Rows[i][0]);
                }
                where += ")";

                int cnt = 0;
                sql = string.Format("select count(*) from wh_transDet where DoNo='{0}' and DoType='SO' and isnull(LotNo,'')='' ", soNo);
                cnt = SafeValue.SafeInt(ConnectSql.ExecuteSql(sql), 0);
                if (cnt > 0)
                {
                    e.Result = "No Balance Qty or No Lot No!";
                    return;
                }
                string update = string.Format(@"update Wh_Schedule set StatusCode='Closed' where Id='{1}'", soNo, schId);
                C2.Manager.ORManager.ExecuteCommand(update);
                #endregion
                #region Create SO Invoice
                int    invId = 0;
                string invN  = "";
                inv = Manager.ORManager.GetObject(typeof(XAArInvoice), SafeValue.SafeInt(invId, 0)) as XAArInvoice;
                if (inv == null)// first insert invoice
                {
                    string counterType = "AR-IV";
                    inv         = new XAArInvoice();
                    invN        = C2Setup.GetNextNo("", counterType, so.DoDate);
                    inv.PartyTo = SafeValue.SafeString(so.PartyId, "");
                    inv.DocType = "IV";
                    inv.DocNo   = invN.ToString();
                    inv.DocDate = so.DoDate;
                    string[] currentPeriod = EzshipHelper.GetAccPeriod(so.DoDate);

                    inv.AcYear   = SafeValue.SafeInt(currentPeriod[1], so.DoDate.Year);
                    inv.AcPeriod = SafeValue.SafeInt(currentPeriod[0], so.DoDate.Month);
                    inv.Term     = so.PayTerm;

                    //
                    int dueDay = 0;
                    if (so.PayTerm != null)
                    {
                        dueDay = SafeValue.SafeInt(so.PayTerm.ToUpper().Replace("DAYS", ""), 0);
                    }

                    inv.DocDueDate  = inv.DocDate.AddDays(dueDay);//SafeValue.SafeDate(dueDt.Text, DateTime.Now);
                    inv.Description = so.Remark;
                    inv.CurrencyId  = so.Currency;
                    inv.ExRate      = SafeValue.SafeDecimal(so.ExRate, 1);
                    if (inv.ExRate <= 0)
                    {
                        inv.ExRate = 1;
                    }
                    inv.AcCode      = EzshipHelper.GetAccArCode(inv.PartyTo, inv.CurrencyId);
                    inv.AcSource    = "DB";
                    inv.SpecialNote = "";

                    inv.MastType  = "WH";
                    inv.MastRefNo = so.DoNo;
                    inv.JobRefNo  = "";

                    inv.ExportInd  = "N";
                    inv.UserId     = HttpContext.Current.User.Identity.Name;
                    inv.EntryDate  = DateTime.Now;
                    inv.CancelDate = new DateTime(1900, 1, 1);
                    inv.CancelInd  = "N";
                    try
                    {
                        C2.Manager.ORManager.StartTracking(inv, Wilson.ORMapper.InitialState.Inserted);
                        C2.Manager.ORManager.PersistChanges(inv);
                        C2Setup.SetNextNo("", counterType, invN, inv.DocDate);
                    }
                    catch
                    {
                    }
                }
                #endregion
                #region Create DO
                //Create DoNo
                string doId = "";
                Wilson.ORMapper.OPathQuery query2 = new Wilson.ORMapper.OPathQuery(typeof(WhDo), "Id='" + doId + "'");
                WhDo whDo = C2.Manager.ORManager.GetObject(query2) as WhDo;

                if (whDo == null)
                {
                    whDo        = new WhDo();
                    isNew       = true;
                    issueN      = C2Setup.GetNextNo("", "DOOUT", so.DoDate);
                    whDo.DoType = "OUT";
                }
                whDo.DoNo           = issueN;
                whDo.PoNo           = so.DoNo;
                whDo.DoDate         = so.DoDate;
                whDo.PoDate         = so.DoDate;
                whDo.StatusCode     = "CLS";
                whDo.PartyId        = so.PartyId;
                whDo.PartyName      = so.PartyName;
                whDo.AgentId        = so.AgentId;
                whDo.AgentName      = so.AgentName;
                whDo.AgentTel       = so.AgentTel;
                whDo.AgentZip       = so.AgentZip;
                whDo.AgentCountry   = so.AgentCountry;
                whDo.AgentCity      = so.AgentCity;
                whDo.NotifyId       = so.NotifyId;
                whDo.NotifyName     = so.NotifyName;
                whDo.WareHouseId    = so.WareHouseId;
                whDo.CreateBy       = so.CreateBy;
                whDo.CreateDateTime = so.CreateDateTime;
                whDo.UpdateBy       = so.UpdateBy;
                whDo.UpdateDateTime = so.UpdateDateTime;
                if (isNew)
                {
                    Manager.ORManager.StartTracking(whDo, Wilson.ORMapper.InitialState.Inserted);
                    Manager.ORManager.PersistChanges(whDo);
                    C2Setup.SetNextNo("", "DOOUT", issueN, DateTime.Now);
                }
                #endregion
                #region Create DO Invoice
                inv_Do = Manager.ORManager.GetObject(typeof(XAArInvoice), SafeValue.SafeInt(invId, 0)) as XAArInvoice;
                if (inv_Do == null)// first insert invoice
                {
                    string counterType = "AR-IV";
                    inv_Do         = new XAArInvoice();
                    invN           = C2Setup.GetNextNo("", counterType, so.DoDate);
                    inv_Do.PartyTo = SafeValue.SafeString(so.PartyId, "");
                    inv_Do.DocType = "IV";
                    inv_Do.DocNo   = invN.ToString();
                    inv_Do.DocDate = so.DoDate;
                    string[] currentPeriod = EzshipHelper.GetAccPeriod(so.DoDate);

                    inv_Do.AcYear   = SafeValue.SafeInt(currentPeriod[1], so.DoDate.Year);
                    inv_Do.AcPeriod = SafeValue.SafeInt(currentPeriod[0], so.DoDate.Month);
                    inv_Do.Term     = so.PayTerm;

                    //
                    int dueDay = 0;
                    if (so.PayTerm != null)
                    {
                        dueDay = SafeValue.SafeInt(so.PayTerm.ToUpper().Replace("DAYS", ""), 0);
                    }

                    inv_Do.DocDueDate  = inv.DocDate.AddDays(dueDay);//SafeValue.SafeDate(dueDt.Text, DateTime.Now);
                    inv_Do.Description = so.Remark;
                    inv_Do.CurrencyId  = so.Currency;
                    inv_Do.ExRate      = SafeValue.SafeDecimal(so.ExRate, 1);
                    if (inv_Do.ExRate <= 0)
                    {
                        inv_Do.ExRate = 1;
                    }
                    inv_Do.AcCode      = EzshipHelper.GetAccArCode(inv.PartyTo, inv.CurrencyId);
                    inv_Do.AcSource    = "DB";
                    inv_Do.SpecialNote = "";

                    inv_Do.MastType  = "WH";
                    inv_Do.MastRefNo = whDo.DoNo;
                    inv_Do.JobRefNo  = "";

                    inv_Do.ExportInd  = "N";
                    inv_Do.UserId     = HttpContext.Current.User.Identity.Name;
                    inv_Do.EntryDate  = DateTime.Now;
                    inv_Do.CancelDate = new DateTime(1900, 1, 1);
                    inv_Do.CancelInd  = "N";
                    try
                    {
                        C2.Manager.ORManager.StartTracking(inv_Do, Wilson.ORMapper.InitialState.Inserted);
                        C2.Manager.ORManager.PersistChanges(inv_Do);
                        C2Setup.SetNextNo("", counterType, invN, inv_Do.DocDate);
                    }
                    catch
                    {
                    }
                }
                #endregion
            }
            #region Create Transfer
            for (int i = 0; i < tab.Rows.Count; i++)
            {
                string  product  = SafeValue.SafeString(tab.Rows[i]["ProductCode"]);
                string  lotNo    = SafeValue.SafeString(tab.Rows[i]["LotNo"]);
                int     qty      = SafeValue.SafeInt(tab.Rows[i]["Qty1"], 0);
                decimal price    = SafeValue.SafeDecimal(tab.Rows[i]["Price"]);
                string  des1     = SafeValue.SafeString(tab.Rows[i]["Des1"]);
                string  location = SafeValue.SafeString(tab.Rows[i]["LocationCode"]);

                sql  = @"Insert Into wh_DoDet(JobStatus,DoNo, DoType,ProductCode,ExpiredDate,Price,Qty1,Qty2,Qty3,Qty4,Qty5,LotNo,BatchNo,CustomsLot,Uom1,Uom2,Uom3,Uom4,[QtyPackWhole],[QtyWholeLoose],[QtyLooseBase],Att1,Att2,Att3,Att4,Att5,Att6,Att7,Att8,Att9,Att10,Des1,Packing,[CreateBy],[CreateDateTime],[UpdateBy],[UpdateDateTime],DoInId)";
                sql += string.Format(@" select * from (select 'Picked' as JobStatus,'{1}'as DoNo, 'Out' as DoType,ProductCode,ExpiredDate,Price
,Qty1 as Qty1
,0 as Qty2
,0 as Qty3
,Qty1 as Qty4
,0 as Qty5
, LotNo,BatchNo,CustomsLot,Uom1,Uom2,Uom3,Uom4,[QtyPackWhole],[QtyWholeLoose],[QtyLooseBase],Att1,Att2,Att3,Att4,Att5,Att6,Att7,Att8,Att9,Att10,Des1,Packing,'{2}' as CreateBy,getdate() as CreateDateTime,'{2}' as UpdateBy,getdate() as UpdateDateTime,Id as DoInId from Wh_TransDet where DoNo='{0}' and ProductCode='{4}' and LotNo='{5}' and DoType='SO' and LocationCode='{3}'
 ) as tab_aa where qty4>0  ", soNo, issueN, userId, location, product, lotNo);

                C2.Manager.ORManager.ExecuteCommand(sql);

                sql  = @"Insert Into Wh_DoDet2(DoNo,DoType,Product,Qty1,Qty2,Qty3,Price,LotNo,Uom1,Uom2,Uom3,Uom4,[QtyPackWhole],[QtyWholeLoose],[QtyLooseBase],[CreateBy],[CreateDateTime],[UpdateBy],[UpdateDateTime],Att1,Att2,Att3,Att4,Att5,Att6,Des1,Packing,Location,ProcessStatus)";
                sql += string.Format(@"select '{0}'as DoNo, 'OUT' as DoType,'{1}' as Sku
 ,'{2}' as Qty1
 ,0 as Qty2
 ,0 as Qty3
 ,'{3}' as Price
,'{4}' as LotNo
,ref.UomPacking as Uom1,ref.UomWhole as Uom2,ref.UomLoose as Uom3,ref.UomBase as Uom4
,ref.QtyPackingWhole as QtyPackWhole,ref.QtyWholeLoose as  QtyWholeLoose,ref.QtyLooseBase as QtyLooseBase
,'{5}' as CreateBy,getdate() as CreateDateTime,'{5}' as UpdateBy,getdate() as UpdateDateTime
,ref.Att4 as Att1,ref.Att5 as Att2,ref.att6 as Att3,ref.att7 as Att4,ref.att8 as Att5,ref.att9 as Att6,ref.Description as Des1,'' as Packing,'{6}' as Location,'Delivered' as ProcessStatus
from (select '{1}' as Sku) as tab inner join ref_product ref on ref.Code=tab.Sku", issueN, product, qty, price, lotNo, userId, location);
                C2.Manager.ORManager.ExecuteCommand(sql);
                InsertInv_Det(inv.SequenceId, inv.DocNo, i + 1, product, lotNo, des1, qty, price, inv.CurrencyId, inv.ExRate, 0, inv.MastRefNo, "", inv.MastType, "IV");
                UpdateMaster(inv.SequenceId);

                InsertInv_Det(inv_Do.SequenceId, inv_Do.DocNo, i + 1, product, lotNo, des1, qty, price, inv_Do.CurrencyId, inv_Do.ExRate, 0, inv_Do.MastRefNo, "", inv_Do.MastType, "IV");
                UpdateMaster(inv_Do.SequenceId);
                if (soNo.Length > 0)
                {
                    result = true;
                }
            }
            #endregion
            if (result)
            {
                e.Result = issueN;
            }
            else
            {
                e.Result = "Fail,Please keyin select product ";
            }
        }
    }
    private void SaveAndUpdate()
    {
        ASPxTextBox  invNCtr     = this.ASPxGridView1.FindEditFormTemplateControl("txt_Oid") as ASPxTextBox;
        ASPxComboBox partyTo     = this.ASPxGridView1.FindEditFormTemplateControl("cmb_PartyTo") as ASPxComboBox;
        ASPxTextBox  docN        = this.ASPxGridView1.FindEditFormTemplateControl("txt_DocNo") as ASPxTextBox;
        ASPxComboBox docType     = this.ASPxGridView1.FindEditFormTemplateControl("cbo_DocType") as ASPxComboBox;
        ASPxDateEdit docDate     = this.ASPxGridView1.FindEditFormTemplateControl("txt_DocDt") as ASPxDateEdit;
        ASPxMemo     remarks1    = this.ASPxGridView1.FindEditFormTemplateControl("txt_Remarks1") as ASPxMemo;
        ASPxComboBox termId      = this.ASPxGridView1.FindEditFormTemplateControl("txt_TermId") as ASPxComboBox;
        ASPxDateEdit dueDt       = this.ASPxGridView1.FindEditFormTemplateControl("txt_DueDt") as ASPxDateEdit;
        ASPxTextBox  docCurr     = this.ASPxGridView1.FindEditFormTemplateControl("txt_Currency") as ASPxTextBox;
        ASPxSpinEdit exRate      = this.ASPxGridView1.FindEditFormTemplateControl("txt_DocExRate") as ASPxSpinEdit;
        ASPxTextBox  acCode      = this.ASPxGridView1.FindEditFormTemplateControl("txt_AcCode") as ASPxTextBox;
        ASPxComboBox acSource    = this.ASPxGridView1.FindEditFormTemplateControl("txt_AcSource") as ASPxComboBox;
        ASPxTextBox  specialNote = this.ASPxGridView1.FindEditFormTemplateControl("txt_SpecialNote") as ASPxTextBox;

        ASPxTextBox mastRefNCtr = this.ASPxGridView1.FindEditFormTemplateControl("txt_MastRefNo") as ASPxTextBox;
        ASPxTextBox jobRefNCtr  = this.ASPxGridView1.FindEditFormTemplateControl("txt_JobRefNo") as ASPxTextBox;
        ASPxTextBox jobType     = this.ASPxGridView1.FindEditFormTemplateControl("txt_MastType") as ASPxTextBox;

        string invN = docN.Text;

        C2.XAArInvoice inv = Manager.ORManager.GetObject(typeof(XAArInvoice), SafeValue.SafeInt(invNCtr.Text, 0)) as XAArInvoice;
        if (inv == null)// first insert invoice
        {
            string counterType = "AR-IV";
            if (docType.Value.ToString() == "DN")
            {
                counterType = "AR-DN";
            }

            inv         = new XAArInvoice();
            invN        = C2Setup.GetNextNo("", counterType, docDate.Date);
            inv.PartyTo = SafeValue.SafeString(partyTo.Value, "");
            inv.DocType = docType.Value.ToString();
            inv.DocNo   = invN.ToString();
            inv.DocDate = docDate.Date;
            string[] currentPeriod = EzshipHelper.GetAccPeriod(docDate.Date);

            inv.AcYear   = SafeValue.SafeInt(currentPeriod[1], docDate.Date.Year);
            inv.AcPeriod = SafeValue.SafeInt(currentPeriod[0], docDate.Date.Month);

            //
            int dueDay = SafeValue.SafeInt(termId.Text.ToUpper().Replace("DAYS", "").Trim(), 0);
            inv.DocDueDate  = inv.DocDate.AddDays(dueDay);//SafeValue.SafeDate(dueDt.Text, DateTime.Now);
            inv.Description = remarks1.Text;
            inv.CurrencyId  = docCurr.Text.ToString();
            inv.ExRate      = SafeValue.SafeDecimal(exRate.Value, 1);
            if (inv.ExRate <= 0)
            {
                inv.ExRate = 1;
            }
            inv.AcCode = EzshipHelper.GetAccArCode(inv.PartyTo, inv.CurrencyId);
            if (inv.AcCode == "")
            {
                throw new Exception("Please frist set account code!");
            }
            inv.AcSource    = acSource.Value.ToString();
            inv.SpecialNote = specialNote.Text;

            inv.MastType  = jobType.Text;
            inv.MastRefNo = mastRefNCtr.Text;
            inv.JobRefNo  = jobRefNCtr.Text;

            inv.ExportInd  = "N";
            inv.UserId     = HttpContext.Current.User.Identity.Name;
            inv.EntryDate  = DateTime.Now;
            inv.CancelDate = new DateTime(1900, 1, 1);
            inv.CancelInd  = "N";
            try
            {
                C2.Manager.ORManager.StartTracking(inv, Wilson.ORMapper.InitialState.Inserted);
                C2.Manager.ORManager.PersistChanges(inv);
                C2Setup.SetNextNo("", counterType, invN, inv.DocDate);
            }
            catch
            {
            }
        }
        else
        {
            inv.PartyTo = SafeValue.SafeString(partyTo.Value, "");

            inv.Term    = termId.Text;
            inv.DocDate = docDate.Date;
            string[] currentPeriod = EzshipHelper.GetAccPeriod(docDate.Date);

            inv.AcYear   = SafeValue.SafeInt(currentPeriod[1], docDate.Date.Year);
            inv.AcPeriod = SafeValue.SafeInt(currentPeriod[0], docDate.Date.Month);

            int dueDay = SafeValue.SafeInt(termId.Text.ToUpper().Replace("DAYS", "").Trim(), 0);
            inv.DocDueDate  = inv.DocDate.AddDays(dueDay);//SafeValue.SafeDate(dueDt.Text, DateTime.Now);
            inv.Description = remarks1.Text;
            inv.CurrencyId  = docCurr.Text.ToString();
            inv.ExRate      = SafeValue.SafeDecimal(exRate.Value, 1);
            if (inv.ExRate <= 0)
            {
                inv.ExRate = 1;
            }
            inv.AcCode      = EzshipHelper.GetAccArCode(inv.PartyTo, inv.CurrencyId);
            inv.AcSource    = acSource.Text;
            inv.SpecialNote = specialNote.Text;

            inv.MastType  = jobType.Text;
            inv.MastRefNo = mastRefNCtr.Text;
            inv.JobRefNo  = jobRefNCtr.Text;
            try
            {
                Manager.ORManager.StartTracking(inv, InitialState.Updated);
                Manager.ORManager.PersistChanges(inv);
                UpdateMaster(inv.SequenceId);
            }
            catch
            {
            }
        }
        Session["SeaIvEditWhere"]         = "SequenceId=" + inv.SequenceId;
        this.dsArInvoice.FilterExpression = Session["SeaIvEditWhere"].ToString();
        if (this.ASPxGridView1.GetRow(0) != null)
        {
            this.ASPxGridView1.StartEdit(0);
        }
    }
示例#4
0
    protected void grid_CustomDataCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewCustomDataCallbackEventArgs e)
    {
        if (e.Parameters != null)
        {
            string quoteId = e.Parameters;

            string  sql      = string.Format("SELECT SequenceId,DocNo,  DocFromDate, DocToDate, CurrencyId, Term,  Pol, Pod, Description FROM SeaQuote where SequenceId='{0}'", quoteId);
            string  currency = "SGD";
            decimal exRate   = 1;
            string  term     = "CASH";

            string refType = Request.QueryString["JobType"].ToString();
            string refNo   = Request.QueryString["RefN"].ToString();
            string jobNo   = Request.QueryString["JobN"].ToString();

            string partyTo = "";
            string sql_Job = "";
            if (refType == "SI")
            {
                sql_Job = string.Format(@"SELECT job.CustomerId, cust.TermId, ref.ExRate FROM SeaImport AS job INNER JOIN  XXParty AS cust ON job.CustomerId = cust.PartyId INNER JOIN
                      SeaImportRef AS ref ON ref.RefNo = job.RefNo
WHERE (job.RefNo = '{0}') AND (job.JobNo = '{1}')", refNo, jobNo);
            }
            else
            {
                sql_Job = string.Format(@"SELECT job.CustomerId, cust.TermId, ref.ExRate FROM SeaExport AS job INNER JOIN  XXParty AS cust ON job.CustomerId = cust.PartyId 
INNER JOIN SeaExportRef AS ref ON ref.RefNo = job.RefNo
WHERE (job.RefNo = '{0}') AND (job.JobNo = '{1}')", refNo, jobNo);
            }
            DataTable tab = C2.Manager.ORManager.GetDataSet(sql_Job).Tables[0];
            if (tab.Rows.Count == 1)
            {
                partyTo = SafeValue.SafeString(tab.Rows[0][0], "");
                term    = SafeValue.SafeString(tab.Rows[0][1], "");
                exRate  = SafeValue.SafeDecimal(tab.Rows[0][2], 1);
            }

            string counterType = "AR-IV";

            XAArInvoice inv  = new XAArInvoice();
            string      invN = C2Setup.GetNextNo(counterType);
            inv         = new XAArInvoice();
            inv.PartyTo = partyTo;
            inv.DocType = "IV";
            inv.DocNo   = invN.ToString();
            inv.DocDate = DateTime.Today;
            string[] currentPeriod = EzshipHelper.GetAccPeriod(inv.DocDate);

            inv.AcYear   = SafeValue.SafeInt(currentPeriod[1], inv.DocDate.Year);
            inv.AcPeriod = SafeValue.SafeInt(currentPeriod[0], inv.DocDate.Month);

            inv.Term = term;
            //
            int dueDay = SafeValue.SafeInt(term.ToUpper().Replace("DAYS", "").Trim(), 0);
            inv.DocDueDate  = inv.DocDate.AddDays(dueDay);//SafeValue.SafeDate(dueDt.Text, DateTime.Now);
            inv.Description = "";
            inv.CurrencyId  = currency;
            inv.ExRate      = SafeValue.SafeDecimal(exRate, 1);
            if (inv.ExRate <= 0)
            {
                inv.ExRate = 1;
            }
            inv.AcCode = EzshipHelper.GetAccArCode(inv.PartyTo, inv.CurrencyId);
            if (inv.AcCode == "")
            {
                throw new Exception("Please frist set account code!");
            }
            inv.AcSource = "DB";

            inv.MastType  = refType;
            inv.MastRefNo = refNo;
            inv.JobRefNo  = jobNo;

            inv.ExportInd  = "N";
            inv.UserId     = HttpContext.Current.User.Identity.Name;
            inv.EntryDate  = DateTime.Now;
            inv.CancelDate = new DateTime(1900, 1, 1);
            inv.CancelInd  = "N";

            try
            {
                C2.Manager.ORManager.StartTracking(inv, Wilson.ORMapper.InitialState.Inserted);
                C2.Manager.ORManager.PersistChanges(inv);
                C2Setup.SetNextNo(invN, counterType);

                sql = string.Format(@"SELECT QuoteLineNo, ChgCode, Currency, Price, Unit, MinAmt, Rmk, Qty, Amt, gsttype, gst FROM SeaQuoteDet1 Where QuoteId='{0}' order by QuoteLineNo", quoteId);
                tab = C2.Manager.ORManager.GetDataSet(sql).Tables[0];
                int index = 1;
                for (int i = 0; i < tab.Rows.Count; i++)
                {
                    try
                    {
                        string chgCode = SafeValue.SafeString(tab.Rows[i]["ChgCode"], "").Trim();
                        if (chgCode.Length == 0)
                        {
                            continue;
                        }

                        string  chgDes1     = " ";
                        decimal qty         = SafeValue.SafeDecimal(tab.Rows[i]["Qty"], 1);
                        decimal price       = SafeValue.SafeDecimal(tab.Rows[i]["Price"], 0);
                        string  unit        = tab.Rows[i]["Unit"].ToString();
                        string  currencyDes = tab.Rows[i]["Currency"].ToString();
                        decimal gst         = SafeValue.SafeDecimal(tab.Rows[i]["Gst"], 0);
                        string  gstType     = tab.Rows[i]["GstType"].ToString();

                        XAArInvoiceDet det       = new XAArInvoiceDet();
                        string         impExpInd = "Import";
                        if (refType == "SE")
                        {
                            impExpInd = "Export";
                        }
                        string sql_chgCode = string.Format("SELECT ArCode, ChgcodeDes,GstTypeId, GstP FROM XXChgCode WHERE (ImpExpInd = '{1}' or ImpExpInd='Full') AND (ChgcodeId = '{0}')", chgCode, impExpInd);
                        // DataTable
                        DataTable tab_chgCode = C2.Manager.ORManager.GetDataSet(sql_chgCode).Tables[0];
                        if (tab_chgCode.Rows.Count == 1)
                        {
                            det.AcCode  = SafeValue.SafeString(tab_chgCode.Rows[0]["ArCode"], "5001");
                            chgDes1     = SafeValue.SafeString(tab_chgCode.Rows[0]["ChgcodeDes"], " ");
                            det.Gst     = SafeValue.SafeDecimal(tab_chgCode.Rows[0]["GstP"], 0);
                            det.GstType = SafeValue.SafeString(tab_chgCode.Rows[0]["GstTypeId"], "Z");
                        }
                        else
                        {
                            det.Gst     = gst;
                            det.GstType = gstType;
                            string sql_acCode = "select AcCode from XXGstAcount where GstSrc='AR'";
                            det.AcCode = SafeValue.SafeString(C2.Manager.ORManager.ExecuteScalar(sql_acCode));
                        }
                        det.AcSource = "CR";
                        det.ChgCode  = chgCode;
                        det.ChgDes1  = chgDes1;
                        det.ChgDes2  = "";
                        det.ChgDes3  = "";
                        det.Currency = currencyDes;
                        if (currency == currencyDes)
                        {
                            det.ExRate = 1;
                        }
                        else
                        {
                            det.ExRate = exRate;
                        }

                        det.Price = price;
                        det.Qty   = qty;
                        det.Unit  = unit;

                        decimal amt    = SafeValue.ChinaRound(det.Qty * det.Price, 2);
                        decimal gstAmt = SafeValue.ChinaRound(amt * det.Gst, 2);
                        decimal docAmt = amt + gstAmt;
                        decimal locAmt = SafeValue.ChinaRound(docAmt * det.ExRate, 2);
                        det.GstAmt = gstAmt;
                        det.DocAmt = docAmt;
                        det.LocAmt = locAmt;

                        det.DocId     = inv.SequenceId;
                        det.DocLineNo = index;
                        det.DocNo     = invN;
                        det.DocType   = "IV";
                        det.MastType  = refType;
                        det.MastRefNo = refNo;
                        det.JobRefNo  = jobNo;
                        C2.Manager.ORManager.StartTracking(det, Wilson.ORMapper.InitialState.Inserted);
                        C2.Manager.ORManager.PersistChanges(det);
                        index++;
                    }
                    catch { }
                }
                UpdateMaster(inv.SequenceId);
                e.Result = inv.DocNo;
            }
            catch
            {
                e.Result = "Fail";
            }
        }
    }
    protected void btn_CreateInv_Click(object sender, EventArgs e)
    {
        string   invNo    = "";
        string   mastType = "WH";
        DateTime dt       = DateTime.Today;
        bool     isNew    = false;
        int      docId    = 0;

        if (list.Count > 0)
        {
            XAArInvoice iv = null;
            for (int i = 0; i < list.Count; i++)
            {
                string  counterType = "AR-IV";
                string  partyId     = list[i].partyId;
                string  product     = list[i].code;
                string  doNo        = list[i].doNo;
                string  des         = list[i].des;
                string  lotNo       = list[i].lotNo;
                decimal qty         = list[i].qty;
                decimal price       = list[i].price;
                int     days        = list[i].days;
                decimal surcharge   = list[i].surcharge;
                //string sql = string.Format(@"select DocNo from XAArInvoice where MastRefNo='{0}' and InvType='STORAGE'", doNo);
                //invNo = SafeValue.SafeString(C2.Manager.ORManager.ExecuteScalar(sql));
                //if (invNo.Length==0)
                //{
                //    iv = new XAArInvoice();
                //    invNo = C2Setup.GetNextNo("", counterType, dt);
                //    isNew = true;
                //}
                //else
                //{
                //    Wilson.ORMapper.OPathQuery query = new Wilson.ORMapper.OPathQuery(typeof(XAArInvoice), "DocNo='" + invNo + "'");
                //    iv = C2.Manager.ORManager.GetObject(query) as XAArInvoice;
                //    isNew = false;
                //}
                iv             = new XAArInvoice();
                invNo          = C2Setup.GetNextNo("", counterType, dt);
                isNew          = true;
                iv.DocType     = "IV";
                iv.DocDate     = dt;
                iv.DocNo       = invNo;
                iv.PartyTo     = partyId;
                iv.CurrencyId  = System.Configuration.ConfigurationManager.AppSettings["Currency"];
                iv.ExRate      = 1;
                iv.AcCode      = EzshipHelper.GetAccApCode(iv.PartyTo, iv.CurrencyId);
                iv.AcSource    = "DB";
                iv.Description = "";
                iv.Term        = "CASH";

                string[] currentPeriod = EzshipHelper.GetAccPeriod(iv.DocDate);
                iv.AcYear   = SafeValue.SafeInt(currentPeriod[1], iv.DocDate.Year);
                iv.AcPeriod = SafeValue.SafeInt(currentPeriod[0], iv.DocDate.Month);

                iv.MastRefNo   = doNo;
                iv.JobRefNo    = "";
                iv.MastType    = mastType;
                iv.DocAmt      = 0;
                iv.LocAmt      = 0;
                iv.BalanceAmt  = 0;
                iv.CancelDate  = new DateTime(1900, 1, 1);
                iv.CancelInd   = "N";
                iv.DocDueDate  = dt;
                iv.ExportInd   = "N";
                iv.SpecialNote = "";
                iv.UserId      = EzshipHelper.GetUserName();
                iv.EntryDate   = DateTime.Now;
                iv.InvType     = "STORAGE";
                //if (isNew)
                //{
                C2.Manager.ORManager.StartTracking(iv, Wilson.ORMapper.InitialState.Inserted);
                C2.Manager.ORManager.PersistChanges(iv);
                C2Setup.SetNextNo(iv.DocType, counterType, invNo, iv.DocDate);
                //}
                //else
                //{
                Manager.ORManager.StartTracking(iv, Wilson.ORMapper.InitialState.Updated);
                Manager.ORManager.PersistChanges(iv);
                //}

                try
                {
                    C2.XAArInvoiceDet det = new C2.XAArInvoiceDet();
                    det.DocId     = iv.SequenceId;
                    det.DocLineNo = i + 1;
                    det.DocNo     = invNo;
                    det.DocType   = "IV";
                    det.AcCode    = SafeValue.SafeString(ConnectSql.ExecuteScalar(string.Format("select ArCode from ref_product where Code='{0}'", product)), System.Configuration.ConfigurationManager.AppSettings["ItemArCode"]);
                    det.AcSource  = "CR";
                    det.MastRefNo = doNo;
                    det.JobRefNo  = lotNo;
                    det.MastType  = mastType;
                    det.SplitType = "";

                    //sql = string.Format(@"select * from XXChgCode where ChgcodeId='{0}'", product);
                    //DataTable tab_chg = ConnectSql.GetTab(sql);
                    //for (int j = 0; j < tab_chg.Rows.Count; j++)
                    //{
                    //    det.Gst = SafeValue.SafeDecimal(tab_chg.Rows[j]["GstP"]);
                    //}

                    det.ChgCode = product;
                    det.ChgDes1 = des;
                    det.ChgDes2 = "";
                    det.ChgDes3 = "";

                    det.Price    = price;
                    det.Qty      = qty;
                    det.Unit     = "";
                    det.Currency = iv.CurrencyId;
                    det.ExRate   = 1;
                    det.Gst      = 0;
                    if (det.ExRate == 0)
                    {
                        det.ExRate = 1;
                    }
                    if (det.Gst > 0)
                    {
                        det.GstType = "S";
                    }
                    else if (det.Currency == System.Configuration.ConfigurationManager.AppSettings["Currency"])
                    {
                        det.GstType = "E";
                    }
                    else
                    {
                        det.GstType = "Z";
                    }
                    decimal amt         = SafeValue.ChinaRound(det.Qty * det.Price, 2);//*days
                    decimal gstAmt      = SafeValue.ChinaRound((amt * det.Gst), 2);
                    decimal docAmt      = amt + gstAmt;
                    decimal locAmt      = SafeValue.ChinaRound(docAmt * det.ExRate, 2);
                    decimal surchageAmt = SafeValue.ChinaRound(surcharge * qty, 2);
                    det.GstAmt   = gstAmt;
                    det.DocAmt   = docAmt;
                    det.LocAmt   = locAmt;
                    det.OtherAmt = surchageAmt;
                    C2.Manager.ORManager.StartTracking(det, Wilson.ORMapper.InitialState.Inserted);
                    C2.Manager.ORManager.PersistChanges(det);
                    if (surcharge != 0)
                    {
                        det.ChgCode = "STORE";

                        det.Qty   = 1;
                        det.Price = surcharge;
                        string    sql = string.Format(@"select * from XXChgCode where ChgcodeId='{0}'", det.ChgCode);
                        DataTable tab = ConnectSql.GetTab(sql);
                        for (int j = 0; j < tab.Rows.Count; j++)
                        {
                            det.AcCode  = SafeValue.SafeString(tab.Rows[j]["ArCode"]);
                            det.ChgDes1 = SafeValue.SafeString(tab.Rows[j]["ChgcodeDes"]);
                            det.GstType = SafeValue.SafeString(tab.Rows[j]["GstTypeId"]);
                            det.Gst     = SafeValue.SafeDecimal(tab.Rows[j]["GstP"]);
                        }

                        amt    = SafeValue.ChinaRound(det.Qty * det.Price, 2);
                        gstAmt = SafeValue.ChinaRound((amt * det.Gst), 2);

                        docAmt = amt + gstAmt;

                        locAmt     = SafeValue.ChinaRound(docAmt * det.ExRate, 2);
                        det.GstAmt = gstAmt;
                        det.DocAmt = docAmt;
                        det.LocAmt = locAmt;
                        C2.Manager.ORManager.StartTracking(det, Wilson.ORMapper.InitialState.Inserted);
                        C2.Manager.ORManager.PersistChanges(det);
                    }
                    docId = iv.SequenceId;
                }
                catch
                {
                }
                UpdateMaster(docId);
            }

            Response.Redirect("/opsAccount/ArInvoiceEdit.aspx?no=" + invNo);
        }
    }
    protected void ASPxGridView1_CustomDataCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewCustomDataCallbackEventArgs e)
    {
        string s     = e.Parameters;
        string schId = SafeValue.SafeString(Request.QueryString["SchId"].ToString());
        //string code = SafeValue.SafeString(Request.QueryString["Loc"].ToString());
        string salesman = SafeValue.SafeString(Request.QueryString["Salesman"].ToString());
        string location = SafeValue.SafeString(cmb_Location.Text.Trim());
        string userId   = HttpContext.Current.User.Identity.Name;

        if (s == "Save")
        {
            bool   result = false;
            string soNo   = "";
            string issueN = "";
            for (int i = 0; i < list.Count; i++)
            {
                if (list[i].qty == 0)
                {
                    e.Result = "Fail,Please keyin Qty ";
                    return;
                }
            }
            C2.XAArInvoice inv    = null;
            C2.XAArInvoice inv_Do = null;
            if (list.Count > 0)
            {
                //Create SO
                #region Create So
                Wilson.ORMapper.OPathQuery query = new Wilson.ORMapper.OPathQuery(typeof(WhSchedule), "Id='" + schId + "'");
                WhSchedule sch   = C2.Manager.ORManager.GetObject(query) as WhSchedule;
                bool       isNew = false;
                Wilson.ORMapper.OPathQuery query1 = new Wilson.ORMapper.OPathQuery(typeof(WhTrans), "DoNo='" + 0 + "'");
                WhTrans so = C2.Manager.ORManager.GetObject(query1) as WhTrans;
                if (so == null)
                {
                    isNew = true;
                    so    = new WhTrans();
                    soNo  = C2Setup.GetNextNo("", "SaleOrders", DateTime.Now);
                }


                so.DoNo           = soNo;
                so.DoDate         = DateTime.Now;
                so.PartyId        = sch.PartyId;
                so.PartyName      = sch.PartyName;
                so.Pic            = sch.PartyContact;
                so.PartyAdd       = sch.PartyAdd;
                so.AgentId        = sch.DoctorId;
                so.AgentName      = EzshipHelper.GetPartyName(sch.DoctorId);
                so.NotifyId       = sch.Patient;
                so.NotifyName     = GetPatientName(sch.Patient);
                so.Currency       = "SGD";
                so.DoType         = "SO";
                so.DoStatus       = "Draft";
                so.ExRate         = 1;
                so.SalesId        = salesman;
                so.CreateBy       = userId;
                so.CreateDateTime = DateTime.Now;
                so.UpdateBy       = userId;
                so.UpdateDateTime = DateTime.Now;
                if (isNew)
                {
                    Manager.ORManager.StartTracking(so, Wilson.ORMapper.InitialState.Inserted);
                    Manager.ORManager.PersistChanges(so);
                    C2Setup.SetNextNo("", "SaleOrders", soNo, DateTime.Now);
                }
                else
                {
                    Manager.ORManager.StartTracking(so, Wilson.ORMapper.InitialState.Updated);
                    Manager.ORManager.PersistChanges(so);
                }
                sch.DoNo = soNo;
                string update = string.Format(@"update Wh_Schedule set DoNo='{0}',StatusCode='Finished' where Id='{1}'", soNo, schId);
                C2.Manager.ORManager.ExecuteCommand(update);
                #endregion
                #region Create SO Invoice
                int    invId = 0;
                string invN  = "";
                inv = Manager.ORManager.GetObject(typeof(XAArInvoice), SafeValue.SafeInt(invId, 0)) as XAArInvoice;
                if (inv == null)// first insert invoice
                {
                    string counterType = "AR-IV";
                    inv         = new XAArInvoice();
                    invN        = C2Setup.GetNextNo("", counterType, so.DoDate);
                    inv.PartyTo = SafeValue.SafeString(so.PartyId, "");
                    inv.DocType = "IV";
                    inv.DocNo   = invN.ToString();
                    inv.DocDate = so.DoDate;
                    string[] currentPeriod = EzshipHelper.GetAccPeriod(so.DoDate);

                    inv.AcYear   = SafeValue.SafeInt(currentPeriod[1], so.DoDate.Year);
                    inv.AcPeriod = SafeValue.SafeInt(currentPeriod[0], so.DoDate.Month);
                    inv.Term     = so.PayTerm;

                    //
                    int dueDay = 0;
                    if (so.PayTerm != null)
                    {
                        dueDay = SafeValue.SafeInt(so.PayTerm.ToUpper().Replace("DAYS", ""), 0);
                    }

                    inv.DocDueDate  = inv.DocDate.AddDays(dueDay);//SafeValue.SafeDate(dueDt.Text, DateTime.Now);
                    inv.Description = so.Remark;
                    inv.CurrencyId  = so.Currency;
                    inv.ExRate      = SafeValue.SafeDecimal(so.ExRate, 1);
                    if (inv.ExRate <= 0)
                    {
                        inv.ExRate = 1;
                    }
                    inv.AcCode      = EzshipHelper.GetAccArCode(inv.PartyTo, inv.CurrencyId);
                    inv.AcSource    = "DB";
                    inv.SpecialNote = "";

                    inv.MastType  = "WH";
                    inv.MastRefNo = so.DoNo;
                    inv.JobRefNo  = "";

                    inv.ExportInd  = "N";
                    inv.UserId     = HttpContext.Current.User.Identity.Name;
                    inv.EntryDate  = DateTime.Now;
                    inv.CancelDate = new DateTime(1900, 1, 1);
                    inv.CancelInd  = "N";
                    try
                    {
                        C2.Manager.ORManager.StartTracking(inv, Wilson.ORMapper.InitialState.Inserted);
                        C2.Manager.ORManager.PersistChanges(inv);
                        C2Setup.SetNextNo("", counterType, invN, inv.DocDate);
                    }
                    catch
                    {
                    }
                }
                #endregion
                #region Create DO
                //Create DoNo
                string doId = "";
                Wilson.ORMapper.OPathQuery query2 = new Wilson.ORMapper.OPathQuery(typeof(WhDo), "Id='" + doId + "'");
                WhDo whDo = C2.Manager.ORManager.GetObject(query2) as WhDo;

                if (whDo == null)
                {
                    whDo        = new WhDo();
                    isNew       = true;
                    issueN      = C2Setup.GetNextNo("", "DOOUT", so.DoDate);
                    whDo.DoType = "OUT";
                }
                whDo.DoNo           = issueN;
                whDo.PoNo           = so.DoNo;
                whDo.DoDate         = so.DoDate;
                whDo.PoDate         = so.DoDate;
                whDo.StatusCode     = "CLS";
                whDo.PartyId        = so.PartyId;
                whDo.PartyName      = so.PartyName;
                whDo.AgentId        = so.AgentId;
                whDo.AgentName      = so.AgentName;
                whDo.AgentTel       = so.AgentTel;
                whDo.AgentZip       = so.AgentZip;
                whDo.AgentCountry   = so.AgentCountry;
                whDo.AgentCity      = so.AgentCity;
                whDo.NotifyId       = so.NotifyId;
                whDo.NotifyName     = so.NotifyName;
                whDo.WareHouseId    = location;
                whDo.CreateBy       = so.CreateBy;
                whDo.CreateDateTime = so.CreateDateTime;
                whDo.UpdateBy       = so.UpdateBy;
                whDo.UpdateDateTime = so.UpdateDateTime;
                if (isNew)
                {
                    Manager.ORManager.StartTracking(whDo, Wilson.ORMapper.InitialState.Inserted);
                    Manager.ORManager.PersistChanges(whDo);
                    C2Setup.SetNextNo("", "DOOUT", issueN, DateTime.Now);
                }
                #endregion
                #region Create DO Invoice
                inv_Do = Manager.ORManager.GetObject(typeof(XAArInvoice), SafeValue.SafeInt(invId, 0)) as XAArInvoice;
                if (inv_Do == null)// first insert invoice
                {
                    string counterType = "AR-IV";
                    inv_Do         = new XAArInvoice();
                    invN           = C2Setup.GetNextNo("", counterType, so.DoDate);
                    inv_Do.PartyTo = SafeValue.SafeString(so.PartyId, "");
                    inv_Do.DocType = "IV";
                    inv_Do.DocNo   = invN.ToString();
                    inv_Do.DocDate = so.DoDate;
                    string[] currentPeriod = EzshipHelper.GetAccPeriod(so.DoDate);

                    inv_Do.AcYear   = SafeValue.SafeInt(currentPeriod[1], so.DoDate.Year);
                    inv_Do.AcPeriod = SafeValue.SafeInt(currentPeriod[0], so.DoDate.Month);
                    inv_Do.Term     = so.PayTerm;

                    //
                    int dueDay = 0;
                    if (so.PayTerm != null)
                    {
                        dueDay = SafeValue.SafeInt(so.PayTerm.ToUpper().Replace("DAYS", ""), 0);
                    }

                    inv_Do.DocDueDate  = inv.DocDate.AddDays(dueDay);//SafeValue.SafeDate(dueDt.Text, DateTime.Now);
                    inv_Do.Description = so.Remark;
                    inv_Do.CurrencyId  = so.Currency;
                    inv_Do.ExRate      = SafeValue.SafeDecimal(so.ExRate, 1);
                    if (inv_Do.ExRate <= 0)
                    {
                        inv_Do.ExRate = 1;
                    }
                    inv_Do.AcCode      = EzshipHelper.GetAccArCode(inv.PartyTo, inv.CurrencyId);
                    inv_Do.AcSource    = "DB";
                    inv_Do.SpecialNote = "";

                    inv_Do.MastType  = "WH";
                    inv_Do.MastRefNo = whDo.DoNo;
                    inv_Do.JobRefNo  = "";

                    inv_Do.ExportInd  = "N";
                    inv_Do.UserId     = HttpContext.Current.User.Identity.Name;
                    inv_Do.EntryDate  = DateTime.Now;
                    inv_Do.CancelDate = new DateTime(1900, 1, 1);
                    inv_Do.CancelInd  = "N";
                    try
                    {
                        C2.Manager.ORManager.StartTracking(inv_Do, Wilson.ORMapper.InitialState.Inserted);
                        C2.Manager.ORManager.PersistChanges(inv_Do);
                        C2Setup.SetNextNo("", counterType, invN, inv_Do.DocDate);
                    }
                    catch
                    {
                    }
                }
                #endregion
            }
            #region Create Transfer
            for (int i = 0; i < list.Count; i++)
            {
                string  id      = list[i].id;
                string  product = list[i].product;
                string  lotNo   = list[i].lotNo;
                int     qty     = list[i].qty;
                decimal price   = list[i].price;
                //string loction = list[i].location;
                string des1   = list[i].des1;
                int    hanQty = list[i].hanQty;
                if (qty > hanQty)
                {
                    e.Result = "Fail,Please keyin the correct qty ";
                    return;
                }
                //string salesman = list[i].salesman;
                string sql = @"Insert Into Wh_TransDet(DoNo, DoType,ProductCode,Qty1,Qty2,Qty3,Price,LotNo,Uom1,Uom2,Uom3,Uom4,[QtyPackWhole],[QtyWholeLoose],[QtyLooseBase],[CreateBy],[CreateDateTime],[UpdateBy],[UpdateDateTime],Att1,Att2,Att3,Att4,Att5,Att6,Des1,LocationCode,DocAmt)";
                sql += string.Format(@"select '{0}'as DoNo, 'SO' as DoType,'{1}' as ProductCode
 ,'{2}' as Qty1
 ,0 as Qty2
 ,0 as Qty3
 ,'{3}' as Price
,'{4}' as LotNo
,ref.UomPacking as Uom1,ref.UomWhole as Uom2,ref.UomLoose as Uom3,ref.UomBase as Uom4
,ref.QtyPackingWhole as QtyPackWhole,ref.QtyWholeLoose as  QtyWholeLoose,ref.QtyLooseBase as QtyLooseBase
,'{5}' as CreateBy,getdate() as CreateDateTime,'{5}' as UpdateBy,getdate() as UpdateDateTime
,ref.Att4 as Att1,ref.Att5 as Att2,ref.att6 as Att3,ref.att7 as Att4,ref.att8 as Att5,ref.att9 as Att6,ref.Description as Des1,'{6}' as LocationCode,{2}*{3} as DocAmt
from (select '{1}' as Sku) as tab inner join ref_product ref on ref.Code=tab.Sku", soNo, product, qty, price, lotNo, EzshipHelper.GetUserName(), location);
                C2.Manager.ORManager.ExecuteCommand(sql);

                sql  = @"Insert Into wh_DoDet(JobStatus,DoNo, DoType,ProductCode,ExpiredDate,Price,Qty1,Qty2,Qty3,Qty4,Qty5,LotNo,BatchNo,CustomsLot,Uom1,Uom2,Uom3,Uom4,[QtyPackWhole],[QtyWholeLoose],[QtyLooseBase],Att1,Att2,Att3,Att4,Att5,Att6,Att7,Att8,Att9,Att10,Des1,Packing,[CreateBy],[CreateDateTime],[UpdateBy],[UpdateDateTime],DoInId)";
                sql += string.Format(@" select * from (select 'Picked' as JobStatus,'{1}'as DoNo, 'Out' as DoType,ProductCode,ExpiredDate,Price
,Qty1 as Qty1
,0 as Qty2
,0 as Qty3
,Qty1 as Qty4
,0 as Qty5
, LotNo,BatchNo,CustomsLot,Uom1,Uom2,Uom3,Uom4,[QtyPackWhole],[QtyWholeLoose],[QtyLooseBase],Att1,Att2,Att3,Att4,Att5,Att6,Att7,Att8,Att9,Att10,Des1,Packing,'{2}' as CreateBy,getdate() as CreateDateTime,'{2}' as UpdateBy,getdate() as UpdateDateTime,Id as DoInId from Wh_TransDet where DoNo='{0}' and ProductCode='{4}' and LotNo='{5}' and DoType='SO' and LocationCode='{3}'
 ) as tab_aa where qty4>0  ", soNo, issueN, userId, location, product, lotNo);

                C2.Manager.ORManager.ExecuteCommand(sql);

                sql  = @"Insert Into Wh_DoDet2(DoNo,DoType,Product,Qty1,Qty2,Qty3,Price,LotNo,Uom1,Uom2,Uom3,Uom4,[QtyPackWhole],[QtyWholeLoose],[QtyLooseBase],[CreateBy],[CreateDateTime],[UpdateBy],[UpdateDateTime],Att1,Att2,Att3,Att4,Att5,Att6,Des1,Packing,Location,ProcessStatus)";
                sql += string.Format(@"select '{0}'as DoNo, 'OUT' as DoType,'{1}' as Sku
 ,'{2}' as Qty1
 ,0 as Qty2
 ,0 as Qty3
 ,'{3}' as Price
,'{4}' as LotNo
,ref.UomPacking as Uom1,ref.UomWhole as Uom2,ref.UomLoose as Uom3,ref.UomBase as Uom4
,ref.QtyPackingWhole as QtyPackWhole,ref.QtyWholeLoose as  QtyWholeLoose,ref.QtyLooseBase as QtyLooseBase
,'{5}' as CreateBy,getdate() as CreateDateTime,'{5}' as UpdateBy,getdate() as UpdateDateTime
,ref.Att4 as Att1,ref.Att5 as Att2,ref.att6 as Att3,ref.att7 as Att4,ref.att8 as Att5,ref.att9 as Att6,ref.Description as Des1,'' as Packing,'{6}' as Location,'Delivered' as ProcessStatus
from (select '{1}' as Sku) as tab inner join ref_product ref on ref.Code=tab.Sku", issueN, product, qty, price, lotNo, userId, location);
                C2.Manager.ORManager.ExecuteCommand(sql);
                InsertInv_Det(inv.SequenceId, inv.DocNo, i + 1, product, lotNo, des1, qty, price, inv.CurrencyId, inv.ExRate, 0, inv.MastRefNo, "", inv.MastType, "IV");
                UpdateMaster(inv.SequenceId);

                InsertInv_Det(inv_Do.SequenceId, inv_Do.DocNo, i + 1, product, lotNo, des1, qty, price, inv_Do.CurrencyId, inv_Do.ExRate, 0, inv_Do.MastRefNo, "", inv_Do.MastType, "IV");
                UpdateMaster(inv_Do.SequenceId);
                if (soNo.Length > 0)
                {
                    result = true;
                }
            }
            #endregion
            if (result)
            {
                e.Result = soNo;
            }
            else
            {
                e.Result = "Fail,Please keyin select product ";
            }
        }
    }
示例#7
0
    protected void ASPxGridView1_CustomCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewCustomCallbackEventArgs e)
    {
        ASPxTextBox  invNCtr  = this.ASPxGridView1.FindEditFormTemplateControl("txt_Oid") as ASPxTextBox;
        ASPxComboBox partyTo  = this.ASPxGridView1.FindEditFormTemplateControl("cmb_PartyTo") as ASPxComboBox;
        ASPxTextBox  docN     = this.ASPxGridView1.FindEditFormTemplateControl("txt_DocNo") as ASPxTextBox;
        ASPxComboBox docType  = this.ASPxGridView1.FindEditFormTemplateControl("cbo_DocType") as ASPxComboBox;
        ASPxDateEdit docDate  = this.ASPxGridView1.FindEditFormTemplateControl("txt_DocDt") as ASPxDateEdit;
        ASPxMemo     remarks1 = this.ASPxGridView1.FindEditFormTemplateControl("txt_Remarks1") as ASPxMemo;
        ASPxComboBox termId   = this.ASPxGridView1.FindEditFormTemplateControl("txt_TermId") as ASPxComboBox;
        ASPxDateEdit dueDt    = this.ASPxGridView1.FindEditFormTemplateControl("txt_DueDt") as ASPxDateEdit;
        ASPxTextBox  docCurr  = this.ASPxGridView1.FindEditFormTemplateControl("txt_Currency") as ASPxTextBox;
        ASPxSpinEdit exRate   = this.ASPxGridView1.FindEditFormTemplateControl("txt_DocExRate") as ASPxSpinEdit;
        ASPxTextBox  acCode   = this.ASPxGridView1.FindEditFormTemplateControl("txt_AcCode") as ASPxTextBox;
        ASPxComboBox acSource = this.ASPxGridView1.FindEditFormTemplateControl("txt_AcSource") as ASPxComboBox;
        string       invN     = docN.Text;

        C2.XAArInvoice inv   = Manager.ORManager.GetObject(typeof(XAArInvoice), SafeValue.SafeInt(invNCtr.Text, 0)) as XAArInvoice;
        bool           isNew = false;

        if (inv == null)        // first insert invoice
        {
            isNew = true;
            string counterType = "AR-CN";

            inv         = new XAArInvoice();
            invN        = C2Setup.GetNextNo(counterType);
            inv.PartyTo = SafeValue.SafeString(partyTo.Value, "");
            inv.DocType = docType.Value.ToString();
            inv.DocNo   = invN.ToString();
            inv.DocDate = docDate.Date;
            string[] currentPeriod = EzshipHelper.GetAccPeriod(docDate.Date);

            inv.AcYear   = SafeValue.SafeInt(currentPeriod[1], docDate.Date.Year);
            inv.AcPeriod = SafeValue.SafeInt(currentPeriod[0], docDate.Date.Month);
            inv.Term     = termId.Text;
            int dueDay = SafeValue.SafeInt(termId.Text.ToUpper().Replace("DAYS", "").Trim(), 0);
            inv.DocDueDate  = inv.DocDate.AddDays(dueDay);           //SafeValue.SafeDate(dueDt.Text, DateTime.Now);
            inv.Description = remarks1.Text;
            inv.CurrencyId  = docCurr.Text.ToString();
            inv.ExRate      = SafeValue.SafeDecimal(exRate.Value, 1);
            if (inv.ExRate <= 0)
            {
                inv.ExRate = 1;
            }
            inv.AcSource = acSource.Value.ToString();

            inv.ExportInd  = "N";
            inv.UserId     = HttpContext.Current.User.Identity.Name;
            inv.EntryDate  = DateTime.Now;
            inv.CancelDate = new DateTime(1900, 1, 1);
            inv.CancelInd  = "N";
            inv.MastRefNo  = "0";
            inv.JobRefNo   = "0";
            inv.MastType   = "";

            inv.AcCode = EzshipHelper.GetAccArCode(inv.PartyTo, inv.CurrencyId);
            try
            {
                C2.Manager.ORManager.StartTracking(inv, Wilson.ORMapper.InitialState.Inserted);
                C2.Manager.ORManager.PersistChanges(inv);
                C2Setup.SetNextNo(counterType, invN);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message + ex.StackTrace);
            }
        }
        else
        {
            inv.PartyTo = SafeValue.SafeString(partyTo.Value, "");

            inv.Term    = termId.Text;
            inv.DocDate = docDate.Date;
            string[] currentPeriod = EzshipHelper.GetAccPeriod(docDate.Date);

            inv.AcYear   = SafeValue.SafeInt(currentPeriod[1], docDate.Date.Year);
            inv.AcPeriod = SafeValue.SafeInt(currentPeriod[0], docDate.Date.Month);
            int dueDay = SafeValue.SafeInt(termId.Text.ToUpper().Replace("DAYS", "").Trim(), 0);
            inv.DocDueDate  = inv.DocDate.AddDays(dueDay);//SafeValue.SafeDate(dueDt.Text, DateTime.Now);
            inv.Description = remarks1.Text;
            inv.CurrencyId  = docCurr.Text.ToString();
            inv.ExRate      = SafeValue.SafeDecimal(exRate.Value, 1);
            if (inv.ExRate <= 0)
            {
                inv.ExRate = 1;
            }
            inv.AcSource = acSource.Text;

            inv.AcCode = EzshipHelper.GetAccArCode(inv.PartyTo, inv.CurrencyId);
            try
            {
                Manager.ORManager.StartTracking(inv, InitialState.Updated);
                Manager.ORManager.PersistChanges(inv);
                UpdateMaster(inv.SequenceId);
            }
            catch
            {
            }
        }
        if (isNew)
        {
            Session["CnEditWhere"]            = "SequenceId=" + inv.SequenceId;
            this.dsArInvoice.FilterExpression = Session["CnEditWhere"].ToString();
            if (this.ASPxGridView1.GetRow(0) != null)
            {
                this.ASPxGridView1.StartEdit(0);
            }
        }
    }
    /// <summary>
    /// if dotype=in, then calc lastschqty and preqty
    /// if dotype=out , calc preqty
    /// don't calc the transfer data(which dono='').
    /// for do in
    /// if isSch= N , only get lastSchQty
    /// if isSch=Y , need LastSchQty and qty-preQty
    /// for do out
    /// only get the qty-preqty
    ///
    /// update create invoice,
    /// update preqty=qty,lastschqty=inqty-outqty where dotype=in and dono!=''
    /// update preqty=qty,lastschqty=0 where dotype=out and dono!=''
    /// </summary>

    protected void btn_CreateIV_Click1(object sender, EventArgs e)
    {
        //1: issch=false , the qty=qty1   n=schdate-dodate
        //2:issch=true, qty=lastschqty    n=currentschdate-lastschdate
        //3:issch=true, qty=qty-preqty    n=schdate-dodate

        string sql = @"select * from (select mast.DoNo,mast.DoDate,mast.DoType,mast.PartyId,mast.Quotation as ContractNo,det.Product as Sku,det.LotNo
,Case when isnull(det.isSch,0)=0 then isnull(det.Qty1,0)  else isnull(det.Qty1,0)-isnull(det.PreQty1,0) end  as Qty1
,Case when isnull(det.isSch,0)=0 then isnull(det.Qty2,0)  else isnull(det.Qty2,0)-isnull(det.PreQty2,0) end  as Qty2
,Case when isnull(det.isSch,0)=0 then isnull(det.Qty3,0)  else isnull(det.Qty3,0)-isnull(det.PreQty3,0) end  as Qty3

,Case when isnull(det.isSch,0)=1 and det.DoType='IN' then isnull(det.LastSchQty1,0)  else 0 end  as LastSchQty1
,Case when isnull(det.isSch,0)=1 and det.DoType='IN' then isnull(det.LastSchQty2,0)  else 0 end  as LastSchQty2
,Case when isnull(det.isSch,0)=1 and det.DoType='IN' then isnull(det.LastSchQty3,0)  else 0 end  as LastSchQty3
,det.IsSch,det.LastSchDate,ref.ArCode,ref.Description
 from wh_dodet2 det 
inner join wh_do mast on mast.DoNo=det.DoNo and mast.DoType=det.Dotype
inner join ref_product ref on ref.Code=det.Product
where mast.StatusCode!='CNL' and len(isnull(det.DoNo,''))>0
) as tab where (Qty1+Qty2+Qty3>0 or LastSchQty1+LastSchQty2+LastSchQty3>0)
order by PartyId,DoDate,DoNo";
        //one customer only have one invoice
        DataTable tab         = ConnectSql.GetTab(sql);
        string    lastPartyId = "";
        int       lastInvId   = 0;
        string    lastInvNo   = "";

        for (int i = 0; i < tab.Rows.Count; i++)
        {
            string   sku         = SafeValue.SafeString(tab.Rows[i]["Sku"]);
            string   lotNo       = SafeValue.SafeString(tab.Rows[i]["LotNo"]);
            string   contractNo  = SafeValue.SafeString(tab.Rows[i]["ContractNo"]);
            DateTime doDate      = SafeValue.SafeDate(tab.Rows[i]["DoDate"], DateTime.Today);
            string   partyId     = SafeValue.SafeString(tab.Rows[i]["PartyId"]);
            int      qty1        = SafeValue.SafeInt(tab.Rows[i]["Qty1"], 0);
            int      qty2        = SafeValue.SafeInt(tab.Rows[i]["Qty2"], 0);
            int      qty3        = SafeValue.SafeInt(tab.Rows[i]["Qty3"], 0);
            bool     isSch       = SafeValue.SafeBool(tab.Rows[i]["IsSch"], false);
            DateTime lastSchDate = SafeValue.SafeDate(tab.Rows[i]["LastSchDate"], DateTime.Today);
            int      LastSchQty1 = SafeValue.SafeInt(tab.Rows[i]["LastSchQty1"], 0);
            int      LastSchQty2 = SafeValue.SafeInt(tab.Rows[i]["LastSchQty2"], 0);
            int      LastSchQty3 = SafeValue.SafeInt(tab.Rows[i]["LastSchQty3"], 0);
            string   doType      = SafeValue.SafeString(tab.Rows[i]["DoType"]).ToUpper();
            string   arCode      = SafeValue.SafeString(tab.Rows[i]["ArCode"]);
            string   des         = SafeValue.SafeString(tab.Rows[i]["Description"]);
            //DateTime peroidDate = SafeValue.SafeDate(tab.Rows[i]["PeroidDate"], DateTime.Today);
            //string refNo = SafeValue.SafeString(tab.Rows[i]["DoNo"]);
            //int detId = SafeValue.SafeInt(tab.Rows[i]["detId"], 0);
            //int preQty = SafeValue.SafeInt(tab.Rows[i]["PreQty"], 0);
            //int lastSchQty = SafeValue.SafeInt(tab.Rows[i]["LastSchQty"], 0);
            //string IsSch = SafeValue.SafeString(tab.Rows[i]["IsSch"]);
            decimal   price1    = 0;
            decimal   price2    = 0;
            decimal   price3    = 0;
            int       dailyNo   = 0;
            bool      isFixed   = false;
            bool      isYearly  = false;
            bool      isMonthly = false;
            bool      isWeekly  = false;
            bool      isDaily   = false;
            DateTime  dt        = DateTime.Today;
            DataTable tab1      = new DataTable();
            if (doType == "IN")
            {
                tab1 = GetContractByNo(contractNo, sku);
            }
            else//out get contractno, by sku,lotno>>dotype=in, doNo>>PO no>> get ContractNo
            {
                string conNo = string.Format(@"select Quotation from wh_do mast 
inner join Wh_DoDet2 det on det.DoNo=mast.DoNo and det.DoType=mast.DoType 
 where det.DoType='in' and det.Product='{0}' and det.LotNo='{1}' and len(det.DoNo)>0", sku, lotNo);

                tab1 = GetContractByNo(SafeValue.SafeString(C2.Manager.ORManager.ExecuteScalar(conNo)), sku);
            }
            int n     = 0;
            int n_sch = 0;
            for (int j = 0; j < tab1.Rows.Count; j++)
            {
                isFixed   = SafeValue.SafeBool(tab1.Rows[j]["IsFixed"], true);
                isYearly  = SafeValue.SafeBool(tab1.Rows[j]["IsYearly"], true);
                isMonthly = SafeValue.SafeBool(tab1.Rows[j]["IsMonthly"], true);
                isWeekly  = SafeValue.SafeBool(tab1.Rows[j]["IsWeekly"], true);
                isDaily   = SafeValue.SafeBool(tab1.Rows[j]["IsDaily"], true);
                #region get sch and price
                if (isYearly)
                {
                    TimeSpan span = dt - doDate;
                    if (dt.ToString("MM-dd") == "01-01")
                    {
                        n = SafeValue.SafeInt(dt.Year - doDate.Year, 0);
                        if (isSch)
                        {
                            n_sch = SafeValue.SafeInt(dt.Year - lastSchDate.Year, 0);
                        }
                        price1 = SafeValue.SafeDecimal(tab1.Rows[j]["Price1"]);
                        price2 = SafeValue.SafeDecimal(tab1.Rows[j]["Price2"]);
                        price3 = SafeValue.SafeDecimal(tab1.Rows[j]["Price3"]);
                    }
                    else
                    {
                        continue;
                    }
                }
                else if (isMonthly)
                {
                    if (dt.ToString("dd") == "01")
                    {
                        price1 = SafeValue.SafeDecimal(tab1.Rows[j]["Price1"]);
                        price2 = SafeValue.SafeDecimal(tab1.Rows[j]["Price2"]);
                        price3 = SafeValue.SafeDecimal(tab1.Rows[j]["Price3"]);
                        int year = dt.Year;
                        n = (dt.Year - doDate.Year) * 12 + dt.Month - doDate.Month;
                        if (isSch)
                        {
                            n_sch = (dt.Year - lastSchDate.Year) * 12 + dt.Month - lastSchDate.Month;
                        }
                    }
                    else
                    {
                        continue;
                    }
                }
                else if (isWeekly)
                {
                    if (dt.DayOfWeek == DayOfWeek.Monday)
                    {
                        price1 = SafeValue.SafeDecimal(tab1.Rows[j]["Price1"]);
                        price2 = SafeValue.SafeDecimal(tab1.Rows[j]["Price2"]);
                        price3 = SafeValue.SafeDecimal(tab1.Rows[j]["Price3"]);

                        TimeSpan day = GetMondayByDate(dt) - GetMondayByDate(doDate);
                        n = SafeValue.SafeInt(day.TotalDays / 7, 0);
                        if (isSch)
                        {
                            day   = GetMondayByDate(dt) - GetMondayByDate(lastSchDate);
                            n_sch = SafeValue.SafeInt(day.TotalDays / 7, 0);
                        }
                    }
                    else
                    {
                        continue;
                    }
                }
                else if (isDaily)
                {
                    dailyNo = SafeValue.SafeInt(tab1.Rows[j]["DailyNo"], 1);
                    if (dailyNo == 0)
                    {
                        dailyNo = 1;
                    }

                    TimeSpan day = dt.Date - doDate.Date;
                    if (day.Days % dailyNo == 0)
                    {
                        price1 = SafeValue.SafeDecimal(tab1.Rows[j]["Price1"]);
                        price2 = SafeValue.SafeDecimal(tab1.Rows[j]["Price2"]);
                        price3 = SafeValue.SafeDecimal(tab1.Rows[j]["Price3"]);
                        n      = SafeValue.SafeInt(day.TotalDays / dailyNo, 0);
                        if (isSch)
                        {
                            day   = dt.Date - lastSchDate.Date;
                            n_sch = SafeValue.SafeInt(day.TotalDays / dailyNo, 0);
                        }
                    }
                    else
                    {
                        continue;
                    }
                }

                #endregion

                XAArInvoice iv       = null;
                string      mastType = "WH";
                if (lastInvId == 0 || lastPartyId != partyId) //is the frist invoice or is next party then generate new invoice
                {
                    if (lastInvId > 0)                        //update last invoice ,set linelocamat, and mast.docamt/locamt/balanceamt
                    {
                        UpdateMaster(lastInvId);
                    }
                    #region generate invoice
                    iv = new XAArInvoice();
                    string counterType = "AR-IV";

                    iv.DocType     = "IV";
                    iv.DocDate     = dt;
                    lastInvNo      = C2Setup.GetNextNo(iv.DocType, counterType, iv.DocDate);
                    iv.DocNo       = lastInvNo;
                    iv.PartyTo     = partyId;
                    iv.CurrencyId  = System.Configuration.ConfigurationManager.AppSettings["Currency"];
                    iv.ExRate      = 1;
                    iv.AcCode      = EzshipHelper.GetAccApCode(iv.PartyTo, iv.CurrencyId);
                    iv.AcSource    = "DB";
                    iv.Description = "";
                    iv.Term        = "CASH";

                    string[] currentPeriod = EzshipHelper.GetAccPeriod(iv.DocDate);
                    iv.AcYear   = SafeValue.SafeInt(currentPeriod[1], iv.DocDate.Year);
                    iv.AcPeriod = SafeValue.SafeInt(currentPeriod[0], iv.DocDate.Month);

                    iv.MastRefNo   = "";
                    iv.JobRefNo    = "";
                    iv.MastType    = mastType;
                    iv.DocAmt      = 0;
                    iv.LocAmt      = 0;
                    iv.BalanceAmt  = 0;
                    iv.CancelDate  = new DateTime(1900, 1, 1);
                    iv.CancelInd   = "N";
                    iv.DocDueDate  = dt;
                    iv.ExportInd   = "N";
                    iv.SpecialNote = "";
                    iv.UserId      = EzshipHelper.GetUserName();
                    iv.EntryDate   = DateTime.Now;

                    C2.Manager.ORManager.StartTracking(iv, Wilson.ORMapper.InitialState.Inserted);
                    C2.Manager.ORManager.PersistChanges(iv);
                    C2Setup.SetNextNo(iv.DocType, counterType, lastInvNo, iv.DocDate);
                    lastInvId = iv.SequenceId;
                    #endregion
                }
                if (doType == "OUT") // form modify the qty
                {
                    qty1        = -qty1;
                    qty2        = -qty2;
                    qty3        = -qty3;
                    LastSchQty1 = 0;
                    LastSchQty2 = 0;
                    LastSchQty3 = 0;
                }
                lastPartyId = partyId;
                #region create det
                if (isFixed)// only do one time
                {
                    int cnt = SafeValue.SafeInt(ConnectSql.ExecuteScalar(string.Format("select count(*) from XAArInvoiceDet where DocId='{0}' and ChgDes1 like 'SKU {1}%,'", lastInvId, sku)), 0);
                    if (cnt == 0)//sku balQty>0
                    {
                        int count = SafeValue.SafeInt(C2.Manager.ORManager.ExecuteScalar(string.Format("select sum(case when DoType='in' then Qty1 else -qty1 end) as cnt from wh_dodet2 where Product='{0}'", sku)), 0);
                        InsertInv_det(lastInvId, lastInvNo, mastType, 1, price1 + price2 + price3, sku, arCode, des, lotNo);
                    }
                }
                else
                {
                    if (qty1 * n + LastSchQty1 * n_sch != 0)
                    {
                        InsertInv_det(lastInvId, lastInvNo, mastType, qty1 * n + LastSchQty1 * n_sch, price1, sku, arCode, des, lotNo);
                    }
                    if (qty2 * n + LastSchQty2 * n_sch != 0)
                    {
                        InsertInv_det(lastInvId, lastInvNo, mastType, qty2 * n + LastSchQty2 * n_sch, price2, sku, arCode, des, lotNo);
                    }
                    if (qty3 * n + LastSchQty3 * n_sch != 0)
                    {
                        InsertInv_det(lastInvId, lastInvNo, mastType, qty3 * n + LastSchQty3 * n_sch, price3, sku, arCode, des, lotNo);
                    }
                }
                #endregion
                UpdateDoDet(sku, lotNo, doType);
            }
        }
    }