Beispiel #1
0
        public void DeleteSalesOrderHeaderTest()
        {
            // Get a test user
            var testUser     = GetTestUser();
            var testCompany  = GetTestCompany(testUser, true);
            var testCustomer = GetTestCustomer(testCompany, testUser);

            // Create a purchase
            var model = GetTestSalesOrderHeader(testCompany, testCustomer, testUser);

            // Check that it was written
            var result = db.FindSalesOrderHeader(model.Id);
            SalesOrderHeaderModel test = SalesService.MapToModel(result);

            var excludes = new List <string>();

            excludes.Add("SalesOrderDetails");  // SalesOrderDetail is a list of objects
            excludes.Add("OrderNumberUrl");     // Because it isn't known at test prep
            AreEqual(model, test, excludes);

            // Now delete it
            SalesService.DeleteSalesOrderHeader(model.Id);

            // And check that is was deleted
            result = db.FindSalesOrderHeader(model.Id);
            Assert.IsTrue(result == null, "Error: A non-NULL value was returned when a NULL value was expected - record delete failed");
        }
Beispiel #2
0
        public Error SendMSQOverrideEMail(CompanyModel company,
                                          UserModel sender,
                                          UserModel recipient,
                                          SalesOrderHeaderModel model)
        {
            var error = new Error();

            // Send a message to the selected user, indicating that they have been
            // nominated as an approver of an MSQ override
            var message = new EMailMessage(sender, recipient, MessageTemplateType.MSQChangeNotification);

            message.AddProperty("ORDERNO", model.OrderNumber);
            message.AddProperty("SALESPERSON", sender.FullName);
            message.AddProperty("URL", GetConfigurationSetting("SiteHttp", "") + "/Sales/Sales/Edit?id=" + model.Id.ToString());

            EMailService.EMailService emailService = new Evolution.EMailService.EMailService(db, company);
            error = emailService.SendEMail(message);

            if (!error.IsError)
            {
                var NotificationService = GetTaskManagerService(company);

                error = NotificationService.SendTask(Enumerations.MessageTemplateType.MSQChangeNotification,
                                                     TaskType.MSQChangeNotification,
                                                     LookupService.FindLOVItemsModel(company, LOVName.BusinessUnit)
                                                     .Where(bu => bu.ItemText == "Sales")
                                                     .FirstOrDefault(),
                                                     recipient,
                                                     model.CustomerId,
                                                     message.Dict);
            }
            return(error);
        }
Beispiel #3
0
        public Error AttachNoteToSalesOrder(SalesOrderHeaderModel soh, UserModel sender,
                                            string subject, string message,
                                            List <string> attachments = null,
                                            FileCopyType copyType     = FileCopyType.Move)
        {
            var error = new Error();

            var note = new NoteModel {
                CompanyId   = soh.CompanyId,
                NoteType    = NoteType.Sale,
                ParentId    = soh.Id,
                CreatedById = sender.Id,
                Subject     = subject,
                Message     = message
            };

            InsertOrUpdateNote(note, sender, "");

            error.Id = note.Id;
            if (!error.IsError && attachments != null)
            {
                foreach (var attachment in attachments)
                {
                    AttachMediaItemToNote(note, sender, attachment, attachment.FileName(), copyType);
                }
            }
            return(error);
        }
        public FileTransferConfigurationModel FindDataTransferConfigurationModel(SalesOrderHeaderModel soh)
        {
            var item = db.FindFileTransferConfigurations()
                       .Where(ftc => ftc.CompanyId == soh.CompanyId &&
                              ftc.LocationId == soh.LocationId)
                       .FirstOrDefault();

            return(MapToModel(item));
        }
        // Single Or Default
        public async Task <SalesOrderHeaderModel> SingleOrDefaultDemoQueryAsync(SalesOrderHeaderModel salesOrderHeaderModel)
        {
            return(await Task.Run(() => {
                var data =
                    adventureWorks2012Context
                    ?.SalesOrderHeader
                    ?.AsEnumerable()
                    ?.Select(this.FuncSalesOrdersColumnsMapping())
                    ?.SingleOrDefault((leSalesOrderHeaderModel) => leSalesOrderHeaderModel.SalesOrderID == salesOrderHeaderModel.SalesOrderID);

                return data;
            }));
        }
        // Where Clause
        public async Task <List <SalesOrderHeaderModel> > WhereClauseQueryDemo(SalesOrderHeaderModel salesOrderHeaderModel)
        {
            return(await Task.Run(() => {
                var data =
                    adventureWorks2012Context
                    ?.SalesOrderHeader
                    ?.AsEnumerable()
                    ?.Where((leSalesOrderHeader) => leSalesOrderHeader?.SalesOrderId == salesOrderHeaderModel.SalesOrderID)
                    ?.Select(this.FuncSalesOrdersColumnsMapping())
                    ?.ToList();

                return data;
            }));
        }
Beispiel #7
0
        public TransactionDrillDownListModel FindTransactionDrillDown(SalesOrderHeaderModel soh,
                                                                      int index = 0, int pageNo = 1, int pageSize = Int32.MaxValue)
        {
            var model = new TransactionDrillDownListModel();

            model.GridIndex = index;
            var allItems = db.FindTransactionDrillDown(soh.Id, soh.LocationId)
                           .ToList();

            model.TotalRecords = allItems.Count();
            foreach (var item in allItems.Skip((pageNo - 1) * pageSize)
                     .Take(pageSize))
            {
                var newItem = Mapper.Map <FindTransactionDrillDown_Result, TransactionDrillDownModel>(item);
                model.Items.Add(newItem);
            }

            return(model);
        }
        public Error CreateSalesDocumentPdf(SalesOrderHeaderModel soh,
                                            int templateId,
                                            string pdfFile,
                                            bool showCancelledItems,
                                            ref string outputFile,
                                            int maxItems = Int32.MaxValue)
        {
            // This method is used by th Sale/Print option where the user chooses
            // the template they wish to print with.
            var error = new Error();

            var template = LookupService.FindDocumentTemplateModel(templateId);

            if (template == null)
            {
                error.SetRecordError("DocumentTemplate", templateId);
            }
            else
            {
                switch (template.TemplateType)
                {
                case DocumentTemplateType.SaleCancellation:
                case DocumentTemplateType.ProFormaInvoice:
                case DocumentTemplateType.ConfirmedOrder:
                    error = createSalesOrderPdf(soh, template,
                                                pdfFile,
                                                true,
                                                ref outputFile,
                                                maxItems);
                    break;

                case DocumentTemplateType.OrderConfirmation:
                    error = CreateOrderConfirmationPdf(soh, template,
                                                       pdfFile,
                                                       showCancelledItems,
                                                       ref outputFile,
                                                       maxItems);
                    break;
                }
            }
            return(error);
        }
Beispiel #9
0
        public SalesOrderHeaderModel MapToModel(SalesOrderHeader item)
        {
            SalesOrderHeaderModel newItem = Mapper.Map <SalesOrderHeader, SalesOrderHeaderModel>(item);

            newItem.OrderNumberUrl = $"<a href=\"/Sales/Sales/Edit?id={item.Id}\">{item.OrderNumber}</a>";

            if (item.Customer != null)
            {
                newItem.CustomerName = item.Customer.Name;
                newItem.RegionText   = item.Customer.Region.RegionName;
            }
            if (item.SalesOrderHeaderStatu != null)
            {
                newItem.SOStatusText  = item.SalesOrderHeaderStatu.StatusName;
                newItem.SOStatusValue = (SalesOrderHeaderStatus)item.SalesOrderHeaderStatu.StatusValue;
            }
            if (item.SalesOrderHeaderSubStatu != null)
            {
                newItem.SOSubStatusText = item.SalesOrderHeaderSubStatu.StatusName;
            }

            newItem.SalesPersonName = db.MakeName(item.User_SalesPerson);

            if (item.SaleNextAction != null)
            {
                newItem.NextActionText = item.SaleNextAction.NextActionDescription;
            }
            if (item.BrandCategory != null)
            {
                newItem.BrandCategoryText = item.BrandCategory.CategoryName;
            }
            if (item.Country != null)
            {
                newItem.CountryText = item.Country.CountryName;
            }
            if (item.Location != null)
            {
                newItem.LocationText = item.Location.LocationName;
            }

            return(newItem);
        }
