Exemplo n.º 1
0
        /// <summary>
        /// Checks all lines of a Sales Order to make sure all CI and CII drugs has a 222 form attached
        ///
        /// </summary>
        /// <param name="so"></param>
        /// <returns></returns>
        public bool ControlLinesHas222(SOHeader so)

        {
            int          errcount    = 0;
            IObjectSpace objectSpace = this.application.CreateObjectSpace(typeof(SODetails));
            // int goodcount = 0;

            CriteriaOperator op  = CriteriaOperator.Parse("SalesOrder = ?", so.SalesOrderNumber);
            IList            SOD = objectSpace.GetObjects(typeof(SODetails), op);

            foreach (SODetails sod in SOD)
            {
                if (sod.ItemNumber.ItemNumber.DeaClass == DeaClassEnum.CII || sod.ItemNumber.ItemNumber.DeaClass == DeaClassEnum.CI)
                {
                    if (sod.Form222Img.Length <= 100)
                    {
                        errcount++;
                    }
                }
            }
            if (errcount == 0)
            {
                return(success);
            }

            return(failed);
        }
Exemplo n.º 2
0
        public async Task <IActionResult> PutSOHeader([FromRoute] int id, [FromBody] SOHeader sOHeader)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != sOHeader.SOHeaderID)
            {
                return(BadRequest());
            }

            _context.Entry(sOHeader).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!SOHeaderExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
Exemplo n.º 3
0
        //public ActionResult ReadDetail([DataSourceRequest] DataSourceRequest request, string SONumber)
        //{
        //    log4net.Config.XmlConfigurator.Configure();
        //    string whereCondition = "";
        //    if (request.Filters.Count > 0)
        //    {
        //        whereCondition = " AND " + new KendoApplyFilter().ApplyFilter(request.Filters[0]);
        //    }
        //    var data = new DC_AD_SO_Detail().GetPage(request, whereCondition, SONumber);
        //    return Json(data);
        //}
        public ActionResult Update([DataSourceRequest] DataSourceRequest request, [Bind(Prefix = "models")] IEnumerable <Products> list, string SONumber)
        {
            var dbConn = new OrmliteConnection().openConn();

            try
            {
                if (list != null && ModelState.IsValid)
                {
                    foreach (var item in list)
                    {
                        if (item.Qty > 0)
                        {
                            //string SONumber = Request["SONumber"];
                            var header = new SOHeader();
                            var detail = new SODetail();

                            if (dbConn.Select <SODetail>(s => s.SONumber == SONumber && s.ItemCode == item.Code).Count() > 0)
                            {
                                dbConn.Update <SODetail>(set: "Qty = '" + item.Qty + "', TotalAmt = '" + item.Qty * item.Price + "'", where : "SONumber = '" + SONumber + "'");
                            }
                            else
                            {
                                var data = new SODetail();
                                data.ItemName  = item.Name;
                                data.ItemCode  = item.Code;
                                data.Note      = "";
                                data.Price     = item.VATPrice;
                                data.Qty       = item.Qty;
                                data.SONumber  = SONumber;
                                data.UnitID    = item.Unit;
                                data.UnitName  = dbConn.Select <INUnit>(s => s.UnitID == item.Unit).FirstOrDefault().UnitName;
                                data.TotalAmt  = item.Qty * item.VATPrice;
                                data.Status    = "";
                                data.CreatedAt = DateTime.Now;
                                data.CreatedBy = currentUser.UserID;
                                //data.UpdatedAt = DateTime.Parse("1900-01-01");
                                data.UpdatedAt = DateTime.Now;
                                data.UpdatedBy = "";
                                dbConn.Insert <SODetail>(data);
                            }
                            dbConn.Update <SOHeader>(set: "TotalQty ='" + dbConn.Select <SODetail>(s => s.SONumber == SONumber).Sum(s => s.Qty) + "', TotalAmt = '" + +dbConn.Select <SODetail>(s => s.SONumber == SONumber).Sum(s => s.TotalAmt) + "'", where : "SONumber ='" + SONumber + "'");
                        }
                        else
                        {
                            dbConn.Delete <SOHeader>(s => s.SONumber == SONumber);
                            ModelState.AddModelError("error", "Đơn hàng được tạo khi số lượng > 0");
                            return(Json(list.ToDataSourceResult(request, ModelState)));
                        }
                    }
                }
                dbConn.Close();
            }
            catch (Exception e)
            {
                dbConn.Close();
                ModelState.AddModelError("error", e.Message);
                return(Json(list.ToDataSourceResult(request, ModelState)));
            }
            return(Json(new { sussess = true }));
        }
        public async Task <IActionResult> Edit(int id, [Bind("SOHeaderID,MemberID,NamaMember,Tanggal")] SOHeader sOHeader)
        {
            if (id != sOHeader.SOHeaderID)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(sOHeader);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!SOHeaderExists(sOHeader.SOHeaderID))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            ViewData["MemberID"] = new SelectList(_context.Member, "MemberID", "MemberID", sOHeader.MemberID);
            return(View(sOHeader));
        }
