예제 #1
0
        /// <summary>
        /// Loads the fresh.
        /// </summary>
        /// <returns></returns>
        private TaxDto LoadFresh()
        {
            TaxDto tax = TaxManager.GetTax(TaxId);

            // persist in session
            Session[_TaxDtoEditSessionKey] = tax;

            return(tax);
        }
예제 #2
0
 public async Task <TaxDto> AddTax(TaxDto taxDto)
 {
     if (taxDto.TaxDecimal == 0 ||
         Enum.IsDefined(typeof(TaxType), (int)taxDto.TaxType) == false)
     {
         throw new Exception("Wrong properties, try again");
     }
     return(await _textRepository.AddTaxAsync(taxDto));
 }
        private static decimal GetShippingVatPercentage()
        {
            TaxDto taxDto = TaxManager.GetTaxDto(TaxType.ShippingTax);

            if (taxDto.TaxValue.Count == 0)
            {
                return(0);
            }
            return((decimal)taxDto.TaxValue[0].Percentage);
        }
예제 #4
0
        /// <summary>
        /// Saves the changes.
        /// </summary>
        /// <param name="context">The context.</param>
        public void SaveChanges(IDictionary context)
        {
            TaxDto dto = (TaxDto)context[_TaxDtoContextString];

            if (_Tax != null && dto != null)
            {
                ProcessTableEvents(_Tax);
                dto.TaxValue.Merge(_Tax.TaxValue, false);
            }
        }
        public async Task <IHttpActionResult> AddTax([FromBody] TaxDto taxDto)
        {
            var addTax = await _taxesService.AddTax(taxDto);

            if (addTax == null)
            {
                return(BadRequest("Something wrong data to allow it to add"));
            }

            return(Ok(addTax));
        }
예제 #6
0
 /// <summary>
 /// Creates the empty dto.
 /// </summary>
 /// <param name="tax">The pm.</param>
 /// <param name="persistInSession">if set to <c>true</c> [persist in session].</param>
 private void CreateEmptyDto(ref TaxDto tax, bool persistInSession)
 {
     if (tax == null || tax.Tax.Count == 0)
     {
         tax = new TaxDto();
         if (persistInSession)
         {
             Session[_TaxDtoEditSessionKey] = tax;
         }
     }
 }
예제 #7
0
 public async Task <ActionResult <Tax> > PostTaxDaily(TaxDto taxDto)
 {
     try
     {
         return(await _taxCommands.PostTaxDaily(taxDto));
     }
     catch (ArgumentOutOfRangeException)
     {
         return(BadRequest(Messages.MonthOrDayOutOfRange));
     }
 }
        public void PostTaxWeekly(TaxDto taxDto)
        {
            Console.WriteLine("COMMAND: Post tax weekly");
            RestRequest request = new RestRequest("Weekly", Method.POST);

            request.AddJsonBody(taxDto);
            var response = _client.Execute(request);

            Console.WriteLine(response.Content);
            Console.WriteLine();
        }
        public async Task <IHttpActionResult> UpadateTaxAsync([FromBody] TaxDto taxDto)
        {
            var updateTax = await _taxesService.UpdateTax(taxDto);

            if (updateTax == null)
            {
                return(BadRequest("Something wrong data to allow it to update"));
            }

            return(Ok(updateTax));
        }
예제 #10
0
        /// <summary>
        /// Checks if entered name is unique.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="args">The <see cref="System.Web.UI.WebControls.ServerValidateEventArgs"/> instance containing the event data.</param>
        public void NameCheck(object sender, ServerValidateEventArgs args)
        {
            // load tax by name
            TaxDto dto = TaxManager.GetTax(args.Value);

            // check if jurisdiction with specified code is loaded
            if (dto != null && dto.Tax.Count > 0 &&
                dto.Tax[0].TaxId != TaxId &&
                String.Compare(dto.Tax[0].Name, args.Value, StringComparison.CurrentCultureIgnoreCase) == 0)
            {
                args.IsValid = false;
                return;
            }

            args.IsValid = true;
        }
예제 #11
0
        /// <summary>
        /// Saves changes in TaxDto.
        /// </summary>
        /// <param name="dto">The dto.</param>
        public static void SaveTax(TaxDto dto)
        {
            if (dto == null)
            {
                throw new ArgumentNullException("dto", String.Format("TaxDto can not be null"));
            }

            // TODO: Check if user is allowed to perform this operation
            DataCommand cmd = OrderDataHelper.CreateConfigDataCommand();

            using (TransactionScope scope = new TransactionScope())
            {
                DataHelper.SaveDataSetSimple(OrderContext.MetaDataContext, cmd, dto, "Tax", "TaxLanguage", "TaxValue");
                scope.Complete();
            }
        }
예제 #12
0
        public async Task <TaxDto> AddTaxAsync(TaxDto taxDto)
        {
            var result = _dbContext.Taxes.Add(new Tax()
            {
                Id             = Guid.NewGuid(),
                MunicipalityId = taxDto.MunicipalityId,
                TaxDecimal     = taxDto.TaxDecimal,
                TaxType        = taxDto.TaxType,
                Date           = taxDto.Date
            });

            await _dbContext.SaveChangesAsync();

            taxDto.Id = result.Id;

            return(taxDto);
        }