Beispiel #10
0
        private Error validateModel(SalesOrderHeaderModel model)
        {
            var error = isValidNonRequiredString(getFieldValue(model.EndUserName), 52, "EndUserName", EvolutionResources.errTextDataRequiredInField);

            if (!error.IsError)
            {
                error = isValidNonRequiredString(getFieldValue(model.ShipAddress1), 255, "ShipAddress1", EvolutionResources.errTextDataRequiredInField);
            }
            if (!error.IsError)
            {
                error = isValidNonRequiredString(getFieldValue(model.ShipAddress2), 255, "ShipAddress2", EvolutionResources.errTextDataRequiredInField);
            }
            if (!error.IsError)
            {
                error = isValidNonRequiredString(getFieldValue(model.ShipAddress3), 255, "ShipAddress3", EvolutionResources.errTextDataRequiredInField);
            }
            if (!error.IsError)
            {
                error = isValidNonRequiredString(getFieldValue(model.ShipAddress4), 255, "ShipAddress4", EvolutionResources.errTextDataRequiredInField);
            }
            if (!error.IsError)
            {
                error = isValidNonRequiredString(getFieldValue(model.ShipSuburb), 60, "ShipSuburb", EvolutionResources.errTextDataRequiredInField);
            }
            if (!error.IsError)
            {
                error = isValidNonRequiredString(getFieldValue(model.ShipState), 20, "ShipState", EvolutionResources.errTextDataRequiredInField);
            }
            if (!error.IsError)
            {
                error = isValidNonRequiredString(getFieldValue(model.ShipPostcode), 12, "ShipPostcode", EvolutionResources.errTextDataRequiredInField);
            }
            if (!error.IsError)
            {
                error = isValidNonRequiredString(getFieldValue(model.WarehouseInstructions), 100, "WarehouseInstructions", EvolutionResources.errTextDataRequiredInField);
            }

            return(error);
        }
Beispiel #11
0
        // The following method is called by the Sales Service when a Sales Order is saved.
        // It could also be called manually by the user for allocation optimisation
        public void AllocateOnSalesOrderSave(SalesOrderHeaderModel soh)
        {
            if (soh.SOStatus != null)
            {
                var sohStatus = db.FindSalesOrderHeaderStatus(soh.SOStatus.Value);
                if (sohStatus != null && sohStatus.AllowAllocation)
                {
                    // The status of the sale allows an allocation

                    // Find all the lines which have an AllocQty different to the OrderQty
                    // as these may need modification
                    var orderLines = db.FindSalesOrderDetails(soh.CompanyId, soh.Id)
                                     .Where(sod => sod.AllocQty != sod.OrderQty)
                                     .ToList();

                    foreach (var sod in orderLines)
                    {
                        db.NewItemAllocation(sod.Id, sod.ProductId, soh.LocationId, soh.DeliveryWindowOpen);
                    }
                }
            }
        }
Beispiel #12
0
        public SalesOrderHeaderModel FindSalesOrderHeaderModel(int id, CompanyModel company, bool bCreateEmptyIfNotfound = true, bool bLoadDetails = false)
        {
            SalesOrderHeaderModel model = null;

            var p = db.FindSalesOrderHeader(id);

            if (p == null)
            {
                if (bCreateEmptyIfNotfound)
                {
                    model = new SalesOrderHeaderModel {
                        CompanyId     = company.Id,
                        OrderNumber   = (int)LookupService.GetNextSequenceNumber(company, SequenceNumberType.SalesOrderNumber),
                        OrderDate     = DateTimeOffset.Now,
                        ShipCountryId = company.DefaultCountryID,
                        LocationId    = company.DefaultLocationID,
                        SOStatus      = db.FindSalesOrderHeaderStatuses()
                                        .Where(sohs => sohs.StatusValue == (int)SalesOrderHeaderStatus.Quote)
                                        .FirstOrDefault()
                                        .Id,
                        NextActionId = db.FindSaleNextActions()
                                       .Where(sna => sna.Id == (int)Enumerations.SaleNextAction.None)
                                       .FirstOrDefault()
                                       .Id
                    }
                }
                ;
            }
            else
            {
                model = MapToModel(p);
            }
            if (model != null && bLoadDetails)
            {
                model.SalesOrderDetails = FindSalesOrderDetailListModel(company, model);
            }

            return(model);
        }
Beispiel #13
0
 public string LockSalesOrderHeader(SalesOrderHeaderModel model)
 {
     return(db.LockRecord(typeof(SalesOrderHeader).ToString(), model.Id));
 }
Beispiel #14
0
 public void DeleteSalesOrderHeader(SalesOrderHeaderModel model)
 {
     db.DeleteSalesOrderHeader(model.Id);
 }
Beispiel #15
0
        public Error InsertOrUpdateSalesOrderHeader(SalesOrderHeaderModel soh, UserModel user, string lockGuid)
        {
            var error = validateModel(soh);

            if (!error.IsError)
            {
                // Check that the lock is still current
                if (!db.IsLockStillValid(typeof(SalesOrderHeader).ToString(), soh.Id, lockGuid))
                {
                    error.SetError(EvolutionResources.errRecordChangedByAnotherUser, "OrderNumber");
                }
                else
                {
                    SalesOrderHeader temp = null;
                    if (soh.Id != 0)
                    {
                        temp = db.FindSalesOrderHeader(soh.Id);
                    }
                    if (temp == null)
                    {
                        temp = new SalesOrderHeader();
                    }

                    var before = Mapper.Map <SalesOrderHeader, SalesOrderHeader>(temp);

                    Mapper.Map <SalesOrderHeaderModel, SalesOrderHeader>(soh, temp);

                    db.InsertOrUpdateSalesOrderHeader(temp);
                    soh.Id = temp.Id;

                    logChanges(before, temp, user);

                    // If shanges have occured, we need to send an email to any sales person
                    // who has allocations reliant on the order
                    if (before.SOStatus != temp.SOStatus && temp.SOStatus == (int)SalesOrderHeaderStatus.Cancelled)
                    {
                        // Order has been cancelled, so send a cancellation notification to everyone

                        /*
                         * public int POStatus { set; get; } = 0;	// Cancelled
                         * public DateTimeOffset? CancelDate { set; get; } = null;
                         *
                         */
                    }
                    else
                    {
                        // Check the dates and email everyone of the changes

                        /*
                         * public DateTimeOffset? RequiredDate { set; get; }
                         * public DateTimeOffset? CompletedDate { set; get; }
                         *
                         * public DateTimeOffset? RequiredShipDate { set; get; } = null;       // SRD Final
                         * public DateTimeOffset? RealisticRequiredDate { set; get; } = null;  // Reallistic ETA
                         *
                         * public DateTimeOffset? RequiredDate_Original { set; get; } = null;
                         * public DateTimeOffset? DateOrderConfirmed { set; get; } = null;
                         * public DateTimeOffset? RequiredShipDate_Original { set; get; } = null;  // SRD Initial
                         */
                    }
                }
            }
            return(error);
        }
