public async Task <ActionResult <BillingCycle> > UpdateCyclo([FromBody] BillingCycle cycle) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (cycle == null) { return(BadRequest()); } _context.Entry(cycle).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!CycleExists(cycle.CycleID)) { return(NotFound()); } else { throw; } } return(Ok()); }
public BillingCycle FetchOrCreateCurrentBillingCycle() { BillingCycle cycle = GetBillingCycle(0); if (cycle != null) { //check that cycle is still current if (cycle.StartDate.Month != this.GetCurrentTime().Month) { cycle = null; //this will invoke cache refresh and creation of new billing cycle } } if (cycle == null) //create a new cycle { DalBillingCycle dal = new DalBillingCycle(this, this.storageAccount); cycle = dal.GetLatestBillingCycle(); if (cycle == null) //create a new cycle, since persisted storage does not contain any cycle { DateTime currentDate = this.GetCurrentTime(); DateTime startDate = new DateTime(currentDate.Year, currentDate.Month, 1); DateTime endDate = new DateTime(currentDate.Year, currentDate.Month, 28); //using 28 since it exists in every month, leap year etc cycle = new BillingCycle { Id = Guid.NewGuid(), StartDate = startDate, EndDate = endDate }; dal.SaveBillingCycle(cycle); string cacheKey = string.Format("{0}#{1}", cycle.StartDate.Year.ToString(), cycle.StartDate.Month.ToString()); billingCycleCache.AddObject(cacheKey, cycle); //add to cache } } return(cycle); }
public void YearlyBillingIsCorrect() { var recurringPayment = new RecurringPaymentInfo { Interval = Interval.FromIsoDuration("P1Y"), Start = new DateTime(2008, 1, 1) }; Assert.AreEqual(TimeUnit.Year, recurringPayment.GetTimeUnit()); Assert.AreEqual(1, recurringPayment.GetTimeUnitFrequency()); var cycle = BillingCycle.CalculateFirst( start: recurringPayment.Start, interval: recurringPayment.Interval ); Assert.AreEqual(TimeUnit.Year, cycle.GetTimeUnit()); Assert.AreEqual(new DateTime(2008, 1, 1), cycle.Start); Assert.AreEqual(new DateTime(2009, 1, 1), cycle.End); var nextCycle = cycle.CalculateNext(); Assert.AreEqual(TimeUnit.Year, nextCycle.GetTimeUnit()); Assert.AreEqual(1, nextCycle.GetTimeFrequency()); Assert.AreEqual(new DateTime(2009, 1, 1), nextCycle.Start); Assert.AreEqual(new DateTime(2010, 1, 1), nextCycle.End); nextCycle = nextCycle.CalculateNext(); Assert.AreEqual(TimeUnit.Year, nextCycle.GetTimeUnit()); Assert.AreEqual(1, nextCycle.GetTimeFrequency()); Assert.AreEqual(new DateTime(2010, 1, 1), nextCycle.Start); Assert.AreEqual(new DateTime(2011, 1, 1), nextCycle.End); }
private async void UpdateBillingInfoAsync() { BillingCycle cycle = BillingCycle.SelectedItem as BillingCycle; if (cycle != null) { Dictionary <string, string> filter = new Dictionary <string, string>(); filter.Add("billing_cycle_id", cycle.Id.ToString()); await BaseViewModels.PaymentViewModel.QueryUserBillingTasksAsync(filter); } }
public bool UpdateBillingCycleStatus(int year, int month, int status) { BillingCycle cycle = GetBillingCycle(year, month); cycle.Status = status; this.tableContext.UpdateObject(cycle); DataServiceResponse response = this.tableContext.SaveChangesWithRetries(SaveChangesOptions.Batch); return(response.BatchStatusCode == Http200); }
public HttpResponseMessage PutBillingCycle(int id, BillingCycle billing) { if (!billingRepositorio.Update(billing)) { return(Request.CreateErrorResponse(HttpStatusCode.NotModified, "Não foi possível atualizar seus dados")); } else { return(Request.CreateResponse(HttpStatusCode.OK)); } }
public IList <UsageAggregatePerUserByBillingCycle> GetUsageAggregatePerUserByBillingCycle(Guid orderId, int cycleNumber) { IList <UsageAggregatePerUserByBillingCycle> list = null; BillingCycle cycle = this.manager.GetBillingCycle(cycleNumber); if (cycle != null) { list = GetUsageAggregatePerUserByBillingCycle(orderId, cycle.Id); } return(list); }
public bool SaveBillingCycle(BillingCycle cycle) { //cycle.PartitionKey = cycle.RowKey = Guid.NewGuid().ToString(); cycle.PartitionKey = PartitionKey; cycle.RowKey = RowKeyGenerator(cycle.StartDate.Year, cycle.StartDate.Month); cycle.Timestamp = this.manager.GetCurrentTime(); this.tableContext.AddObject(BillingCycleTableName, cycle); DataServiceResponse response = this.tableContext.SaveChangesWithRetries(SaveChangesOptions.Batch); return(response.BatchStatusCode == Http200); }
public async Task <ActionResult <BillingCycle> > DeleteCyclo([FromRoute] int id) { BillingCycle cycle = await _context.BillingCyles.FindAsync(id); if (cycle == null) { return(NotFound()); } _context.BillingCyles.Remove(cycle); await _context.SaveChangesAsync(); return(Ok()); }
private void LoadBillingCycle() { try { BillingCycle cycle = StorehouseHelper.GetBillingCycle(ecPanelRequest.BillingCycleId); txtCycleName.Text = cycle.CycleName; txtPeriodLength.Text = cycle.PeriodLength.ToString(); ecUtils.SelectListItem(ddlBillingPeriod, cycle.BillingPeriod); } catch (Exception ex) { ShowErrorMessage("BILLING_CYCLE_LOAD", ex); } }
public async Task <ResultMultiple <BillingCycle> > QueryBillingCyclesAsync( bool doCache = true, bool throwIfError = true) { BillingCycle seed = new BillingCycle(); ResultMultiple <BillingCycle> result = await ResultMultipleUI <BillingCycle> .WaitForObjectsAsync( true, seed, new CachedHttpRequest <BillingCycle, ResultMultiple <BillingCycle> >( Backend.QueryAsyncListAsync), true); if (result.Code == 0) { BillingCycles = result.Data.Payload; } return(result); }
public BillingCycle GetBillingCycle(int year, int month) { string rowKey = RowKeyGenerator(year, month); try { BillingCycle cycle = (from e in this.tableContext.CreateQuery <BillingCycle>(BillingCycleTableName) where e.PartitionKey == PartitionKey && e.RowKey == rowKey select e).FirstOrDefault(); return(cycle); } catch { return(null); //TODO cleanse the code } }
public async Task <ActionResult <BillingCycle> > CreateCycle([FromBody] BillingCycle cycle) { if (cycle == null || cycle.Name.Equals(null) || cycle.Month == 0 || cycle.Year == 0) { return(BadRequest()); } if (!ModelState.IsValid) { return(BadRequest(ModelState)); } await _context.BillingCyles.AddAsync(cycle); await _context.SaveChangesAsync(); return(Ok()); }
/// <summary> /// Fetch a given cycle /// where cycleNumber = 0, implies current billing cycle /// -1, previous cycle /// -2, previous to previous and so on /// </summary> /// <param name="cycleNumber"></param> /// <returns></returns> public BillingCycle GetBillingCycle(int cycleNumber, bool forceCacheRefresh) { if (cycleNumber > 0 || cycleNumber < -11) { throw new ArgumentException("Cycles from current to last 1 year are supported"); } int currentMonth = this.GetCurrentTime().Month; //since cycle number is counted -ve backwards, so need to add to current month int requestedCycleMonth = currentMonth + cycleNumber; int requestedYear = this.GetCurrentTime().Year; if (requestedCycleMonth < 1) { //wrap around of 1 year requestedCycleMonth += 12; requestedYear--; } string cacheKey = string.Format("{0}#{1}", requestedYear, requestedCycleMonth); BillingCycle cycle = billingCycleCache.GetObject(cacheKey) as BillingCycle; if (cycle == null || forceCacheRefresh) { //fetch from table storage DalBillingCycle dal = new DalBillingCycle(this, this.storageAccount); cycle = dal.GetBillingCycle(requestedYear, requestedCycleMonth); } if (cycle != null) //add to cache { billingCycleCache.AddObject(cacheKey, cycle); } else if (forceCacheRefresh) { //dummy up the cache entry simulating discarding the entry billingCycleCache.AddObject(cacheKey, "dummy"); } return(cycle); }
public IList <BillingCycleSummary> GetBillingCycleSummary(Guid orderId, int howManyCycles) { IList <BillingCycleSummary> summaryList = new List <BillingCycleSummary>(); DalBillingCycleSummary dal = new DalBillingCycleSummary(this, this.storageAccount); for (int i = 0; i < howManyCycles; i++) { BillingCycle cycle = GetBillingCycle(-1 * i); if (cycle == null) { break; } BillingCycleSummary summary = dal.GetBillingCycleSummary(orderId, cycle.StartDate.Year, cycle.StartDate.Month); summaryList.Add(summary); } return(summaryList); }
public void DailyBillingIsCorrect() { var cycle = BillingCycle.CalculateFirst( start: new DateTime(2008, 1, 1), interval: Interval.Daily(30) ); Assert.AreEqual(TimeUnit.Day, cycle.GetTimeUnit()); Assert.AreEqual(30, cycle.GetTimeFrequency()); Assert.AreEqual(30, cycle.Period.TimeSpan.Days); Assert.AreEqual(new DateTime(2008, 1, 31), cycle.End); var nextCycle = cycle.CalculateNext(); Assert.AreEqual(TimeUnit.Day, nextCycle.GetTimeUnit()); Assert.AreEqual(30, nextCycle.GetTimeFrequency()); Assert.AreEqual(new DateTime(2008, 1, 31), nextCycle.Start); Assert.AreEqual(new DateTime(2008, 3, 1), nextCycle.End); // 29 days in Feb 2008 }
public string ToggleCycle(string token = "") { if (string.IsNullOrEmpty(token)) { token = Factory.Job.GetCurrentToken(); } var cycle = Factory.Job.GetLastCycle(token); if (cycle.IsActive == false) { cycle = new BillingCycle { Number = cycle.Number }; cycle.Number++; } cycle.IsActive = !cycle.IsActive; cycle.Token = token; Factory.Job.AddAndSave(cycle); return($"Цикл {cycle.Token}_{cycle.Number} {(cycle.IsActive ? "стартовал" : "остановлен")}"); }
public async Task <ActionResult <Debt> > IncludeDebt([FromBody] Debt debt) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } BillingCycle billing = await _context.BillingCyles.FindAsync(debt.CycleID); if (billing == null) { return(NotFound()); } debt.CycleID = billing.CycleID; await _context.Debts.AddAsync(debt); await _context.SaveChangesAsync(); return(Ok()); }
public void MonthlyBillingIsCorrect() { var cycle = new BillingCycle( interval: Interval.Monthly(1), start: new DateTime(2006, 1, 1), end: new DateTime(2006, 2, 1) ); var nextCycle = cycle.CalculateNext(); Assert.AreEqual(TimeUnit.Month, nextCycle.GetTimeUnit()); Assert.AreEqual(1, nextCycle.GetTimeFrequency()); Assert.AreEqual(new DateTime(2006, 2, 1), nextCycle.Start); Assert.AreEqual(new DateTime(2006, 3, 1), nextCycle.End); // Calculate the next billing cycle (using the previous calculated billing cycle) nextCycle = nextCycle.CalculateNext(); Assert.AreEqual(TimeUnit.Month, nextCycle.GetTimeUnit()); Assert.AreEqual(1, nextCycle.GetTimeFrequency()); Assert.AreEqual(new DateTime(2006, 3, 1), nextCycle.Start); Assert.AreEqual(new DateTime(2006, 4, 1), nextCycle.End); }
public void MonthlyBillingIsCorrect() { var cycle = new BillingCycle( interval: Interval.Monthly(1), start: new DateTime(2006, 1, 1), end: new DateTime(2006, 2, 1) ); var nextCycle = cycle.CalculateNext(); Assert.AreEqual(TimeUnit.Month, nextCycle.GetTimeUnit()); Assert.AreEqual(1, nextCycle.GetTimeFrequency()); Assert.AreEqual(new DateTime(2006, 2, 1), nextCycle.Start); Assert.AreEqual(new DateTime(2006, 3, 1), nextCycle.End); // Calculate the next billing cycle (using the previous calculated billing cycle) nextCycle = nextCycle.CalculateNext(); Assert.AreEqual(TimeUnit.Month, nextCycle.GetTimeUnit()); Assert.AreEqual(1, nextCycle.GetTimeFrequency()); Assert.AreEqual(new DateTime(2006, 3, 1), nextCycle.Start); Assert.AreEqual(new DateTime(2006, 4, 1), nextCycle.End); }
private void AddBillingCycleToHostingPlan() { // sync entered data prior SyncGridViewDataEntered(); // load selected billing cycle BillingCycle chosenCycle = StorehouseHelper.GetBillingCycle(Convert.ToInt32(ddlBillingCycles.SelectedValue)); // convert billing to hosting plan HostingPlanCycle cycle = new HostingPlanCycle(); // fill fields cycle.CycleId = chosenCycle.CycleId; cycle.CycleName = chosenCycle.CycleName; cycle.BillingPeriod = chosenCycle.BillingPeriod; cycle.PeriodLength = chosenCycle.PeriodLength; // put into viewstate PlanBillingCycles.Add(cycle); // bind new plan cycles BindHostingPlanCycles(); // re-load billing cycles LoadBillingCyclesDDL(); }
public IList <UsageEvent> GetRawUsage(Guid orderId, int cycleNumber) { BillingCycle cycle = this.manager.GetBillingCycle(cycleNumber); IEnumerator enumerator = null; if (cycle != null) { string partitionKey = string.Format("{0}-{1}", orderId.ToString(), cycle.Id.ToString()); try { enumerator = (from e in this.tableContext.CreateQuery <UsageAggregateByBillingCycle>(AggregateUsageTableName) where e.PartitionKey == partitionKey select e).Take(1000).GetEnumerator(); } catch { //do nothing, this covers the case when the entity does not exist //TODO handle other cases } } IList <UsageEvent> list = new List <UsageEvent>(); if (enumerator != null) { while (enumerator.MoveNext()) { list.Add((UsageEvent)enumerator.Current); } } return(list); }
public HttpResponseMessage PostBillingCycle(BillingCycle billing) { var r = billingRepositorio.GetAll(); billing.id = r.Count() + 1; if (string.IsNullOrEmpty(billing.name) || int.Equals(billing.month, 0)) { return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Erro ao tentar criar ciclo.")); } bool result = billingRepositorio.Add(billing); if (result) { var response = Request.CreateResponse(HttpStatusCode.Created, billing); string uri = Url.Link("DefaultApi", new { billing.id }); response.Headers.Location = new Uri(uri); return(response); } else { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Billing obteve erro para ser inserido.")); } }
public async Task <ActionResult <BillingCycle> > GetById([FromRoute] int id) { BillingCycle cycle = await _context.BillingCyles.FindAsync(id); if (cycle == null) { return(NotFound()); } var creditQuery = _context.Credits.Where(c => c.CycleID == id); var debtQuery = _context.Debts.Where(d => d.CycleID == id); List <Credit> credits = await creditQuery.ToListAsync(); List <Debt> debts = await debtQuery.ToListAsync(); cycle.Credits = credits; cycle.Debts = debts; string text = JsonConvert.SerializeObject(cycle, Formatting.None); var token = JToken.Parse(text); return(Ok(token)); }
public CycleDto(BillingCycle cycle) { Token = cycle.Token; Number = cycle.Number; IsActive = cycle.IsActive; }
protected void Page_LoadComplete(object sender, EventArgs e) { getSensorID(); IEnumerable <SampleResponse> samples; using (var db = new LiteDatabase(Path.Combine(dataLocation, sensor + ".db"))) { var cycle = db.GetCollection <BillingCycle>("BillingCycles"); DateTime startDate = DateTime.Now; DateTime endDate = DateTime.Now; var startOffset = 6; BillingCycle billingCycle = null; if (Session["Operation"] != null) { var cycles = cycle.FindAll().OrderBy(x => x.startDate).ToList(); var index = cycles.IndexOf(cycles.First(x => x.Id == (int)Session["lastCycleID"])); switch (Session["Operation"].ToString()) { case "prev": if (index > 0) { index--; } break; case "next": if (index <= cycles.Count() - 2) { index++; } break; } Session["Operation"] = null; billingCycle = cycles[index]; } else { if (!DateTime.TryParse(TextBox1.Text, out startDate) || !DateTime.TryParse(TextBox2.Text, out endDate) || endDate <= startDate) { var current = cycle.Find(x => x.endDate >= DateTime.Now && x.startDate <= DateTime.Now); if (current.Count() > 0) { billingCycle = current.First(); } else { startDate = DateTime.SpecifyKind(TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, rateStructure.timeZone), DateTimeKind.Local); startDate = DateTime.SpecifyKind(new DateTime(((DateTime)startDate).Year, ((DateTime)startDate).Month, 1 + startOffset), DateTimeKind.Local); endDate = startDate.AddMonths(1); } } else { startDate = DateTime.SpecifyKind(TimeZoneInfo.ConvertTimeToUtc(startDate, rateStructure.timeZone), DateTimeKind.Local); endDate = DateTime.SpecifyKind(TimeZoneInfo.ConvertTimeToUtc(endDate, rateStructure.timeZone), DateTimeKind.Local); } } if (billingCycle != null) { startDate = billingCycle.startDate; endDate = billingCycle.endDate; Session["lastCycleID"] = billingCycle.Id; } TextBox1.Text = startDate.ToShortDateString(); TextBox2.Text = endDate.ToShortDateString(); Label1.Text = startDate.ToLocalTime().ToString("MMMM (MM/dd/yyyy - ") + endDate.ToLocalTime().ToString("MM/dd/yyyy)"); samples = getSamples(startDate, endDate, db); if (cycle.Find(x => x.startDate == startDate && x.endDate == endDate).Count() == 0) { cycle.Insert(new BillingCycle { startDate = startDate, endDate = endDate }); } } Table tbl = new Table { CellPadding = 40, HorizontalAlign = HorizontalAlign.Center }; foreach (var x in rateStructure.ratePeriods) { var tr = new TableRow(); tr.Cells.Add(GetTable(false, x.periods, samples, x.title + " with Solar", ref x.totalWithSolar, x.generationRate, x.fuelSurcharge)); tr.Cells.Add(GetTable(true, x.periods, samples, x.title + " without Solar", ref x.totalWithoutSolar, x.generationRate, x.fuelSurcharge)); tbl.Rows.Add(tr); } PlaceHolder1.Controls.Add(tbl); Label2.Text = String.Format("Total savings = {0:$0.00}", rateStructure.ratePeriods.Last().totalWithoutSolar - rateStructure.ratePeriods.First().totalWithSolar); }
public bool TrackUsage(UsageEvent usage) { int statusCode = -1; BillingCycle currentBillingCyle = this.manager.FetchOrCreateCurrentBillingCycle(); usage.BillingCycleId = currentBillingCyle.Id; //PartitionKey = orderId + billingCycleId //RowKey = NewGuid usage.PartitionKey = string.Format("{0}-{1}", usage.OrderId.ToString(), usage.BillingCycleId.ToString()); usage.RowKey = Guid.NewGuid().ToString(); //locking to reduce contention for aggregate update if multiple events for same order are coming at the same time //this is not foolproff though. TODO - when updates happen from different servers. check what error Azure //returns when server1 read, server2 updated, server1 updated //based on that tweak the business logic lock (lockObject) { //step1 - fetchORcreate and increment aggregate usage UsageAggregateByBillingCycle aggregate = GetUsageAggregateByBillingCycle(usage.OrderId, usage.BillingCycleId, usage.ResourceId); bool isNew = false; if (aggregate == null) { aggregate = new UsageAggregateByBillingCycle { OrderId = usage.OrderId, BillingCycleId = usage.BillingCycleId, ResourceId = usage.ResourceId }; aggregate.PartitionKey = string.Format("{0}-{1}", usage.OrderId.ToString(), usage.BillingCycleId.ToString()); aggregate.RowKey = usage.ResourceId; isNew = true; } aggregate.AmountConsumed += usage.AmountConsumed; //step2 - save raw usage this.tableContext.AddObject(RawUsageTableName, usage); if (isNew) { this.aggregateTableServiceContext.AddObject(AggregateUsageTableName, aggregate); } else { this.aggregateTableServiceContext.UpdateObject(aggregate); } //Now add logic for per user aggregate UsageAggregatePerUserByBillingCycle aggregatePerUser = GetUsageAggregatePerUserByBillingCycle(usage.OrderId, usage.BillingCycleId, usage.ResourceId, usage.UserId); isNew = false; if (aggregatePerUser == null) { aggregatePerUser = new UsageAggregatePerUserByBillingCycle { OrderId = usage.OrderId, BillingCycleId = usage.BillingCycleId, ResourceId = usage.ResourceId, UserId = usage.UserId }; aggregatePerUser.PartitionKey = string.Format("{0}-{1}", usage.OrderId.ToString(), usage.BillingCycleId.ToString()); aggregatePerUser.RowKey = string.Format("{0}-{1}", usage.ResourceId, usage.UserId); isNew = true; } aggregatePerUser.AmountConsumed += usage.AmountConsumed; if (isNew) { this.aggregatePerUserTableServiceContext.AddObject(AggregatePerUserUsageTableName, aggregatePerUser); } else { this.aggregatePerUserTableServiceContext.UpdateObject(aggregatePerUser); } //end DataServiceResponse response = this.tableContext.SaveChangesWithRetries(SaveChangesOptions.Batch); response = this.aggregateTableServiceContext.SaveChangesWithRetries(SaveChangesOptions.Batch); statusCode = response.BatchStatusCode; } return(statusCode == Http200 || statusCode == 202); }