예제 #13
0
        public async Task <TaxDto> UpadateTaxAsync(TaxDto taxDto)
        {
            var tax = await _dbContext.Taxes
                      .FirstOrDefaultAsync(x => x.Id == taxDto.Id);

            if (tax != null)
            {
                tax.MunicipalityId = taxDto.MunicipalityId;
                tax.TaxDecimal     = taxDto.TaxDecimal;
                tax.TaxType        = taxDto.TaxType;
                tax.Date           = taxDto.Date;
            }

            await _dbContext.SaveChangesAsync();

            return(taxDto);
        }
예제 #14
0
        public async Task <Tax> PostTaxDaily(TaxDto taxDto)
        {
            Frequency frequency = Frequency.Daily;

            // provide date for daily schedule
            int      year = DateTime.Now.Year;
            DateTime date = new DateTime(year, taxDto.Month, taxDto.Day);

            Tax tax = new Tax()
            {
                Municipality = taxDto.Municipality,
                Frequency    = frequency,
                StartDate    = date,
                EndDate      = date,
                TaxAmount    = taxDto.TaxAmount
            };

            return(await AddTax(tax));
        }
예제 #15
0
        void ProcessDeleteCommand(string[] items)
        {
            for (int i = 0; i < items.Length; i++)
            {
                string[] keys = EcfListView.GetPrimaryKeyIdStringItems(items[i]);
                if (keys != null)
                {
                    int id = Int32.Parse(keys[0]);

                    // delete selected tax
                    TaxDto dto = TaxManager.GetTax(id);
                    if (dto != null && dto.Tax.Count > 0)
                    {
                        dto.Tax[0].Delete();
                        TaxManager.SaveTax(dto);
                    }
                }
            }
        }
예제 #16
0
        public async Task <Tax> PostTaxWeekly(TaxDto taxDto)
        {
            Frequency frequency = Frequency.Weekly;

            // provide dates for weekly schedule
            int      year      = DateTime.Now.Year;
            DateTime startDate = ISOWeek.ToDateTime(year, taxDto.Week, DayOfWeek.Monday);
            DateTime endDate   = ISOWeek.ToDateTime(year, taxDto.Week, DayOfWeek.Sunday);

            Tax tax = new Tax()
            {
                Municipality = taxDto.Municipality,
                Frequency    = frequency,
                StartDate    = startDate,
                EndDate      = endDate,
                TaxAmount    = taxDto.TaxAmount
            };

            return(await AddTax(tax));
        }
예제 #17
0
        public async Task <Tax> PostTaxYearly(TaxDto taxDto)
        {
            Frequency frequency = Frequency.Yearly;

            // provide dates for yearly schedule
            int      year      = DateTime.Now.Year;
            DateTime startDate = new DateTime(year, 1, 1);
            DateTime endDate   = startDate.AddYears(1).AddTicks(-1).Date;

            Tax tax = new Tax()
            {
                Municipality = taxDto.Municipality,
                Frequency    = frequency,
                StartDate    = startDate,
                EndDate      = endDate,
                TaxAmount    = taxDto.TaxAmount
            };

            return(await AddTax(tax));
        }
예제 #18
0
        public async Task <Tax> PostTaxMonthly(TaxDto taxDto)
        {
            Frequency frequency = Frequency.Monthly;

            // provide dates for monthly schedule
            int      year      = DateTime.Now.Year;
            DateTime startDate = new DateTime(year, taxDto.Month, 1);
            DateTime endDate   = new DateTime(year, taxDto.Month, DateTime.DaysInMonth(year, taxDto.Month));

            Tax tax = new Tax()
            {
                Municipality = taxDto.Municipality,
                Frequency    = frequency,
                StartDate    = startDate,
                EndDate      = endDate,
                TaxAmount    = taxDto.TaxAmount
            };

            return(await AddTax(tax));
        }
예제 #19
0
        /// <summary>
        /// Handles the SaveChanges event of the EditSaveControl control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Mediachase.Commerce.Manager.Core.SaveControl.SaveEventArgs"/> instance containing the event data.</param>
        void EditSaveControl_SaveChanges(object sender, SaveControl.SaveEventArgs e)
        {
            // Validate form
            if (!this.Page.IsValid)
            {
                e.RunScript = false;
                return;
            }

            TaxDto tax = null;

            if (TaxId > 0)
            {
                tax = (TaxDto)Session[_TaxDtoEditSessionKey];
            }

            if (tax == null && TaxId > 0)
            {
                tax = TaxManager.GetTax(TaxId);
            }

            CreateEmptyDto(ref tax, true);

            IDictionary dic = new ListDictionary();

            dic.Add(_TaxDtoString, tax);

            ViewControl.SaveChanges(dic);

            // save changes
            if (tax.HasChanges())
            {
                TaxManager.SaveTax(tax);
            }

            ViewControl.CommitChanges(dic);

            // we don't need to store Dto in session any more
            Session.Remove(_TaxDtoEditSessionKey);
        }