Exemplo n.º 5
0
        public async Task <IActionResult> PostSOHeader([FromBody] SOHeader sOHeader)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            _context.SOHeader.Add(sOHeader);
            await _context.SaveChangesAsync();

            return(CreatedAtAction("GetSOHeader", new { id = sOHeader.SOHeaderID }, sOHeader));
        }
        public async Task <IActionResult> Create([Bind("SOHeaderID,MemberID,NamaMember,Tanggal")] SOHeader sOHeader)
        {
            if (ModelState.IsValid)
            {
                _context.Add(sOHeader);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            ViewData["MemberID"] = new SelectList(_context.Member, "MemberID", "MemberID", sOHeader.MemberID);
            return(View(sOHeader));
        }
Exemplo n.º 7
0
        private void SOPack_CustomizePopupWindowParams(object sender, CustomizePopupWindowParamsEventArgs e)
        {
            TargetViewId = "SOHeader_DetailView_Packing";
            IObjectSpace objectSpace = Application.CreateObjectSpace();
            SOHeader     SOH         = objectSpace.CreateObject <SOHeader>();

            SOH            = objectSpace.GetObject <SOHeader>((SOHeader)View.CurrentObject);
            SOH.Scan       = "";
            e.View         = Application.CreateDetailView(objectSpace, TargetViewId, true, SOH);
            e.View.Caption = e.View.Caption + " - " + SOH.CustomerNumber.CustomerName;
            e.View.ObjectSpace.ObjectChanged += ObjectSpace_ObjectChanged;
        }
Exemplo n.º 8
0
        /// <summary>
        /// Checks for the following
        /// 1) valid DEA Number and Exp Date
        /// 2) Has a State License and state Exp date or state Pharma License
        /// 3) whse has license to ship into cust state.
        /// 4) All CI and CII drugs has a 222 form attached.
        ///
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <returns></returns>
        public int SoComplianceCheck(SOHeader SO, out string erromsg)
        {
            string errmsg   = "";
            int    errcount = 0;

            // Check dea

            if (IsValidDEANumber(SO.CustomerNumber.DeaNo) < 0)
            {
                errcount++;
                errmsg = errmsg + "(" + errcount.ToString() + ") Invalid Dea Number. Does not comply with the format  of  AA####### ." + Environment.NewLine;
            }


            if (!(SO.CustomerNumber.DeaExpDate >= DateTime.Now))
            {
                errcount++;
                errmsg = errmsg + "(" + errcount.ToString() + ") Expired DEA Number '" + SO.CustomerNumber.DeaExpDate + "' " + Environment.NewLine;
            }
            if (string.IsNullOrEmpty(SO.CustomerNumber.StateLicense) || SO.CustomerNumber.StateLicense.Trim().Length < 4)
            {
                errcount++;
                errmsg = errmsg + "(" + errcount.ToString() + ") Invalid State License Must be longer then 4" + Environment.NewLine;
            }
            if (!(SO.CustomerNumber.StateLicExpDate >= DateTime.Now))
            {
                errcount++;
                errmsg = errmsg + "(" + errcount.ToString() + ") Expired State License '" + SO.CustomerNumber.DeaExpDate + "' " + Environment.NewLine;
            }
            if (!AbleToShipInto(SO.DistributionCenterWhse.DistributionCenter, SO.CustomerNumber.ShipState))
            {
                errcount++;
                errmsg = errmsg + "(" + errcount.ToString() + ")" + string.Format("Unable to ship into ? from ? ", SO.CustomerNumber.ShipState.StateCode, SO.DistributionCenterWhse.DistributionCenter.DCName) + Environment.NewLine;
            }
            if (!ControlLinesHas222(SO))
            {
                errcount++;
                errmsg = errmsg + "(" + errcount.ToString() + ") No 222 Form attached" + Environment.NewLine;
            }

            SO.LastComplianceMsg = errmsg;
            SO.Save();

            if (errcount > 0)
            {
                erromsg = errmsg;
                SO.CustomerNumber.AddNote(SO.CustomerNumber, errmsg);
                return(errcount);
            }
            erromsg = "";
            return(0);
        }
Exemplo n.º 9
0
        private void SalesOrderPopup_Execute(object sender, PopupWindowShowActionExecuteEventArgs e)
        {
            SOHeader       so = (SOHeader)e.PopupWindowViewCurrentObject;
            string         erromsg;
            ComplianceBL   CBL     = new ComplianceBL(Application);
            MessageOptions options = new MessageOptions();

            if (CBL.SoComplianceCheck(so, out erromsg) == 0)
            {
                options.Duration     = 20000;
                options.Message      = string.Format("Sales Order for {0} has been entered", so.CustomerNumber.CustomerName);
                options.Type         = InformationType.Success;
                options.Web.Position = InformationPosition.Right;
                options.Win.Caption  = "Success";
                options.Win.Type     = WinMessageType.Alert;
                so.SOStatus          = SalesOrderStatus.Submitted;
                if (so.SalesOrderNumber == null || so.SalesOrderNumber?.Length < 2)
                {
                    so.SalesOrderNumber = so.AccountingSONumber;
                }

                so.Save();
            }
            else
            {
                options.Duration     = 20000;
                options.Message      = string.Format("Sales Order for {0} has been entered is in Compliance due to the following {1}", so.CustomerNumber.CustomerName, erromsg);
                options.Type         = InformationType.Warning;
                options.Web.Position = InformationPosition.Right;
                options.Win.Caption  = "Success Need Compliance";
                options.Win.Type     = WinMessageType.Alert;
                so.SOStatus          = SalesOrderStatus.ComplianceCheck;
                if (so.SalesOrderNumber == null || so.SalesOrderNumber?.Length < 2)
                {
                    so.SalesOrderNumber = so.AccountingSONumber;
                }

                so.Save();
            }
            Application.ShowViewStrategy.ShowMessage(options);
            string msg = string.Format("Sales order: {2} entered by {0} {1} ", SecuritySystem.CurrentUserName, System.Environment.NewLine, so.SalesOrderNumber);

            foreach (SODetails det in so.SODetails)
            {
                msg = msg + string.Format(det.ItemNumber.ItemNumber.ToString() + " {0:C2} @ {1} {2} ", det.QtyOrdered, det.UnitPrice, System.Environment.NewLine);
            }
            so.CustomerNumber.AddNote(so.CustomerNumber, msg);
            so.Session.CommitTransaction();


            View.Refresh();
        }
Exemplo n.º 10
0
        private void popupWindowShowAction1_CustomizePopupWindowParams(object sender, CustomizePopupWindowParamsEventArgs e)
        {
            TargetViewId = "SODetails_DetailView_NewLine";
            View.ObjectSpace.CommitChanges();



            IObjectSpace objectSpace = Application.CreateObjectSpace();
            SODetails    SOD         = objectSpace.CreateObject <SODetails>();

            PropertyCollectionSource collectionSource = (PropertyCollectionSource)((ListView)View).CollectionSource;
            SOHeader header = (SOHeader)collectionSource.MasterObject;

            SOD.SalesOrder = objectSpace.GetObject <SOHeader>(header);
            e.View         = Application.CreateDetailView(objectSpace, TargetViewId, true, SOD);
        }
Exemplo n.º 11
0
        private void SalesOrderPopup_CustomizePopupWindowParams(object sender, CustomizePopupWindowParamsEventArgs e)
        {
            TargetViewId = "SOHeader_NewSO";
            IObjectSpace objectSpace = Application.CreateObjectSpace();
            SOHeader     newOrder    = objectSpace.CreateObject <SOHeader>();

            newOrder.CustomerNumber   = objectSpace.GetObject <Customer>((Customer)View.CurrentObject);
            newOrder.SalesRep         = newOrder.CustomerNumber.SalesRep;
            newOrder.SalesOrderDate   = DateTime.Now;
            newOrder.SOStatus         = SalesOrderStatus.New;
            newOrder.ShippingType     = newOrder.CustomerNumber.ShippingType;
            newOrder.SalesOrderNumber = "test0001";
            if (newOrder.ShippingType == null)
            {
                newOrder.ShippingType = ApplicationOptions.getDefaultShippingType(objectSpace);
            }

            e.View         = Application.CreateDetailView(objectSpace, TargetViewId, true, newOrder);
            e.View.Caption = e.View.Caption + " - " + newOrder.CustomerNumber.CustomerName;
        }
    public static SharedObject Parse(string filename, SharedObject so = null)
    {
        if (so == null)
        {
            so = new SharedObject();
        }
        if (!File.Exists(filename))
        {
            Console.WriteLine("SharedObject " + filename + " doesn't exist.");
            return(so);
        }
        SOReader      file         = new SOReader(filename);
        List <string> string_table = new List <string>();

        //Read header
        SOHeader header = new SOHeader();

        header.padding1  = file.Read16();
        header.file_size = file.Read32();
        file.file_size   = (int)header.file_size + 6;
        header.padding2  = file.Read32();
        header.padding3  = file.Read16();
        header.padding4  = file.Read32();
        Console.WriteLine("Data size: " + header.file_size);

        //Read SO name and othe rparameters
        UInt16 so_name_length = file.Read16();
        string so_name        = file.ReadString(so_name_length);

        //string_table.Add(so_name);
        Console.WriteLine("SO name: " + so_name);
        UInt32 so_type = file.Read32();

        Console.WriteLine("SO type: " + so_type);

        while (file.pos < file.file_size)
        {
            SOValue so_value = new SOValue();

            // Read parameter name. Name length is encoded into 7 bits, 8th bit is flag if name is inline or indexed.
            UInt32 length_int  = (UInt32)file.ReadCompressedInt();
            bool   name_inline = (length_int & 0x01) > 0;
            length_int >>= 1;
            if (name_inline)
            {
                so_value.key = file.ReadString((int)length_int);
                string_table.Add(so_value.key);
            }
            else
            {
                so_value.key = string_table[(int)length_int];
            }
            Console.WriteLine(so_value.key + " (inline: " + name_inline + ")");

            // Read parameter value. First byte is value type.
            so_value.type = file.Read8();
            if (so_value.type == SOTypes.TYPE_NULL)
            {
                Console.WriteLine("\tNULL");
            }
            else if (so_value.type == SOTypes.TYPE_BOOL_FALSE)
            {
                so_value.bool_val = false;
                Console.WriteLine("\tFalse");
            }
            else if (so_value.type == SOTypes.TYPE_BOOL_TRUE)
            {
                so_value.bool_val = true;
                Console.WriteLine("\tTrue");
            }
            else if (so_value.type == SOTypes.TYPE_INT)
            {
                so_value.int_val = (int)file.ReadCompressedInt();
                Console.WriteLine("\t" + so_value.int_val);
            }
            else if (so_value.type == SOTypes.TYPE_DOUBLE)
            {
                so_value.double_val = file.ReadDouble();
                Console.WriteLine("\t" + so_value.double_val);
            }
            else if (so_value.type == SOTypes.TYPE_STRING)
            {
                Int32 val_length = file.ReadCompressedInt();
                bool  val_inline = (val_length & 0x00000001) > 0;
                val_length >>= 1;
                if (!val_inline)
                {
                    Console.WriteLine("\tReference to string: " + val_length);
                    if (val_length < string_table.Count)
                    {
                        so_value.string_val = string_table[(int)val_length];
                        Console.WriteLine("\t" + so_value.string_val);
                    }
                }
                else
                {
                    so_value.string_val = file.ReadString((int)val_length);
                    string_table.Add(so_value.string_val);
                    Console.WriteLine("\t" + so_value.string_val + " (" + val_length + ")");
                }
            }
            else
            {
                Console.WriteLine("Type not implemented yet: " + so_value.type);
                //Move read position to next item
                while (file.pos < file.file_size)
                {
                    byte next_byte = file.Read8();
                    if (next_byte == 0)
                    {
                        --file.pos;
                        break;
                    }
                }
            }
            so.values.Add(so_value);
            if (file.pos < file.file_size)
            {
                file.Read8();   //Padding
            }
        }
        return(so);
    }
Exemplo n.º 13
0
        public ActionResult CreateHeader(SOHeader item)
        {
            var dbConn = new OrmliteConnection().openConn();

            if (userAsset.ContainsKey("Insert") && userAsset["Insert"])
            {
                try
                {
                    string SONumber = Request["SONumber"];
                    var    header   = new SOHeader();
                    var    detail   = new SODetail();
                    if (string.IsNullOrEmpty(SONumber))
                    {
                        string datetimeSO = DateTime.Now.ToString("yyMMdd");
                        var    existSO    = dbConn.SingleOrDefault <SOHeader>("SELECT id, SONumber FROM SOHeader ORDER BY Id DESC");
                        if (existSO != null)
                        {
                            var nextNo = Int32.Parse(existSO.SONumber.Substring(8, 5)) + 1;
                            SONumber = "SO" + datetimeSO + String.Format("{0:00000}", nextNo);
                        }
                        else
                        {
                            SONumber = "SO" + datetimeSO + "00001";
                        }
                    }
                    if (string.IsNullOrEmpty(Request["VendorID"]))
                    {
                        return(Json(new { message = "Nhà cung cấp không tồn tai." }));
                    }
                    if (!string.IsNullOrEmpty(Request["SODate"]))
                    {
                        DateTime fromDateValue;
                        if (!DateTime.TryParseExact(Request["SODate"], "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out fromDateValue))
                        {
                            return(Json(new { message = "Ngày tạo không đúng." }));
                        }
                    }
                    header.SONumber  = SONumber;
                    header.SODate    = !string.IsNullOrEmpty(Request["SODate"]) ? DateTime.Parse(DateTime.ParseExact(Request["SODate"], "dd/MM/yyyy", CultureInfo.InvariantCulture).ToString("yyyy-MM-dd")) : DateTime.Now;
                    header.VendorID  = !string.IsNullOrEmpty(Request["VendorID"]) ? Request["VendorID"] : "";
                    header.Note      = !string.IsNullOrEmpty(Request["Note"]) ? Request["Note"] : "";
                    header.TotalQty  = 0;
                    header.WHID      = "";
                    header.Status    = "Mới";
                    header.WHLID     = "";
                    header.TotalAmt  = 0;
                    header.CreatedBy = currentUser.UserID;
                    header.CreatedAt = DateTime.Now;
                    header.UpdatedBy = "";
                    header.UpdatedAt = DateTime.Now;
                    //header.UpdatedAt = DateTime.Parse("1900-01-01");
                    dbConn.Insert <SOHeader>(header);
                    dbConn.Close();
                    return(Json(new { success = true, SONumber = SONumber }));
                }
                catch (Exception e)
                {
                    return(Json(new { success = false, message = e.Message }));
                }
            }
            else
            {
                dbConn.Close();
                return(Json(new { success = false, message = "Không có quyền tạo." }));
            }
        }
Exemplo n.º 14
0
        private int LoadScan(Dictionary <string, string> ScanDecodeDictionary, ObjectChangedEventArgs e)
        {
            bool   addCount = false;
            string pstring;

            ScanDecodeDictionary.TryGetValue("01", out pstring);

            string pItemnumber = pstring;


            ScanDecodeDictionary.TryGetValue("17", out pstring);
            string pExpDt = pstring;

            ScanDecodeDictionary.TryGetValue("10", out pstring);
            string pLot = pstring;

            ScanDecodeDictionary.TryGetValue("21", out pstring);
            string pSerialNumber = pstring;
            int    cc            = 0;

            cc = cc++;
            IObjectSpace objectSpace = Application.CreateObjectSpace();
            SOHeader     SOH         = objectSpace.CreateObject <SOHeader>();

            SOH = objectSpace.GetObject <SOHeader>((SOHeader)View.CurrentObject);
            SOItemDistibution SID = new SOItemDistibution(SOH.Session);

            // lets see if the serial number exists in so
            CriteriaOperator  SerialCriteria = CriteriaOperator.Parse("[ItemNumber] = ? and [SerialNumber] = ?", pItemnumber, pSerialNumber);
            SOPackingSerialNo SOPSN          = (SOPackingSerialNo)objectSpace.FindObject(typeof(SOPackingSerialNo), SerialCriteria);

            if (SOPSN != null)
            {
                return(-1);
            }

            else // Lets add the serial number in the serial packing list

            {
                SOPSN                = new SOPackingSerialNo(SOH.Session);
                SOPSN.SalesOrder     = SOH;
                SOPSN.ItemNumber     = pItemnumber.Substring(3);
                SOPSN.ShipQty        = 1;
                SOPSN.Lot            = pLot;
                SOPSN.ShipQty        = 1;
                SOPSN.SerialNumber   = pSerialNumber;
                SOPSN.Lot            = pLot;
                SOPSN.DateEntered    = System.DateTime.Today;
                SOPSN.UserName       = SecuritySystem.CurrentUserName;
                SOPSN.ExpirationDate = DateTime.ParseExact(pExpDt, "yyMMdd", CultureInfo.CurrentCulture);
                SOPSN.Save();
                SOH.Session.CommitTransaction();
                addCount = true;
            }
            // lets see if item exists on the  SO Packing table

            CriteriaOperator ItemCriteria = CriteriaOperator.Parse("[ItemNumber] = ? ", pItemnumber);
            SOPacking        SOP          = (SOPacking)objectSpace.FindObject(typeof(SOPacking), ItemCriteria);

            if (addCount)
            {
                if (SOP != null)
                {
                    SOP.ItemQty = SOP.ItemQty++;
                }
                else
                {
                    SOP            = new SOPacking(SOH.Session);
                    SOP.ItemNumber = pItemnumber;
                    SOP.SalesOrder = SOH;
                    SOP.ItemQty    = 1;
                }
                SOP.Save();
            }
            SOH.Save();
            SOH.Session.CommitTransaction();
            SOH.Reload();
            SOH.SOPacking.Reload();
            SOH.SoPackingSerialNumbers.Reload();
            SOH.Scan = null;
            return(0);
        }
Exemplo n.º 15
0
        public ActionResult ConfirmCreate()
        {
            var dbConn = new OrmliteConnection().openConn();

            if (userAsset.ContainsKey("Insert") && userAsset["Insert"])
            {
                try
                {
                    string SONumber = Request["SONumber"];
                    var    header   = new SOHeader();
                    var    detail   = new SODetail();
                    if (string.IsNullOrEmpty(SONumber))
                    {
                        string datetimeSO = DateTime.Now.ToString("yyMMdd");
                        var    existSO    = dbConn.SingleOrDefault <SOHeader>("SELECT id, SONumber FROM SOHeader ORDER BY Id DESC");
                        if (existSO != null)
                        {
                            var nextNo = Int32.Parse(existSO.SONumber.Substring(8, 5)) + 1;
                            SONumber = "SO" + datetimeSO + String.Format("{0:00000}", nextNo);
                        }
                        else
                        {
                            SONumber = "SO" + datetimeSO + "00001";
                        }
                    }
                    if (!string.IsNullOrEmpty(Request["SODate"]))
                    {
                        DateTime fromDateValue;
                        if (!DateTime.TryParseExact(Request["SODate"], "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out fromDateValue))
                        {
                            return(Json(new { message = "Ngày tạo không đúng." }));
                        }
                    }
                    if (dbConn.Select <DC_OCM_Merchant>(p => p.MerchantID == Request["MerchantID"]).Count() <= 0)
                    {
                        return(Json(new { success = false, message = "Nhà cung cấp không tồn tại." }));
                    }

                    if (dbConn.Select <SODetail>(p => p.SONumber == SONumber).Count() > 0)
                    {
                        if (!string.IsNullOrEmpty(Request["ItemCode"]))
                        {
                            if (dbConn.Select <Products>(p => p.Code == Request["ItemCode"]).Count() <= 0)
                            {
                                return(Json(new { success = false, message = "Ấn phẩm không tồn tại." }));
                            }
                            var itemcode = dbConn.Select <Products>(s => s.Code == Request["ItemCode"]).FirstOrDefault();
                            var itemunit = dbConn.Select <Products>(s => s.UnitID == itemcode.Unit).FirstOrDefault();
                            if (dbConn.Select <SODetail>(p => p.ItemCode == Request["ItemCode"] && p.SONumber == SONumber).Count() > 0)
                            {
                                var success = dbConn.Execute(@"UPDATE SODetail Set Qty = @Qty, TotalAmt =@TotalAmt ,UpdatedAt = @UpdatedAt, UpdatedBy =  @UpdatedBy, Price = @Price
                                WHERE SONumber = '" + SONumber + "' AND ItemCode = '" + Request["ItemCode"] + "'", new
                                {
                                    Qty       = dbConn.Select <SODetail>(s => s.ItemCode == Request["ItemCode"] && s.SONumber == SONumber).Sum(s => s.Qty) + int.Parse(Request["Qty"]),
                                    TotalAmt  = itemcode != null ? itemcode.VATPrice * (dbConn.Select <SODetail>(s => s.ItemCode == Request["ItemCode"] && s.SONumber == SONumber).Sum(s => s.Qty) + int.Parse(Request["Qty"])) : 0,
                                    Price     = itemcode.VATPrice,
                                    UpdatedBy = currentUser.UserID,
                                    UpdatedAt = DateTime.Now,
                                }) == 1;
                                if (!success)
                                {
                                    return(Json(new { success = false, message = "Không thể lưu" }));
                                }
                            }
                            else
                            {
                                detail.SONumber  = SONumber;
                                detail.ItemCode  = !string.IsNullOrEmpty(Request["ItemCode"]) ? Request["ItemCode"] : "";
                                detail.ItemName  = !string.IsNullOrEmpty(itemcode.Name) ? itemcode.Name : "";
                                detail.Price     = itemcode != null ? itemcode.VATPrice : 0;
                                detail.Qty       = int.Parse(Request["Qty"]);
                                detail.TotalAmt  = itemcode.VATPrice * int.Parse(Request["Qty"]);
                                detail.UnitID    = !string.IsNullOrEmpty(itemunit.UnitID) ? itemunit.UnitID : "";
                                detail.UnitName  = !string.IsNullOrEmpty(itemunit.UnitName) ? itemunit.UnitName : "";
                                detail.Note      = "";
                                detail.Status    = "";
                                detail.CreatedBy = currentUser.UserID;
                                detail.CreatedAt = DateTime.Now;
                                detail.UpdatedBy = "";
                                detail.UpdatedAt = DateTime.Parse("1900-01-01");
                                dbConn.Insert <SODetail>(detail);
                            }
                        }
                    }
                    else
                    {
                        if (string.IsNullOrEmpty(Request["ItemCode"]) || dbConn.Select <Products>(p => p.Code == Request["ItemCode"]).Count() <= 0)
                        {
                            return(Json(new { success = false, message = "Ấn phẩm không tồn tại." }));
                        }
                        var itemcode = dbConn.Select <Products>(s => s.Code == Request["ItemCode"]).FirstOrDefault();
                        var itemunit = dbConn.Select <Products>(s => s.UnitID == itemcode.Unit).FirstOrDefault();
                        detail.SONumber  = SONumber;
                        detail.ItemCode  = !string.IsNullOrEmpty(Request["ItemCode"]) ? Request["ItemCode"] : "";
                        detail.ItemName  = !string.IsNullOrEmpty(itemcode.Name) ? itemcode.Name : "";
                        detail.Price     = itemcode != null ? itemcode.VATPrice :0;
                        detail.Qty       = int.Parse(Request["Qty"]);
                        detail.TotalAmt  = itemcode.VATPrice * int.Parse(Request["Qty"]);
                        detail.UnitID    = !string.IsNullOrEmpty(itemunit.UnitID) ? itemunit.UnitID : "";
                        detail.UnitName  = !string.IsNullOrEmpty(itemunit.UnitName) ? itemunit.UnitName : "";
                        detail.Note      = "";
                        detail.Status    = "";
                        detail.CreatedBy = currentUser.UserID;
                        detail.CreatedAt = DateTime.Now;
                        detail.UpdatedBy = "";
                        detail.UpdatedAt = DateTime.Parse("1900-01-01");
                        dbConn.Insert <SODetail>(detail);
                    }
                    if (dbConn.Select <SOHeader>(p => p.SONumber == SONumber).Count() > 0)
                    {
                        var success = dbConn.Execute(@"UPDATE SOHeader Set TotalQty = @TotalQty, TotalAmt =@TotalAmt ,UpdatedAt = @UpdatedAt, UpdatedBy =  @UpdatedBy,
                        MerchantID = @MerchantID, SODate = @SODate , WHLID =@WHLID, WHID =@WHID WHERE SONumber = '" + SONumber + "'", new
                        {
                            TotalQty   = dbConn.Select <SODetail>(s => s.SONumber == SONumber).Sum(s => s.Qty),
                            TotalAmt   = dbConn.Select <SODetail>(s => s.SONumber == SONumber).Sum(s => s.TotalAmt),
                            SODate     = !string.IsNullOrEmpty(Request["SODate"]) ? DateTime.Parse(DateTime.ParseExact(Request["SODate"], "dd/MM/yyyy", CultureInfo.InvariantCulture).ToString("yyyy-MM-dd")) : DateTime.Now,
                            WHID       = !string.IsNullOrEmpty(Request["WHID"]) ? Request["WHID"] : "",
                            WHLID      = !string.IsNullOrEmpty(Request["WHLID"]) ? Request["WHLID"] : "",
                            MerchantID = !string.IsNullOrEmpty(Request["MerchantID"]) ? Request["MerchantID"] : "",
                            UpdatedBy  = currentUser.UserID,
                            UpdatedAt  = DateTime.Now,
                        }) == 1;
                        if (!success)
                        {
                            return(Json(new { success = false, message = "Không thể lưu" }));
                        }
                    }
                    else
                    {
                        header.SONumber  = SONumber;
                        header.SODate    = !string.IsNullOrEmpty(Request["SODate"]) ? DateTime.Parse(DateTime.ParseExact(Request["SODate"], "dd/MM/yyyy", CultureInfo.InvariantCulture).ToString("yyyy-MM-dd")) : DateTime.Now;
                        header.VendorID  = !string.IsNullOrEmpty(Request["MerchantID"]) ? Request["MerchantID"] : "";
                        header.Note      = !string.IsNullOrEmpty(Request["Note"]) ? Request["Note"] : "";
                        header.TotalQty  = dbConn.Select <SODetail>(s => s.SONumber == SONumber).Sum(s => s.Qty);
                        header.WHID      = Request["WHID"];
                        header.Status    = "Mới";
                        header.WHLID     = !string.IsNullOrEmpty(Request["WHLID"]) ? Request["WHLID"] : "";
                        header.TotalAmt  = dbConn.Select <SODetail>(s => s.SONumber == SONumber).Sum(s => s.TotalAmt);
                        header.CreatedBy = currentUser.UserID;
                        header.CreatedAt = DateTime.Now;
                        header.UpdatedBy = "";
                        header.UpdatedAt = DateTime.Parse("1900-01-01");
                        dbConn.Insert <SOHeader>(header);
                    }

                    return(Json(new { success = true, SONumber = SONumber }));
                }
                catch (Exception e)
                {
                    return(Json(new { success = false, message = e.Message }));
                }
            }

            else
            {
                return(Json(new { success = false, message = "Không có quyền tạo." }));
            }
        }