Exemple #1
0
        public override DTO.ModelMng.EditFormData GetData(int id, int iRequesterID, out Library.DTO.Notification notification)
        {
            // query data
            DTO.ModelMng.EditFormData        result    = factory.GetData(iRequesterID, id, out notification);
            Module.Framework.DAL.DataFactory fwFactory = new Module.Framework.DAL.DataFactory();
            if (fwFactory.CheckModelPricePermission(iRequesterID) <= 0)
            {
                // clear pricing data if not allow
                result.Data.ModelFixPriceConfigurations.Clear();
                result.Data.ModelPriceConfigurations.Clear();
                result.ModelPriceConfigurationDefault.Clear();
                result.IsPriceEnabled = false;
            }
            else
            {
                result.IsPriceEnabled = true;
            }

            if (fwFactory.CanPerformAction(iRequesterID, "ModelMng", Library.DTO.ModuleAction.CanApprove))
            {
                result.CanApprove = true;
            }
            else
            {
                result.CanApprove = false;
            }
            return(result);
        }
Exemple #2
0
        public object GetDataCreateModel(int userId, int id, int sampleProductID, out Notification notification)
        {
            DTO.ModelMng.CreateModelEditData result = factory.GetDataCreateModel(userId, id, sampleProductID, out notification);

            Module.Framework.DAL.DataFactory fwFactory = new Module.Framework.DAL.DataFactory();

            if (fwFactory.CheckModelPricePermission(userId) <= 0)
            {
                // clear pricing data if not allow
                result.Data.ModelFixPriceConfigurations.Clear();
                result.Data.ModelPriceConfigurations.Clear();
                result.ModelPriceConfigurationDefault.Clear();
                result.IsPriceEnabled = false;
            }
            else
            {
                result.IsPriceEnabled = true;
            }

            if (fwFactory.CanPerformAction(userId, "ModelMng", Library.DTO.ModuleAction.CanApprove))
            {
                result.CanApprove = true;
            }
            else
            {
                result.CanApprove = false;
            }

            return(result);
        }
 public DTO.SaleOrder UploadClientPOFile(int saleOrderID, string newFile, string oldPointer, string tempFolder, out Library.DTO.Notification notification)
 {
     Module.Framework.DAL.DataFactory framework_factory = new Module.Framework.DAL.DataFactory();
     DTO.SaleOrder dtoSaleOrder = new DTO.SaleOrder();
     notification = new Library.DTO.Notification {
         Type = Library.DTO.NotificationType.Success, Message = "Upload success"
     };
     try
     {
         using (SaleOrderMngEntities context = CreateContext())
         {
             string newPointer = framework_factory.CreateNoneImageFilePointer(tempFolder, newFile, oldPointer);
             if (saleOrderID > 0)
             {
                 var saleOrder = context.SaleOrder.Where(o => o.SaleOrderID == saleOrderID).FirstOrDefault();
                 saleOrder.ClientPOFile = newPointer;
                 context.SaveChanges();
                 //get return data
                 dtoSaleOrder = GetBackData(saleOrderID, out notification);
             }
         }
         return(dtoSaleOrder);
     }
     catch (Exception ex)
     {
         notification.Type    = Library.DTO.NotificationType.Error;
         notification.Message = ex.Message;
         if (ex.InnerException != null && !string.IsNullOrEmpty(ex.InnerException.Message))
         {
             notification.DetailMessage.Add(ex.InnerException.Message);
         }
         return(dtoSaleOrder);
     }
 }
Exemple #4
0
 public override bool UpdateData(int userId, int id, ref object dtoItem, out Library.DTO.Notification notification)
 {
     notification = new Library.DTO.Notification()
     {
         Type = Library.DTO.NotificationType.Success
     };
     DTO.TransportOfferDTO dtoTransportOffer = ((Newtonsoft.Json.Linq.JObject)dtoItem).ToObject <DTO.TransportOfferDTO>();
     try
     {
         using (TransportOfferEntities context = CreateContext())
         {
             TransportOffer dbItem = null;
             if (id > 0)
             {
                 dbItem = context.TransportOffer.Where(o => o.TransportOfferID == id).FirstOrDefault();
             }
             else
             {
                 dbItem = new TransportOffer();
                 context.TransportOffer.Add(dbItem);
             }
             if (dbItem == null)
             {
                 notification.Message = "data not found!";
                 return(false);
             }
             else
             {
                 Module.Framework.DAL.DataFactory fwFactory = new Module.Framework.DAL.DataFactory();
                 string tempFolder = FrameworkSetting.Setting.AbsoluteUserTempFolder + userId.ToString() + @"\";
                 if (dtoTransportOffer.File_HasChange.HasValue && dtoTransportOffer.File_HasChange.Value)
                 {
                     dtoTransportOffer.FileUD = fwFactory.CreateFilePointer(tempFolder, dtoTransportOffer.File_NewFile, dtoTransportOffer.FileUD, dtoTransportOffer.FriendlyName);
                 }
                 //convert dto to db
                 converter.DTO2DB_TransportOffer(dtoTransportOffer, ref dbItem);
                 dbItem.UpdatedBy = userId;
                 //remove orphan
                 context.TransportOfferCostDetail.Local.Where(o => o.TransportOffer == null).ToList().ForEach(o => context.TransportOfferCostDetail.Remove(o));
                 context.TransportOfferConditionDetail.Local.Where(o => o.TransportOffer == null).ToList().ForEach(o => context.TransportOfferConditionDetail.Remove(o));
                 //save data
                 context.SaveChanges();
                 //get return data
                 dtoItem = GetData(userId, dbItem.TransportOfferID, out notification).Data;
                 return(true);
             }
         }
     }
     catch (Exception ex)
     {
         notification.Type    = Library.DTO.NotificationType.Error;
         notification.Message = ex.Message;
         notification.DetailMessage.Add(ex.Message);
         if (ex.GetBaseException() != null)
         {
             notification.DetailMessage.Add(ex.GetBaseException().Message);
         }
         return(false);
     }
 }
        //
        // CUSTOM FUNCTION HERE
        //
        public override object GetInitData(int userID, out Notification notification)
        {
            notification = new Notification()
            {
                Type = NotificationType.Success
            };

            Module.Framework.DAL.DataFactory fwFactory = new Module.Framework.DAL.DataFactory();
            int?companyID = fwFactory.GetCompanyID(userID);

            SupportFormData data = new SupportFormData();

            data.EmployeeDTOs = new List <EmployeeDTO>();
            data.CompanyDTOs  = new List <CompanyDTO>();
            try
            {
                using (AnnualLeaveRptEntities context = CreateContext())
                {
                    data.EmployeeDTOs = converter.DB2DTO_EmployeeDTO(context.AnnualLeaveRpt_Employee_View.ToList());
                    data.CompanyDTOs  = converter.DB2DTO_CompanyDTO(context.AnnualLeaveRpt_Company_View.Where(s => s.CompanyID == companyID).ToList());
                }

                return(data);
            }
            catch (Exception ex)
            {
                notification.Type    = NotificationType.Error;
                notification.Message = ex.Message;

                return(data);
            }
        }
Exemple #6
0
 private void cmdImportToFilesTable_Click(object sender, EventArgs e)
 {
     Module.Framework.DAL.DataFactory fwFactory = new Module.Framework.DAL.DataFactory();
     foreach (FileInfo fInfo in (new DirectoryInfo(txtFolderToImport.Text)).GetFiles())
     {
         fwFactory.CreateNoneImageFilePointer(txtFolderToImport.Text, fInfo.Name, string.Empty);
     }
 }
        public DTO.EditFormData GetData(int userId, int id, out Library.DTO.Notification notification)
        {
            DTO.EditFormData editFormData = new DTO.EditFormData();
            notification = new Library.DTO.Notification()
            {
                Type = Library.DTO.NotificationType.Success
            };
            Module.Support.DAL.DataFactory   support_factory = new Support.DAL.DataFactory();
            Module.Framework.DAL.DataFactory fwFactory       = new Module.Framework.DAL.DataFactory();
            //Details
            editFormData.Data = new DTO.LabelingPackaging();
            editFormData.Data.LabelingPackagingDetails          = new List <DTO.LabelingPackagingDetail>();
            editFormData.Data.LabelingPackagingSparepartDetails = new List <DTO.LabelingPackagingSparepartDetail>();
            editFormData.Data.LabelingPackagingRemarks          = new List <DTO.LabelingPackagingRemark>();

            try
            {
                using (LPOverviewEntities context = CreateContext())
                {
                    if (id > 0)
                    {
                        LabelingPackagingMng_LabelingPackaging_View dbItem;
                        dbItem = context.LabelingPackagingMng_LabelingPackaging_View.FirstOrDefault(o => o.LabelingPackagingID == id);

                        //check permission on factory
                        int FactoryID = Convert.ToInt32(dbItem.FactoryID);
                        if (fwFactory.CheckFactoryPermission(userId, FactoryID) == 0)
                        {
                            throw new Exception("You do not have access permission on this factory");
                        }
                        editFormData.Data = converter.DB2DTO_LabelingPackaging(dbItem);
                    }
                    else
                    {
                        editFormData.Data = new DTO.LabelingPackaging();
                        editFormData.Data.LabelingPackagingDetails          = new List <DTO.LabelingPackagingDetail>();
                        editFormData.Data.LabelingPackagingSparepartDetails = new List <DTO.LabelingPackagingSparepartDetail>();
                        editFormData.Data.LabelingPackagingRemarks          = new List <DTO.LabelingPackagingRemark>();
                        editFormData.Data.LabelingPackagingOtherFiles       = new List <DTO.LabelingPackagingOtherFile>();
                    }
                    //editFormData.Factories = support_factory.GetFactory(userId);
                    return(editFormData);
                }
            }
            catch (Exception ex)
            {
                notification.Type    = Library.DTO.NotificationType.Error;
                notification.Message = ex.Message;
                notification.DetailMessage.Add(ex.Message);
                if (ex.GetBaseException() != null)
                {
                    notification.DetailMessage.Add(ex.GetBaseException().Message);
                }
                return(editFormData);
            }
        }
Exemple #8
0
        public DTO.EditFormData GetData(int userId, int id, out Library.DTO.Notification notification)
        {
            DTO.EditFormData editFormData = new DTO.EditFormData();
            notification = new Library.DTO.Notification()
            {
                Type = Library.DTO.NotificationType.Success
            };
            Module.Support.DAL.DataFactory   support_factory = new Support.DAL.DataFactory();
            Module.Framework.DAL.DataFactory fwFactory       = new Module.Framework.DAL.DataFactory();
            try
            {
                using (FactoryStockReceiptEntities context = CreateContext())
                {
                    //auto create production item
                    context.FactoryStockReceiptMng_function_CreateProductionItem();
                    if (id > 0)
                    {
                        FactoryStockReceiptMng_FactoryStockReceipt_View dbItem;
                        dbItem = context.FactoryStockReceiptMng_FactoryStockReceipt_View.FirstOrDefault(o => o.FactoryStockReceiptID == id);
                        //check permission on factory
                        if (fwFactory.CheckFactoryPermission(userId, dbItem.FactoryID.Value) == 0)
                        {
                            throw new Exception("You do not have access permission on this factory");
                        }
                        editFormData.Data = converter.DB2DTO_FactoryStockReceipt(dbItem);
                    }
                    else
                    {
                        editFormData.Data = new DTO.FactoryStockReceipt();
                        editFormData.Data.FactoryStockReceiptDetails = new List <DTO.FactoryStockReceiptDetail>();
                    }
                    editFormData.Factories = support_factory.GetFactory(userId);

                    return(editFormData);
                }
            }
            catch (Exception ex)
            {
                notification.Type    = Library.DTO.NotificationType.Error;
                notification.Message = ex.Message;
                notification.DetailMessage.Add(ex.Message);
                if (ex.GetBaseException() != null)
                {
                    notification.DetailMessage.Add(ex.GetBaseException().Message);
                }
                return(editFormData);
            }
        }
Exemple #9
0
        public override bool UpdateData(int id, ref DTO.ModelMng.Model dtoItem, int iRequesterID, out Library.DTO.Notification notification)
        {
            // keep log entry
            fwBLL.WriteLog(iRequesterID, 0, "update Model " + id.ToString());

            // query data
            dtoItem.UpdatedBy = iRequesterID;
            dtoItem.CreatedBy = iRequesterID;
            Module.Framework.DAL.DataFactory fwFactory = new Module.Framework.DAL.DataFactory();
            if (fwFactory.CheckModelPricePermission(iRequesterID) <= 0)
            {
                // clear pricing data if not allow
                dtoItem.ModelPriceConfigurations    = null;
                dtoItem.ModelFixPriceConfigurations = null;
            }

            return(factory.UpdateData(id, ref dtoItem, iRequesterID, out notification));
        }
        public override bool DeleteData(int id, out Library.DTO.Notification notification)
        {
            notification = new Library.DTO.Notification()
            {
                Type = Library.DTO.NotificationType.Success
            };
            try
            {
                using (PLCMngEntities context = CreateContext())
                {
                    PLC dbItem = context.PLC.FirstOrDefault(o => o.PLCID == id);
                    if (dbItem == null)
                    {
                        notification.Message = "PLC not found!";
                        return(false);
                    }
                    else
                    {
                        Module.Framework.DAL.DataFactory frameworkFactory = new Module.Framework.DAL.DataFactory();
                        foreach (PLCImage dbImage in dbItem.PLCImage)
                        {
                            if (!string.IsNullOrEmpty(dbImage.ImageFile))
                            {
                                // remove image
                                frameworkFactory.RemoveImageFile(dbImage.ImageFile);
                            }
                        }

                        context.PLC.Remove(dbItem);
                        context.SaveChanges();

                        return(true);
                    }
                }
            }
            catch (Exception ex)
            {
                notification = new Library.DTO.Notification()
                {
                    Message = ex.Message
                };
                return(false);
            }
        }