예제 #20
0
        /// <summary>
        /// Loads the context.
        /// </summary>
        private void LoadContext()
        {
            TaxDto tax = null;

            if (!this.IsPostBack && (!this.Request.QueryString.ToString().Contains("Callback=yes")))             // load fresh on initial load
            {
                tax = LoadFresh();

                CreateEmptyDto(ref tax, true);
            }
            else             // load from session
            {
                tax = (TaxDto)Session[_TaxDtoEditSessionKey];

                if (tax == null)
                {
                    tax = LoadFresh();
                }
            }

            // Put a dictionary key that can be used by other tabs
            IDictionary dic = new ListDictionary();

            dic.Add(_TaxDtoString, tax);

            // Call tabs load context
            ViewControl.LoadContext(dic);

            // set redirect functiond for editsave control
            string langId = String.Empty;

            //if (tax != null && tax.TaxLanguage != null && tax.TaxLanguage.Count > 0)
            //    langId = tax.TaxLanguage[0].LanguageId;
            //else
            //	langId = LanguageCode;

            EditSaveControl.CancelClientScript = "CSOrderClient.TaxSaveRedirect();";
            EditSaveControl.SavedClientScript  = "CSOrderClient.TaxSaveRedirect();";
        }
예제 #21
0
        /// <summary>
        /// Processes the table events.
        /// </summary>
        /// <param name="dto">The dto.</param>
        private void ProcessTableEvents(TaxDto dto)
        {
            if (dto == null)
            {
                return;
            }

            foreach (GridItem item in _removedItems)
            {
                int id = 0;
                if (item[_GridTaxValueIdString] != null && Int32.TryParse(item[_GridTaxValueIdString].ToString(), out id))
                {
                    // find the value
                    TaxDto.TaxValueRow value = dto.TaxValue.FindByTaxValueId(id);
                    if (value != null)
                    {
                        value.Delete();
                    }
                }
            }

            _removedItems.Clear();
        }
예제 #22
0
        /// <summary>
        /// Loads the context.
        /// </summary>
        /// <param name="context">The context.</param>
        public void LoadContext(IDictionary context)
        {
            _Tax = (TaxDto)context[_TaxDtoContextString];
            if (_Tax != null && _Tax.Tax.Rows.Count > 0)
            {
                _taxId = _Tax.Tax[0].TaxId;
            }
            else
            {
                _taxId = -1;

                TaxDto.TaxRow taxRow = _Tax.Tax.NewTaxRow();
                taxRow.ApplicationId = OrderConfiguration.Instance.ApplicationId;
                taxRow.TaxId         = _taxId;
                taxRow.TaxType       = 0;
                taxRow.Name          = String.Empty;
                taxRow.SortOrder     = 0;

                if (taxRow.RowState == DataRowState.Detached)
                {
                    _Tax.Tax.Rows.Add(taxRow);
                }
            }
        }
