public void Should_reserve_shipping_for_orders() { var batch1 = new OrderBatch { Id = 5, Type = OrderType.Normal, TotalWeight = 10m }; var batch2 = new OrderBatch { Id = 6, Type = OrderType.Normal, TotalWeight = 15m }; var processor = Stub <IOrderProcessor>(); var shipper = Stub <IShippingReservationService>(); var args = shipper .Capture() .Args <int, decimal>((s, orderId, weight) => s.Reserve(orderId, weight)); var batchProcessor = new OrderBatchProcessor(processor, shipper); batchProcessor.ProcessBatches(new[] { batch1, batch2 }); args.Count.ShouldEqual(2); args[0].Item1.ShouldEqual(batch1.Id); args[0].Item2.ShouldEqual(batch1.TotalWeight); args[1].Item1.ShouldEqual(batch2.Id); args[1].Item2.ShouldEqual(batch2.TotalWeight); }
public async Task DoItemMarketCheck(string name) { Console.WriteLine("Starting Job: ItemMarketCheck"); using var dbContext = this.dbContextFactory(); var item = dbContext.Items.FirstOrDefault(i => i.Name == name); if (item == null) { RecurringJob.RemoveIfExists(GetJobName(name)); throw new KeyNotFoundException($"Could not find item {name} in database. Task has been removed."); } var result = await this.marketCheckService.RequestMarketCheck(name); if (result != null && result.Length > 0) { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine($"Updated Prices on item: {name}"); Debug.WriteLine($"Updated Prices on item: {name}"); Console.ForegroundColor = ConsoleColor.White; var batch = new OrderBatch() { Date = DateTime.Now, Item = item, ItemId = item.ItemId, Entries = result }; dbContext.OrderBatch.Add(batch); await dbContext.SaveChangesAsync(); } }
public void Should_prefer_express_orders_to_process() { var batch1 = new OrderBatch { Type = OrderType.Normal }; var batch2 = new OrderBatch { Type = OrderType.Express }; var batch3 = new OrderBatch { Type = OrderType.Normal }; var processor = Stub <IOrderProcessor>(); var shipper = Stub <IShippingReservationService>(); var batchProcessor = new OrderBatchProcessor(processor, shipper); IList <OrderBatch> args = processor .Capture() .Args <OrderBatch>((p, batch) => p.Process(batch)); batchProcessor.ProcessBatches(new[] { batch1, batch2, batch3 }); args.Count().ShouldEqual(3); args.First().ShouldEqual(batch2); }
public ActionResult GetOrderBatchByStatus(OrderBatch model, string orderNo, int page = 1, int rows = 50) { int count = 0; //总共有符合条件的数据条数 var result = obs.GetOrderBatchs(model, orderNo, out count, page, rows); //取得数据 if (result == null) { result = new List <OrderBatch>(); } return(Json(new { total = count, rows = result }));//返回Json数据 }
private List <OrderBatch> GetQueryOrderBatchData(int?page, int?pagesize, OrderBatch model) { var pager = new Pagination(page, pagesize); int totalCount = 0; model.Status = BatchReviewStatus.ReviewPass; var data = obs.GetOrderBatchs(model, null, out totalCount, pager.Page, pager.PageSize);//取得数据 pager.SetPagination(totalCount); ViewBag.Pager = pager; return(data); }
/// <summary> /// 批量下单 /// </summary> /// <param name="order">订单信息</param> /// <returns></returns> public async Task <string> makeOrdersBatchAsync(OrderBatch order) { var url = $"{this.BASEURL}{this.FUTURES_SEGMENT}/orders"; var bodyStr = JsonConvert.SerializeObject(order).Replace("\"[", "[").Replace("]\"", "]").Replace("\\\"", "\""); using (var client = new HttpClient(new HttpInterceptor(this._apiKey, this._secret, this._passPhrase, bodyStr))) { var res = await client.PostAsync(url, new StringContent(bodyStr, Encoding.UTF8, "application/json")); var contentStr = await res.Content.ReadAsStringAsync(); return(contentStr); } }
/// <summary> /// 批量下单 /// </summary> /// <param name="order">订单信息</param> /// <returns></returns> public async Task <OrderBatchResult> makeOrdersBatchAsync(OrderBatch order) { var url = $"{this.BASEURL}{this.SWAP_SEGMENT}/orders"; var bodyStr = JsonConvert.SerializeObject(order); using (var client = new HttpClient(new HttpInterceptor(this._apiKey, this._secret, this._passPhrase, bodyStr))) { var res = await client.PostAsync(url, new StringContent(bodyStr, Encoding.UTF8, "application/json")); var contentStr = await res.Content.ReadAsStringAsync(); var result = ToObject <OrderBatchResult>(contentStr); return(result); } }
/// <summary> /// 批量下单 /// </summary> /// <param name="order">订单信息</param> /// <returns></returns> public async Task <string> makeOrdersBatchAsync(OrderBatch order) { var url = $"{this.BASEURL}{this.SWAP_SEGMENT}/orders"; var bodyStr = JsonConvert.SerializeObject(order).Replace("\"[", "[").Replace("]\"", "]").Replace("\\", ""); bodyStr = "{\"instrument_id\":\"EOS-USD-SWAP\",\"order_data\":[{\"match_price\":\"0\",\"type\":\"4\",\"price\":\"2.668\",\"size\":\"1\",\"order_type\":\"1\"},{\"match_price\":\"0\",\"type\":\"2\",\"price\":\"2.745\",\"size\":\"2\",\"order_type\":\"1\"},{\"match_price\":\"0\",\"type\":\"2\",\"price\":\"2.745\",\"size\":\"2\",\"order_type\":\"1\"}]}"; using (var client = new HttpClient(new HttpInterceptor(this._apiKey, this._secret, this._passPhrase, bodyStr))) { var res = await client.PostAsync(url, new StringContent(bodyStr, Encoding.UTF8, "application/json")); var contentStr = await res.Content.ReadAsStringAsync(); return(contentStr); } }
public List <KitchenMake> CreateKitchenMakes(OrderBatch orderBatch, List <Orders> orders) { List <KitchenMake> makes = new List <KitchenMake>(); foreach (var item in orders) { var make = new KitchenMake(DataHelper.GetSystemID(), orderBatch.BatchNo, item.No, ExecUserId); makes.Add(make); if (item.OrderDetails != null) { var details = CreateKitchenMakeDetails(make, item.OrderDetails); context.KitchenMakeDetails.AddRange(details); } } context.KitchenMakes.AddRange(makes); return(makes); }
public void Approve(WorkingUser user, OrderBatch orderBatch) { using (var dbTransaction = _dbContext.BeginDbTransaction()) { try { ApproveBatch(user, orderBatch); dbTransaction.Commit(); } catch (Exception ex) { dbTransaction.Rollback(); _logger.WriteLog(string.Format("Failed to approve orderBatch {0}", orderBatch.Id), ex); } } }
private void ApproveBatch(WorkingUser user, OrderBatch orderBatch, bool validateStatus = true) { var orderBatchStatus = (OrderBatchStatus)orderBatch.StatusId; // Validate batch status if (validateStatus && orderBatchStatus == OrderBatchStatus.Approved) { throw new StaffingPurchaseException(string.Format("Could not approve orderBatch {0}; statusId: {1}", orderBatch.Id, orderBatch.StatusId)); } // Validate permission of user if (((orderBatchStatus == OrderBatchStatus.HrAdminPending || orderBatchStatus == OrderBatchStatus.RejectedByHrManager) && !user.Roles.Contains(UserRole.HRAdmin)) || (orderBatchStatus == OrderBatchStatus.HrManagerPending && !user.Roles.Contains(UserRole.HRManager))) { throw new StaffingPurchaseException(string.Format("User {0} does not have permission to approve orderBatch {1}", user.UserName, orderBatch.Id)); } if (orderBatchStatus == OrderBatchStatus.HrAdminPending || orderBatchStatus == OrderBatchStatus.RejectedByHrManager) { orderBatch.StatusId = (short)OrderBatchStatus.HrManagerPending; orderBatch.HrAdminApproverId = user.Id; orderBatch.HrAdminApprovalDate = DateTime.Now; } else if (orderBatchStatus == OrderBatchStatus.HrManagerPending) { orderBatch.StatusId = (short)OrderBatchStatus.Approved; orderBatch.HrManagerApproverId = user.Id; orderBatch.HrManagerApprovalDate = DateTime.Now; } orderBatch.ActionDate = DateTime.Now; orderBatch.ActionComment = string.Empty; _orderBatchRepository.Update(orderBatch); // Update order _orderRepository.BulkUpdate( f => f.OrderBatch.Id == orderBatch.Id, u => new Order { StatusId = (short)OrderStatus.Approved }); }
public OrderBatch CreateBatch(List <Orders> orders) { var batchNo = GetBatchNo(_nowTime); //取餐具类型 var otherProductType = CommonRules.OtherProductTypeDicValue; var batch = context.OrderBatchs.Where(ob => ob.BatchNo == batchNo).FirstOrDefault(); if (batch != null) { batchNo = GetBatchNo(_nowTime.AddMilliseconds(1)); } var cakeNum = orders.Select(o => o.OrderDetails).Count(); //过滤掉餐具 if (cakeNum > 0) { foreach (var item in orders) { foreach (var i in item.OrderDetails) { var product = context.Products.SingleOrDefault(p => p.IsDeleted != 1 && p.Id.Equals(i.ProductId)); if (product != null) { if (product.Type == otherProductType) { cakeNum -= i.Num; } } } } } if (cakeNum < 1) { cakeNum = 0; } var newBatch = new OrderBatch(DataHelper.GetSystemID(), ExecUserId, batchNo, orders.Count(), cakeNum); var kitchenMakes = CreateKitchenMakes(newBatch, orders); return(newBatch); }
public OrderBatch GetOrderId(OrderClass order) { string result = ""; int Batch_Id = order.Batch_Id; List <int> order_ids = new List <int> { }; for (int i = 0; i < order.Items.Count; i++) { OrderItem orderItem = order.Items[i]; order_ids.Add(orderItem.id); string order_key = orderItem.order_key; string billing_first_name = orderItem.billing.first_name; string billing_last_name = orderItem.billing.last_name; //Console.WriteLine("order_key: " + order_key + ", billing.first_name: " + billing_first_name + ", billing.last_name: " + billing_last_name + "\n" + "Line_items:"); result += "order_key: " + order_key + ", billing.first_name: " + billing_first_name + ", billing.last_name: " + billing_last_name + "\n" + "Line_items:"; for (int j = 0; j < orderItem.line_items.Count; j++) { int line_item_id = orderItem.line_items[j].id; //Console.WriteLine(" " + line_item_id); result += " " + line_item_id; } //Console.WriteLine("\n"); result += "\n"; } //* response with json format OrderBatch response = new OrderBatch { status = "SUCCESS" , batch_id = Batch_Id , order_ids = order_ids }; //var json = new JavaScriptSerializer().Serialize(response); return(response); }
/// <summary> /// 批次新增 /// </summary> /// <param name="requiredTime">要求完成时间</param> /// <param name="currentUserId">当前登录用户id</param> /// <returns></returns> public OpResult CreatOrderBatch(DateTime requiredTime, string currentUserId, string BatchNo) { OpResult result = new OpResult(); result.Successed = false; //if (BatchNo.Length > 14) //{ // result.Message = "新增失败:批次号格式错误!"; // return result; //} try { OrderBatch batch = new OrderBatch(); //新增一个实体对象 batch.BatchNo = CommonRules.CommonNoRules("orderbatch"); //批次号 batch.Id = FCake.Core.Common.DataHelper.GetSystemID(); //给ID一个guid的值 batch.RequiredTime = requiredTime; batch.MakeStatus = (int)FCake.Domain.Enums.OrderBatchMakeStatus.NotStart; //默认状态为0 batch.CreatedOn = DateTime.Now; batch.CreatedBy = currentUserId; // Helper.UserCache.CurrentUser.Id; batch.IsDeleted = 0; batch.Status = BatchReviewStatus.ReviewPending; context.OrderBatchs.Add(batch); if (context.SaveChanges() > 0)//取得添加结果 { result.Successed = true; result.Message = "新增批次成功"; } else { result.Message = "批次新增失败"; } } catch (Exception e) { result.Message = "新增批次异常:" + e.Message; } return(result); }
/// <summary> /// 根据条件查询批次信息 /// </summary> /// <param name="status">审批状态</param> /// <param name="kitstatus">厨房制作状态</param> /// <param name="sendstatus">物流配送状态</param> /// <param name="page"></param> /// <param name="row"></param> /// <returns></returns> public List <OrderBatch> GetOrderBatchs(OrderBatch model, string orderNo, out int count, int page = 1, int row = 20) { //取出对象 var data = context.OrderBatchs.Where(p => p.IsDeleted != 1); if (model.Status.HasValue)//判断审核状态 { data = data.Where(p => p.Status == model.Status); } if (model.MakeStatus.HasValue)//判断厨房制作状态 { data = data.Where(p => p.MakeStatus == model.MakeStatus); } if (!string.IsNullOrEmpty(model.BatchNo)) { data = data.Where(p => p.BatchNo.Contains(model.BatchNo)); } if (!string.IsNullOrEmpty(orderNo)) { var obj = context.KitchenMakes.Where(p => p.OrderNo.Equals(orderNo) && p.IsDeleted != 1).FirstOrDefault(); if (obj != null) { data = data.Where(p => p.BatchNo.Equals(obj.BatchNo) && p.IsDeleted != 1); } else { count = 0; return(null); } } count = data.Count(); //count 返回总行数 page = page < 1 ? 1 : page; //如果行数<1 默认=1 var temp = data.OrderBy(p => p.Status).ThenBy(p => p.MakeStatus).ThenByDescending(p => p.RequiredTime).Skip((page - 1) * row).Take(row).ToList(); //取出符合条件的集合 return(temp); }
private void RejectBatch(WorkingUser user, OrderBatch orderBatch, string rejectReason, bool validateStatus = true) { if (validateStatus) { var invalidStatuses = new[] { OrderBatchStatus.Approved, OrderBatchStatus.HrAdminPending, OrderBatchStatus.RejectedByHrManager }; if (invalidStatuses.Contains((OrderBatchStatus)orderBatch.StatusId)) { throw new StaffingPurchaseException(string.Format("Could not reject orderBatch {0}; statusId: {1}", orderBatch.Id, orderBatch.StatusId)); } } // Validate permission of user if (!user.Roles.Contains(UserRole.HRManager)) { throw new StaffingPurchaseException(string.Format("User {0} does not have permission to reject orderBatch {1}", user.UserName, orderBatch.Id)); } orderBatch.StatusId = (short)OrderBatchStatus.RejectedByHrManager; orderBatch.ActionDate = DateTime.Now; orderBatch.ActionComment = rejectReason; _orderBatchRepository.Update(orderBatch); }
/// <summary> /// 按批次号结束厨房制作 /// </summary> /// <param name="id"></param> /// <returns></returns> public bool EndBatch(string batchNo, string currentUserId) { //取出批次实体 OrderBatch ob = context.OrderBatchs.SingleOrDefault(a => a.IsDeleted != 1 && a.BatchNo.Equals(batchNo)); if (ob == null) { return(false); } //只有在制作中才能撤销制作 if (ob.MakeStatus == OrderBatchMakeStatus.Making) { //确保没有含有未开始的 var makeDetails = (from x in context.KitchenMakeDetails join y in context.KitchenMakes on x.KitchenMakeId equals y.Id where x.IsDeleted != 1 && y.IsDeleted != 1 && y.BatchNo.Equals(batchNo) select x); if (makeDetails.Any(a => a.Status == OrderBatchMakeStatus.NotStart) == false) { //变更状态为完成 ob.MakeStatus = OrderBatchMakeStatus.Complete; ob.MakeEndTime = DateTime.Now;; ob.ModifiedOn = DateTime.Now; ob.ModifiedBy = currentUserId; //转移数据 var os = (from x in context.Orders join y in context.KitchenMakes on x.No equals y.OrderNo where y.BatchNo.Equals(batchNo) && x.IsDeleted != 1 && y.IsDeleted != 1 select x).ToList(); InsertDistributions(os, currentUserId); } //完成厨房状态 var kitchens = (from x in context.KitchenMakes join y in context.KitchenMakeDetails.Where(a => a.Status != OrderBatchMakeStatus.Complete && a.IsDeleted != 1) on x.Id equals y.KitchenMakeId into details where x.IsDeleted != 1 && x.Status == OrderBatchMakeStatus.Making && details.Any(a => a.Status == OrderBatchMakeStatus.NotStart) == false select x); var orderNos = kitchens.Select(a => a.OrderNo).Distinct().ToList(); foreach (var x in kitchens) { x.Status = OrderBatchMakeStatus.Complete; x.ModifiedOn = DateTime.Now; x.ModifiedBy = currentUserId; } //完成子项 foreach (var x in makeDetails) { if (x.Status == OrderBatchMakeStatus.Making) { x.Status = OrderBatchMakeStatus.Complete; x.EndTime = DateTime.Now; x.ModifiedBy = currentUserId; x.ModifiedOn = DateTime.Now; } } var resultValue = context.SaveChanges(); foreach (var x in orderNos) { //变更订单状态 var order = context.Orders.SingleOrDefault(a => a.IsDeleted != 1 && a.No == x); if (order == null) { return(false); } order.Status = OrderStatus.MakeCompleted;//排产中 order.ModifiedBy = currentUserId; order.ModifiedOn = DateTime.Now; } return((resultValue + context.SaveChanges()) > 0); } return(false); }
private void BatchCreateOrder_ItemClick(object sender, ItemClickEventArgs e) { var orderBatchCreate = new OrderBatch(); orderBatchCreate.ShowDialog(this); }
/// <summary> /// 按批次号开始厨房制作 /// </summary> /// <param name="id">批次号</param> /// <returns></returns> public bool StartBatch(string batchNo, string currentUserId) { //取出批次实体 OrderBatch ob = context.OrderBatchs.SingleOrDefault(a => a.IsDeleted != 1 && a.BatchNo.Equals(batchNo)); if (ob == null) { return(false); } //状态为未开始 if (ob.MakeStatus == OrderBatchMakeStatus.NotStart) { //状态设定为制作中 ob.MakeStatus = OrderBatchMakeStatus.Making; ob.ModifiedBy = currentUserId; ob.ModifiedOn = DateTime.Now; ob.MakeBeginTime = DateTime.Now; } var makeDetails = (from x in context.KitchenMakeDetails join y in context.KitchenMakes on x.KitchenMakeId equals y.Id where x.IsDeleted != 1 && y.IsDeleted != 1 && y.BatchNo.Equals(batchNo) && x.Status == OrderBatchMakeStatus.NotStart select x); if (makeDetails.Any()) { //变更子项状态 foreach (var detail in makeDetails) { detail.Status = OrderBatchMakeStatus.Making; detail.BeginTime = DateTime.Now; detail.ModifiedBy = currentUserId; detail.ModifiedOn = DateTime.Now; } } var kitchenMakes = (from x in context.KitchenMakes where x.IsDeleted != 1 && x.BatchNo.Equals(batchNo) && x.Status == OrderBatchMakeStatus.NotStart select x); foreach (var kitchen in kitchenMakes) { kitchen.ModifiedBy = currentUserId; kitchen.ModifiedOn = DateTime.Now; kitchen.Status = OrderBatchMakeStatus.Making; } //订单状态 //modify:ywb,修改已完成的订单又变成制作中的bug var orders = (from x in context.KitchenMakes join y in context.Orders on x.OrderNo equals y.No where x.IsDeleted != 1 && y.IsDeleted != 1 && x.BatchNo == batchNo //添加了批次过滤条件 select y); foreach (var x in orders) { if (x.Status != OrderStatus.Making && x.Status != OrderStatus.MakeCompleted) { x.Status = OrderStatus.Making; x.ModifiedBy = currentUserId; x.ModifiedOn = DateTime.Now; } } return(context.SaveChanges() > 0); }
public PartialViewResult _PartialOrderBatchView(int?page, int?pagesize, OrderBatch model) { return(PartialView(GetQueryOrderBatchData(page, PageSize, model))); }
public void Reject(WorkingUser user, OrderBatch orderBatch, string rejectReason) { RejectBatch(user, orderBatch, rejectReason); }
public void ResetAndCreateBatch(string filepath) { var trackingNumbers = File.ReadAllLines(filepath); _log.Info("Tracking numbers, source: " + trackingNumbers.Count()); trackingNumbers = trackingNumbers.Where(tr => !String.IsNullOrEmpty(tr)).Distinct().ToArray(); trackingNumbers.ForEach(tr => tr = StringHelper.TrimWhitespace(tr)); _log.Info("Tracking numbers, final: " + trackingNumbers.Count()); using (var db = _dbFactory.GetRWDb()) { //var shippingInfoes = (from sh in db.OrderShippingInfos.GetAll() // join o in db.Orders.GetAll() on sh.OrderId equals o.Id // where o.BatchId == 314 // && sh.IsActive // select sh).ToList(); var shippingInfoes = db.OrderShippingInfos.GetAll().Where(sh => trackingNumbers.Any(tr => tr.EndsWith(sh.TrackingNumber))).ToList(); if (shippingInfoes.Count() != trackingNumbers.Count()) { var missingTrackings = trackingNumbers.Where(tr => !shippingInfoes.Any(sh => sh.TrackingNumber == tr)).ToList(); _log.Error("Not found all shippings, found: " + shippingInfoes.Count() + ", missing: " + String.Join(", ", missingTrackings)); return; } var orderIds = shippingInfoes.Select(sh => sh.OrderId).ToList(); var existShippingIds = shippingInfoes.Select(sh => sh.Id).ToList(); var missingMultiPackageOrderShippings = db.OrderShippingInfos.GetAll().Where(sh => orderIds.Contains(sh.OrderId) && sh.IsActive && !existShippingIds.Contains(sh.Id)); if (missingMultiPackageOrderShippings.Any()) { _log.Error("Missing part packages for orders: " + String.Join(", ", missingMultiPackageOrderShippings.Select(sh => sh.OrderId + ": " + sh.TrackingNumber))); return; } var newBatch = new OrderBatch() { Name = "Reprint: " + Path.GetFileName(filepath), CreateDate = _time.GetAppNowTime(), Type = (int)BatchType.User, }; db.OrderBatches.Add(newBatch); db.Commit(); var orders = db.Orders.GetAll().Where(o => orderIds.Contains(o.Id)).ToList(); orders.ForEach(o => { o.BatchId = newBatch.Id; o.ShipmentProviderType = (int)ShipmentProviderType.FedexGeneral; }); db.Commit(); foreach (var sh in shippingInfoes) { var item = trackingNumbers.FirstOrDefault(tr => tr.EndsWith(sh.TrackingNumber)); var index = Array.IndexOf(trackingNumbers, item); sh.CustomLabelSortOrder = index; sh.LabelPath = null; sh.LabelPurchaseDate = null; sh.LabelPurchaseBy = null; sh.LabelPurchaseMessage = null; sh.LabelPurchaseResult = null; sh.TrackingNumber = null; sh.TrackingRequestAttempts = 0; sh.TrackingStateDate = null; sh.TrackingStateEvent = null; sh.TrackingStateSource = null; sh.IsDelivered = false; sh.IsFeedSubmitted = false; sh.IsFulfilled = false; sh.ShippingDate = null; sh.ShipmentProviderType = (int)ShipmentProviderType.FedexGeneral; if (sh.ShippingMethodId == ShippingUtils.FedexOneRate2DayEnvelope) { sh.ShippingMethodId = ShippingUtils.FedexPriorityOvernightEnvelope; sh.StampsShippingCost = 40; } if (sh.ShippingMethodId == ShippingUtils.FedexOneRate2DayPak) { sh.ShippingMethodId = ShippingUtils.FedexPriorityOvernightPak; sh.StampsShippingCost = 60; } } db.Commit(); } }
public void InitOrderBatches() { var sessionEndDate = GetNearestSessionEndDate(DateTime.Now); if (DateTime.Now.StartOfDate() != sessionEndDate) { return; } try { var cachedBatches = new Dictionary <string, OrderBatch>(); // caches order batches based on locationId & orderTypeId var sessionStartDate = GetSessionStartDateBasedOnEndDate(sessionEndDate); var pvDeductedOrders = new List <Order>(); var processedOrders = _orderRepository.Table .IncludeTable(x => x.Location) .IncludeTable(x => x.User) .Where(x => x.BatchId == null).ToList(); // get non batch-allocated orders _logger.Info(string.Format("Found {0} order(s).", processedOrders.Count)); _logger.Debug("Start prcessing orders"); foreach (var order in processedOrders) { if (order.LocationId.HasValue) { _logger.Info(string.Format("Processing order #{0} at location \"{1}\".", order.Id, order.Location.Name)); int locationId = order.LocationId.Value; short orderTypeId = (short)order.TypeId; string batchKey = GetBatchKey(locationId, orderTypeId); if (!cachedBatches.ContainsKey(batchKey)) { cachedBatches[batchKey] = new OrderBatch { LocationId = locationId, StatusId = (short)OrderBatchStatus.HrAdminPending, TypeId = orderTypeId, StartDate = sessionStartDate, EndDate = sessionEndDate, ActionDate = DateTime.Now }; } // Update order status & queue to PV deducted list if (order.StatusId == (short)OrderStatus.Draft) { if (order.TypeId == (int)OrderType.PV) { pvDeductedOrders.Add(order); } order.StatusId = (short)OrderStatus.Submitted; } // Allocate to batch order.OrderBatch = cachedBatches[batchKey]; _logger.Info(string.Format("Order #{0} was allocated to new batch", order.Id)); } else { _logger.Warn(string.Format("Order {0} is not allocated to any location.", order.Id)); } } // Deduct PV _logger.Debug(string.Format("Start deducting PV from {0} order(s).", pvDeductedOrders.Count)); foreach (var order in pvDeductedOrders) { _orderService.DeductUserPvForOrder(order, true); } // commit transaction _logger.Debug("Start committing transaction."); _orderRepository.SaveChanges(); } catch (Exception ex) { _logger.Error("Failed to init order batches.", ex); } }