Beispiel #16
0
        public SalesOrderHeaderTempModel CopySaleToTemp(CompanyModel company,
                                                        SalesOrderHeaderModel salesOrderHeader,
                                                        UserModel user,
                                                        bool createCopyOfOrder)
        {
            SalesOrderHeaderTempModel result = new SalesOrderHeaderTempModel();
            SalesOrderHeaderTemp      soht   = new SalesOrderHeaderTemp();

            if (salesOrderHeader.Id > 0)
            {
                // Editing an existing sale
                var soh = db.FindSalesOrderHeader(salesOrderHeader.Id);
                if (soh != null)
                {
                    if (createCopyOfOrder)
                    {
                        // Copying/duplicating an order
                        Mapper.Map <SalesOrderHeader, SalesOrderHeaderTemp>(soh, soht);
                        soht.Id             = 0;
                        soht.OriginalRowId  = null;
                        soht.UserId         = user.Id;
                        soht.OrderNumber    = (int)LookupService.GetNextSequenceNumber(company, SequenceNumberType.SalesOrderNumber);
                        soht.OrderDate      = DateTimeOffset.Now;
                        soht.SaleNextAction = db.FindSaleNextActions()
                                              .Where(sna => sna.Id == (int)Enumerations.SaleNextAction.None)
                                              .FirstOrDefault();

                        db.InsertOrUpdateSalesOrderHeaderTemp(soht);
                        result = mapToModel(soht);
                    }
                    else
                    {
                        // Editing an existing order
                        // Copy the header
                        soht = db.FindSalesOrderHeaderTemps(company.Id)
                               .Where(p => p.UserId == user.Id &&
                                      p.OriginalRowId == salesOrderHeader.Id)
                               .FirstOrDefault();
                        if (soht != null)
                        {
                            // Already exists in the temp tables so update it with the latest data
                            int tempId = soht.Id;
                            Mapper.Map <SalesOrderHeader, SalesOrderHeaderTemp>(soh, soht);
                            soht.Id            = tempId;
                            soht.OriginalRowId = (createCopyOfOrder ? 0 : salesOrderHeader.Id);
                            soht.UserId        = user.Id;

                            db.InsertOrUpdateSalesOrderHeaderTemp(soht);
                            result = mapToModel(soht);
                        }
                        else
                        {
                            // Doesn't exist, so copy
                            soht               = Mapper.Map <SalesOrderHeader, SalesOrderHeaderTemp>(soh);
                            soht.Id            = 0;
                            soht.OriginalRowId = (createCopyOfOrder ? 0 : salesOrderHeader.Id);
                            soht.UserId        = user.Id;

                            db.InsertOrUpdateSalesOrderHeaderTemp(soht);
                            result = mapToModel(soht);
                        }
                    }

                    // Now copy/merge the details
                    db.CopySaleToTemp(company.Id, user.Id, salesOrderHeader.Id, soht.Id, (createCopyOfOrder ? 1 : 0));
                }
            }
            else
            {
                // New sale
                soht.CompanyId        = company.Id;
                soht.UserId           = user.Id;
                soht.OrderNumber      = salesOrderHeader.OrderNumber;
                soht.OrderDate        = salesOrderHeader.OrderDate;
                soht.SalespersonId    = salesOrderHeader.SalespersonId;
                soht.BrandCategoryId  = salesOrderHeader.BrandCategoryId;
                soht.LocationId       = salesOrderHeader.LocationId;
                soht.ShipCountryId    = salesOrderHeader.ShipCountryId;
                soht.FreightCarrierId = salesOrderHeader.FreightCarrierId;
                soht.FreightTermId    = salesOrderHeader.FreightTermId;
                soht.NextActionId     = salesOrderHeader.NextActionId;

                db.InsertOrUpdateSalesOrderHeaderTemp(soht);
                result = Mapper.Map <SalesOrderHeaderTemp, SalesOrderHeaderTempModel>(soht);
            }

            return(result);
        }
        public List <SalesOrderDetailModel> FindSalesOrderDetailListModel(CompanyModel company, SalesOrderHeaderModel soh)
        {
            var model = new List <SalesOrderDetailModel>();

            foreach (var item in db.FindSalesOrderDetails(company.Id, soh.Id))
            {
                model.Add(MapToModel(item));
            }

            return(model);
        }
Beispiel #18
0
        public decimal CalculateEstimatedFreight(SalesOrderHeaderModel soh, CustomerModel customer)
        {
            decimal freightValue     = 0,
           totalOrderValue           = 0,
           minFreightPerOrder        = (soh.MinFreightPerOrder == null ? 0 : soh.MinFreightPerOrder.Value),
           freightRate               = (soh.FreightRate == null ? 0 : soh.FreightRate.Value),
           minFreightThreshold       = (customer.MinFreightThreshold == null ? 0 : customer.MinFreightThreshold.Value),
           freightWhenBelowThreshold = (customer.FreightWhenBelowThreshold == null ? 0 : customer.FreightWhenBelowThreshold.Value);

            //string  rateCalcMethod = "";

            foreach (var item in db.FindSalesOrderDetails(soh.CompanyId, soh.Id))
            {
                if (item.LineStatusId == (int)SalesOrderLineStatus.Unpicked ||
                    item.LineStatusId == (int)SalesOrderLineStatus.PickingInProgress ||
                    item.LineStatusId == (int)SalesOrderLineStatus.SentForPicking)
                {
                    totalOrderValue += (item.UnitPriceExTax == null ? 0 : item.UnitPriceExTax.Value) *
                                       (item.OrderQty == null ? 0 : item.OrderQty.Value) *
                                       1 - (item.DiscountPercent == null ? 0 : item.DiscountPercent.Value);
                }
            }

            if (minFreightPerOrder > 0)
            {
                if (freightRate > 0)
                {
                    // If the order specifies a min value per order AND a freight rate,
                    // calculate the freight value based on the larger of the two
                    if (minFreightPerOrder > totalOrderValue * freightRate)
                    {
                        // Min value > freight rate. Charge the entire freight rate.
                        freightValue = minFreightPerOrder;
                        //rateCalcMethod = "Min freight";
                    }
                    else
                    {
                        // Min value < freight rate. Charge the freight rate
                        freightValue = totalOrderValue * freightRate;
                        //rateCalcMethod = "Freight rate";
                    }
                }
                else
                {
                    // A min value is supplied, but a freight rate is not. Charge the min value
                    freightValue = minFreightPerOrder;
                    //rateCalcMethod = "Min freight";
                }
            }
            else if (freightRate > 0)
            {
                // A min value is not supplied, but a freight rate is. Charge the freight rate
                freightValue = totalOrderValue * freightRate;
                //rateCalcMethod = "Freight rate";
            }
            else
            {
                // Nothing is supplied. Charge $0.00 freight
                freightValue = 0;
                //rateCalcMethod = "No Freight";
            }

            // Calculate the pick freight value
            if (totalOrderValue < minFreightThreshold)
            {
                // If the total order value is less than the minimum threshold, then
                // use FreightWhenBelowThreshold for this order.
                freightValue = freightWhenBelowThreshold;
                //rateCalcMethod = "Below min threshold";
            }
            else if (totalOrderValue < minFreightThreshold)
            {
                freightValue = 0;
                //rateCalcMethod = "Below min threshold";
            }

            return(freightValue);
        }