Exemple #11
0
        public void DTO2DB_FactoryMaterial(DTO.FactoryMaterial dtoItem, ref FactoryMaterial dbItem, string tempFolder)
        {
            Module.Framework.DAL.DataFactory fwFactory = new Module.Framework.DAL.DataFactory();
            if (dtoItem.FactoryMaterialImages != null)
            {
                foreach (var item in dbItem.FactoryMaterialImage.ToArray())
                {
                    if (!dtoItem.FactoryMaterialImages.Select(s => s.FactoryMaterialImageID).Contains(item.FactoryMaterialImageID))
                    {
                        dbItem.FactoryMaterialImage.Remove(item);
                    }
                }

                foreach (var item in dtoItem.FactoryMaterialImages)
                {
                    //modify dto image field
                    if (item.ImageFile_HasChange.HasValue && item.ImageFile_HasChange.Value)
                    {
                        item.ImageFile = fwFactory.CreateFilePointer(tempFolder, item.ImageFile_NewFile, item.ImageFile);
                    }

                    //read db image field
                    FactoryMaterialImage dbDetail;
                    if (item.FactoryMaterialImageID < 0)
                    {
                        dbDetail = new FactoryMaterialImage();
                        dbItem.FactoryMaterialImage.Add(dbDetail);
                    }
                    else
                    {
                        dbDetail = dbItem.FactoryMaterialImage.Where(o => o.FactoryMaterialImageID == item.FactoryMaterialImageID).FirstOrDefault();
                    }

                    //map from dto image field to db image field
                    if (dbDetail != null)
                    {
                        AutoMapper.Mapper.Map <DTO.FactoryMaterialImage, FactoryMaterialImage>(item, dbDetail);
                    }
                }
            }
            AutoMapper.Mapper.Map <DTO.FactoryMaterial, FactoryMaterial>(dtoItem, dbItem);
        }