예제 #23
0
 public static Tax FromDto(TaxDto dto)
 => new(new Name(dto.Name)
예제 #24
0
 public async Task <ActionResult <Tax> > PostTaxYearly(TaxDto taxDto)
 {
     return(await _taxCommands.PostTaxYearly(taxDto));
 }
예제 #25
0
            /// <summary>
            /// InvoiceXpress <a href="https://invoicexpress.com/api/taxes/create">Taxes Create</a> Method
            /// </summary>
            public static TaxDto Create(string apiKey, string accountName, TaxDto inputData)
            {
                HttpResponseInfo result = Rest_Create(apiKey, accountName, inputData.XmlSerializeToString());

                return(result.Text.DeserializeXml <TaxDto>());
            }
예제 #26
0
        public async Task <List <TaxDto> > GetZoneTaxesByAddressId(int tenantId, long addressId, bool active)
        {
            List <TaxDto> taxDtos;

            if (addressId != (long)-1)
            {
                Address async = await this._addressRepository.GetAsync(addressId);

                IQueryable <Zone> all   = this._zoneRepository.GetAll();
                IQueryable <Zone> zones =
                    from p in all
                    where p.TenantId == tenantId
                    select p;
                bool flag = active;
                IQueryable <Zone> zones1    = zones.WhereIf <Zone>(flag, (Zone p) => p.IsActive == active);
                List <Zone>       listAsync = await System.Data.Entity.QueryableExtensions.Include <Zone, ICollection <ZoneTax> >(zones1, (Zone n) => n.Taxes).OrderBy <Zone>("Name", new object[0]).ToListAsync <Zone>();

                List <ZoneDto>  zoneDtos        = new List <ZoneDto>();
                CustomDbContext customDbContext = new CustomDbContext();
                foreach (Zone zone in listAsync)
                {
                    ZoneDto      zoneDto       = zone.MapTo <ZoneDto>();
                    object[]     sqlParameter  = new object[] { new SqlParameter("@ZoneId", (object)zoneDto.Id), new SqlParameter("@AddressId", (object)async.Id), null };
                    SqlParameter sqlParameter1 = new SqlParameter()
                    {
                        ParameterName = "@retVal",
                        SqlDbType     = SqlDbType.Int,
                        Direction     = ParameterDirection.Output,
                        Value         = 0
                    };
                    sqlParameter[2] = sqlParameter1;
                    if (customDbContext.Database.SqlQuery <int>("exec @retVal = Geo_AddressIdInZone @ZoneId, @AddressId", sqlParameter).Single <int>() != 1)
                    {
                        continue;
                    }
                    zoneDtos.Add(zoneDto);
                }
                customDbContext.Dispose();
                List <ZoneDto> zoneDtos1 = new List <ZoneDto>(zoneDtos.MapTo <List <ZoneDto> >());
                List <TaxDto>  taxDtos1  = new List <TaxDto>();
                List <long>    nums      = new List <long>();
                foreach (ZoneDto zoneDto1 in zoneDtos1)
                {
                    foreach (ZoneTaxDto taxis in zoneDto1.Taxes)
                    {
                        TaxDto taxDto = taxis.Tax.MapTo <TaxDto>();
                        if (nums.Contains(taxDto.Id))
                        {
                            continue;
                        }
                        nums.Add(taxDto.Id);
                        taxDtos1.Add(taxDto);
                    }
                }
                taxDtos = new List <TaxDto>(taxDtos1.Distinct <TaxDto>().MapTo <List <TaxDto> >());
            }
            else
            {
                IRepository <TenantDetail, long> repository = this._tenantDetailRepository;
                TenantDetail tenantDetail = await repository.FirstOrDefaultAsync((TenantDetail x) => x.TenantId == tenantId);

                TenantDetail      tenantDetail1 = tenantDetail;
                IQueryable <Zone> all1          = this._zoneRepository.GetAll();
                IQueryable <Zone> zones2        =
                    from p in all1
                    where p.TenantId == tenantId
                    select p;
                bool flag1 = active;
                IQueryable <Zone> zones3     = zones2.WhereIf <Zone>(flag1, (Zone p) => p.IsActive == active);
                List <Zone>       listAsync1 = await System.Data.Entity.QueryableExtensions.Include <Zone, ICollection <ZoneTax> >(zones3, (Zone n) => n.Taxes).OrderBy <Zone>("Name", new object[0]).ToListAsync <Zone>();

                List <ZoneDto>  zoneDtos2        = new List <ZoneDto>();
                CustomDbContext customDbContext1 = new CustomDbContext();
                foreach (Zone zone1 in listAsync1)
                {
                    ZoneDto      zoneDto2      = zone1.MapTo <ZoneDto>();
                    object[]     objArray      = new object[] { new SqlParameter("@ZoneId", (object)zoneDto2.Id), new SqlParameter("@CompanyAddressId", (object)tenantDetail1.Id), null };
                    SqlParameter sqlParameter2 = new SqlParameter()
                    {
                        ParameterName = "@retVal",
                        SqlDbType     = SqlDbType.Int,
                        Direction     = ParameterDirection.Output,
                        Value         = 0
                    };
                    objArray[2] = sqlParameter2;
                    if (customDbContext1.Database.SqlQuery <int>("exec @retVal = Geo_CompanyAddressIdInZone @ZoneId, @CompanyAddressId", objArray).Single <int>() != 1)
                    {
                        continue;
                    }
                    zoneDtos2.Add(zoneDto2);
                }
                customDbContext1.Dispose();
                List <ZoneDto> zoneDtos3 = new List <ZoneDto>(zoneDtos2.MapTo <List <ZoneDto> >());
                List <TaxDto>  taxDtos2  = new List <TaxDto>();
                List <long>    nums1     = new List <long>();
                foreach (ZoneDto zoneDto3 in zoneDtos3)
                {
                    foreach (ZoneTaxDto zoneTaxDto in zoneDto3.Taxes)
                    {
                        TaxDto taxDto1 = zoneTaxDto.Tax.MapTo <TaxDto>();
                        if (nums1.Contains(taxDto1.Id))
                        {
                            continue;
                        }
                        nums1.Add(taxDto1.Id);
                        taxDtos2.Add(taxDto1);
                    }
                }
                taxDtos = new List <TaxDto>(taxDtos2.Distinct <TaxDto>().MapTo <List <TaxDto> >());
            }
            return(taxDtos);
        }
예제 #27
0
 /// <summary>
 /// InvoiceXpress <a href="https://invoicexpress.com/api/taxes/update">Taxes Update</a> Method
 /// </summary>
 public static void Update(string apiKey, string accountName, int taxId, TaxDto inputData)
 {
     Rest_Update(apiKey, accountName, taxId, inputData.XmlSerializeToString());
 }
예제 #28
0
 /// <summary>
 /// Loads the context.
 /// </summary>
 /// <param name="context">The context.</param>
 public void LoadContext(IDictionary context)
 {
     _Tax = (TaxDto)context[_TaxDtoContextString];
     TaxValueDialog.LoadContext(context);
 }
예제 #29
0
        /// <summary>
        /// Imports the specified input.
        /// </summary>
        /// <param name="input">The input.</param>
        /// <param name="applicationId">The application id.</param>
        /// <param name="baseFilePath">The base file path.</param>
        public void Import(string pathToCsvFile, Guid applicationId, Guid?siteId, char delimiter)
        {
            CultureInfo currentCultureInfo = GetImportExportCulture();

            int totalImportSteps = GetTotalImportSteps();

            OnEvent("Starting import...", 0);

            string fileName = Path.GetFileName(pathToCsvFile);

            // 1. Parse csv file
            OnEvent("Start parsing csv file", GetProgressPercent((int)ImportSteps.StartParseFile, totalImportSteps));

            CsvIncomingDataParser parser = new CsvIncomingDataParser(Path.GetDirectoryName(pathToCsvFile), true, delimiter);

            DataSet taxDataSet = parser.Parse(fileName, null);

            OnEvent("Finished parsing csv file", GetProgressPercent((int)ImportSteps.EndParseFile, totalImportSteps));

            // 2. Create Dtos from parsed DataSet
            if (taxDataSet.Tables[fileName] == null)
            {
                throw new OrdersImportExportException(String.Format("Unknown problem with parsing file {0}.", fileName));
            }

            OnEvent("Start processing parsed rows", GetProgressPercent((int)ImportSteps.StartImport, totalImportSteps));

            int totalRowCount = taxDataSet.Tables[fileName].Rows.Count;

            JurisdictionDto currentJurisdictionDto = JurisdictionManager.GetJurisdictions(Mediachase.Commerce.Orders.Managers.JurisdictionManager.JurisdictionType.Tax);
            TaxDto          currentTaxDto          = TaxManager.GetTaxDto(TaxType.SalesTax);

            JurisdictionDto jurisdictionDto = new JurisdictionDto();
            TaxDto          taxDto          = new TaxDto();

            for (int i = 0; i <= totalRowCount - 1; i++)
            {
                DataRow currentRow = taxDataSet.Tables[fileName].Rows[i];

                #region Import Jurisdictions
                #region JurisdictionDto
                string jurisdictionCode = currentRow.ItemArray.GetValue(9).ToString();

                JurisdictionDto.JurisdictionRow jRow = null;

                JurisdictionDto.JurisdictionRow[] jRows = (JurisdictionDto.JurisdictionRow[])currentJurisdictionDto.Jurisdiction.Select(String.Format("Code='{0}'", jurisdictionCode));

                // check if row has already been imported
                // (to support multiple values for the same jurisdiction need to check if jurisdiction with the given name already exists in jurisdictionDto)
                JurisdictionDto.JurisdictionRow[] jRows2 = (JurisdictionDto.JurisdictionRow[])jurisdictionDto.Jurisdiction.Select(String.Format("Code='{0}'", jurisdictionCode));
                bool jurisdictionExists = jRows2 != null && jRows2.Length > 0;

                if (jurisdictionExists)
                {
                    jRow = jRows2[0];
                }
                else
                {
                    if (jRows != null && jRows.Length > 0)
                    {
                        jurisdictionDto.Jurisdiction.ImportRow(jRows[0]);
                        jRow = jurisdictionDto.Jurisdiction[jurisdictionDto.Jurisdiction.Count - 1];
                    }
                    else
                    {
                        jRow = jurisdictionDto.Jurisdiction.NewJurisdictionRow();
                        jRow.ApplicationId    = applicationId;
                        jRow.JurisdictionType = Mediachase.Commerce.Orders.Managers.JurisdictionManager.JurisdictionType.Tax.GetHashCode();
                    }
                }

                jRow.DisplayName        = currentRow.ItemArray.GetValue(0).ToString();
                jRow.StateProvinceCode  = GetStringValue(currentRow.ItemArray.GetValue(1));
                jRow.CountryCode        = currentRow.ItemArray.GetValue(2).ToString();
                jRow.ZipPostalCodeStart = GetStringValue(currentRow.ItemArray.GetValue(3));
                jRow.ZipPostalCodeEnd   = GetStringValue(currentRow.ItemArray.GetValue(4));
                jRow.City     = GetStringValue(currentRow.ItemArray.GetValue(5));
                jRow.District = GetStringValue(currentRow.ItemArray.GetValue(6));
                jRow.County   = GetStringValue(currentRow.ItemArray.GetValue(7));
                jRow.GeoCode  = GetStringValue(currentRow.ItemArray.GetValue(8));
                jRow.Code     = jurisdictionCode;

                if (jRow.RowState == DataRowState.Detached)
                {
                    jurisdictionDto.Jurisdiction.Rows.Add(jRow);
                }
                #endregion

                #region JurisdictionGroupDto

                string jurisdictionGroupCode = currentRow.ItemArray.GetValue(11).ToString();

                JurisdictionDto.JurisdictionGroupRow jGroupRow = null;

                JurisdictionDto.JurisdictionGroupRow[] jGroupRows = (JurisdictionDto.JurisdictionGroupRow[])currentJurisdictionDto.JurisdictionGroup.Select(String.Format("Code='{0}'", jurisdictionGroupCode));

                // check if row has already been imported
                // (to support multiple values for the same jurisdiction need to check if jurisdiction with the given name already exists in jurisdictionDto)
                JurisdictionDto.JurisdictionGroupRow[] jGroupRows2 = (JurisdictionDto.JurisdictionGroupRow[])jurisdictionDto.JurisdictionGroup.Select(String.Format("Code='{0}'", jurisdictionGroupCode));
                bool jurisdictionGroupExists = jGroupRows2 != null && jGroupRows2.Length > 0;

                if (jurisdictionGroupExists)
                {
                    jGroupRow = jGroupRows2[0];
                }
                else
                {
                    if (jGroupRows != null && jGroupRows.Length > 0)
                    {
                        jurisdictionDto.JurisdictionGroup.ImportRow(jGroupRows[0]);
                        jGroupRow = jurisdictionDto.JurisdictionGroup[jurisdictionDto.JurisdictionGroup.Count - 1];
                    }
                    else
                    {
                        jGroupRow = jurisdictionDto.JurisdictionGroup.NewJurisdictionGroupRow();
                        jGroupRow.ApplicationId    = applicationId;
                        jGroupRow.JurisdictionType = Mediachase.Commerce.Orders.Managers.JurisdictionManager.JurisdictionType.Tax.GetHashCode();
                    }
                }

                jGroupRow.DisplayName = currentRow.ItemArray.GetValue(10).ToString();
                jGroupRow.Code        = jurisdictionGroupCode;

                if (jGroupRow.RowState == DataRowState.Detached)
                {
                    jurisdictionDto.JurisdictionGroup.Rows.Add(jGroupRow);
                }
                #endregion

                #region JurisdictionRelationDto
                JurisdictionDto.JurisdictionRelationRow jRelationRow = null;
                if (jRow.JurisdictionId > 0 && jGroupRow.JurisdictionGroupId > 0)
                {
                    // check if relation already exists
                    JurisdictionDto.JurisdictionRelationRow[] jRelationRows = (JurisdictionDto.JurisdictionRelationRow[])currentJurisdictionDto.JurisdictionRelation.Select(String.Format("JurisdictionId={0} AND JurisdictionGroupId={1}", jRow.JurisdictionId, jGroupRow.JurisdictionGroupId));
                    if (jRelationRows != null && jRelationRows.Length > 0)
                    {
                        jurisdictionDto.JurisdictionRelation.ImportRow(jRelationRows[0]);
                        jRelationRow = jurisdictionDto.JurisdictionRelation[jurisdictionDto.JurisdictionRelation.Count - 1];
                    }
                }
                if (jRelationRow == null)
                {
                    // create new relation
                    jRelationRow = jurisdictionDto.JurisdictionRelation.NewJurisdictionRelationRow();
                    jRelationRow.JurisdictionId      = jRow.JurisdictionId;
                    jRelationRow.JurisdictionGroupId = jGroupRow.JurisdictionGroupId;
                    jurisdictionDto.JurisdictionRelation.Rows.Add(jRelationRow);
                }
                #endregion

                // save jurisdictionDto
                if (jurisdictionDto.HasChanges())
                {
                    JurisdictionManager.SaveJurisdiction(jurisdictionDto);
                }
                #endregion

                #region Import Taxes
                #region TaxDto
                TaxDto.TaxRow taxRow = null;

                string taxName = currentRow.ItemArray.GetValue(13).ToString();

                // check if row already exists
                TaxDto.TaxRow[] taxRows = (TaxDto.TaxRow[])currentTaxDto.Tax.Select(String.Format("Name='{0}'", taxName));

                // check if row has already been imported
                TaxDto.TaxRow[] taxRows2  = (TaxDto.TaxRow[])taxDto.Tax.Select(String.Format("Name='{0}'", taxName));
                bool            taxExists = taxRows2 != null && taxRows2.Length > 0;

                if (taxExists)
                {
                    taxRow = taxRows2[0];
                }
                else
                {
                    #region if tax is not in the destination dto
                    if (taxRows != null && taxRows.Length > 0)
                    {
                        taxDto.Tax.ImportRow(taxRows[0]);
                        taxRow = taxDto.Tax[taxDto.Tax.Count - 1];
                    }
                    else
                    {
                        taxRow = taxDto.Tax.NewTaxRow();
                        taxRow.ApplicationId = applicationId;
                        taxRow.TaxType       = TaxType.SalesTax.GetHashCode();
                        taxRow.Name          = taxName;
                    }
                    #endregion
                }

                taxRow.SortOrder = Int32.Parse(currentRow.ItemArray.GetValue(14).ToString());

                if (taxRow.RowState == DataRowState.Detached)
                {
                    taxDto.Tax.Rows.Add(taxRow);
                }
                #endregion

                #region TaxLanguageDto
                TaxDto.TaxLanguageRow taxLanguageRow = null;

                string langCode = currentRow.ItemArray.GetValue(15).ToString();

                // check if row already exists
                TaxDto.TaxLanguageRow[] taxLanguageRows = (TaxDto.TaxLanguageRow[])currentTaxDto.TaxLanguage.Select(String.Format("LanguageCode='{0}' and TaxId={1}", langCode, taxRow.TaxId));

                // check if row has already been imported
                TaxDto.TaxLanguageRow[] taxLanguageRows2 = (TaxDto.TaxLanguageRow[])taxDto.TaxLanguage.Select(String.Format("LanguageCode='{0}' and TaxId={1}", langCode, taxRow.TaxId));
                bool taxLanguageExists = taxLanguageRows2 != null && taxLanguageRows2.Length > 0;

                string displayName = currentRow.ItemArray.GetValue(12).ToString();

                if (taxLanguageExists)
                {
                    taxLanguageRow = taxLanguageRows2[0];
                }
                else
                {
                    #region if tax is not in the destination dto
                    if (taxLanguageRows != null && taxLanguageRows.Length > 0)
                    {
                        taxDto.TaxLanguage.ImportRow(taxLanguageRows[0]);
                        taxLanguageRow = taxDto.TaxLanguage[taxDto.TaxLanguage.Count - 1];
                    }
                    else
                    {
                        taxLanguageRow = taxDto.TaxLanguage.NewTaxLanguageRow();
                        taxLanguageRow.LanguageCode = langCode;
                        taxLanguageRow.TaxId        = taxRow.TaxId;
                    }
                    #endregion
                }

                taxLanguageRow.DisplayName = displayName;

                if (taxLanguageRow.RowState == DataRowState.Detached)
                {
                    taxDto.TaxLanguage.Rows.Add(taxLanguageRow);
                }
                #endregion

                #region TaxValueDto
                TaxDto.TaxValueRow taxValueRow = null;

                // check if row already exists
                TaxDto.TaxValueRow[] taxValueRows = null;
                if (siteId.HasValue)
                {
                    taxValueRows = (TaxDto.TaxValueRow[])currentTaxDto.TaxValue.Select(String.Format("TaxId={0} and SiteId={1} and JurisdictionGroupId={2}", taxRow.TaxId, siteId.Value, jRelationRow.JurisdictionGroupId));
                }
                else
                {
                    taxValueRows = (TaxDto.TaxValueRow[])currentTaxDto.TaxValue.Select(String.Format("TaxId={0} and JurisdictionGroupId={1}", taxRow.TaxId, jRelationRow.JurisdictionGroupId));
                }

                // check if row has already been imported
                TaxDto.TaxValueRow[] taxValueRows2 = null;
                if (siteId.HasValue)
                {
                    taxValueRows2 = (TaxDto.TaxValueRow[])taxDto.TaxValue.Select(String.Format("TaxId={0} and SiteId={1} and JurisdictionGroupId={2}", taxRow.TaxId, siteId.Value, jRelationRow.JurisdictionGroupId));
                }
                else
                {
                    taxValueRows2 = (TaxDto.TaxValueRow[])taxDto.TaxValue.Select(String.Format("TaxId={0} and JurisdictionGroupId={1}", taxRow.TaxId, jRelationRow.JurisdictionGroupId));
                }

                bool taxValueExists = taxValueRows2 != null && taxValueRows2.Length > 0;

                if (taxValueExists)
                {
                    taxValueRow = taxValueRows2[0];
                }
                else
                {
                    if (taxValueRows != null && taxValueRows.Length > 0)
                    {
                        taxDto.TaxValue.ImportRow(taxValueRows[0]);
                        taxValueRow = taxDto.TaxValue[taxDto.TaxValue.Count - 1];
                    }
                    else
                    {
                        taxValueRow       = taxDto.TaxValue.NewTaxValueRow();
                        taxValueRow.TaxId = taxRow.TaxId;
                    }
                }

                // assign tax values
                taxValueRow.JurisdictionGroupId = jGroupRow.JurisdictionGroupId;
                taxValueRow.TaxCategory         = currentRow.ItemArray.GetValue(16).ToString();
                taxValueRow.Percentage          = float.Parse(currentRow.ItemArray.GetValue(17).ToString(), currentCultureInfo);
                taxValueRow.AffectiveDate       = DateTime.Parse(currentRow.ItemArray.GetValue(18).ToString(), currentCultureInfo);
                if (siteId.HasValue)
                {
                    taxValueRow.SiteId = siteId.Value;
                }

                // add row to dto, if needed
                if (taxValueRow.RowState == DataRowState.Detached)
                {
                    taxDto.TaxValue.Rows.Add(taxValueRow);
                }

                // create tax category, if it doesn't exist yet
                CatalogTaxManager.CreateTaxCategory(taxValueRow.TaxCategory, true);
                #endregion

                if (taxDto.HasChanges())
                {
                    TaxManager.SaveTax(taxDto);
                }
                #endregion

                if ((i + 1) % 20 == 0)
                {
                    OnEvent(String.Format("Processed {0} of {1} rows", i + 1, totalRowCount), GetProgressPercent((int)ImportSteps.StartImport, totalImportSteps));
                }
            }

            OnEvent(String.Format("Finished processing parsed rows. Total processed: {0}", totalRowCount), GetProgressPercent((int)ImportSteps.Finish, totalImportSteps));

            OnEvent("CSV file successfully imported.", 100);
        }
예제 #30
0
        public void Dump()
        {
            var languageBranch = _languageBranchRepository.ListAll().First();

            var taxCategory = CatalogTaxManager.CreateTaxCategory("Tax category", true);

            CatalogTaxManager.SaveTaxCategory(taxCategory);

            var jurisdictionDto = new JurisdictionDto();
            var applicationId   = AppContext.Current.ApplicationId;

            jurisdictionDto.Jurisdiction.AddJurisdictionRow("Jurisdiction", null, languageBranch.LanguageID, (int)JurisdictionManager.JurisdictionType.Tax, null, null, null, null, null, null, applicationId, "ABC");
            jurisdictionDto.JurisdictionGroup.AddJurisdictionGroupRow(applicationId, "Group", (int)JurisdictionManager.JurisdictionType.Tax, "ABC");
            JurisdictionManager.SaveJurisdiction(jurisdictionDto);

            var taxDto = new TaxDto();

            taxDto.Tax.AddTaxRow((int)TaxType.SalesTax, "Tax", 1, applicationId);
            taxDto.TaxValue.AddTaxValueRow(20d, taxDto.Tax[0], "Tax category", jurisdictionDto.JurisdictionGroup[0].JurisdictionGroupId, DateTime.Now, Guid.Empty);
            TaxManager.SaveTax(taxDto);

            var currentMarket = _currentMarket.GetCurrentMarket();
            var market        = (MarketImpl)_marketService.GetMarket(currentMarket.MarketId);

            market.DefaultCurrency = Currency.EUR;
            market.DefaultLanguage = languageBranch.Culture;
            _marketService.UpdateMarket(market);

            var rootLink = _referenceConverter.GetRootLink();
            var catalog  = _contentRepository.GetDefault <CatalogContent>(rootLink, languageBranch.Culture);

            catalog.Name             = "Catalog";
            catalog.DefaultCurrency  = market.DefaultCurrency;
            catalog.CatalogLanguages = new ItemCollection <string> {
                languageBranch.LanguageID
            };
            catalog.DefaultLanguage = "en";
            catalog.WeightBase      = "kg";
            catalog.LengthBase      = "cm";
            var catalogRef = _contentRepository.Save(catalog, SaveAction.Publish, AccessLevel.NoAccess);

            var category = _contentRepository.GetDefault <NodeContent>(catalogRef);

            category.Name        = "Category";
            category.DisplayName = "Category";
            category.Code        = "category";
            var categoryRef = _contentRepository.Save(category, SaveAction.Publish, AccessLevel.NoAccess);

            var product = _contentRepository.GetDefault <ProductContent>(categoryRef);

            product.Name        = "Product";
            product.DisplayName = "Product";
            product.Code        = "product";
            var productRef = _contentRepository.Save(product, SaveAction.Publish, AccessLevel.NoAccess);

            var variant = _contentRepository.GetDefault <VariationContent>(productRef);

            variant.Name          = "Variant";
            variant.DisplayName   = "Variant";
            variant.Code          = Constants.VariationCode;
            variant.TaxCategoryId = taxCategory.TaxCategory.First().TaxCategoryId;
            variant.MinQuantity   = 1;
            variant.MaxQuantity   = 100;
            _contentRepository.Save(variant, SaveAction.Publish, AccessLevel.NoAccess);

            var price = new PriceValue
            {
                UnitPrice       = new Money(100, market.DefaultCurrency),
                CatalogKey      = new CatalogKey(applicationId, variant.Code),
                MarketId        = market.MarketId,
                ValidFrom       = DateTime.Today.AddYears(-1),
                ValidUntil      = DateTime.Today.AddYears(1),
                CustomerPricing = CustomerPricing.AllCustomers,
                MinQuantity     = 0
            };

            _priceService.SetCatalogEntryPrices(price.CatalogKey, new[] { price });

            var campaign = _contentRepository.GetDefault <SalesCampaign>(SalesCampaignFolder.CampaignRoot);

            campaign.Name       = "QuickSilver";
            campaign.Created    = DateTime.UtcNow.AddHours(-1);
            campaign.IsActive   = true;
            campaign.ValidFrom  = DateTime.Today;
            campaign.ValidUntil = DateTime.Today.AddYears(1);
            var campaignRef = _contentRepository.Save(campaign, SaveAction.Publish, AccessLevel.NoAccess);

            var promotion = _contentRepository.GetDefault <BuyFromCategoryGetItemDiscount>(campaignRef);

            promotion.IsActive            = true;
            promotion.Name                = "25 % off";
            promotion.Category            = categoryRef;
            promotion.Discount.UseAmounts = false;
            promotion.Discount.Percentage = 25m;
            _contentRepository.Save(promotion, SaveAction.Publish, AccessLevel.NoAccess);

            var paymentDto = new PaymentMethodDto();
            var created    = DateTime.UtcNow.AddHours(-1);

            paymentDto.PaymentMethod.AddPaymentMethodRow(Constants.PaymentMethodId, "Payment", "Payment", languageBranch.LanguageID, "Keyword", true, true, typeof(GenericPaymentGateway).AssemblyQualifiedName, typeof(OtherPayment).AssemblyQualifiedName, false, 1, created, created, applicationId);
            paymentDto.MarketPaymentMethods.AddMarketPaymentMethodsRow(market.MarketId.Value, paymentDto.PaymentMethod[0]);
            PaymentManager.SavePayment(paymentDto);
        }