Beispiel #19
0
        public Error ImportSales(CompanyModel company,
                                 UserModel user,
                                 int soStatusId,
                                 int sourceId,
                                 List <string> headings,
                                 string dateFormat,
                                 int tz)
        {
            var error = new Error();

            int lastCustomerId        = -1,
                lineNo                = 0;
            SalesOrderHeaderModel soh = null;

            var lineStatus = db.FindSalesOrderLineStatuses()
                             .Where(s => s.StatusName.ToLower() == "unpicked")
                             .FirstOrDefault();

            var nextAction = db.FindSaleNextActions()
                             .Where(na => na.Id == (int)Enumerations.SaleNextAction.None)
                             .FirstOrDefault();

            // Create an order for each supplier
            foreach (var row in db.FindFileImportRows(company.Id, user.Id)
                     .Skip(1)                      // Skip first record (headers)
                     .OrderBy(r => r.CustomerId)
                     .ToList())
            {
                if (row.CustomerId != lastCustomerId)
                {
                    // Found another supplier, so start a new order
                    soh = new SalesOrderHeaderModel {
                        CompanyId          = company.Id,
                        SourceId           = sourceId,
                        CustomerId         = row.CustomerId,
                        OrderNumber        = (int)LookupService.GetNextSequenceNumber(company, SequenceNumberType.SalesOrderNumber),
                        OrderDate          = DateTimeOffset.Now,
                        SOStatus           = soStatusId,
                        SalespersonId      = user.Id,
                        IsConfirmedAddress = false,
                        IsManualFreight    = false,
                        DateCreated        = DateTimeOffset.Now,
                    };

                    soh.EndUserName = getFieldValue(row, "EndUserName");

                    soh.ShipAddress1  = getFieldValue(row, "ShipAddress1");
                    soh.ShipSuburb    = getFieldValue(row, "ShipSuburb");
                    soh.ShipState     = getFieldValue(row, "ShipState");
                    soh.ShipPostcode  = getFieldValue(row, "ShipPostcode");
                    soh.ShipCountryId = db.FindCountry(getFieldValue(row, "ShipCountry")).Id;
                    soh.LocationId    = db.FindLocation(company.Id, getFieldValue(row, "LocationId")).Id;

                    soh.WarehouseInstructions = getFieldValue(row, "WarehouseInstructions");

                    soh.CustPO = getFieldValue(row, "CustPO");

                    soh.DeliveryWindowOpen  = getFieldValue(row, "DeliveryWindowOpen").PadLeft(10, '0').ParseDateTime(dateFormat, tz);
                    soh.DeliveryWindowClose = getFieldValue(row, "DeliveryWindowClose").PadLeft(10, '0').ParseDateTime(dateFormat, tz);

                    soh.ManualDWSet  = getFieldValue(row, "ManualDWSet").ParseBool();
                    soh.NextActionId = nextAction.Id;

                    soh.DeliveryInstructions = getFieldValue(row, "DeliveryInstructions");
                    soh.DeliveryContact      = getFieldValue(row, "DeliveryContact");

                    soh.BrandCategoryId = db.FindBrandCategory(company.Id, getFieldValue(row, "BrandCategory")).Id;

                    InsertOrUpdateSalesOrderHeader(soh, user, "");

                    lastCustomerId = row.CustomerId.Value;
                    lineNo         = 1000;
                }

                // Add items to the new order
                var sod = new SalesOrderDetailModel {
                    CompanyId          = company.Id,
                    SalesOrderHeaderId = soh.Id,
                    LineNumber         = lineNo,
                    ProductId          = row.ProductId,
                    ProductDescription = row.Product.ItemName,
                    UnitPriceExTax     = Convert.ToDecimal(getField(row, "UnitPriceExTax").Value),
                    DiscountPercent    = Convert.ToDecimal(getField(row, "DiscountPercent").Value),
                    TaxCodeId          = null,
                    OrderQty           = Convert.ToInt32(getField(row, "Quantity").Value),
                    LineStatusId       = null
                };
                if (row.Supplier != null)
                {
                    sod.TaxCodeId = row.Supplier.TaxCodeId.Value;
                }
                if (lineStatus != null)
                {
                    sod.LineStatusId = lineStatus.Id;
                }

                InsertOrUpdateSalesOrderDetail(sod, "");

                lineNo += 1000;
            }

            return(error);
        }
        private CreditClaimReplacementOrderModel getCreditClaimReplacementOrder(CompanyModel company, CreditClaimHeaderModel cch, SalesOrderHeaderModel soh)
        {
            var model = new CreditClaimReplacementOrderModel();

            model.CompanyId           = company.Id;
            model.CreditClaimHeaderId = cch.Id;
            model.SalesOrderHeaderId  = soh.Id;
            return(model);
        }