Exemple #12
0
        public override bool UpdateData(int userId, int id, ref object dtoItem1, out Notification notification)
        {
            DTO.CostInvoice2 dtoItem = ((Newtonsoft.Json.Linq.JObject)dtoItem1).ToObject <DTO.CostInvoice2>();

            notification      = new Notification();
            notification.Type = NotificationType.Success;

            try
            {
                using (var context = CreateContext())
                {
                    CostInvoice2 dbItem;

                    if (id > 0)
                    {
                        dbItem = context.CostInvoice2.FirstOrDefault(s => s.CostInvoice2ID == id);

                        if (dbItem == null)
                        {
                            notification.Type    = NotificationType.Error;
                            notification.Message = "Can not find data";

                            return(false);
                        }
                    }
                    else
                    {
                        dbItem = new CostInvoice2();
                        dbItem.CostInvoice2UD = (context.CostInvoice2.Count() + 1).ToString().PadLeft(10, '0');

                        context.CostInvoice2.Add(dbItem);
                    }
                    //upload file
                    Module.Framework.DAL.DataFactory fwFactory = new Module.Framework.DAL.DataFactory();
                    string tempFolder = FrameworkSetting.Setting.AbsoluteUserTempFolder + userId.ToString() + @"\";
                    if (dtoItem.File_HasChange.HasValue && dtoItem.File_HasChange.Value)
                    {
                        dtoItem.RelatedDocumentFile = fwFactory.CreateFilePointer(tempFolder, dtoItem.File_NewFile, dtoItem.RelatedDocumentFile, dtoItem.FriendlyName);
                    }
                    //
                    converter.DTO2DB_CostInvoice2(dtoItem, ref dbItem);

                    dbItem.UpdatedBy   = userId;
                    dbItem.UpdatedDate = DateTime.Now;

                    dbItem.InvoiceDate = dtoItem.InvoiceDate.ConvertStringToDateTime();
                    dbItem.DueDate     = dtoItem.DueDate.ConvertStringToDateTime();
                    dbItem.PaidDate    = dtoItem.PaidDate.ConvertStringToDateTime();

                    context.CostInvoice2Client.Local.Where(o => o.CostInvoice2 == null).ToList().ForEach(o => context.CostInvoice2Client.Remove(o));
                    context.CostInvoice2Factory.Local.Where(o => o.CostInvoice2 == null).ToList().ForEach(o => context.CostInvoice2Factory.Remove(o));

                    context.SaveChanges();

                    dtoItem1 = GetData(dbItem.CostInvoice2ID, out notification);
                }

                return(true);
            }
            catch (Exception ex)
            {
                notification.Type    = NotificationType.Error;
                notification.Message = ex.Message;

                if (ex.InnerException != null && !string.IsNullOrEmpty(ex.InnerException.Message))
                {
                    notification.DetailMessage.Add(ex.InnerException.Message);
                }

                return(false);
            }
        }
        public DTO.OfferSeasonDetailDTO UpdateOfferSeasonDetail(int userId, int offerSeasonID, int offerSeasonDetailID, object dtoItem, out Library.DTO.Notification notification)
        {
            notification = new Library.DTO.Notification()
            {
                Type = Library.DTO.NotificationType.Success
            };
            DTO.OfferSeasonDetailDTO dtoOfferSeasonDetail = ((Newtonsoft.Json.Linq.JObject)dtoItem).ToObject <DTO.OfferSeasonDetailDTO>();
            try
            {
                using (OfferSeasonMngEntities context = CreateContext())
                {
                    //find offer season to attach offerSeasonDetail
                    OfferSeason dbOfferSeason = context.OfferSeason.Where(o => o.OfferSeasonID == offerSeasonID).FirstOrDefault();
                    if (dbOfferSeason == null)
                    {
                        throw new Exception("Could not find offer season");
                    }

                    //offer seasons detail
                    OfferSeasonDetail dbItem   = null;
                    bool isAllowEditProperties = true;
                    if (offerSeasonDetailID > 0)
                    {
                        //get item to update
                        dbItem = context.OfferSeasonDetail.Where(o => o.OfferSeasonDetailID == offerSeasonDetailID).FirstOrDefault();

                        //check item is in factory order so we can allow edit property of item
                        bool isInFactoryOrder = context.OfferSeasonMng_function_CheckOfferItemIsInFactoryOrder(offerSeasonDetailID).FirstOrDefault().Value > 0;
                        isAllowEditProperties = !isInFactoryOrder;

                        //get admin permission
                        Module.Framework.DAL.DataFactory fwFactory = new Module.Framework.DAL.DataFactory();
                        if (fwFactory.HasSpecialPermission(userId, Module.Framework.ConstantIdentifier.SPECIAL_PERMISSION_CHANGE_OFFER_ITEM_OPTION))
                        {
                            isAllowEditProperties = true;
                        }
                    }
                    else
                    {
                        //create new OfferSeasonDetail
                        dbItem = new OfferSeasonDetail();
                        dbOfferSeason.OfferSeasonDetail.Add(dbItem);
                    }
                    if (dbItem == null)
                    {
                        throw new Exception("data not found offer season item!");
                    }
                    else
                    {
                        //convert dto 2 db
                        converter.DTO2DB_OfferSeasonDetail(userId, dbOfferSeason.OfferSeasonTypeID, offerSeasonDetailID, dtoOfferSeasonDetail, isAllowEditProperties, ref dbItem);
                        if (dbItem.IsPlaningPurchasingPriceSelected.HasValue && dbItem.IsPlaningPurchasingPriceSelected.Value && dbItem.PlaningPurchasingPriceSelectedBy == null)
                        {
                            dbItem.PlaningPurchasingPriceSelectedBy   = userId;
                            dbItem.PlaningPurchasingPriceSelectedDate = DateTime.Now;
                        }

                        //save data
                        context.SaveChanges();

                        //auto make quotation request to quotation
                        //context.OfferSeasonQuotatonRequestMng_function_AddOfferSeasonItemToQuotation(dbItem.OfferSeasonDetailID, userId);
                        // disabled, using trigger instead

                        //auto reset quotation status if change property of item
                        if (dtoOfferSeasonDetail.IsChangedProperties.HasValue && dtoOfferSeasonDetail.IsChangedProperties.Value && isAllowEditProperties)
                        {
                            context.OfferSeasonMng_function_ResetStatusOfQuotation(dbItem.OfferSeasonDetailID);
                        }

                        //get return data
                        dtoOfferSeasonDetail = GetOfferSeasonDetail(dbItem.OfferSeasonDetailID, out notification);

                        return(dtoOfferSeasonDetail);
                    }
                }
            }
            catch (Exception ex)
            {
                notification.Type    = Library.DTO.NotificationType.Error;
                notification.Message = Library.Helper.HandleExceptionSingleLine(ex);
                return(null);
            }
        }
        public override bool UpdateData(int userId, int id, ref object dtoItem, out Notification notification)
        {
            notification = new Notification()
            {
                Type = NotificationType.Success
            };

            DTO.QualityDocumentDTO dtoItems = ((Newtonsoft.Json.Linq.JObject)dtoItem).ToObject <DTO.QualityDocumentDTO>();

            try
            {
                using (var context = CreatContex())
                {
                    QualityDocument dbItem;

                    if (id == 0)
                    {
                        dbItem = new QualityDocument();
                        context.QualityDocument.Add(dbItem);
                    }
                    else
                    {
                        dbItem = context.QualityDocument.Where(o => o.QualityDocumentID == id).FirstOrDefault();
                    }
                    if (dbItem == null)
                    {
                        notification.Message = "Data Not Found !";
                        return(false);
                    }
                    else
                    {
                        converter.DTO2DB_QualityDocument(dtoItems, ref dbItem);

                        //upload file
                        Module.Framework.DAL.DataFactory fwFactory = new Module.Framework.DAL.DataFactory();
                        string tempFolder = FrameworkSetting.Setting.AbsoluteUserTempFolder + userId.ToString() + @"\";
                        if (dtoItems.File_HasChange.HasValue && dtoItems.File_HasChange.Value)
                        {
                            dbItem.AttachedFile = fwFactory.CreateFilePointer(tempFolder, dtoItems.File_NewFile, dtoItems.AttachedFile, dtoItems.FriendlyName);
                        }

                        dbItem.UpdatedBy   = userId;
                        dbItem.UpdatedDate = DateTime.Now;

                        //save
                        context.SaveChanges();

                        dtoItem = GetData(dbItem.QualityDocumentID, out notification).Data;
                        return(true);
                    }
                }
            }
            catch (Exception ex)
            {
                notification.Type    = Library.DTO.NotificationType.Error;
                notification.Message = ex.Message;
                notification.DetailMessage.Add(ex.Message);

                if (ex.GetBaseException() != null)
                {
                    notification.DetailMessage.Add(ex.GetBaseException().Message);
                }
            }

            return(true);
        }
        public void DTO2DB(DTO.FactoryInvoice dtoItem, ref FactoryInvoice dbItem, string _tempFolder)
        {
            // map fields
            AutoMapper.Mapper.Map <DTO.FactoryInvoice, FactoryInvoice>(dtoItem, dbItem);

            // insert file
            Module.Framework.DAL.DataFactory fwFactory = new Module.Framework.DAL.DataFactory();
            if (dtoItem.ScanFile_HasChange)
            {
                dbItem.ScanFile = fwFactory.CreateNoneImageFilePointer(_tempFolder, dtoItem.ScanFile_NewFile, dtoItem.ScanFile);
            }
            if (!string.IsNullOrEmpty(dtoItem.InvoiceDate))
            {
                if (DateTime.TryParse(dtoItem.InvoiceDate, nl, System.Globalization.DateTimeStyles.None, out tmpDate))
                {
                    dbItem.InvoiceDate = tmpDate;
                }
            }
            decimal subtotal = 0;

            // map detail
            if (dtoItem.FactoryInvoiceDetails != null)
            {
                // check for child rows deleted
                foreach (FactoryInvoiceDetail dbDetail in dbItem.FactoryInvoiceDetail.ToArray())
                {
                    if (!dtoItem.FactoryInvoiceDetails.Select(o => o.FactoryInvoiceDetailID).Contains(dbDetail.FactoryInvoiceDetailID))
                    {
                        dbItem.FactoryInvoiceDetail.Remove(dbDetail);
                    }
                }

                // map child rows
                foreach (DTO.FactoryInvoiceDetail dtoDetail in dtoItem.FactoryInvoiceDetails)
                {
                    FactoryInvoiceDetail dbDetail;
                    if (dtoDetail.FactoryInvoiceDetailID <= 0)
                    {
                        dbDetail = new FactoryInvoiceDetail();
                        dbItem.FactoryInvoiceDetail.Add(dbDetail);
                    }
                    else
                    {
                        dbDetail = dbItem.FactoryInvoiceDetail.FirstOrDefault(o => o.FactoryInvoiceDetailID == dtoDetail.FactoryInvoiceDetailID);
                    }

                    if (dbDetail != null)
                    {
                        AutoMapper.Mapper.Map <DTO.FactoryInvoiceDetail, FactoryInvoiceDetail>(dtoDetail, dbDetail);

                        if (dtoDetail.UnitPrice.HasValue && dtoDetail.Quantity.HasValue)
                        {
                            dbDetail.SubTotal = Math.Round(dtoDetail.UnitPrice.Value * dtoDetail.Quantity.Value, 2, MidpointRounding.AwayFromZero);
                            subtotal         += Math.Round(dtoDetail.UnitPrice.Value * dtoDetail.Quantity.Value, 2, MidpointRounding.AwayFromZero);
                        }
                    }
                }
            }

            // map sparepart detail
            if (dtoItem.FactoryInvoiceSparepartDetails != null)
            {
                // check for child rows deleted
                foreach (FactoryInvoiceSparepartDetail dbSparepartDetail in dbItem.FactoryInvoiceSparepartDetail.ToArray())
                {
                    if (!dtoItem.FactoryInvoiceSparepartDetails.Select(o => o.FactoryInvoiceSparepartDetailID).Contains(dbSparepartDetail.FactoryInvoiceSparepartDetailID))
                    {
                        dbItem.FactoryInvoiceSparepartDetail.Remove(dbSparepartDetail);
                    }
                }

                // map child rows
                foreach (DTO.FactoryInvoiceSparepartDetail dtoSparepartDetail in dtoItem.FactoryInvoiceSparepartDetails)
                {
                    FactoryInvoiceSparepartDetail dbSparepartDetail;
                    if (dtoSparepartDetail.FactoryInvoiceSparepartDetailID <= 0)
                    {
                        dbSparepartDetail = new FactoryInvoiceSparepartDetail();
                        dbItem.FactoryInvoiceSparepartDetail.Add(dbSparepartDetail);
                    }
                    else
                    {
                        dbSparepartDetail = dbItem.FactoryInvoiceSparepartDetail.FirstOrDefault(o => o.FactoryInvoiceSparepartDetailID == dtoSparepartDetail.FactoryInvoiceSparepartDetailID);
                    }

                    if (dbSparepartDetail != null)
                    {
                        AutoMapper.Mapper.Map <DTO.FactoryInvoiceSparepartDetail, FactoryInvoiceSparepartDetail>(dtoSparepartDetail, dbSparepartDetail);

                        if (dtoSparepartDetail.UnitPrice.HasValue && dtoSparepartDetail.Quantity.HasValue)
                        {
                            dbSparepartDetail.SubTotal = Math.Round(dtoSparepartDetail.UnitPrice.Value * dtoSparepartDetail.Quantity.Value, 2, MidpointRounding.AwayFromZero);
                            subtotal += Math.Round(dtoSparepartDetail.UnitPrice.Value * dtoSparepartDetail.Quantity.Value, 2, MidpointRounding.AwayFromZero);
                        }
                    }
                }
            }

            // map extra
            if (dtoItem.FactoryInvoiceExtras != null)
            {
                // check for child rows deleted
                foreach (FactoryInvoiceExtra dbExtra in dbItem.FactoryInvoiceExtra.ToArray())
                {
                    if (!dtoItem.FactoryInvoiceExtras.Select(o => o.FactoryInvoiceExtraID).Contains(dbExtra.FactoryInvoiceExtraID))
                    {
                        dbItem.FactoryInvoiceExtra.Remove(dbExtra);
                    }
                }

                // map child rows
                foreach (DTO.FactoryInvoiceExtra dtoExtra in dtoItem.FactoryInvoiceExtras)
                {
                    FactoryInvoiceExtra dbExtra;
                    if (dtoExtra.FactoryInvoiceExtraID <= 0)
                    {
                        dbExtra = new FactoryInvoiceExtra();
                        dbItem.FactoryInvoiceExtra.Add(dbExtra);
                    }
                    else
                    {
                        dbExtra = dbItem.FactoryInvoiceExtra.FirstOrDefault(o => o.FactoryInvoiceExtraID == dtoExtra.FactoryInvoiceExtraID);
                    }

                    if (dbExtra != null)
                    {
                        AutoMapper.Mapper.Map <DTO.FactoryInvoiceExtra, FactoryInvoiceExtra>(dtoExtra, dbExtra);

                        if (dtoExtra.UnitPrice.HasValue && dtoExtra.Quantity.HasValue)
                        {
                            dbExtra.SubTotal = Math.Round(dtoExtra.UnitPrice.Value * dtoExtra.Quantity.Value, 2, MidpointRounding.AwayFromZero);
                            subtotal        += Math.Round(dtoExtra.UnitPrice.Value * dtoExtra.Quantity.Value, 2, MidpointRounding.AwayFromZero);
                        }
                    }
                }
            }

            dbItem.SubTotalAmount = subtotal;
            if (dbItem.DeductedAmount.HasValue)
            {
                dbItem.TotalAmount = dbItem.SubTotalAmount.Value - dbItem.DeductedAmount.Value;
            }
            else
            {
                dbItem.TotalAmount = dbItem.SubTotalAmount;
            }
        }
        public override bool UpdateData(int userId, int id, ref object dtoItem, out Notification notification)
        {
            notification = new Library.DTO.Notification()
            {
                Type = Library.DTO.NotificationType.Success
            };
            DTO.ReceiptNoteEditResult dtoReceipt = ((Newtonsoft.Json.Linq.JObject)dtoItem).ToObject <DTO.ReceiptNoteEditResult>();
            try
            {
                //get companyID
                Module.Framework.DAL.DataFactory fw_factory = new Framework.DAL.DataFactory();
                int?companyID = fw_factory.GetCompanyID(userId);
                using (var context = CreateContext())
                {
                    //Check Client
                    if (dtoReceipt.ReceiptNoteTypeID == 2)
                    {
                        foreach (var item in dtoReceipt.receiptNoteClientResults)
                        {
                            if (item.FactoryRawMaterialID == null)
                            {
                                throw new Exception("missing Client !!!");
                            }
                        }
                    }
                    //if (dtoReceipt.ReceiptNoteTypeID == 3)
                    //{
                    //    foreach (var item in dtoReceipt.receiptNoteOtherResults)
                    //    {
                    //        if (item.EmployeeID == null)
                    //        {
                    //            throw new Exception("missing Client !!!");
                    //        }
                    //    }
                    //}

                    if (dtoReceipt.ReceiptNoteTypeID == 4 || dtoReceipt.ReceiptNoteTypeID == 3)
                    {
                        dtoReceipt.SupplierID = null;
                        dtoReceipt.SupplierNM = null;
                        dtoReceipt.SupplierUD = null;
                    }

                    ReceiptNote dbItem = null;

                    if (id == 0)
                    {
                        if (dtoReceipt.StatusID == 2 || dtoReceipt.StatusID == 3)
                        {
                            throw new Exception("Set Status open to Save !!!");
                        }

                        dbItem = new ReceiptNote();
                        context.ReceiptNote.Add(dbItem);

                        //Automatically generate code
                        if (dtoReceipt.ReceiveTypeID == 1)// Receive type Cash
                        {
                            int    year            = DateTime.Now.Year;
                            string month           = DateTime.Now.Month.ToString().PadLeft(2, '0');
                            string receipt_pattern = "PT" + "_" + year.ToString().Substring(2) + month;
                            var    db_receiptNo    = context.ReceiptNote.Where(o => o.ReceiptNoteNo.Substring(0, 7) == receipt_pattern).OrderByDescending(o => o.ReceiptNoteNo);
                            if (db_receiptNo.ToList().Count() == 0)
                            {
                                dtoReceipt.ReceiptNoteNo = receipt_pattern + "_" + "001";
                            }
                            else
                            {
                                var select_receipt = db_receiptNo.FirstOrDefault();
                                int iNo            = Convert.ToInt32(select_receipt.ReceiptNoteNo.Substring(8, 3)) + 1;
                                dtoReceipt.ReceiptNoteNo = select_receipt.ReceiptNoteNo.Substring(0, 7) + "_" + iNo.ToString().PadLeft(3, '0');
                            }
                        }
                        else if (dtoReceipt.ReceiveTypeID == 2)// Receive type Bank
                        {
                            int    year            = DateTime.Now.Year;
                            string month           = DateTime.Now.Month.ToString().PadLeft(2, '0');
                            string receipt_pattern = "BC" + "_" + year.ToString().Substring(2) + month;
                            var    db_receiptNo    = context.ReceiptNote.Where(o => o.ReceiptNoteNo.Substring(0, 7) == receipt_pattern).OrderByDescending(o => o.ReceiptNoteNo);
                            if (db_receiptNo.ToList().Count() == 0)
                            {
                                dtoReceipt.ReceiptNoteNo = receipt_pattern + "_" + "001";
                            }
                            else
                            {
                                var select_receipt = db_receiptNo.FirstOrDefault();
                                int iNo            = Convert.ToInt32(select_receipt.ReceiptNoteNo.Substring(8, 3)) + 1;
                                dtoReceipt.ReceiptNoteNo = select_receipt.ReceiptNoteNo.Substring(0, 7) + "_" + iNo.ToString().PadLeft(3, '0');
                            }
                        }
                    }
                    else
                    {
                        dbItem = context.ReceiptNote.Where(o => o.ReceiptNoteID == id).FirstOrDefault();

                        if (dbItem.ReceiptNoteTypeID != dtoReceipt.ReceiptNoteTypeID)
                        {
                            throw new Exception("Can't change Receipt Note type !!!");
                        }
                    }
                    if (dbItem == null)
                    {
                        notification.Message = "data not found!";
                        return(false);
                    }
                    else
                    {
                        //check  status

                        /*
                         *  WorkOrderStatusID :
                         *      1 : Open
                         *      2 : Confimred
                         */

                        if (dbItem.StatusID == 2 || dbItem.StatusID == 3)
                        {
                            throw new Exception("Can't Update because receipt comfirmed !!!");
                        }

                        if (dtoReceipt.StatusID == 2 && dtoReceipt.ReceiptNoteTypeID == 1)
                        {
                            ValidatePayment(dbItem.ReceiptNoteID, 2);
                        }

                        //convert dto to db
                        converter.DTO2DB_Update(dtoReceipt, ref dbItem, userId);

                        //upload file
                        Module.Framework.DAL.DataFactory fwFactory = new Module.Framework.DAL.DataFactory();
                        string tempFolder = FrameworkSetting.Setting.AbsoluteUserTempFolder + userId.ToString() + @"\";
                        if (dtoReceipt.File_HasChange.HasValue && dtoReceipt.File_HasChange.Value)
                        {
                            dbItem.AttachedFile = fwFactory.CreateFilePointer(tempFolder, dtoReceipt.File_NewFile, dtoReceipt.AttachedFile, dtoReceipt.FriendlyName);
                        }

                        if (id == 0)
                        {
                            dbItem.CreateDate = DateTime.Now;
                            dbItem.CreateBy   = userId;
                        }
                        else
                        {
                            dbItem.UpdateDate = DateTime.Now;
                            dbItem.UpdateBy   = userId;
                        }

                        //remove orphan
                        context.ReceiptNoteClient.Local.Where(o => o.ReceiptNote == null).ToList().ForEach(o => context.ReceiptNoteClient.Remove(o));
                        context.ReceiptNoteInvoice.Local.Where(o => o.ReceiptNote == null).ToList().ForEach(o => context.ReceiptNoteInvoice.Remove(o));
                        context.ReceiptNoteOther.Local.Where(o => o.ReceiptNote == null).ToList().ForEach(o => context.ReceiptNoteOther.Remove(o));

                        //save data
                        context.SaveChanges();
                        dtoItem = GetData(userId, dbItem.ReceiptNoteID, null, out notification).Data;
                        return(true);
                    }
                }
            }
            catch (Exception ex)
            {
                notification.Type    = Library.DTO.NotificationType.Error;
                notification.Message = Library.Helper.GetInnerException(ex).Message;
                return(false);
            }
        }
        public override bool UpdateData(int userId, int id, ref object dtoItem, out Notification notification)
        {
            notification = new Library.DTO.Notification()
            {
                Type = Library.DTO.NotificationType.Success
            };
            DTO.PurchaseInvoiceDTO dtoPurchaseInvoice = ((Newtonsoft.Json.Linq.JObject)dtoItem).ToObject <DTO.PurchaseInvoiceDTO>();
            try
            {
                using (PurchaseInvoiceMngEntities context = CreateContext())
                {
                    PurchaseInvoice dbItem = null;
                    if (id == 0)
                    {
                        dbItem = new PurchaseInvoice();
                        context.PurchaseInvoice.Add(dbItem);
                    }
                    else
                    {
                        dbItem = context.PurchaseInvoice.Where(o => o.PurchaseInvoiceID == id).FirstOrDefault();
                    }
                    if (dbItem == null)
                    {
                        notification.Message = "data not found!";
                        return(false);
                    }
                    else
                    {
                        if (!dtoPurchaseInvoice.PurchaseInvoiceTypeID.HasValue)
                        {
                            throw new Exception("Please select type of purchasing invoice");
                        }

                        //upload file
                        Module.Framework.DAL.DataFactory fwFactory = new Module.Framework.DAL.DataFactory();
                        string tempFolder = FrameworkSetting.Setting.AbsoluteUserTempFolder + userId.ToString() + @"\";
                        if (dtoPurchaseInvoice.File_HasChange.HasValue && dtoPurchaseInvoice.File_HasChange.Value)
                        {
                            dtoPurchaseInvoice.AttachedFile = fwFactory.CreateFilePointer(tempFolder, dtoPurchaseInvoice.File_NewFile, dtoPurchaseInvoice.AttachedFile, dtoPurchaseInvoice.FriendlyName);
                        }
                        //convert dto to db
                        converter.DTO2DB_PurchaseInvoice(dtoPurchaseInvoice, ref dbItem, userId);

                        if (id == 0)
                        {
                            dbItem.PurchaseInvoiceStatusID = 1;
                            dbItem.SetStatusBy             = userId;
                            dbItem.SetStatusDate           = DateTime.Now;
                        }
                        //remove orphan
                        context.PurchaseInvoiceDetail.Local.Where(o => o.PurchaseInvoice == null).ToList().ForEach(o => context.PurchaseInvoiceDetail.Remove(o));

                        //save data
                        context.SaveChanges();

                        //generate purchase invoice code
                        if (string.IsNullOrEmpty(dbItem.PurchaseInvoiceUD))
                        {
                            context.PurchaseInvoiceMng_function_GeneratePurchaseInvoiceUD(dbItem.PurchaseInvoiceID, dbItem.PurchaseInvoiceDate.Value.Year, dbItem.PurchaseInvoiceDate.Value.Month);
                        }

                        //get return data
                        dtoItem = GetData(userId, dbItem.PurchaseInvoiceID, null, out notification).Data;
                        return(true);
                    }
                }
            }
            catch (Exception ex)
            {
                notification.Type    = Library.DTO.NotificationType.Error;
                notification.Message = Library.Helper.GetInnerException(ex).Message;
                return(false);
            }
        }
        public void DTO2DB_PurchasingInvoice(int iRequesterID, PurchasingInvoiceMng_Booking_View dbBooking, DTO.PurchasingInvoiceMng.PurchasingInvoice dtoItem, ref PurchasingInvoice dbItem)
        {
            Module.Framework.DAL.DataFactory fwFactory = new Module.Framework.DAL.DataFactory();
            //int userOfficeID = fwFactory.GetUserOffice(iRequesterID);
            int[] internalCompanyID = new int[] { 1, 2, 3 };
            int   userOfficeID      = 1;

            if (!internalCompanyID.ToList().Contains(fwFactory.GetCompanyID(iRequesterID).Value)) // 1, 2, 3 = AVF, AVS, AVT
            {
                userOfficeID = 4;                                                                 // fake the office id equal to 4, backward compatible
            }
            //Purchasing Invoice Detail
            if (dtoItem.PurchasingInvoiceDetails != null)
            {
                //CHECK
                foreach (var item in dbItem.PurchasingInvoiceDetail.ToArray())
                {
                    if (!dtoItem.PurchasingInvoiceDetails.Select(s => s.PurchasingInvoiceDetailID).Contains(item.PurchasingInvoiceDetailID))
                    {
                        dbItem.PurchasingInvoiceDetail.Remove(item);
                    }
                }
                //MAP
                foreach (var dtoDetail in dtoItem.PurchasingInvoiceDetails)
                {
                    PurchasingInvoiceDetail dbDetail;
                    if (dtoDetail.PurchasingInvoiceDetailID < 0)
                    {
                        dbDetail           = new PurchasingInvoiceDetail();
                        dbDetail.UnitPrice = dbBooking.PurchasingInvoiceMng_LoadingPlanDetail_View.Where(o => o.LoadingPlanDetailID == dtoDetail.LoadingPlanDetailID).FirstOrDefault().UnitPrice;
                        dbItem.PurchasingInvoiceDetail.Add(dbDetail);
                    }
                    else
                    {
                        dbDetail = dbItem.PurchasingInvoiceDetail.FirstOrDefault(o => o.PurchasingInvoiceDetailID == dtoDetail.PurchasingInvoiceDetailID);
                        if (userOfficeID != 4)
                        {
                            dbDetail.UnitPrice = dtoDetail.UnitPrice;
                        }
                    }
                    if (dbDetail != null)
                    {
                        AutoMapper.Mapper.Map <DTO.PurchasingInvoiceMng.PurchasingInvoiceDetail, PurchasingInvoiceDetail>(dtoDetail, dbDetail);
                    }
                }
            }
            //Purchasing Invoice Sparepart Detail
            if (dtoItem.PurchasingInvoiceSparepartDetails != null)
            {
                //CHECK
                foreach (var item in dbItem.PurchasingInvoiceSparepartDetail.ToArray())
                {
                    if (!dtoItem.PurchasingInvoiceSparepartDetails.Select(s => s.PurchasingInvoiceSparepartDetailID).Contains(item.PurchasingInvoiceSparepartDetailID))
                    {
                        dbItem.PurchasingInvoiceSparepartDetail.Remove(item);
                    }
                }
                //MAP
                foreach (var dtoDetail in dtoItem.PurchasingInvoiceSparepartDetails)
                {
                    PurchasingInvoiceSparepartDetail dbDetail;
                    if (dtoDetail.PurchasingInvoiceSparepartDetailID < 0)
                    {
                        dbDetail           = new PurchasingInvoiceSparepartDetail();
                        dbDetail.UnitPrice = dbBooking.PurchasingInvoiceMng_LoadingPlanSparepartDetail_View.Where(o => o.LoadingPlanSparepartDetailID == dtoDetail.LoadingPlanSparepartDetailID).FirstOrDefault().UnitPrice;
                        dbItem.PurchasingInvoiceSparepartDetail.Add(dbDetail);
                    }
                    else
                    {
                        dbDetail = dbItem.PurchasingInvoiceSparepartDetail.FirstOrDefault(o => o.PurchasingInvoiceSparepartDetailID == dtoDetail.PurchasingInvoiceSparepartDetailID);
                        if (userOfficeID != 4)
                        {
                            dbDetail.UnitPrice = dtoDetail.UnitPrice;
                        }
                    }
                    if (dbDetail != null)
                    {
                        AutoMapper.Mapper.Map <DTO.PurchasingInvoiceMng.PurchasingInvoiceSparepartDetail, PurchasingInvoiceSparepartDetail>(dtoDetail, dbDetail);
                    }
                }
            }

            //Purchasing Invoice Sparepart Detail
            if (dtoItem.PurchasingInvoiceExtraDetails != null)
            {
                //CHECK
                foreach (var item in dbItem.PurchasingInvoiceExtraDetail.ToArray())
                {
                    if (!dtoItem.PurchasingInvoiceExtraDetails.Select(s => s.PurchasingInvoiceExtraDetailID).Contains(item.PurchasingInvoiceExtraDetailID))
                    {
                        dbItem.PurchasingInvoiceExtraDetail.Remove(item);
                    }
                }
                //MAP
                foreach (var dtoDetail in dtoItem.PurchasingInvoiceExtraDetails)
                {
                    PurchasingInvoiceExtraDetail dbDetail;
                    if (dtoDetail.PurchasingInvoiceExtraDetailID < 0)
                    {
                        dbDetail = new PurchasingInvoiceExtraDetail();
                        dbItem.PurchasingInvoiceExtraDetail.Add(dbDetail);
                    }
                    else
                    {
                        dbDetail = dbItem.PurchasingInvoiceExtraDetail.FirstOrDefault(o => o.PurchasingInvoiceExtraDetailID == dtoDetail.PurchasingInvoiceExtraDetailID);
                    }
                    if (dbDetail != null)
                    {
                        AutoMapper.Mapper.Map <DTO.PurchasingInvoiceMng.PurchasingInvoiceExtraDetail, PurchasingInvoiceExtraDetail>(dtoDetail, dbDetail);
                    }
                }
            }

            //Purchasing Invoice Sample Detail
            if (dtoItem.PurchasingInvoiceSampleDetails != null)
            {
                //CHECK
                foreach (var item in dbItem.PurchasingInvoiceSampleDetail.ToArray())
                {
                    if (!dtoItem.PurchasingInvoiceSampleDetails.Select(s => s.PurchasingInvoiceSampleDetailID).Contains(item.PurchasingInvoiceSampleDetailID))
                    {
                        dbItem.PurchasingInvoiceSampleDetail.Remove(item);
                    }
                }
                //MAP
                foreach (var dtoDetail in dtoItem.PurchasingInvoiceSampleDetails)
                {
                    PurchasingInvoiceSampleDetail dbDetail;
                    if (dtoDetail.PurchasingInvoiceSampleDetailID < 0)
                    {
                        dbDetail           = new PurchasingInvoiceSampleDetail();
                        dbDetail.UnitPrice = dbBooking.PurchasingInvoiceMng_LoadingPlanSampleDetail_View.Where(o => o.LoadingPlanSampleDetailID == dtoDetail.LoadingPlanSampleDetailID).FirstOrDefault().UnitPrice;
                        dbItem.PurchasingInvoiceSampleDetail.Add(dbDetail);
                    }
                    else
                    {
                        dbDetail = dbItem.PurchasingInvoiceSampleDetail.FirstOrDefault(o => o.PurchasingInvoiceSampleDetailID == dtoDetail.PurchasingInvoiceSampleDetailID);
                        if (userOfficeID != 4)
                        {
                            dbDetail.UnitPrice = dtoDetail.UnitPrice;
                        }
                    }
                    if (dbDetail != null)
                    {
                        AutoMapper.Mapper.Map <DTO.PurchasingInvoiceMng.PurchasingInvoiceSampleDetail, PurchasingInvoiceSampleDetail>(dtoDetail, dbDetail);
                    }
                }
            }

            //Purchasing Invoice
            AutoMapper.Mapper.Map <DTO.PurchasingInvoiceMng.PurchasingInvoice, PurchasingInvoice>(dtoItem, dbItem);
            if (dtoItem.PurchasingInvoiceID > 0)
            {
                dbItem.UpdatedDate = DateTime.Now;
                dbItem.UpdatedBy   = dtoItem.UpdatedBy;
            }
            else
            {
                dbItem.CreatedDate = DateTime.Now;
                dbItem.CreatedBy   = dtoItem.UpdatedBy;
            }
            dbItem.InvoiceDate = dtoItem.InvoiceDate.ConvertStringToDateTime();
            if (dbItem.SupplierID == 336037)
            {
                dbItem.FactoryRawMaterialID = 250;
            }
        }
Exemple #19
0
        public override bool UpdateData(int userId, int id, ref object dtoItem, out Library.DTO.Notification notification)
        {
            notification = new Library.DTO.Notification()
            {
                Type = Library.DTO.NotificationType.Success
            };
            DTO.FactoryStockReceipt dtoFactoryStockReceipt = ((Newtonsoft.Json.Linq.JObject)dtoItem).ToObject <DTO.FactoryStockReceipt>();
            dtoFactoryStockReceipt.UpdatedBy = userId;
            Module.Framework.DAL.DataFactory fwFactory = new Module.Framework.DAL.DataFactory();
            try
            {
                using (FactoryStockReceiptEntities context = CreateContext())
                {
                    FactoryStockReceipt dbItem = null;
                    if (id == 0)
                    {
                        dbItem = new FactoryStockReceipt();
                        context.FactoryStockReceipt.Add(dbItem);
                    }
                    else
                    {
                        dbItem = context.FactoryStockReceipt.Where(o => o.FactoryStockReceiptID == id).FirstOrDefault();
                    }

                    if (dbItem == null)
                    {
                        notification.Message = "data not found!";
                        return(false);
                    }
                    else
                    {
                        //
                        if (!dtoFactoryStockReceipt.FactoryID.HasValue) // 2 : Export
                        {
                            throw new Exception("Factory is empty. You should fill-in factory");
                        }
                        //check permission on factory
                        if (fwFactory.CheckFactoryPermission(userId, dtoFactoryStockReceipt.FactoryID.Value) == 0)
                        {
                            throw new Exception("You do not have access permission on this factory");
                        }

                        //validate quantity
                        if (dtoFactoryStockReceipt.ReceiptTypeID == 1) //import
                        {
                            ValidateQntImport(dtoFactoryStockReceipt);
                        }
                        else if (dtoFactoryStockReceipt.ReceiptTypeID == 2)  //export
                        {
                            ValidateQntExport(dtoFactoryStockReceipt);
                        }

                        //convert dto to db
                        converter.DTO2DB_FactoryStockReceipt(dtoFactoryStockReceipt, ref dbItem);
                        //remove orphan item
                        context.FactoryStockReceiptDetail.Local.Where(o => o.FactoryStockReceipt == null).ToList().ForEach(o => context.FactoryStockReceiptDetail.Remove(o));
                        //save data
                        context.SaveChanges();
                        //update receipt no
                        context.FactoryStockReceiptMng_function_GenerateReceipNo(dbItem.FactoryStockReceiptID, dbItem.ReceiptTypeID);
                        //get return data
                        dtoItem = GetData(userId, dbItem.FactoryStockReceiptID, out notification).Data;
                        return(true);
                    }
                }
            }
            catch (Exception ex)
            {
                notification.Type    = Library.DTO.NotificationType.Error;
                notification.Message = ex.Message;
                notification.DetailMessage.Add(ex.Message);
                if (ex.GetBaseException() != null)
                {
                    notification.DetailMessage.Add(ex.GetBaseException().Message);
                }
                return(false);
            }
        }