Beispiel #21
0
        // This method is called by others in this module to provide a single point
        // fo creating sales-related PDFs
        private Error createSalesOrderPdf(SalesOrderHeaderModel soh, DocumentTemplateModel template,
                                          string pdfFile, bool showCancelledItems,
                                          ref string outputFile, int maxItems = Int32.MaxValue)
        {
            var error = new Error();

            string tempFile = MediaService.MediaService.GetTempFile(".html");

            if (string.IsNullOrEmpty(pdfFile))
            {
                outputFile = MediaService.MediaService.GetTempFile().FolderName() + "\\" + soh.OrderNumber + "_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".pdf";
            }
            else
            {
                outputFile = pdfFile;
            }

            // Insert the lines
            decimal subTotal       = 0,
                    subTotalIncGst = 0,
                    freightTotal   = 0;

            CompanyService.CompanyService companyService = new CompanyService.CompanyService(db);
            var company = companyService.FindCompanyModel(soh.CompanyId);

            CustomerService.CustomerService customerService = new CustomerService.CustomerService(db);
            var customer = customerService.FindCustomerModel(soh.CustomerId == null ? 0 : soh.CustomerId.Value,
                                                             company);

            var paymentTerms = LookupService.FindPaymentTermModel(soh.TermsId == null ? 0 : soh.TermsId.Value);

            var taxCode = LookupService.FindTaxCodeModel(customer.TaxCodeId);

            var currency = LookupService.FindCurrencyModel(company.DefaultCurrencyID == null ? 0 : company.DefaultCurrencyID.Value);

            Dictionary <string, string>         headerProps = new Dictionary <string, string>();
            List <Dictionary <string, string> > records     = new List <Dictionary <string, string> >();

            AddCompanyInformation(company, headerProps);

            headerProps.AddProperty("ORDERNUMBER", soh.OrderNumber.ToString());
            headerProps.AddProperty("CUSTPO", soh.CustPO);
            headerProps.AddProperty("ORDERDATE", formatDate(soh.OrderDate, company.DateFormat));
            headerProps.AddProperty("PAYMENTTERMS", paymentTerms.TermText);

            var salesMgr = customerService.FindBrandCategorySalesPersonsModel(company, customer, soh.BrandCategoryId.Value, SalesPersonType.AccountAdmin).FirstOrDefault();

            if (salesMgr != null)
            {
                headerProps.AddProperty("ACCOUNTMANAGER", salesMgr.UserName);
            }
            else
            {
                headerProps.AddProperty("ACCOUNTMANAGER", "");
            }

            headerProps.AddProperty("CUSTOMERNAME", customer.Name);

            var contact = customerService.FindPrimaryCustomerContactsModel(customer)
                          .FirstOrDefault();

            headerProps.AddProperty("CUSTOMERCONTACT", contact.ContactFirstname + " " + contact.ContactSurname);

            var addrs = customerService.FindCurrentCustomerAddresses(customer, AddressType.Billing)
                        .FirstOrDefault();

            if (addrs == null)
            {
                addrs = new CustomerAddressModel();
            }

            headerProps.AddProperty("STREET", addrs.Street);
            headerProps.AddProperty("CITY", addrs.City);
            headerProps.AddProperty("STATE", addrs.State);
            headerProps.AddProperty("POSTCODE", addrs.Postcode);
            headerProps.AddProperty("COUNTRY", addrs.CountryName);
            headerProps.AddProperty("PHONENO", contact.ContactPhone1);
            headerProps.AddProperty("FAXNUMBER", contact.ContactFax);

            headerProps.AddProperty("DELIVERYADDRESS", soh.FullAddress.Replace("\r\n", "<br/>"));

            headerProps.AddProperty("TAXNAME", taxCode.TaxCode);
            headerProps.AddProperty("CURRENCYSYMBOL", currency.CurrencySymbol);

            var shipMethod = LookupService.FindLOVItemModel((soh.ShippingMethodId == null ? 0 : soh.ShippingMethodId.Value),
                                                            LOVName.ShippingMethod);

            headerProps.AddProperty("DELIVERYVIA", shipMethod.ItemText);

            headerProps.AddProperty("REQUIREDDATE", (soh.RequiredDate == null ? "" : soh.RequiredDate.Value.ToString(company.DateFormat)));

            headerProps.AddProperty("SALESPERSON", soh.SalesPersonName);

            // Add items
            var barCodeService = new BarCodeService.BarCodeService(db);

            int itemCount = 1;

            foreach (var sod in FindSalesOrderDetailListModel(company, soh))
            {
                if ((template.TemplateType == DocumentTemplateType.SaleCancellation && sod.LineStatusId == (int)SalesOrderLineStatus.Cancelled) ||
                    (template.TemplateType != DocumentTemplateType.SaleCancellation && (sod.LineStatusId != (int)SalesOrderLineStatus.Cancelled || showCancelledItems)))
                {
                    decimal unitPriceExTax = (sod.UnitPriceExTax == null ? 0 : sod.UnitPriceExTax.Value);
                    decimal discountPc     = (sod.DiscountPercent == null ? 0 : sod.DiscountPercent.Value);
                    decimal orderQty       = (sod.OrderQty == null ? 0 : sod.OrderQty.Value);
                    decimal totalExTax     = unitPriceExTax * orderQty;
                    decimal linePrice      = (orderQty * unitPriceExTax - ((orderQty * unitPriceExTax) / 100 * discountPc));

                    Dictionary <string, string> line = new Dictionary <string, string>();
                    line.AddProperty("ORDERQTY", sod.OrderQty);

                    var    product    = ProductService.FindProductModel(sod.ProductId.Value, null, company, false);
                    string mediaImage = ProductService.GetProductImage(product, MediaSize.Large, 640, 480, false);
                    line.AddProperty("PRODUCTIMAGE", mediaImage);

                    line.AddProperty("ITEMNUMBER", product.ItemNumber);
                    line.AddProperty("ITEMNAME", product.ItemName);
                    line.AddProperty("DESCRIPTION", itemCount.ToString() + " " + sod.ProductDescription);
                    line.AddProperty("UNITPRICEEXTAX", unitPriceExTax.ToString("#,##0.00"));
                    line.AddProperty("TOTALEXTAX", totalExTax.ToString("#,##0.00"));
                    line.AddProperty("DISCOUNTPERCENT", discountPc.ToString("#,##0.00"));
                    line.AddProperty("LINEPRICE", linePrice.ToString("#,##0.00"));
                    //line.AddProperty("RRP", "");

                    line.AddProperty("BRANDNAME", product.BrandName);
                    line.AddProperty("CATEGORY", product.Category);     // NOT Brand Category

                    string dimensions = "";
                    if (product.Length != null && product.Width != null && product.Height != null)
                    {
                        if (company.UnitOfMeasure == UnitOfMeasure.Imperial)
                        {
                            dimensions  = product.Length.CmToInches().ToString();
                            dimensions += " x " + product.Width.CmToInches().ToString();
                            dimensions += " x " + product.Height.CmToInches().ToString();
                            dimensions += " " + company.LengthUnit;
                        }
                        else
                        {
                            dimensions  = product.Length.ToString();
                            dimensions += " x " + product.Width.ToString();
                            dimensions += " x " + product.Height.ToString();
                            dimensions += " " + company.LengthUnit;
                        }
                    }
                    line.AddProperty("DIMENSIONS", dimensions);

                    string barCodeFile = "";
                    if (!string.IsNullOrEmpty(product.BarCode))
                    {
                        barCodeFile = barCodeService.GetBarCode(product.BarCode, true);
                        if (!string.IsNullOrEmpty(barCodeFile))
                        {
                            line.AddProperty("BARCODE", $"<img src=\"{barCodeFile}\"/>");
                        }
                        else
                        {
                            line.AddProperty("BARCODE", "");
                        }
                    }
                    else
                    {
                        line.AddProperty("BARCODE", "");
                    }

                    line.AddProperty("MINSALEQTY", product.MinSaleQty.ToString());
                    line.AddProperty("MATERIAL", product.MaterialText);

                    subTotal += linePrice;

                    records.Add(line);
                    itemCount++;
                }
            }

            headerProps.AddProperty("TAXNAME", taxCode.TaxCode);
            headerProps.AddProperty("CURRENCYSYMBOL", currency.CurrencySymbol);
            headerProps.AddProperty("CURRENCYCODE", currency.CurrencyCode);

            headerProps.AddProperty("SALEAMOUNTEX", subTotal.ToString("#,##0.00"));

            if (template.TemplateType == DocumentTemplateType.ProFormaInvoice ||
                template.TemplateType == DocumentTemplateType.OrderConfirmation)
            {
                freightTotal = CalculateEstimatedFreight(soh, customer);
            }
            headerProps.AddProperty("ESTIMATEDFREIGHT", freightTotal.ToString("#,##0.00"));

            subTotal      += freightTotal;
            subTotalIncGst = subTotal + (taxCode.TaxPercentageRate == null ? 0 : (subTotal / 100 * taxCode.TaxPercentageRate.Value));

            headerProps.AddProperty("SALEAMOUNTINC", subTotalIncGst.ToString("#,##0.00"));

            headerProps.AddProperty("GST", (subTotalIncGst - subTotal).ToString("#,##0.00"));

            return(DocumentService.CreateDocumentPdf(headerProps, records, template.QualTemplateFile, outputFile, maxItems));
        }