Exemple #20
0
        public override bool UpdateData(int userId, int id, ref object dtoItem, out Notification notification)
        {
            notification = new Library.DTO.Notification()
            {
                Type = Library.DTO.NotificationType.Success
            };
            DTO.PurchaseOrderDto dtoPurchaseOrder = ((Newtonsoft.Json.Linq.JObject)dtoItem).ToObject <DTO.PurchaseOrderDto>();
            try
            {
                //get companyID
                Module.Framework.DAL.DataFactory fw_factory = new Framework.DAL.DataFactory();
                int?companyID = fw_factory.GetCompanyID(userId);
                using (PurchaseOrderMngEntities context = CreateContext())
                {
                    PurchaseOrder dbItem = null;
                    if (id == 0)
                    {
                        dbItem = new PurchaseOrder();
                        context.PurchaseOrder.Add(dbItem);
                    }
                    else
                    {
                        dbItem = context.PurchaseOrder.Where(o => o.PurchaseOrderID == id).FirstOrDefault();
                    }
                    if (dbItem == null)
                    {
                        notification.Message = "data not found!";
                        return(false);
                    }
                    else
                    {
                        //upload file
                        Module.Framework.DAL.DataFactory fwFactory = new Module.Framework.DAL.DataFactory();
                        string tempFolder = FrameworkSetting.Setting.AbsoluteUserTempFolder + userId.ToString() + @"\";
                        if (dtoPurchaseOrder.File_HasChange.HasValue && dtoPurchaseOrder.File_HasChange.Value)
                        {
                            dtoPurchaseOrder.AttachedFile = fwFactory.CreateFilePointer(tempFolder, dtoPurchaseOrder.File_NewFile, dtoPurchaseOrder.AttachedFile, dtoPurchaseOrder.FriendlyName);
                        }

                        //
                        //convert dto to db
                        converter.DTO2DB_PurchaseOrder(dtoPurchaseOrder, ref dbItem);
                        dbItem.CompanyID   = companyID;
                        dbItem.UpdatedBy   = userId;
                        dbItem.UpdatedDate = DateTime.Now;

                        if (id == 0)
                        {
                            //dbItem.PurchaseOrderUD = context.PurchaseOrderMng_function_GeneratePurchaseOrderUD(dtoPurchaseOrder.FactoryRawMaterialUD, dtoPurchaseOrder.PurchaseOrderDate, dtoPurchaseOrder.FactoryRawMaterialID).FirstOrDefault();
                            dbItem.CreatedBy   = userId;
                            dbItem.CreatedDate = DateTime.Now;
                            if (dtoPurchaseOrder.PurchaseOrderStatusID != 4)
                            {
                                dbItem.PurchaseOrderStatusID = 1;
                            }
                        }

                        // loop dto item detail
                        foreach (var item in dtoPurchaseOrder.PurchaseOrderDetailDTOs)
                        {
                            if (item.IsChangePrice == true)
                            {
                                PurchaseOrderDetailPriceHistory dbItemPriceHistory = new PurchaseOrderDetailPriceHistory();
                                context.PurchaseOrderDetailPriceHistory.Add(dbItemPriceHistory);
                                dbItemPriceHistory.PurchaseOrderDetailID = (int)item.PurchaseOrderDetailID;
                                dbItemPriceHistory.UnitPrice             = (decimal)item.UnitPrice;
                                dbItemPriceHistory.ApprovedBy            = userId;
                                dbItemPriceHistory.ApprovedDate          = DateTime.Now;
                            }
                        }
                        //remove orphan

                        context.PurchaseOrderDetail.Local.Where(o => o.PurchaseOrder == null).ToList().ForEach(o => context.PurchaseOrderDetail.Remove(o));
                        context.PurchaseOrderWorkOrderDetail.Local.Where(o => o.PurchaseOrderDetail == null).ToList().ForEach(o => context.PurchaseOrderWorkOrderDetail.Remove(o));
                        context.PurchaseOrderDetailReceivingPlan.Local.Where(o => o.PurchaseOrderDetail == null).ToList().ForEach(o => context.PurchaseOrderDetailReceivingPlan.Remove(o));
                        context.PurchaseOrderDetailPriceHistory.Local.Where(o => o.PurchaseOrderDetail == null).ToList().ForEach(o => context.PurchaseOrderDetailPriceHistory.Remove(o));
                        //save data
                        context.SaveChanges();

                        // Generate PurchaseOrderUD.
                        if (id == 0)
                        {
                            context.PurchaseOrderMng_function_GeneratePurchaseOrderUD(dbItem.Season, dbItem.FactoryRawMaterialID, dbItem.PurchaseOrderID);
                        }
                        else
                        {
                            // Auto update unit price in receiving note
                            UpdateUnitPriceReceivingNoteDetail(dbItem.PurchaseOrderID, out notification);
                        }

                        //get return data
                        dtoItem = GetData(userId, dbItem.PurchaseOrderID, out notification).Data;

                        if (id == 0)
                        {
                            string emailSubject = string.Format("[Tilsoft] - Purchasing Order - {0} - {1}", dbItem.PurchaseOrderUD, dtoPurchaseOrder.FactoryRawMaterialShortNM);
                            string emailBody    = string.Format("Please approve PO: {0} - {1} - {2}", dbItem.PurchaseOrderUD, dtoPurchaseOrder.FactoryRawMaterialShortNM, "http://app.tilsoft.bg/PurchaseOrderMng/Edit/" + dbItem.PurchaseOrderID);
                            SendNotification(emailSubject, emailBody);
                        }

                        return(true);
                    }
                }
            }
            catch (Exception ex)
            {
                notification.Type    = Library.DTO.NotificationType.Error;
                notification.Message = ex.Message;
                notification.DetailMessage.Add(ex.Message);
                if (ex.GetBaseException() != null)
                {
                    notification.DetailMessage.Add(ex.GetBaseException().Message);
                }
                return(false);
            }
        }
Exemple #21
0
        public void DTO2DB(DTO.LoadingPlan dtoItem, ref LoadingPlan dbItem, string _tempFolder, bool mapDetail)
        {
            // map fields
            AutoMapper.Mapper.Map <DTO.LoadingPlan, LoadingPlan>(dtoItem, dbItem);

            // insert image
            Module.Framework.DAL.DataFactory fwFactory = new Module.Framework.DAL.DataFactory();
            if (dtoItem.ProductPicture1_HasChange)
            {
                dbItem.ProductPicture1 = fwFactory.CreateFilePointer(_tempFolder, dtoItem.ProductPicture1_NewFile, dtoItem.ProductPicture1);
            }
            if (dtoItem.ProductPicture2_HasChange)
            {
                dbItem.ProductPicture2 = fwFactory.CreateFilePointer(_tempFolder, dtoItem.ProductPicture2_NewFile, dtoItem.ProductPicture2);
            }
            if (dtoItem.ContainerPicture1_HasChange)
            {
                dbItem.ContainerPicture1 = fwFactory.CreateFilePointer(_tempFolder, dtoItem.ContainerPicture1_NewFile, dtoItem.ContainerPicture1);
            }
            if (dtoItem.ContainerPicture2_HasChange)
            {
                dbItem.ContainerPicture2 = fwFactory.CreateFilePointer(_tempFolder, dtoItem.ContainerPicture2_NewFile, dtoItem.ContainerPicture2);
            }
            if (!string.IsNullOrEmpty(dtoItem.ShipmentDate))
            {
                if (DateTime.TryParse(dtoItem.ShipmentDate, nl, System.Globalization.DateTimeStyles.None, out tmpDate))
                {
                    dbItem.ShipmentDate = tmpDate;
                }
            }
            if (!string.IsNullOrEmpty(dtoItem.LoadingDate))
            {
                if (DateTime.TryParse(dtoItem.LoadingDate, nl, System.Globalization.DateTimeStyles.None, out tmpDate))
                {
                    dbItem.LoadingDate = tmpDate;
                }
            }

            if (mapDetail)
            {
                // map detail
                if (dtoItem.LoadingPlanDetails != null)
                {
                    // check for child rows deleted
                    foreach (LoadingPlanDetail dbDetail in dbItem.LoadingPlanDetail.ToArray())
                    {
                        if (!dtoItem.LoadingPlanDetails.Select(o => o.LoadingPlanDetailID).Contains(dbDetail.LoadingPlanDetailID))
                        {
                            dbItem.LoadingPlanDetail.Remove(dbDetail);
                        }
                    }

                    // map child rows
                    foreach (DTO.LoadingPlanDetail dtoDetail in dtoItem.LoadingPlanDetails)
                    {
                        LoadingPlanDetail dbDetail;
                        if (dtoDetail.LoadingPlanDetailID <= 0)
                        {
                            dbDetail = new LoadingPlanDetail();
                            dbItem.LoadingPlanDetail.Add(dbDetail);
                        }
                        else
                        {
                            dbDetail = dbItem.LoadingPlanDetail.FirstOrDefault(o => o.LoadingPlanDetailID == dtoDetail.LoadingPlanDetailID);
                        }

                        if (dbDetail != null)
                        {
                            AutoMapper.Mapper.Map <DTO.LoadingPlanDetail, LoadingPlanDetail>(dtoDetail, dbDetail);
                        }
                    }
                }

                // map sparepart detail
                if (dtoItem.LoadingPlanSparepartDetails != null)
                {
                    // check for child rows deleted
                    foreach (LoadingPlanSparepartDetail dbSparepartDetail in dbItem.LoadingPlanSparepartDetail.ToArray())
                    {
                        if (!dtoItem.LoadingPlanSparepartDetails.Select(o => o.LoadingPlanSparepartDetailID).Contains(dbSparepartDetail.LoadingPlanSparepartDetailID))
                        {
                            dbItem.LoadingPlanSparepartDetail.Remove(dbSparepartDetail);
                        }
                    }

                    // map child rows
                    foreach (DTO.LoadingPlanSparepartDetail dtoSparepartDetail in dtoItem.LoadingPlanSparepartDetails)
                    {
                        LoadingPlanSparepartDetail dbSparepartDetail;
                        if (dtoSparepartDetail.LoadingPlanSparepartDetailID <= 0)
                        {
                            dbSparepartDetail = new LoadingPlanSparepartDetail();
                            dbItem.LoadingPlanSparepartDetail.Add(dbSparepartDetail);
                        }
                        else
                        {
                            dbSparepartDetail = dbItem.LoadingPlanSparepartDetail.FirstOrDefault(o => o.LoadingPlanSparepartDetailID == dtoSparepartDetail.LoadingPlanSparepartDetailID);
                        }

                        if (dbSparepartDetail != null)
                        {
                            AutoMapper.Mapper.Map <DTO.LoadingPlanSparepartDetail, LoadingPlanSparepartDetail>(dtoSparepartDetail, dbSparepartDetail);
                        }
                    }
                }
            }
        }