Beispiel #22
0
        private Error createPick(CompanyModel company, SalesOrderHeaderModel soh, ref PickHeaderModel pickHeader)
        {
            // Creates a pick in the pick database tables.
            // This method does not create any files.
            var error = new Error();

            if (soh.SalesOrderDetails == null || soh.SalesOrderDetails.Count == 0)
            {
                error.SetError(EvolutionResources.errCannotCreatePickWithNoItems, "", soh.OrderNumber.ToString());
            }
            else
            {
                LookupService.LookupService lookupService = new LookupService.LookupService(db);
                var pickH = new PickHeader {
                    CompanyId  = soh.CompanyId,
                    CustomerId = soh.CustomerId,
                    //public DateTimeOffset? PickDate { set; get; }
                    //public int? PickStatusId { set; get; }
                    LocationId = soh.LocationId,
                    //public DateTimeOffset? STWDate { set; get; }
                    //public DateTimeOffset? PickComplete { set; get; }
                    //public DateTimeOffset? PackComplete { set; get; }
                    ShipAddress1 = soh.ShipAddress1,
                    ShipAddress2 = soh.ShipAddress2,
                    ShipAddress3 = soh.ShipAddress3,
                    ShipAddress4 = soh.ShipAddress4,
                    ShipSuburb   = soh.ShipSuburb,
                    ShipState    = soh.ShipState,
                    ShipPostcode = soh.ShipPostcode,
                    //public DateTimeOffset? InvoiceDate { set; get; }
                    InvoiceNumber = Convert.ToInt32(lookupService.GetNextSequenceNumber(company, SequenceNumberType.InvoiceNumber)),
                    //public bool InvoiceFinalised { set; get; }
                    ShipMethodId  = soh.ShippingMethodId,
                    SalesPersonId = soh.SalespersonId,
                    //public DateTimeOffset? ShipDate { set; get; }
                    //public string TrackingNumber { set; get; }
                    //public int? BoxCount { set; get; }
                    //public int? PickPriority { set; get; }
                    //public int? PickedById { set; get; }
                    //public int? PackedById { set; get; }
                    //public DateTimeOffset? ReadyForShippingDate { set; get; }
                    //public int? ShippingDocumentId { set; get; }
                    //public DateTimeOffset? AddedToShipManifestDate { set; get; }
                    //public bool DocumentPrinted { set; get; }
                    CustPO = soh.CustPO,
                    //public string SecretComment { set; get; }
                    //public string PickComment { set; get; }
                    //public string ShipMethodAccount { set; get; }
                    //public double? FreightCost { set; get; }
                    DeliveryInstructions = soh.DeliveryInstructions,
                    //public string CustomerContact { set; get; }
                    IsManualFreight = soh.IsManualFreight,
                    ShipCountryId   = soh.ShipCountryId,
                    //public decimal? OurFreightCost { set; get; }
                    //public string EnteredBy { set; get; }
                    WarehouseInstructions = soh.WarehouseInstructions,
                    EndUserName           = soh.EndUserName,
                    CreditCardId          = soh.CreditCardId,
                    //public bool IsRetailPick { set; get; }
                    //public bool IsUploadedToWarehouse { set; get; }
                    TermsID = soh.TermsId,
                    //public string UnregisteredFreightCarrier { set; get; }
                    //public DateTimeOffset? DateCreditCardCharged { set; get; }
                    OrderTypeId = soh.OrderTypeId
                };
                db.InsertOrUpdatePickHeader(pickH);
                mapToModel(pickH, pickHeader);
            }
            return(error);
        }
        public void IntegrationTest()
        {
            var connection = TestSession.GetConnection();

            connection.Open();
            #region good insertion and select by id test
            SalesOrderHeaderModel inserted = new SalesOrderHeaderModel();
            inserted.RevisionNumber         = Convert.ToByte(TestSession.Random.RandomString(3));
            inserted.OrderDate              = TestSession.Random.RandomDateTime();
            inserted.DueDate                = TestSession.Random.RandomDateTime();
            inserted.ShipDate               = TestSession.Random.RandomDateTime();
            inserted.Status                 = Convert.ToByte(TestSession.Random.RandomString(3));
            inserted.OnlineOrderFlag        = Convert.ToBoolean(TestSession.Random.Next(1));
            inserted.SalesOrderNumber       = TestSession.Random.RandomString(25);
            inserted.PurchaseOrderNumber    = TestSession.Random.RandomString(25);
            inserted.AccountNumber          = TestSession.Random.RandomString(15);
            inserted.CustomerID             = TestSession.Random.Next();
            inserted.SalesPersonID          = TestSession.Random.Next();
            inserted.TerritoryID            = TestSession.Random.Next();
            inserted.BillToAddressID        = TestSession.Random.Next();
            inserted.ShipToAddressID        = TestSession.Random.Next();
            inserted.ShipMethodID           = TestSession.Random.Next();
            inserted.CreditCardID           = TestSession.Random.Next();
            inserted.CreditCardApprovalCode = TestSession.Random.RandomString(15);
            inserted.CurrencyRateID         = TestSession.Random.Next();
            inserted.SubTotal               = TestSession.Random.RandomDecimal();
            inserted.TaxAmt                 = TestSession.Random.RandomDecimal();
            inserted.Freight                = TestSession.Random.RandomDecimal();
            inserted.TotalDue               = TestSession.Random.RandomDecimal();
            inserted.Comment                = TestSession.Random.RandomString(128);
            inserted.rowguid                = Guid.NewGuid();
            inserted.ModifiedDate           = TestSession.Random.RandomDateTime();

            _tested.Insert(connection, new[] { inserted });

            var selectedAfterInsertion = _tested.GetByPrimaryKey(connection, new SalesOrderHeaderModelPrimaryKey()
            {
                SalesOrderID = inserted.SalesOrderID,
            });

            CollectionAssert.IsNotEmpty(selectedAfterInsertion);
            var selectedAfterInsert = selectedAfterInsertion.Single();
            Assert.AreEqual(inserted.SalesOrderID, selectedAfterInsert.SalesOrderID);
            Assert.AreEqual(inserted.RevisionNumber, selectedAfterInsert.RevisionNumber);
            Assert.AreEqual(inserted.OrderDate, selectedAfterInsert.OrderDate);
            Assert.AreEqual(inserted.DueDate, selectedAfterInsert.DueDate);
            Assert.AreEqual(inserted.ShipDate, selectedAfterInsert.ShipDate);
            Assert.AreEqual(inserted.Status, selectedAfterInsert.Status);
            Assert.AreEqual(inserted.OnlineOrderFlag, selectedAfterInsert.OnlineOrderFlag);
            Assert.AreEqual(inserted.SalesOrderNumber, selectedAfterInsert.SalesOrderNumber);
            Assert.AreEqual(inserted.PurchaseOrderNumber, selectedAfterInsert.PurchaseOrderNumber);
            Assert.AreEqual(inserted.AccountNumber, selectedAfterInsert.AccountNumber);
            Assert.AreEqual(inserted.CustomerID, selectedAfterInsert.CustomerID);
            Assert.AreEqual(inserted.SalesPersonID, selectedAfterInsert.SalesPersonID);
            Assert.AreEqual(inserted.TerritoryID, selectedAfterInsert.TerritoryID);
            Assert.AreEqual(inserted.BillToAddressID, selectedAfterInsert.BillToAddressID);
            Assert.AreEqual(inserted.ShipToAddressID, selectedAfterInsert.ShipToAddressID);
            Assert.AreEqual(inserted.ShipMethodID, selectedAfterInsert.ShipMethodID);
            Assert.AreEqual(inserted.CreditCardID, selectedAfterInsert.CreditCardID);
            Assert.AreEqual(inserted.CreditCardApprovalCode, selectedAfterInsert.CreditCardApprovalCode);
            Assert.AreEqual(inserted.CurrencyRateID, selectedAfterInsert.CurrencyRateID);
            Assert.AreEqual(inserted.SubTotal, selectedAfterInsert.SubTotal);
            Assert.AreEqual(inserted.TaxAmt, selectedAfterInsert.TaxAmt);
            Assert.AreEqual(inserted.Freight, selectedAfterInsert.Freight);
            Assert.AreEqual(inserted.TotalDue, selectedAfterInsert.TotalDue);
            Assert.AreEqual(inserted.Comment, selectedAfterInsert.Comment);
            Assert.AreEqual(inserted.rowguid, selectedAfterInsert.rowguid);
            Assert.AreEqual(inserted.ModifiedDate, selectedAfterInsert.ModifiedDate);

            #endregion

            #region update and select by id test
            inserted.RevisionNumber         = Convert.ToByte(TestSession.Random.RandomString(3));
            inserted.OrderDate              = TestSession.Random.RandomDateTime();
            inserted.DueDate                = TestSession.Random.RandomDateTime();
            inserted.ShipDate               = TestSession.Random.RandomDateTime();
            inserted.Status                 = Convert.ToByte(TestSession.Random.RandomString(3));
            inserted.OnlineOrderFlag        = Convert.ToBoolean(TestSession.Random.Next(1));
            inserted.SalesOrderNumber       = TestSession.Random.RandomString(25);
            inserted.PurchaseOrderNumber    = TestSession.Random.RandomString(25);
            inserted.AccountNumber          = TestSession.Random.RandomString(15);
            inserted.CustomerID             = TestSession.Random.Next();
            inserted.SalesPersonID          = TestSession.Random.Next();
            inserted.TerritoryID            = TestSession.Random.Next();
            inserted.BillToAddressID        = TestSession.Random.Next();
            inserted.ShipToAddressID        = TestSession.Random.Next();
            inserted.ShipMethodID           = TestSession.Random.Next();
            inserted.CreditCardID           = TestSession.Random.Next();
            inserted.CreditCardApprovalCode = TestSession.Random.RandomString(15);
            inserted.CurrencyRateID         = TestSession.Random.Next();
            inserted.SubTotal               = TestSession.Random.RandomDecimal();
            inserted.TaxAmt                 = TestSession.Random.RandomDecimal();
            inserted.Freight                = TestSession.Random.RandomDecimal();
            inserted.TotalDue               = TestSession.Random.RandomDecimal();
            inserted.Comment                = TestSession.Random.RandomString(128);
            inserted.rowguid                = Guid.NewGuid();
            inserted.ModifiedDate           = TestSession.Random.RandomDateTime();

            _tested.Update(connection, new[] { inserted });

            var selectedAfterUpdateAddresss = _tested.GetByPrimaryKey(connection, new SalesOrderHeaderModelPrimaryKey()
            {
                SalesOrderID = inserted.SalesOrderID,
            });

            CollectionAssert.IsNotEmpty(selectedAfterUpdateAddresss);
            var selectedAfterUpdate = selectedAfterUpdateAddresss.Single();
            Assert.AreEqual(inserted.SalesOrderID, selectedAfterUpdate.SalesOrderID);
            Assert.AreEqual(inserted.RevisionNumber, selectedAfterUpdate.RevisionNumber);
            Assert.AreEqual(inserted.OrderDate, selectedAfterUpdate.OrderDate);
            Assert.AreEqual(inserted.DueDate, selectedAfterUpdate.DueDate);
            Assert.AreEqual(inserted.ShipDate, selectedAfterUpdate.ShipDate);
            Assert.AreEqual(inserted.Status, selectedAfterUpdate.Status);
            Assert.AreEqual(inserted.OnlineOrderFlag, selectedAfterUpdate.OnlineOrderFlag);
            Assert.AreEqual(inserted.SalesOrderNumber, selectedAfterUpdate.SalesOrderNumber);
            Assert.AreEqual(inserted.PurchaseOrderNumber, selectedAfterUpdate.PurchaseOrderNumber);
            Assert.AreEqual(inserted.AccountNumber, selectedAfterUpdate.AccountNumber);
            Assert.AreEqual(inserted.CustomerID, selectedAfterUpdate.CustomerID);
            Assert.AreEqual(inserted.SalesPersonID, selectedAfterUpdate.SalesPersonID);
            Assert.AreEqual(inserted.TerritoryID, selectedAfterUpdate.TerritoryID);
            Assert.AreEqual(inserted.BillToAddressID, selectedAfterUpdate.BillToAddressID);
            Assert.AreEqual(inserted.ShipToAddressID, selectedAfterUpdate.ShipToAddressID);
            Assert.AreEqual(inserted.ShipMethodID, selectedAfterUpdate.ShipMethodID);
            Assert.AreEqual(inserted.CreditCardID, selectedAfterUpdate.CreditCardID);
            Assert.AreEqual(inserted.CreditCardApprovalCode, selectedAfterUpdate.CreditCardApprovalCode);
            Assert.AreEqual(inserted.CurrencyRateID, selectedAfterUpdate.CurrencyRateID);
            Assert.AreEqual(inserted.SubTotal, selectedAfterUpdate.SubTotal);
            Assert.AreEqual(inserted.TaxAmt, selectedAfterUpdate.TaxAmt);
            Assert.AreEqual(inserted.Freight, selectedAfterUpdate.Freight);
            Assert.AreEqual(inserted.TotalDue, selectedAfterUpdate.TotalDue);
            Assert.AreEqual(inserted.Comment, selectedAfterUpdate.Comment);
            Assert.AreEqual(inserted.rowguid, selectedAfterUpdate.rowguid);
            Assert.AreEqual(inserted.ModifiedDate, selectedAfterUpdate.ModifiedDate);

            #endregion

            #region delete test
            _tested.Delete(connection, new[] { inserted });
            var selectedAfterDeleteAddresss = _tested.GetByPrimaryKey(connection, new SalesOrderHeaderModelPrimaryKey()
            {
                SalesOrderID = inserted.SalesOrderID,
            });
            CollectionAssert.IsEmpty(selectedAfterDeleteAddresss);
            #endregion
            connection.Close();
        }