Exemple #22
0
        public bool UpdateData(int id, ref DTO.MaterialTypeMng.MaterialType dtoItem, int userId, out Library.DTO.Notification notification)
        {
            notification      = new Notification();
            notification.Type = NotificationType.Success;

            int    number;
            string indexName;

            try
            {
                using (var context = CreateContext())
                {
                    MaterialType materialType = null;

                    if (id == 0)
                    {
                        materialType = new MaterialType();

                        context.MaterialType.Add(materialType);
                    }
                    else
                    {
                        materialType = context.MaterialType.FirstOrDefault(o => o.MaterialTypeID == id);
                    }

                    if (materialType == null)
                    {
                        notification.Message = "Material Type not found!";

                        return(false);
                    }
                    else
                    {
                        //hangtag image
                        Module.Framework.DAL.DataFactory fwFactory = new Module.Framework.DAL.DataFactory();
                        // Fixed bug check dtoItem.HangTagFileHasChange has value after get value - 21 FEB 2018.
                        if (dtoItem.HangTagFileHasChange.HasValue)
                        {
                            dtoItem.HangTagFile = fwFactory.CreateNoneImageFilePointer(FrameworkSetting.Setting.AbsoluteUserTempFolder + userId.ToString() + @"\", dtoItem.NewHangTagFile, dtoItem.HangTagFile);
                        }
                        converter.DTO2BD_MaterialType(dtoItem, ref materialType);
                        if (id <= 0)
                        {
                            // Generate code.
                            using (var trans = context.Database.BeginTransaction())
                            {
                                context.Database.ExecuteSqlCommand("SELECT * FROM MaterialType WITH (TABLOCKX, HOLDLOCK)");

                                try
                                {
                                    var newCode = context.MaterialTypeMng_function_GenerateCode().FirstOrDefault();

                                    if (!"**".Equals(newCode))
                                    {
                                        materialType.MaterialTypeUD = newCode;

                                        context.SaveChanges();
                                    }
                                    else
                                    {
                                        notification.Type    = NotificationType.Error;
                                        notification.Message = "Auto generated code exceed maximum option: [ZZ]";
                                    }
                                }
                                catch (Exception ex)
                                {
                                    trans.Rollback();
                                    throw ex;
                                }
                                finally
                                {
                                    trans.Commit();
                                }
                            }
                        }
                        else
                        {
                            context.SaveChanges();
                        }

                        dtoItem = GetData(materialType.MaterialTypeID, out notification).Data;

                        return(true);
                    }
                }
            }
            catch (DataException exData)
            {
                notification.Type = NotificationType.Error;
                ErrorHelper.DataExceptionParser(exData, out number, out indexName);

                if (number == 2601 && !string.IsNullOrEmpty(indexName))
                {
                    if ("MaterialTypeUDUnique".Equals(indexName))
                    {
                        notification.Message = "The Material Type Code is already exists.";
                    }
                }
                else
                {
                    notification.Message = exData.Message;
                }

                return(false);
            }
            catch (Exception ex)
            {
                notification.Type    = NotificationType.Error;
                notification.Message = ex.Message;

                return(false);
            }
        }
        public void DTO2BD_Forwarder(DTO.ForwarderMng.Forwarder dtoItem, ref Forwarder dbItem, string tempFolder)
        {
            if (dtoItem.ForwarderImages != null)
            {
                foreach (var item in dbItem.ForwarderImage.ToArray())
                {
                    if (!dtoItem.ForwarderImages.Select(s => s.ForwarderImageID).Contains(item.ForwarderImageID))
                    {
                        dbItem.ForwarderImage.Remove(item);
                    }
                }

                foreach (var dto in dtoItem.ForwarderImages)
                {
                    ForwarderImage item;

                    if (dto.ForwarderImageID < 0)
                    {
                        item = new ForwarderImage();

                        dbItem.ForwarderImage.Add(item);
                    }
                    else
                    {
                        item = dbItem.ForwarderImage.FirstOrDefault(s => s.ForwarderImageID == dto.ForwarderImageID);
                    }

                    if (item != null)
                    {
                        AutoMapper.Mapper.Map <DTO.ForwarderMng.ForwarderImage, ForwarderImage>(dto, item);

                        if (dto.File_HasChange.HasValue && dto.File_HasChange.Value)
                        {
                            Module.Framework.DAL.DataFactory fwFactory = new Module.Framework.DAL.DataFactory();
                            item.FileUD = fwFactory.CreateNoneImageFilePointer(tempFolder, dto.File_NewFile, dto.FileUD);
                        }
                    }
                }
            }

            if (dtoItem.ForwarderPICs != null)
            {
                foreach (var item1 in dbItem.ForwarderPIC.ToArray())
                {
                    if (!dtoItem.ForwarderPICs.Select(s => s.ForwarderPICID).Contains(item1.ForwarderPICID))
                    {
                        dbItem.ForwarderPIC.Remove(item1);
                    }
                }

                foreach (var dto1 in dtoItem.ForwarderPICs)
                {
                    ForwarderPIC item1;

                    if (dto1.ForwarderPICID < 0)
                    {
                        item1 = new ForwarderPIC();
                        dbItem.ForwarderPIC.Add(item1);
                    }
                    else
                    {
                        item1 = dbItem.ForwarderPIC.FirstOrDefault(s => s.ForwarderPICID == dto1.ForwarderPICID);
                    }

                    if (item1 != null)
                    {
                        AutoMapper.Mapper.Map <DTO.ForwarderMng.ForwarderPIC, ForwarderPIC>(dto1, item1);
                    }
                }
            }

            AutoMapper.Mapper.Map <DTO.ForwarderMng.Forwarder, Forwarder>(dtoItem, dbItem);
        }
Exemple #24
0
        public void DTO2BD(DTO.CushionColorMng.CushionColor dtoItem, string tempFolder, ref CushionColor dbItem)
        {
            AutoMapper.Mapper.Map <DTO.CushionColorMng.CushionColor, CushionColor>(dtoItem, dbItem);
            dbItem.UpdatedDate = DateTime.Now;

            // Tri
            // Add created Cushion Color
            if (dtoItem.CushionColorID == 0)
            {
                dbItem.CreatedBy   = dtoItem.CreatedBy;
                dbItem.CreatedDate = DateTime.Now;
            }

            // map child
            if (dtoItem.CushionColorProductGroups != null)
            {
                // map child rows
                foreach (DTO.CushionColorMng.CushionColorProductGroup dtoGroup in dtoItem.CushionColorProductGroups)
                {
                    CushionColorProductGroup dbGroup;
                    if (dtoGroup.CushionColorProductGroupID <= 0)
                    {
                        dbGroup = new CushionColorProductGroup();
                        dbItem.CushionColorProductGroup.Add(dbGroup);
                    }
                    else
                    {
                        dbGroup = dbItem.CushionColorProductGroup.FirstOrDefault(o => o.CushionColorProductGroupID == dtoGroup.CushionColorProductGroupID);
                    }

                    if (dbGroup != null)
                    {
                        AutoMapper.Mapper.Map <DTO.CushionColorMng.CushionColorProductGroup, CushionColorProductGroup>(dtoGroup, dbGroup);
                    }
                }
            }

            // Mapping cushion color test report
            if (dtoItem.CushionColorTestReports != null)
            {
                foreach (var item in dbItem.CushionColorTestReport.ToArray())
                {
                    if (!dtoItem.CushionColorTestReports.Select(s => s.CushionColorTestReportID).Contains(item.CushionColorTestReportID))
                    {
                        dbItem.CushionColorTestReport.Remove(item);
                    }
                }

                Module.Framework.DAL.DataFactory fwFactory = new Module.Framework.DAL.DataFactory();

                // Mapping cushion color test report rows
                foreach (DTO.CushionColorMng.CushionColorTestReport dtoCushionColorTestReport in dtoItem.CushionColorTestReports)
                {
                    CushionColorTestReport dbCushionColorTestReport;

                    if (dtoCushionColorTestReport.CushionColorTestReportID <= 0)
                    {
                        dbCushionColorTestReport = new CushionColorTestReport();
                        dbItem.CushionColorTestReport.Add(dbCushionColorTestReport);
                    }
                    else
                    {
                        dbCushionColorTestReport = dbItem.CushionColorTestReport.FirstOrDefault(o => o.CushionColorTestReportID == dtoCushionColorTestReport.CushionColorTestReportID);
                    }

                    if (dbCushionColorTestReport != null)
                    {
                        Mapper.Map <DTO.CushionColorMng.CushionColorTestReport, CushionColorTestReport>(dtoCushionColorTestReport, dbCushionColorTestReport);

                        if (dtoCushionColorTestReport.File_HasChange.HasValue && dtoCushionColorTestReport.File_HasChange.Value)
                        {
                            dbCushionColorTestReport.FileUD = fwFactory.CreateNoneImageFilePointer(tempFolder, dtoCushionColorTestReport.File_NewFile, dtoCushionColorTestReport.FileUD);
                        }
                    }
                }
            }
        }
        public override bool UpdateData(int userId, int id, ref object dtoItem, out Notification notification)
        {
            notification = new Notification {
                Type = NotificationType.Success
            };

            DTO.PurchaseQuotationDTO dtoPurchaseQuotation = ((Newtonsoft.Json.Linq.JObject)dtoItem).ToObject <DTO.PurchaseQuotationDTO>();

            try
            {
                // 1. Check validation validFrom and validTo
                var validFrom = dtoPurchaseQuotation.ValidFrom.ConvertStringToDateTime();
                var validTo   = dtoPurchaseQuotation.ValidTo.ConvertStringToDateTime();

                // 1.1. Case validFrom not value
                if (!validFrom.HasValue)
                {
                    notification.Type    = NotificationType.Error;
                    notification.Message = "Valid From is invalid!";
                    return(false);
                }

                // 1.2. Compare
                if (validTo.HasValue)
                {
                    if (validTo.Value.CompareTo(validFrom.Value) < 0)
                    {
                        notification.Type    = NotificationType.Error;
                        notification.Message = "Valid From is less than Valid To!";
                        return(false);
                    }
                }

                using (var context = CreatContext())
                {
                    PurchaseQuotation dbItem;

                    if (id == 0)
                    {
                        dbItem = new PurchaseQuotation();
                        context.PurchaseQuotation.Add(dbItem);
                    }
                    else
                    {
                        dbItem = context.PurchaseQuotation.Where(o => o.PurchaseQuotationID == id).FirstOrDefault();
                    }

                    if (dbItem == null)
                    {
                        notification.Type    = NotificationType.Error;
                        notification.Message = "Data Not Found !";
                        return(false);
                    }
                    else
                    {
                        //converter
                        converter.DTO2DB_PurchaseQuatation(dtoPurchaseQuotation, ref dbItem);

                        //upload file
                        Module.Framework.DAL.DataFactory fwFactory = new Module.Framework.DAL.DataFactory();
                        string tempFolder = FrameworkSetting.Setting.AbsoluteUserTempFolder + userId.ToString() + @"\";
                        if (dtoPurchaseQuotation.File_HasChange.HasValue && dtoPurchaseQuotation.File_HasChange.Value)
                        {
                            dbItem.AttachedFile = fwFactory.CreateFilePointer(tempFolder, dtoPurchaseQuotation.File_NewFile, dtoPurchaseQuotation.AttachedFile, dtoPurchaseQuotation.FriendlyName);
                        }

                        //Remove
                        context.PurchaseQuotationDetail.Local.Where(o => o.PurchaseQuotation == null).ToList().ForEach(o => context.PurchaseQuotationDetail.Remove(o));

                        int?companyID = fwFactory.GetCompanyID(userId);
                        dbItem.CompanyID   = companyID;
                        dbItem.UpdatedBy   = userId;
                        dbItem.UpdatedDate = DateTime.Now;

                        if (id == 0)
                        {
                            dbItem.PurchaseQuotationUD = context.PurchaseQuotationMng_function_GeneratePurchaseQuotationUD().FirstOrDefault();
                            dbItem.CreatedBy           = userId;
                            dbItem.CreatedDate         = DateTime.Now;
                        }

                        /// cuong.tran: ProductionFrameWeight - start
                        foreach (var item in dtoPurchaseQuotation.PurchaseQuotationDetailDTOs)
                        {
                            /// Only material is component
                            if (item.ProductionItemTypeID == 1 && item.FrameWeight.HasValue)
                            {
                                var dtoFrameWeight = context.ProductionFrameWeight.FirstOrDefault(o => o.ProductionItemID == item.ProductionItemID);

                                if (dtoFrameWeight == null)
                                {
                                    // Insert table ProductionFrameWeight
                                    ProductionFrameWeight dbFrameWeight = new ProductionFrameWeight();
                                    context.ProductionFrameWeight.Add(dbFrameWeight);

                                    dbFrameWeight.ProductionItemID = item.ProductionItemID;
                                    dbFrameWeight.FrameWeight      = item.FrameWeight;
                                    dbFrameWeight.UpdatedBy        = userId;
                                    dbFrameWeight.UpdatedDate      = DateTime.Now;

                                    context.SaveChanges();

                                    // Insert table ProductionFrameWeightHistory
                                    ProductionFrameWeightHistory dbFrameWeightHistory = new ProductionFrameWeightHistory();
                                    context.ProductionFrameWeightHistory.Add(dbFrameWeightHistory);

                                    dbFrameWeightHistory.ProductionFrameWeightID = dbFrameWeight.ProductionFrameWeightID;
                                    dbFrameWeightHistory.FrameWeight             = item.FrameWeight;
                                    dbFrameWeightHistory.UpdatedBy   = userId;
                                    dbFrameWeightHistory.UpdatedDate = DateTime.Now;

                                    context.SaveChanges();
                                }
                            }
                        }
                        /// cuong.tran: ProductionFrameWeight - e n d

                        //Save
                        context.SaveChanges();

                        dtoItem = GetData(dbItem.PurchaseQuotationID, out notification).Data;
                        return(true);
                    }
                }
            }
            catch (Exception ex)
            {
                notification.Type    = NotificationType.Error;
                notification.Message = Library.Helper.GetInnerException(ex).Message;
                return(false);
            }
        }
        public override bool UpdateData(int userId, int id, ref object dtoItem, out Library.DTO.Notification notification)
        {
            ComplianceProcessDTO inputParam = ((Newtonsoft.Json.Linq.JObject)dtoItem).ToObject <ComplianceProcessDTO>();

            notification = new Library.DTO.Notification()
            {
                Type = Library.DTO.NotificationType.Success
            };
            Module.Framework.DAL.DataFactory fwFactory = new Module.Framework.DAL.DataFactory();
            try
            {
                using (ComplianceMngEntities context = CreateContext())
                {
                    ComplianceProcess dbItem = null;
                    if (id == 0)
                    {
                        dbItem = new ComplianceProcess();
                        context.ComplianceProcess.Add(dbItem);

                        dbItem.ComplianceProcessUD = context.ComplianceMng_function_GenerateCode().FirstOrDefault();
                    }
                    else
                    {
                        //get db item
                        dbItem = context.ComplianceProcess.FirstOrDefault(o => o.ComplianceProcessID == id);
                    }

                    if (dbItem == null)
                    {
                        notification.Message = "Comliance not found!";
                        return(false);
                    }
                    else
                    {
                        dbItem.UpdatedBy   = userId;
                        dbItem.UpdatedDate = DateTime.Now;

                        // process Detail
                        foreach (DTO.ComplianceAttachedFileDTO dtoDetail in inputParam.ComplianceAttachedFileDTOs)
                        {
                            // FileUD
                            if (dtoDetail.FileUDHasChange)
                            {
                                if (string.IsNullOrEmpty(dtoDetail.NewFileUD))
                                {
                                    if (dtoDetail.FileUD == dtoDetail.NewFileUD)
                                    {
                                        dtoDetail.FileUD = null;
                                    }
                                    else
                                    {
                                        fwFactory.RemoveFile(dtoDetail.FileUD);
                                    }
                                }
                                else
                                {
                                    dtoDetail.FileUD = fwFactory.CreateNoneImageFilePointer(FrameworkSetting.Setting.AbsoluteUserTempFolder + userId.ToString() + @"\", dtoDetail.NewFileUD, dtoDetail.FileUD, dtoDetail.FileUDFriendlyName);
                                }
                            }
                        }
                        foreach (DTO.CompliancePICDTO dtoDetail in inputParam.CompliancePICDTOs)
                        {
                            // FileUD
                            if (dtoDetail.FileUDHasChange)
                            {
                                if (string.IsNullOrEmpty(dtoDetail.NewFileUD))
                                {
                                    if (dtoDetail.FileUD == dtoDetail.NewFileUD)
                                    {
                                        dtoDetail.FileUD = null;
                                    }
                                    else
                                    {
                                        fwFactory.RemoveFile(dtoDetail.FileUD);
                                    }
                                }
                                else
                                {
                                    dtoDetail.FileUD = fwFactory.CreateNoneImageFilePointer(FrameworkSetting.Setting.AbsoluteUserTempFolder + userId.ToString() + @"\", dtoDetail.NewFileUD, dtoDetail.FileUD, dtoDetail.FileUDFriendlyName);
                                }
                            }
                        }

                        //read dto to db
                        converter.DTO2DB_ComplianceProcess(inputParam, ref dbItem, userId);

                        //delete offerline is null
                        context.ComplianceAttachedFile.Local.Where(o => o.ComplianceProcess == null).ToList().ForEach(o => context.ComplianceAttachedFile.Remove(o));
                        context.CompliancePIC.Local.Where(o => o.ComplianceProcess == null).ToList().ForEach(o => context.CompliancePIC.Remove(o));
                        //save data
                        context.SaveChanges();

                        //reload data
                        if (id > 0)
                        {
                            dtoItem = new ComplianceProcessDTO {
                                ComplianceProcessID = id
                            };
                        }
                        else
                        {
                            dtoItem = new ComplianceProcessDTO {
                                ComplianceProcessID = dbItem.ComplianceProcessID
                            };
                        }

                        return(true);
                    }
                }
            }
            catch (Exception ex)
            {
                notification.Type    = Library.DTO.NotificationType.Error;
                notification.Message = Library.Helper.HandleExceptionSingleLine(ex);
            }

            return(false);
        }
        public string GetPrintDataOffer5(int OfferID, bool IsSendEmail, bool IsGetFullSizeImage, int imageOption, int userID, out Library.DTO.Notification notification)
        {
            notification = new Library.DTO.Notification()
            {
                Type = Library.DTO.NotificationType.Success
            };
            PrintDataObject ds = new PrintDataObject();

            try
            {
                SqlDataAdapter adap = new SqlDataAdapter();
                adap.SelectCommand             = new SqlCommand("OfferMng_function_GetPrintData", new SqlConnection(DALBase.Helper.GetSQLConnectionString()));
                adap.SelectCommand.CommandType = System.Data.CommandType.StoredProcedure;
                adap.SelectCommand.Parameters.AddWithValue("@OfferID", OfferID);
                adap.SelectCommand.Parameters.AddWithValue("@IsSendEmail", IsSendEmail);
                adap.SelectCommand.Parameters.AddWithValue("@ImageOption", imageOption);

                adap.TableMappings.Add("Table", "ParamTable");
                adap.TableMappings.Add("Table1", "PrintHeader");
                adap.TableMappings.Add("Table2", "PrintDetail");
                adap.TableMappings.Add("Table3", "ModelPieceReport");
                adap.Fill(ds);

                //logo image
                ds.PrintHeader.FirstOrDefault().LogoImage = FrameworkSetting.Setting.MediaThumbnailUrl + ds.PrintHeader.FirstOrDefault().LogoImage;

                //set image url
                foreach (var item in ds.PrintDetail)
                {
                    if (IsGetFullSizeImage)
                    {
                        item.FileLocation       = FrameworkSetting.Setting.MediaFullSizeUrl + item.FileLocation_FullSize;
                        item.FileGardenLocation = FrameworkSetting.Setting.MediaFullSizeUrl + item.FileGardenLocation_FullSize;
                    }
                    else
                    {
                        item.FileLocation       = FrameworkSetting.Setting.MediaThumbnailUrl + item.FileLocation;
                        item.FileGardenLocation = FrameworkSetting.Setting.MediaThumbnailUrl + item.FileGardenLocation;
                    }
                }

                //DALBase.Helper.DevCreateReportXMLSource(ds, "Offer5");
                // generate xml file
                string reportFile = "";
                Module.Framework.DAL.DataFactory fwFactory = new Module.Framework.DAL.DataFactory();
                int?companyID = fwFactory.GetCompanyID(userID);
                switch (companyID)
                {
                case 13:
                    reportFile = "Offer5_OrangePine";
                    break;

                default:
                    reportFile = "Offer5";
                    break;
                }

                // remove table from dataset
                ds.Tables.Remove("OfferMng_OfferPrintoutPP_View");
                ds.Tables.Remove("OfferMng_OfferPrintoutPP_Detail_View");
                ds.Tables.Remove("OfferMng_OfferPrintoutPP_PieceDetail_View");
                ds.AcceptChanges();

                return(Library.Helper.CreateReportFileWithEPPlus2(ds, reportFile));
            }
            catch (Exception ex)
            {
                notification.Type = Library.DTO.NotificationType.Error;
                Exception iEx = Library.Helper.GetInnerException(ex);
                notification.Message = iEx.Message;
                return(string.Empty);
            }
        }
        public void DTO2DB_Offer(DTO.OfferMng.Offer dtoItem, ref Offer dbItem, int actionType, int userId)
        {
            OfferStatus dbOfferStatus = dbItem.OfferStatus.Where(o => o.IsCurrentStatus.HasValue && o.IsCurrentStatus.Value).FirstOrDefault();

            /*
             * MAP & CHECK  OFFERLINE
             */
            List <OfferLine> ItemNeedDelete_Extends = new List <OfferLine>();

            if (dtoItem.OfferLines != null)
            {
                //CHECK
                foreach (OfferLine dbDetail in dbItem.OfferLine.Where(o => !dtoItem.OfferLines.Select(s => s.OfferLineID).Contains(o.OfferLineID)))
                {
                    ItemNeedDelete_Extends.Add(dbDetail);
                }
                foreach (OfferLine dbDetail in ItemNeedDelete_Extends)
                {
                    dbItem.OfferLine.Remove(dbDetail);
                }
                //MAP
                foreach (DTO.OfferMng.OfferLine dtoDetail in dtoItem.OfferLines)
                {
                    OfferLine            dbDetail;
                    OfferLinePriceOption dbPriceOption;
                    bool isAllowEditItem = true;
                    if (dtoDetail.OfferLineID < 0 || actionType != 1) // actionType { 0:New, 1:Edit,2: Copy, 3:New Version}
                    {
                        dbDetail = new OfferLine();
                        if (dtoDetail.OfferLinePriceOptions != null)
                        {
                            foreach (DTO.OfferMng.OfferLinePriceOption dtoPriceOption in dtoDetail.OfferLinePriceOptions)
                            {
                                dbPriceOption = new OfferLinePriceOption();
                                dbDetail.OfferLinePriceOption.Add(dbPriceOption);
                                AutoMapper.Mapper.Map <DTO.OfferMng.OfferLinePriceOption, OfferLinePriceOption>(dtoPriceOption, dbPriceOption);
                            }
                        }
                        dbItem.OfferLine.Add(dbDetail);
                    }
                    else
                    {
                        dbDetail = dbItem.OfferLine.FirstOrDefault(o => o.OfferLineID == dtoDetail.OfferLineID);
                        if (dbDetail != null && dtoDetail.OfferLinePriceOptions != null)
                        {
                            foreach (DTO.OfferMng.OfferLinePriceOption dtoPriceOption in dtoDetail.OfferLinePriceOptions)
                            {
                                if (dtoPriceOption.OfferLinePriceOptionID < 0)
                                {
                                    dbPriceOption = new OfferLinePriceOption();
                                    dbDetail.OfferLinePriceOption.Add(dbPriceOption);
                                }
                                else
                                {
                                    dbPriceOption = dbDetail.OfferLinePriceOption.FirstOrDefault(o => o.OfferLinePriceOptionID == dtoPriceOption.OfferLinePriceOptionID);
                                }
                                if (dbPriceOption != null)
                                {
                                    Mapper.Map(dtoPriceOption, dbPriceOption);
                                }
                            }
                        }
                        //check item exist in factory order
                        var x = dbDetail.SaleOrderDetail.Where(o => o.FactoryOrderDetail != null && o.FactoryOrderDetail.Count() > 0);
                        isAllowEditItem = !(x != null && x.Count() > 0);

                        // detect changes for approved items
                        if (dtoDetail.OfferItemTypeID == 1 && dtoDetail.IsApproved.HasValue && !dtoDetail.IsApproved.Value)
                        {
                            dbDetail.IsApproved   = false;
                            dbDetail.ApprovedBy   = null;
                            dbDetail.ApprovedDate = null;
                        }

                        //
                        // Author       : The My
                        // Description  : force update configuration changed even if item exists in factory order
                        //
                        Module.Framework.DAL.DataFactory fwFactory = new Module.Framework.DAL.DataFactory();
                        if (fwFactory.HasSpecialPermission(userId, Module.Framework.ConstantIdentifier.SPECIAL_PERMISSION_CHANGE_OFFER_ITEM_OPTION))
                        {
                            isAllowEditItem = true;
                        }
                    }

                    if (dbDetail != null)
                    {
                        dtoDetail.FinalPrice = (
                            (dtoItem.CommissionPercent == null ? 0 : dtoItem.CommissionPercent) +
                            (dtoItem.SurChargePercent == null ? 0 : dtoItem.SurChargePercent) +
                            (dtoDetail.IncreasePercent == null ? 0 : dtoDetail.IncreasePercent)
                            )
                                               / 100 * (dtoDetail.UnitPrice == null ? 0 : dtoDetail.UnitPrice)
                                               + (dtoDetail.UnitPrice == null ? 0 : dtoDetail.UnitPrice);

                        // set update by for est purchasing price
                        if (dtoDetail.EstimatedPurchasingPrice != dbDetail.EstimatedPurchasingPrice)
                        {
                            dbDetail.EstimatedPurchasingPriceUpdatedByID = userId;
                        }

                        // set selected by for planing purchasing price
                        if (dtoDetail.PlaningPurchasingPriceSelectedDate == "just now")
                        {
                            dbDetail.PlaningPurchasingPriceSelectedBy   = userId;
                            dbDetail.PlaningPurchasingPriceSelectedDate = DateTime.Now;
                        }

                        Mapper.Map(dtoDetail, dbDetail);

                        // only allow edit item in case item does not put in factory order detail
                        if (isAllowEditItem)
                        {
                            dbDetail.ModelID              = dtoDetail.ModelID;
                            dbDetail.FrameMaterialID      = dtoDetail.FrameMaterialID;
                            dbDetail.FrameMaterialColorID = dtoDetail.FrameMaterialColorID;
                            dbDetail.MaterialID           = dtoDetail.MaterialID;
                            dbDetail.MaterialTypeID       = dtoDetail.MaterialTypeID;
                            dbDetail.MaterialColorID      = dtoDetail.MaterialColorID;
                            dbDetail.SubMaterialID        = dtoDetail.SubMaterialID;
                            dbDetail.SubMaterialColorID   = dtoDetail.SubMaterialColorID;
                            dbDetail.SeatCushionID        = dtoDetail.SeatCushionID;
                            dbDetail.BackCushionID        = dtoDetail.BackCushionID;
                            dbDetail.CushionColorID       = dtoDetail.CushionColorID;
                            dbDetail.FSCTypeID            = dtoDetail.FSCTypeID;
                            dbDetail.FSCPercentID         = dtoDetail.FSCPercentID;
                        }
                    }
                }
            }

            /*
             * MAP & CHECK  OFFERLINE SPAREPART
             */
            List <OfferLineSparepart> needItemDelete = new List <OfferLineSparepart>();

            if (dtoItem.OfferLineSpareparts != null)
            {
                //CHECK
                foreach (OfferLineSparepart dbDetail in dbItem.OfferLineSparepart.Where(o => !dtoItem.OfferLineSpareparts.Select(s => s.OfferLineSparePartID).Contains(o.OfferLineSparePartID)))
                {
                    needItemDelete.Add(dbDetail);
                }
                foreach (OfferLineSparepart dbDetail in needItemDelete)
                {
                    dbItem.OfferLineSparepart.Remove(dbDetail);
                }
                //MAP
                foreach (DTO.OfferMng.OfferLineSparepart dtoDetail in dtoItem.OfferLineSpareparts)
                {
                    OfferLineSparepart dbDetail;
                    bool isAllowEditItem = true;
                    if (dtoDetail.OfferLineSparePartID < 0 || actionType != 1) // actionType { 0:New, 1:Edit,2: Copy, 3:New Version}
                    {
                        dbDetail = new OfferLineSparepart();
                        dbItem.OfferLineSparepart.Add(dbDetail);
                    }
                    else
                    {
                        dbDetail = dbItem.OfferLineSparepart.FirstOrDefault(o => o.OfferLineSparePartID == dtoDetail.OfferLineSparePartID);
                        var x = dbDetail.SaleOrderDetailSparepart.Where(o => o.FactoryOrderSparepartDetail != null && o.FactoryOrderSparepartDetail.Count() > 0);
                        isAllowEditItem = !(x != null && x.Count() > 0);
                    }

                    if (dbDetail != null)
                    {
                        AutoMapper.Mapper.Map <DTO.OfferMng.OfferLineSparepart, OfferLineSparepart>(dtoDetail, dbDetail);

                        // only allow edit item in case item does not put in factory order detail
                        if (isAllowEditItem)
                        {
                            dbDetail.ModelID = dtoDetail.ModelID;
                            dbDetail.PartID  = dtoDetail.PartID;
                        }
                    }
                }
            }

            /*
             * MAP & CHECK  OFFERLINE SAMPLE PRODUCT
             */
            List <OfferLineSampleProduct> toBeDeletedItems = new List <OfferLineSampleProduct>();

            if (dtoItem.OfferLineSampleProductDTOs != null)
            {
                //CHECK
                foreach (OfferLineSampleProduct dbSample in dbItem.OfferLineSampleProduct.Where(o => !dtoItem.OfferLineSampleProductDTOs.Select(s => s.OfferLineSampleProductID).Contains(o.OfferLineSampleProductID)).ToArray())
                {
                    dbItem.OfferLineSampleProduct.Remove(dbSample);
                }
                //MAP
                foreach (DTO.OfferMng.OfferLineSampleProductDTO dtoSample in dtoItem.OfferLineSampleProductDTOs)
                {
                    OfferLineSampleProduct dbSample = null;
                    if (dtoSample.OfferLineSampleProductID <= 0)
                    {
                        dbSample = new OfferLineSampleProduct();
                        dbItem.OfferLineSampleProduct.Add(dbSample);
                    }
                    else
                    {
                        dbSample = dbItem.OfferLineSampleProduct.FirstOrDefault(o => o.OfferLineSampleProductID == dtoSample.OfferLineSampleProductID);
                        if (dbSample == null)
                        {
                            throw new Exception("Sample item not found!");
                        }
                    }
                    AutoMapper.Mapper.Map <DTO.OfferMng.OfferLineSampleProductDTO, OfferLineSampleProduct>(dtoSample, dbSample);
                }
            }

            /*
             * SETUP FORMATED FIELD
             */
            //dbItem.OfferDate = Library.Helper.ConvertStringToDateTime(dtoItem.OfferDate, new System.Globalization.CultureInfo("vi-VN"));
            //dbItem.ValidUntil = Library.Helper.ConvertStringToDateTime(dtoItem.ValidUntil, new System.Globalization.CultureInfo("vi-VN"));
            //dbItem.LDS = Library.Helper.ConvertStringToDateTime(dtoItem.LDS, new System.Globalization.CultureInfo("vi-VN"));
            //dbItem.EstimatedDeliveryDate = Library.Helper.ConvertStringToDateTime(dtoItem.EstimatedDeliveryDate, new System.Globalization.CultureInfo("vi-VN"));
            Mapper.Map(dtoItem, dbItem);
            dbItem.OfferDate             = dtoItem.OfferDateFormated.ConvertStringToDateTime();
            dbItem.ValidUntil            = dtoItem.ValidUntilFormated.ConvertStringToDateTime();
            dbItem.LDS                   = dtoItem.LDSFormated.ConvertStringToDateTime();
            dbItem.EstimatedDeliveryDate = dtoItem.EstimatedDeliveryDateFormated.ConvertStringToDateTime();

            //var dtoEstimatedPurchasingPriceUpdatedBy = new DTO.OfferMng.OfferLine().EstimatedPurchasingPriceUpdatedByID = userId;
            //dtoItem.OfferLines.Select(x => x.EstimatedPurchasingPriceUpdatedByID = dtoEstimatedPurchasingPriceUpdatedBy).ToList();
            //var dbdtoEstimatedPurchasingPriceUpdatedBy = new OfferLine().EstimatedPurchasingPriceUpdatedByID = userId;
            //dbItem.OfferLine.Select(x => x.EstimatedPurchasingPriceUpdatedByID = dbdtoEstimatedPurchasingPriceUpdatedBy).ToList();

            //dtoEstimatedPurchasingPriceUpdatedBy = dbdtoEstimatedPurchasingPriceUpdatedBy;
        }
        public override bool UpdateData(int userId, int id, ref object dtoItem, out Notification notification)
        {
            notification = new Library.DTO.Notification()
            {
                Type = Library.DTO.NotificationType.Success
            };
            DTO.PaymentNoteEditResult dtoPayment = ((Newtonsoft.Json.Linq.JObject)dtoItem).ToObject <DTO.PaymentNoteEditResult>();
            try
            {
                //get companyID
                Module.Framework.DAL.DataFactory fw_factory = new Framework.DAL.DataFactory();
                int?companyID = fw_factory.GetCompanyID(userId);
                using (var context = CreateContext())
                {
                    if (dtoPayment.PaymentNoteTypeID == 3)
                    {
                        foreach (var item in dtoPayment.paymentNoteOtherResults)
                        {
                            if (item.FactoryRawMaterialID == null)
                            {
                                throw new Exception("missing Suppiler !!!");
                            }
                        }
                    }
                    if (dtoPayment.PaymentNoteTypeID == 1)
                    {
                        foreach (var item in dtoPayment.paymentNoteInvoiceResults)
                        {
                            decimal?totalDpsAmount = 0;

                            if (dtoPayment.Currency == "USD" && item.Currency == "VND")
                            {
                                totalDpsAmount = (item.Amount == null ? 0 : item.Amount * dtoPayment.ExchangeRate);
                            }
                            else if (dtoPayment.Currency == "VND" && item.Currency == "USD")
                            {
                                totalDpsAmount = (item.Amount == null ? 0 : item.Amount / dtoPayment.ExchangeRate);
                            }
                            else
                            {
                                totalDpsAmount = (item.Amount == null ? 0 : item.Amount);
                            }
                            if (item.Remain < totalDpsAmount)
                            {
                                throw new Exception("Amount more than over remain " + item.PurchaseInvoiceUD);
                            }
                        }
                    }
                    ///
                    if (dtoPayment.PaymentNoteTypeID == 2)
                    {
                        foreach (var item in dtoPayment.paymentNoteSupplierResults)
                        {
                            var itemx = context.PaymentNoteMng_CheckingCurrencySupplier_View.FirstOrDefault(o => o.PurchaseOrderID == item.PurchaseOrderID);
                            if (itemx != null && itemx.Currency != dtoPayment.Currency)
                            {
                                throw new Exception("There are differences between the two currencies " + item.PurchaseOrderUD);
                            }
                        }
                    }

                    #region Convert
                    //if (dtoPayment.paymentNoteInvoiceResults != null && dtoPayment.PaymentNoteTypeID == 1)
                    //{
                    //    decimal? totalByCurrency = 0;
                    //    foreach (var dtoItemInvoice in dtoPayment.paymentNoteInvoiceResults)
                    //    {
                    //        string currency = context.PaymentNoteMng_PurchaseInvoiceCurrency_View.Where(o => o.PurchaseInvoiceID == dtoItemInvoice.PurchaseInvoiceID).Select(s => s.Currency).FirstOrDefault();
                    //        //If Purchase Invoice null Currency Throw
                    //        if (string.IsNullOrEmpty(currency))
                    //        {
                    //            string purchaseUD = context.PaymentNoteMng_PurchaseInvoiceCurrency_View.Where(o => o.PurchaseInvoiceID == dtoItemInvoice.PurchaseInvoiceID).Select(s => s.PurchaseInvoiceUD).FirstOrDefault();
                    //            throw new Exception("Missing Currency for Invoice " + purchaseUD);
                    //        }
                    //        //Convert USD => VND or
                    //        if (dtoPayment.Currency == "VND")
                    //        {
                    //            if (currency == "VND")
                    //            {
                    //                dtoItemInvoice.Amount = dtoItemInvoice.AmountByCurrency + dtoItemInvoice.Deposit;
                    //            }
                    //            else
                    //            {
                    //                dtoItemInvoice.Amount = ((dtoItemInvoice.AmountByCurrency == null ? 0 : dtoItemInvoice.AmountByCurrency) + (dtoItemInvoice.Deposit == null ? 0 : dtoItemInvoice.Deposit)) / dtoPayment.ExchangeRate;
                    //            }
                    //            totalByCurrency += (dtoItemInvoice.Deposit == null ? 0 : dtoItemInvoice.Deposit);
                    //        }
                    //        else if (dtoPayment.Currency == "USD")
                    //        {
                    //            if (currency == "VND")
                    //            {
                    //                dtoItemInvoice.Amount = (dtoItemInvoice.AmountByCurrency == null ? 0 : dtoItemInvoice.AmountByCurrency) * dtoPayment.ExchangeRate;
                    //            }
                    //            else
                    //            {
                    //                dtoItemInvoice.Amount = dtoItemInvoice.AmountByCurrency + dtoItemInvoice.Deposit;
                    //            }
                    //            totalByCurrency += ((dtoItemInvoice.Deposit == null ? 0 : dtoItemInvoice.Deposit) + (dtoItemInvoice.Deposit == null ? 0 : dtoItemInvoice.Deposit));
                    //        }
                    //    }
                    //    dtoPayment.TotalByCurrency = totalByCurrency;
                    //}
                    #endregion

                    PaymentNote dbItem = null;

                    if (id == 0)
                    {
                        if (dtoPayment.StatusID == 2 || dtoPayment.StatusID == 3)
                        {
                            throw new Exception("Set Status open to Save !!!");
                        }

                        dbItem = new PaymentNote();
                        context.PaymentNote.Add(dbItem);

                        //Automatically generate code
                        if (dtoPayment.PaymentTypeID == 1)// Payment type Cash
                        {
                            int    year            = DateTime.Now.Year;
                            string month           = DateTime.Now.Month.ToString().PadLeft(2, '0');
                            string receipt_pattern = "PC" + "_" + year.ToString().Substring(2) + month;
                            var    db_receiptNo    = context.PaymentNote.Where(o => o.PaymentNoteNo.Substring(0, 7) == receipt_pattern).OrderByDescending(o => o.PaymentNoteNo);
                            if (db_receiptNo.ToList().Count() == 0)
                            {
                                dtoPayment.PaymentNoteNo = receipt_pattern + "_" + "001";
                            }
                            else
                            {
                                var select_receipt = db_receiptNo.FirstOrDefault();
                                int iNo            = Convert.ToInt32(select_receipt.PaymentNoteNo.Substring(8, 3)) + 1;
                                dtoPayment.PaymentNoteNo = select_receipt.PaymentNoteNo.Substring(0, 7) + "_" + iNo.ToString().PadLeft(3, '0');
                            }
                        }
                        else if (dtoPayment.PaymentTypeID == 2)// Payment type Bank
                        {
                            int    year            = DateTime.Now.Year;
                            string month           = DateTime.Now.Month.ToString().PadLeft(2, '0');
                            string receipt_pattern = "BN" + "_" + year.ToString().Substring(2) + month;
                            var    db_receiptNo    = context.PaymentNote.Where(o => o.PaymentNoteNo.Substring(0, 7) == receipt_pattern).OrderByDescending(o => o.PaymentNoteNo);
                            if (db_receiptNo.ToList().Count() == 0)
                            {
                                dtoPayment.PaymentNoteNo = receipt_pattern + "_" + "001";
                            }
                            else
                            {
                                var select_receipt = db_receiptNo.FirstOrDefault();
                                int iNo            = Convert.ToInt32(select_receipt.PaymentNoteNo.Substring(8, 3)) + 1;
                                dtoPayment.PaymentNoteNo = select_receipt.PaymentNoteNo.Substring(0, 7) + "_" + iNo.ToString().PadLeft(3, '0');
                            }
                        }
                    }
                    else
                    {
                        dbItem = context.PaymentNote.Where(o => o.PaymentNoteID == id).FirstOrDefault();

                        if (dbItem.PaymentNoteTypeID != dtoPayment.PaymentNoteTypeID)
                        {
                            throw new Exception("Can't change Payment Note type !!!");
                        }
                    }
                    if (dbItem == null)
                    {
                        notification.Message = "data not found!";
                        return(false);
                    }
                    else
                    {
                        //check  status

                        /*
                         *  WorkOrderStatusID :
                         *      1 : Open
                         *      2 : Confimred
                         */

                        if (dbItem.StatusID == 2 || dbItem.StatusID == 3)
                        {
                            throw new Exception("Can't Update because Payment Comfirmed or Cancel !!!");
                        }
                        if (dtoPayment.StatusID == 2 && dtoPayment.PaymentNoteTypeID == 1)
                        {
                            ValidatePayment(dbItem.PaymentNoteID, 2);
                        }

                        //convert dto to db
                        converter.DTO2DB_Update(dtoPayment, ref dbItem, userId);

                        //upload file
                        Module.Framework.DAL.DataFactory fwFactory = new Module.Framework.DAL.DataFactory();
                        string tempFolder = FrameworkSetting.Setting.AbsoluteUserTempFolder + userId.ToString() + @"\";
                        if (dtoPayment.File_HasChange.HasValue && dtoPayment.File_HasChange.Value)
                        {
                            dbItem.AttachedFile = fwFactory.CreateFilePointer(tempFolder, dtoPayment.File_NewFile, dtoPayment.AttachedFile, dtoPayment.FriendlyName);
                        }

                        if (id == 0)
                        {
                            dbItem.CreateDate = DateTime.Now;
                            dbItem.CreateBy   = userId;
                        }
                        else
                        {
                            dbItem.UpdateDate = DateTime.Now;
                            dbItem.UpdateBy   = userId;
                        }

                        //remove orphan
                        context.PaymentNoteSupplier.Local.Where(o => o.PaymentNote == null).ToList().ForEach(o => context.PaymentNoteSupplier.Remove(o));
                        context.PaymentNoteInvoice.Local.Where(o => o.PaymentNote == null).ToList().ForEach(o => context.PaymentNoteInvoice.Remove(o));
                        context.PaymentNoteOther.Local.Where(o => o.PaymentNote == null).ToList().ForEach(o => context.PaymentNoteOther.Remove(o));
                        context.PaymentNotePODeposit.Local.Where(o => o.PaymentNoteInvoice == null).ToList().ForEach(o => context.PaymentNotePODeposit.Remove(o));

                        //save data
                        context.SaveChanges();
                        dtoItem = GetData(userId, dbItem.PaymentNoteID, null, out notification).Data;
                        return(true);
                    }
                }
            }
            catch (Exception ex)
            {
                notification.Type    = Library.DTO.NotificationType.Error;
                notification.Message = Library.Helper.GetInnerException(ex).Message;
                return(false);
            }
        }