Beispiel #24
0
        private Error validateOrderBasics(CompanyModel company, SalesOrderHeaderModel soh)
        {
            //  All orders must:
            //      Have a customer
            //      Have a valid/completed delivery address
            //      Have a valid/completed billing address
            //      Have a next action of 'Ship something'
            //      Have no items on the order which violate MSQ
            //      Have a sales person
            //      Have a freight carrier
            //      Have a credit card
            var error      = new Error();
            int errorCount = 0;

            // Check for a customer
            var customer = CustomerService.FindCustomerModel(soh.CustomerId ?? 0, company, false);

            if (soh.CustomerId == null || customer == null)
            {
                error.SetError(EvolutionResources.errCannotDropOrderWithNoCustomer, "", soh.OrderNumber.ToString());
            }
            else
            {
                // Check for a valid billing address
                var billingAddrs = CustomerService.FindCustomerAddressesListModel(soh.CustomerId.Value)
                                   .Items
                                   .Where(addrs => addrs.AddressType == AddressType.Billing)
                                   .FirstOrDefault();
                if (billingAddrs == null || !billingAddrs.IsValid)
                {
                    // Invalid billing address
                    error.SetError(EvolutionResources.errCannotDropOrderWithInvalidCustomerBillingAddress, "", soh.OrderNumber.ToString(), customer.Name);
                }
                else if (soh.NextActionId != (int)Enumerations.SaleNextAction.ShipSomething)
                {
                    // Invalid next action
                    error.SetError(EvolutionResources.errCannotDropOrderWhenNotShipSomething, "", soh.OrderNumber.ToString(), soh.CustomerName);
                }
                else if (soh.SalespersonId == null)
                {
                    // No sales person
                    error.SetError(EvolutionResources.errCannotDropOrderWhenNoSalesPerson, "", soh.OrderNumber.ToString(), soh.CustomerName);
                }
                else if (soh.FreightCarrierId == null)
                {
                    // No freight carrier
                    error.SetError(EvolutionResources.errCannotDropOrderWithNoFreightCarrier, "", soh.OrderNumber.ToString(), soh.CustomerName);
                }
                else if (soh.CreditCardId == null)
                {
                    // No credit card
                    error.SetError(EvolutionResources.errCannotDropOrderWithNoCreditCard, "", soh.OrderNumber.ToString(), soh.CustomerName);
                }
                else
                {
                    // Check for MSQ violations
                    var errorMsg = EvolutionResources.errCannotDropOrderWhenMSQNotMet;
                    foreach (var sod in FindSalesOrderDetailListModel(company, soh))
                    {
                        // Check the MSQ of each line
                        var product = ProductService.FindProductModel(sod.ProductId.Value, null, null, false);
                        if (sod.OrderQty < product.MinSaleQty)
                        {
                            if (!string.IsNullOrEmpty(errorMsg))
                            {
                                errorMsg += "<br/>";
                            }
                            errorMsg += EvolutionResources.errCannotDropOrderWhenMSQNotMet
                                        .Replace("%1", soh.OrderNumber.ToString())
                                        .Replace("%2", soh.CustomerName)
                                        .Replace("%3", product.ItemNumber)
                                        .Replace("%4", product.MinSaleQty.ToString());

                            error.SetError(errorMsg);
                            errorCount++;
                            if (errorCount >= 4)
                            {
                                break;
                            }
                        }
                    }
                }
            }
            return(error);
        }
        public bool IsCreditClaimReplacementOrder(SalesOrderHeaderModel soh)
        {
            var temp = db.FindCreditClaimReplacementOrderForSoh(soh.CompanyId, soh.Id);

            return(temp != null);
        }
        public Error CreateOrderConfirmationPdf(SalesOrderHeaderModel soh, DocumentTemplateModel template,
                                                string pdfFile,
                                                bool showCancelledItems,
                                                ref string outputFile,
                                                int maxItems = Int32.MaxValue)
        {
            var error = new Error();

            string tempFile = MediaService.MediaService.GetTempFile(".html");

            if (string.IsNullOrEmpty(pdfFile))
            {
                outputFile = MediaService.MediaService.GetTempFile().FolderName() + "\\" + soh.OrderNumber + "_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".pdf";
            }
            else
            {
                outputFile = pdfFile;
            }

            // Insert the lines
            decimal subTotal       = 0,
                    subTotalIncGst = 0,
                    freightTotal   = 0;

            CompanyService.CompanyService companyService = new CompanyService.CompanyService(db);
            var company = companyService.FindCompanyModel(soh.CompanyId);

            CustomerService.CustomerService customerService = new CustomerService.CustomerService(db);
            var customer = customerService.FindCustomerModel(soh.CustomerId == null ? 0 : soh.CustomerId.Value,
                                                             company);

            var paymentTerms = LookupService.FindPaymentTermModel(soh.TermsId == null ? 0 : soh.TermsId.Value);

            var taxCode = LookupService.FindTaxCodeModel(customer.TaxCodeId);

            subTotalIncGst = subTotal + (taxCode.TaxPercentageRate == null ? 0 : (subTotal / 100 * taxCode.TaxPercentageRate.Value));

            var currency = LookupService.FindCurrencyModel(company.DefaultCurrencyID == null ? 0 : company.DefaultCurrencyID.Value);

            Dictionary <string, string>         headerProps = new Dictionary <string, string>();
            List <Dictionary <string, string> > records     = new List <Dictionary <string, string> >();

            AddCompanyInformation(company, headerProps);

            headerProps.AddProperty("ORDERNUMBER", soh.OrderNumber.ToString());
            headerProps.AddProperty("CUSTPO", soh.CustPO);
            headerProps.AddProperty("ORDERDATE", formatDate(soh.OrderDate, company.DateFormat));
            headerProps.AddProperty("PAYMENTTERMS", paymentTerms.TermText);

            var salesMgr = customerService.FindBrandCategorySalesPersonsModel(company, customer, soh.BrandCategoryId.Value, SalesPersonType.AccountAdmin).FirstOrDefault();

            if (salesMgr != null)
            {
                headerProps.AddProperty("ACCOUNTMANAGER", salesMgr.UserName);
            }
            else
            {
                headerProps.AddProperty("ACCOUNTMANAGER", "");
            }

            headerProps.AddProperty("CUSTOMERNAME", customer.Name);

            var contact = customerService.FindPrimaryCustomerContactsModel(customer)
                          .FirstOrDefault();

            headerProps.AddProperty("CUSTOMERCONTACT", contact.ContactFirstname + " " + contact.ContactSurname);

            var addrs = customerService.FindCurrentCustomerAddresses(customer, AddressType.Billing)
                        .FirstOrDefault();

            if (addrs == null)
            {
                addrs = new CustomerAddressModel();
            }

            headerProps.AddProperty("STREET", addrs.Street);
            headerProps.AddProperty("CITY", addrs.City);
            headerProps.AddProperty("STATE", addrs.State);
            headerProps.AddProperty("POSTCODE", addrs.Postcode);
            headerProps.AddProperty("COUNTRY", addrs.CountryName);
            headerProps.AddProperty("PHONENO", contact.ContactPhone1);
            headerProps.AddProperty("FAXNUMBER", contact.ContactFax);

            headerProps.AddProperty("DELIVERYADDRESS", soh.FullAddress.Replace("\r\n", "<br/>"));

            headerProps.AddProperty("TAXNAME", taxCode.TaxCode);
            headerProps.AddProperty("CURRENCYSYMBOL", currency.CurrencySymbol);

            var shipMethod = LookupService.FindLOVItemModel((soh.ShippingMethodId == null ? 0 : soh.ShippingMethodId.Value),
                                                            LOVName.ShippingMethod);

            headerProps.AddProperty("DELIVERYVIA", shipMethod.ItemText);

            string deliveryWindow = "";

            if (soh.DeliveryWindowOpen != null)
            {
                deliveryWindow = soh.DeliveryWindowOpen.Value.ToString(company.DateFormat);
            }
            if (soh.DeliveryWindowClose != null)
            {
                if (!string.IsNullOrEmpty(deliveryWindow))
                {
                    deliveryWindow += " - ";
                }
                deliveryWindow += soh.DeliveryWindowClose.Value.ToString(company.DateFormat);
            }
            headerProps.AddProperty("DELIVERYWINDOW", deliveryWindow);
            headerProps.AddProperty("SALESPERSON", soh.SalesPersonName);

            // Add items
            int itemCount = 1;

            foreach (var sod in FindSalesOrderDetailListModel(company, soh))
            {
                if (sod.LineStatusId != (int)SalesOrderLineStatus.Cancelled || showCancelledItems)
                {
                    decimal unitPriceExTax = (sod.UnitPriceExTax == null ? 0 : sod.UnitPriceExTax.Value);
                    decimal discountPc     = (sod.DiscountPercent == null ? 0 : sod.DiscountPercent.Value);
                    decimal linePrice      = (sod.OrderQty.Value * unitPriceExTax - ((sod.OrderQty.Value * unitPriceExTax) / 100 * discountPc));

                    Dictionary <string, string> line = new Dictionary <string, string>();
                    line.AddProperty("ORDERQTY", sod.OrderQty);

                    var product = ProductService.FindProductModel(sod.ProductId == null ? 0 : sod.ProductId.Value,
                                                                  null, company);
                    line.AddProperty("ITEMNUMBER", product.ItemNumber);
                    line.AddProperty("DESCRIPTION", itemCount.ToString() + " " + sod.ProductDescription);

                    var ecd = AllocationService.CalculateExpectedCompletionDate(sod);
                    if (ecd != null)
                    {
                        line.AddProperty("INSTOCK", ecd.Value.ToString(company.DateFormat));
                    }
                    else
                    {
                        line.AddProperty("INSTOCK", "");
                    }

                    line.AddProperty("UNITPRICEEXTAX", unitPriceExTax.ToString("#,##0.000"));
                    line.AddProperty("DISCOUNTPERCENT", discountPc.ToString("#,##0.00"));
                    line.AddProperty("LINEPRICE", linePrice.ToString("#,##0.000"));

                    subTotal += linePrice;

                    records.Add(line);
                    itemCount++;
                }
            }

            headerProps.AddProperty("TAXNAME", taxCode.TaxCode);
            headerProps.AddProperty("CURRENCYSYMBOL", currency.CurrencySymbol);

            headerProps.AddProperty("SALEAMOUNTEX", subTotal.ToString("#,##0.00"));

            freightTotal = CalculateEstimatedFreight(soh, customer);
            headerProps.AddProperty("ESTIMATEDFREIGHT", freightTotal.ToString("#,##0.00"));

            subTotal += freightTotal;

            subTotalIncGst = subTotal + (taxCode.TaxPercentageRate == null ? 0 : (subTotal / 100 * taxCode.TaxPercentageRate.Value));
            headerProps.AddProperty("SALEAMOUNTINC", subTotalIncGst.ToString("#,##0.00"));

            headerProps.AddProperty("GST", (subTotalIncGst - subTotal).ToString("#,##0.00"));

            return(DocumentService.CreateDocumentPdf(headerProps, records, template.QualTemplateFile, outputFile, maxItems));
        }
Beispiel #27
0
 public void RemoveAllocations(SalesOrderHeaderModel soh)
 {
 }