void AddSubDocument(SubOrder subOrder, MainOrder order) { MethodInfo info = typeof (MainOrder) .GetMethod("AddSubOrder", BindingFlags.NonPublic | BindingFlags.Instance); info.Invoke(order, new[] {subOrder}); }
public async Task <IActionResult> DraftOrderAsync([FromBody] CreateOrderInput input) { var sumamount = input.ListItem.Sum(p => p.Amount); List <OrderItem> items = new List <OrderItem>(); input.ListItem.ForEach(p => { OrderItem temp = new OrderItem(); temp.Amount = p.Amount; temp.Count = p.Count; temp.OrderItemName = p.OrderItemName; items.Add(temp); }); Address address = new Address { City = "南通", Country = "正余", State = "青正", Street = "测试", ZipCode = "20033" }; MainOrder order = new MainOrder(input.OrderId, input.OrderName, sumamount, address, 0, 0, DateTime.Now, DateTime.MinValue, 1, items); using (var transaction = _orderDbContext.Database.BeginTransaction()) { try { OrderCreateEvent eventdata = new OrderCreateEvent { OrderId = order.OrderId, PayDecimal = order.OrderSumAmount, PayedDesc = "支付描述", Payer = "Shawn" }; _capBus.Publish("Order.services.Payed", eventdata); await _orderDbContext.AddAsync(order); var result = await _orderDbContext.SaveChangesAsync(); transaction.Commit(); } catch (Exception e) { await transaction.RollbackAsync(); return(BadRequest()); } return(Ok()); } }
/// <summary> /// This function is used to simplify the 2 REST interfaces if changes are needed! /// </summary> /// <param name="context"></param> /// <param name="whatToDo"></param> /// <returns></returns> private IHttpContext storeInDatabase(IHttpContext context, BUYORSELL whatToDo) { string payload = context.Request.Payload.ToString(); //Liefert einen JSON String mit escaped zeichen zurück JToken token = JToken.Parse(payload); JObject json = JObject.Parse(token.ToString()); if (payload == null || payload.Equals("")) { context.Response.SendResponse(Grapevine.Shared.HttpStatusCode.InternalServerError, "Oops, something went wrong!"); return(context); } Order orderObject = JsonConvert.DeserializeObject <Order>(json.ToString()); bool isPresent = checkIfStockExists(orderObject); if (isPresent) { //Die Order ins Orderbuch eintragen. try { var dbOrders = dbConnectionOrders._db; MainOrder mainOrder = new MainOrder(orderObject, whatToDo); var test = new BsonDocument() { { "orderID", mainOrder.receivedOrder.orderID.ToString() }, { "aktienID", mainOrder.receivedOrder.aktienID.ToString() }, { "amount", mainOrder.receivedOrder.amount }, { "limit", mainOrder.receivedOrder.limit }, { "timestamp", mainOrder.receivedOrder.timestamp }, { "hash", mainOrder.receivedOrder.hash ?? "" }, { "useCase", mainOrder.useCase }, { "statusOfOrder", mainOrder.statusOfOrder } }; dbOrders.InsertOne(test); } catch (Exception ex) { Debug.WriteLine(ex); context.Response.SendResponse(Grapevine.Shared.HttpStatusCode.InternalServerError, "Oops, something went wrong!"); return(context); } context.Response.SendResponse(Grapevine.Shared.HttpStatusCode.Ok, "Check again with /check"); return(context); } else { context.Response.SendResponse(Grapevine.Shared.HttpStatusCode.NotFound, "aktienID not found"); return(context); } }
/// <summary> /// 提交订单数据接口到方正电商 /// </summary> public static void FangZheng_Order_Confirm(Guid MyOrderId, bool IsMainOrder) { if (IsMainOrder) { MainOrder.ObjectSet().Where(r => r.MainOrderId == MyOrderId).ToList() .ForEach(Item => { FangZheng_Order_Confirm(Item.SubOrderId); }); } else { FangZheng_Order_Confirm(MyOrderId); } }
public void Submit(MainOrder order) { int sequence = 0; var envelope = new CommandEnvelope(); envelope.Initialize(order); List<DocumentCommand> commandsToExecute = order.GetSubOrderCommandsToExecute(); var createCommand = commandsToExecute.OfType<CreateCommand>().FirstOrDefault(); if (createCommand != null) envelope.CommandsList.Add(new CommandEnvelopeItem(++sequence, createCommand)); var lineItemCommands = commandsToExecute.OfType<AfterCreateCommand>(); foreach (var _item in lineItemCommands) { envelope.CommandsList.Add(new CommandEnvelopeItem(++sequence, _item)); } var editlineItemCommands = commandsToExecute.OfType<ChangeMainOrderLineItemCommand>(); foreach (var _editeditem in editlineItemCommands) { envelope.CommandsList.Add(new CommandEnvelopeItem(++sequence, _editeditem)); } var removedLineitem = commandsToExecute.OfType<RemoveMainOrderLineItemCommand>(); foreach (var _removeditem in removedLineitem) { envelope.CommandsList.Add(new CommandEnvelopeItem(++sequence, _removeditem)); } var co = commandsToExecute.OfType<ConfirmCommand>().FirstOrDefault(); if (co != null) envelope.CommandsList.Add(new CommandEnvelopeItem(++sequence, co)); var rco = commandsToExecute.OfType<RejectMainOrderCommand>().FirstOrDefault(); if (rco != null) envelope.CommandsList.Add(new CommandEnvelopeItem(++sequence, rco)); var approvedlineItemCommands = order.GetSubOrderCommandsToExecute().OfType<ApproveOrderLineItemCommand>(); foreach (var _item in approvedlineItemCommands) { envelope.CommandsList.Add(new CommandEnvelopeItem(++sequence, _item)); } var aop = commandsToExecute.OfType<ApproveCommand>().FirstOrDefault(); if (aop != null) envelope.CommandsList.Add(new CommandEnvelopeItem(++sequence, aop)); var closecommand = commandsToExecute.OfType<CloseOrderCommand>().FirstOrDefault(); if (closecommand != null) envelope.CommandsList.Add(new CommandEnvelopeItem(++sequence, closecommand)); _commandEnvelopeRouter.RouteCommandEnvelope(envelope); }
public void Submit(MainOrder order) { List<DocumentCommand> commandsToExecute = order.GetSubOrderCommandsToExecute(); var createCommand = commandsToExecute.OfType<CreateCommand>().FirstOrDefault(); if (createCommand != null) _commandRouter.RouteDocumentCommand(createCommand); var lineItemCommands = commandsToExecute.OfType<AfterCreateCommand>(); foreach (var _item in lineItemCommands) { _commandRouter.RouteDocumentCommand(_item); } var editlineItemCommands = commandsToExecute.OfType<ChangeMainOrderLineItemCommand>(); foreach (var _editeditem in editlineItemCommands) { _commandRouter.RouteDocumentCommand(_editeditem); } var removedLineitem = commandsToExecute.OfType<RemoveMainOrderLineItemCommand>(); foreach (var _removeditem in removedLineitem) { _commandRouter.RouteDocumentCommand(_removeditem); } var co = commandsToExecute.OfType<ConfirmCommand>().FirstOrDefault(); if (co != null) _commandRouter.RouteDocumentCommand(co); //transfer inventory to pending warehouse HandleApprovedCommand(order); var aop = commandsToExecute.OfType<ApproveCommand>().FirstOrDefault(); if (aop != null) _commandRouter.RouteDocumentCommand(aop); // transfer inventory to pending warehouse HandleDispatchLineItemsCommand(order); HandlePayments(order); var closecommand = commandsToExecute.OfType<CloseOrderCommand>().FirstOrDefault(); if (closecommand != null) _commandRouter.RouteDocumentCommand(closecommand); var rco = commandsToExecute.OfType<RejectMainOrderCommand>().FirstOrDefault(); if (rco != null) { _commandRouter.RouteDocumentCommand(rco); HandleLostSale(order); } }
private SubOrder MakeSubOrder(MainOrder doc) { SubOrder subOrder = DocumentPrivateConstruct<SubOrder>(doc.Id); Map(subOrder,doc.DocumentIssuerCostCentre, doc.DocumentIssuerCostCentreApplicationId, doc.DocumentRecipientCostCentre, doc.DocumentIssuerUser, doc.DocumentReference, null, null); subOrder.DocumentType = doc.DocumentType; subOrder.OrderType = doc.OrderType; subOrder.IssuedOnBehalfOf = doc.IssuedOnBehalfOf; subOrder.DateRequired = doc.DateRequired; subOrder.DocumentParentId = doc.Id; subOrder.ParentId = doc.Id; subOrder.OrderStatus = doc.OrderStatus; subOrder.SaleDiscount = doc.SaleDiscount; subOrder.ShipToAddress = doc.ShipToAddress; subOrder.Note = doc.Note; SetDefaultDates(subOrder); subOrder.EnableAddCommands(); return subOrder; }
public void PrintNonFiscalOrderReceipt(MainOrder order) { Log(string.Format("printing non fiscal order id={0}", order.Id)); var printer = new FiscalPrinterUtility(comPort, comSpeed); if (!FiscalPrinterHelper._isConnected) { printer.ConnectFiscalPrinter(); } if (printer.OpenNonFiscalPrinter()) { int casesQuantity = 0; var spaces = string.Empty; foreach (var item in order.ItemSummary) { if (item.Product.ReturnableType == ReturnableType.Returnable &&item.Value==0) { continue; } double price = (double)Math.Truncate((item.Value + item.VatValue) * 100) / 100; var pricecheck = (item.Value + item.VatValue).GetTruncatedValue(); var bulkQuantity = 0.0m; var calculationPrice = 0.0; using (var container = ObjectFactory.Container.GetNestedContainer()) { var summaryService = container.GetInstance<IProductPackagingSummaryService>(); bulkQuantity = summaryService.GetProductQuantityInBulk(item.Product.Id); var modulo = item.Qty % bulkQuantity; if (modulo != 0) { casesQuantity = (int)item.Qty; calculationPrice = (double)((pricecheck)); } else { casesQuantity = (int)item.Qty / (int)bulkQuantity; calculationPrice = (double)(pricecheck).GetTruncatedValue(); calculationPrice = (double)((decimal)(calculationPrice * (double)bulkQuantity)).GetTotalGross(); } } spaces = GenerateSpaces("\t", item.Product.ProductCode, casesQuantity + " x " + calculationPrice.ToString("0.00"), 48); FP2000KL.CMD_42_0_0(item.Product.ProductCode + spaces + casesQuantity + " x " + calculationPrice.ToString("0.00")); var total = casesQuantity * calculationPrice; spaces = GenerateSpaces("\t", item.Product.Description, total.ToString("0.00"), 48); FP2000KL.CMD_42_0_0(item.Product.Description + spaces + total.ToString("0.00")); } if (order.SaleDiscount > 0) { spaces = GenerateSpaces("\t", "Discount", order.SaleDiscount.ToString("0.00"), 48); FP2000KL.CMD_42_0_0("Discount" + spaces + order.SaleDiscount.ToString("0.00")); } var paidAmount = order.GetPayments.Sum(n => n.Amount); var expectedPayment =order.SaleDiscount>0?(order.TotalGross.GetTotalGross()-order.SaleDiscount):order.TotalGross; var amountDue = paidAmount >= expectedPayment ? paidAmount : expectedPayment.GetTotalGross(); var amountPaid = paidAmount; spaces = GenerateSpaces("-", string.Empty, string.Empty, 48); FP2000KL.CMD_42_0_0(spaces); spaces = GenerateSpaces("\t", "Total", amountDue.ToString("0.00"), 48); FP2000KL.CMD_42_0_0("Total" + spaces + amountDue.ToString("0.00")); spaces = GenerateSpaces("\t", "Paid", amountPaid.ToString("0.00"), 48); FP2000KL.CMD_42_0_0("Paid" + spaces + amountPaid.ToString("0.00")); FP2000KL.CMD_42_0_0("\n"); FP2000KL.CMD_42_0_0("\n"); printer.CloseNonFiscalPrinter(); } }
public Jinher.AMP.BTP.Deploy.CustomDTO.ResultDTO UpdateOrderSpreaderExt(Jinher.AMP.BTP.Deploy.CustomDTO.SpreaderAndBuyerWxDTO sbwxDto) { ResultDTO result = new ResultDTO(); if (sbwxDto == null) { result.ResultCode = 1; result.Message = "参数错误,参数不能为空!"; return(result); } if (string.IsNullOrWhiteSpace(sbwxDto.WxOpenId)) { result.ResultCode = 2; result.Message = "参数错误,微信OpenId不能为空!"; return(result); } if (sbwxDto.BuyerId == Guid.Empty) { result.ResultCode = 3; result.Message = "参数错误,买家用户Id不能为空!"; return(result); } if (sbwxDto.OrderId == Guid.Empty) { result.ResultCode = 4; result.Message = "参数错误,订单Id不能为空!"; return(result); } try { ContextSession contextSession = ContextFactory.CurrentThreadContext; //用户id相关 买家-推广者对照表。 var usQuery = from us in UserSpreader.ObjectSet() where us.UserId == sbwxDto.BuyerId select us; //微信Id相关 买家-推广者对照表。 var wxQuery = from u in UserSpreader.ObjectSet() where u.WxOpenId == sbwxDto.WxOpenId select u; //推广者用户id. Guid spreaderId = Guid.Empty; Guid spreadCode = Guid.Empty; //当前买家已有归属的推广主信息。 if (usQuery.Any()) { //没有wxopenId信息,则更新。 var usFirst = usQuery.FirstOrDefault(); spreaderId = usFirst.SpreaderId; spreadCode = usFirst.SpreadCode; if (string.IsNullOrWhiteSpace(usFirst.WxOpenId)) { usFirst.WxOpenId = sbwxDto.WxOpenId; usFirst.ModifiedOn = DateTime.Now; } //删除其它和当前wxOpenId相关的记录。 foreach (var uu in usQuery) { if (uu.Id == usFirst.Id) { continue; } uu.EntityState = System.Data.EntityState.Deleted; } } else { if (wxQuery.Any()) { UserSpreader usRecord = wxQuery.FirstOrDefault(); usRecord.UserId = sbwxDto.BuyerId; usRecord.ModifiedOn = DateTime.Now; spreaderId = usRecord.SpreaderId; spreadCode = usRecord.SpreadCode; } } //推广分成相关订单Id. List <Guid> orderIds = new List <Guid>(); var moQuery = from mo in MainOrder.ObjectSet() where mo.MainOrderId == sbwxDto.OrderId select mo.SubOrderId; if (moQuery.Any()) { //传入的OrderId为主订单id,找出所有子订单。 orderIds = moQuery.ToList(); } else { orderIds.Add(sbwxDto.OrderId); } var coQuery = from co in CommodityOrder.ObjectSet() where orderIds.Contains(co.Id) select co; foreach (var cOrder in coQuery) { cOrder.SpreaderId = spreaderId; cOrder.ModifiedOn = DateTime.Now; cOrder.SpreadCode = spreadCode; } contextSession.SaveChanges(); result.ResultCode = 0; result.Message = "成功!"; return(result); } catch (Exception ex) { LogHelper.Error(string.Format("UpdateOrderSpreaderExt异常。sbwxDto:{0}", JsonHelper.JsonSerializer(sbwxDto)), ex); result.ResultCode = 10; result.Message = "接口异常,请稍后重试!"; return(result); } }
public void SubmitToWF(MainOrder mainOrder) { _stockistPurchaseOrderWorkflow.Submit(mainOrder, null); }
public void Submit(MainOrder order) { int sequence = 0; var envelope = new CommandEnvelope(); envelope.GeneratedByCostCentreApplicationId = Guid.Empty; envelope.Initialize(order); List<DocumentCommand> commandsToExecute = order.GetSubOrderCommandsToExecute(); var createCommand = commandsToExecute.OfType<CreateCommand>().FirstOrDefault(); if (createCommand != null) { envelope.CommandsList.Add(new CommandEnvelopeItem(++sequence, createCommand)); //AddToMongoDB(createCommand); } var lineItemCommands = commandsToExecute.OfType<AfterCreateCommand>(); foreach (var _item in lineItemCommands) { envelope.CommandsList.Add(new CommandEnvelopeItem(++sequence, _item)); //AddToMongoDB(_item); //_busPublisher.WrapAndPublish(_item, (CommandType)Enum.Parse(typeof(CommandType), _item.CommandTypeRef)); } var editlineItemCommands = commandsToExecute.OfType<ChangeMainOrderLineItemCommand>(); foreach (var _editeditem in editlineItemCommands) { envelope.CommandsList.Add(new CommandEnvelopeItem(++sequence, _editeditem)); } var removedLineitem = commandsToExecute.OfType<RemoveMainOrderLineItemCommand>(); foreach (var _removeditem in removedLineitem) { envelope.CommandsList.Add(new CommandEnvelopeItem(++sequence, _removeditem)); } var co = commandsToExecute.OfType<ConfirmCommand>().FirstOrDefault(); if (co != null) { envelope.CommandsList.Add(new CommandEnvelopeItem(++sequence, co)); } var rco = commandsToExecute.OfType<RejectMainOrderCommand>().FirstOrDefault(); if (rco != null) { envelope.CommandsList.Add(new CommandEnvelopeItem(++sequence, rco)); } var approvedlineItemCommands = order.GetSubOrderCommandsToExecute().OfType<ApproveOrderLineItemCommand>(); foreach (var _item in approvedlineItemCommands) { envelope.CommandsList.Add(new CommandEnvelopeItem(++sequence, _item)); } var aop = commandsToExecute.OfType<ApproveCommand>().FirstOrDefault(); if (aop != null) { envelope.CommandsList.Add(new CommandEnvelopeItem(++sequence, aop)); } AddToMongoDB(envelope); }
public void SubmitToWF(MainOrder mainOrder) { _orderWorkflow.Submit(mainOrder, null); }
private void HandleApprovedCommand(MainOrder order ,BasicConfig config, out Guid invoiceId) { invoiceId = Guid.Empty; var approvedlineItemCommands = order.GetSubOrderCommandsToExecute().OfType<ApproveOrderLineItemCommand>(); if (!approvedlineItemCommands.Any()) return; CostCentre issuer = _costCentreRepository.GetById(config.CostCentreId); CostCentre recepient = null; if (order.DocumentIssuerCostCentre is DistributorSalesman) recepient = order.DocumentIssuerCostCentre; else recepient = order.DocumentRecipientCostCentre; InventoryAdjustmentNote inventoryAdjustmentNote = _inventoryAdjustmentNoteFactory.Create(issuer, config.CostCentreApplicationId, recepient, order.DocumentIssuerUser, order.DocumentReference, InventoryAdjustmentNoteType.Available, order.ParentId); inventoryAdjustmentNote.DocumentParentId = order.Id; string invoiceRef = _getDocumentReference.GetDocReference("Inv",recepient.Id,order.IssuedOnBehalfOf.Id); Domain.Transactional.DocumentEntities.Invoice invoice = _invoiceFactory.Create(issuer, config.CostCentreApplicationId, recepient, order.DocumentIssuerUser, invoiceRef, order.Id, order.Id); invoiceId = invoice.Id; foreach (var _item in approvedlineItemCommands) { ApproveOrderLineItemCommand ap = _item as ApproveOrderLineItemCommand; SubOrderLineItem soli = order.PendingApprovalLineItems.First(s => s.Id == ap.LineItemId); if (ap.ApprovedQuantity > 0) { inventoryAdjustmentNote.AddLineItem(_inventoryAdjustmentNoteFactory.CreateLineItem(0,soli.Product.Id, ap.ApprovedQuantity,0, "Inventory adjustment")); invoice.AddLineItem(_invoiceFactory.CreateLineItem(soli.Product.Id, ap.ApprovedQuantity, soli.Value, order.DocumentReference, 0, soli.LineItemVatValue, soli.ProductDiscount, soli.DiscountType)); } // _commandRouter.RouteDocumentCommand(_item); } inventoryAdjustmentNote.Confirm(); _inventoryAdjustmentNoteWfManager.SubmitChanges(inventoryAdjustmentNote,config); invoice.Confirm(); _invoiceWorkFlowManager.SubmitChanges(invoice,config); }
private void HandleApprovedCommand(MainOrder order) { Config config = _configService.Load(); var approvedlineItemCommands = order.GetSubOrderCommandsToExecute().OfType<ApproveOrderLineItemCommand>(); if (!approvedlineItemCommands.Any()) return; CostCentre issuer = null; CostCentre recepient = null; if (order.DocumentIssuerCostCentre is Distributor) { recepient = order.DocumentIssuerCostCentre; issuer = order.DocumentRecipientCostCentre; } else { recepient = order.DocumentRecipientCostCentre; issuer = order.DocumentIssuerCostCentre; } var getAll = _costCentreRepository.GetAll().OfType<DistributorPendingDispatchWarehouse>(); DistributorPendingDispatchWarehouse pendingDispatchWarehouse = getAll.FirstOrDefault(p => p.ParentCostCentre.Id == recepient.Id); InventoryTransferNote inventoryTransfernote = _inventoryTransferNoteFactory.Create(recepient, config.CostCentreApplicationId, order.DocumentIssuerUser, pendingDispatchWarehouse, order.IssuedOnBehalfOf, order.DocumentReference); inventoryTransfernote.DocumentParentId = inventoryTransfernote.Id; string invoiceRef = _getDocumentReference.GetDocReference("Inv", order.DocumentReference); if (order.IsEditable()) { Invoice invoice = _invoiceFactory.Create(issuer, config.CostCentreApplicationId, recepient, order.DocumentIssuerUser, invoiceRef, order.Id, order.Id); foreach (var _item in order.PendingApprovalLineItems) { invoice.AddLineItem(_invoiceFactory.CreateLineItem(_item.Product.Id, _item.Qty, _item.Value, order.DocumentReference, 0, _item.LineItemVatValue, _item.ProductDiscount, _item.DiscountType)); } invoice.Confirm(); _invoiceWorkFlowManager.SubmitChanges(invoice); if (order.GetPayments.Any(a => a.IsConfirmed && !a.IsProcessed)) { Guid currentInvoice = invoice.Id; string receiptRef = _getDocumentReference.GetDocReference("Rpt", order.DocumentReference); Receipt receipt = _receiptFactory.Create(issuer, config.CostCentreApplicationId, recepient, order.DocumentIssuerUser, receiptRef, order.Id, currentInvoice, Guid.Empty); foreach (var info in order.GetPayments.Where(s => s.IsConfirmed && !s.IsProcessed)) { receipt.AddLineItem(_receiptFactory.CreateLineItem(info.Amount, info.PaymentRefId, info.MMoneyPaymentType, info.NotificationId, 0, info.PaymentModeUsed, info.Description, receipt.Id, info.IsConfirmed) ); } receipt.Confirm(); _receiptWorkFlowManager.SubmitChanges(receipt); } } foreach (var _item in approvedlineItemCommands) { ApproveOrderLineItemCommand ap = _item as ApproveOrderLineItemCommand; SubOrderLineItem soli = order.PendingApprovalLineItems.First(s => s.Id == ap.LineItemId); if (ap.ApprovedQuantity > 0) { inventoryTransfernote.AddLineItem(_inventoryTransferNoteFactory.CreateLineItem(soli.Product.Id, ap.ApprovedQuantity, 0, 0, order.DocumentReference)); } _commandRouter.RouteDocumentCommand(_item); } inventoryTransfernote.Confirm(); _inventoryTransferNoteWfManager.SubmitChanges(inventoryTransfernote); }
private void HandleDispatchLineItemsCommand(MainOrder order) { var dop = order.GetSubOrderCommandsToExecute().OfType<OrderDispatchApprovedLineItemsCommand>().FirstOrDefault(); if (dop == null) return; Config config = _configService.Load(); CostCentre recepient = null; if (order.DocumentIssuerCostCentre is DistributorSalesman) recepient = order.DocumentIssuerCostCentre; else recepient = order.DocumentRecipientCostCentre; CostCentre issuer = _costCentreRepository.GetAll().OfType<DistributorPendingDispatchWarehouse>().First(); InventoryTransferNote _transferToPhone = _inventoryTransferNoteFactory.Create(issuer, config.CostCentreApplicationId, order.DocumentIssuerUser, recepient, order.IssuedOnBehalfOf, order.DocumentReference); _transferToPhone.DocumentParentId = order.Id; DispatchNote dispatctFromPhone = _dispatchNoteFactory.Create(issuer, config.CostCentreApplicationId, recepient, order.DocumentIssuerUser, order.IssuedOnBehalfOf, DispatchNoteType.DispatchToPhone, order.DocumentReference, order.ParentId, order.Id); foreach (var item in order.PendingDispatchLineItems) { _transferToPhone.AddLineItem(_inventoryTransferNoteFactory.CreateLineItem(item.Product.Id, item.ApprovedQuantity, 0, 0, order.DocumentReference)); dispatctFromPhone.AddLineItem(_dispatchNoteFactory.CreateLineItem(item.Product.Id, item.ApprovedQuantity, 0, order.DocumentReference, 0, 0, item.ProductDiscount, item.DiscountType)); } _transferToPhone.Confirm(); _inventoryTransferNoteWfManager.SubmitChanges(_transferToPhone); _commandRouter.RouteDocumentCommand(dop); dispatctFromPhone.Confirm(); _dispatchNoteWfManager.SubmitChanges(dispatctFromPhone); }
private void HandlePayments(MainOrder order) { Config config = _configService.Load(); var orderpaymentInfoitem = order.GetSubOrderCommandsToExecute().OfType<AddOrderPaymentInfoCommand>(); foreach (var paymentInfo in orderpaymentInfoitem) { _commandRouter.RouteDocumentCommand(paymentInfo); } var invoice = _invoiceRepository.GetInvoiceByOrderId(order.Id); if (orderpaymentInfoitem.Any(s => s.IsConfirmed && !s.IsProcessed) && invoice != null) { Guid currentInvoice = invoice.Id; string receiptRef = _getDocumentReference.GetDocReference("Rpt", order.DocumentReference); Receipt receipt = _receiptFactory.Create(order.DocumentIssuerCostCentre, config.CostCentreApplicationId, order.DocumentRecipientCostCentre, order.DocumentIssuerUser, receiptRef, order.Id, currentInvoice, Guid.Empty); foreach (var info in orderpaymentInfoitem.Where(s => s.IsConfirmed && !s.IsProcessed)) { receipt.AddLineItem(_receiptFactory.CreateLineItem(info.ConfirmedAmount, info.PaymentRefId, info.MMoneyPaymentType, info.NotificationId, 0, (PaymentMode)info.PaymentModeId, info.Description, receipt.Id, info.IsConfirmed) ); } receipt.Confirm(); _receiptWorkFlowManager.SubmitChanges(receipt); } }
private void HandleLostSale(MainOrder order) { if (!order.IsEditable()) { Invoice invoice = _invoiceRepository.GetInvoiceByOrderId(order.Id); string creditnoteRef = _getDocumentReference.GetDocReference("CN", order.DocumentReference); CreditNote cn = _creditNoteFactory .Create(order.DocumentIssuerCostCentre, order.DocumentIssuerCostCentreApplicationId, order.DocumentRecipientCostCentre, order.DocumentIssuerUser, creditnoteRef, order.Id, invoice.Id); foreach (var _item in order.PendingApprovalLineItems) { cn.AddLineItem(_creditNoteFactory.CreateLineItem(_item.Product.Id, _item.Qty, _item.Value, order.DocumentReference, 0, _item.LineItemVatValue, _item.ProductDiscount )); } cn.Confirm(); _confirmCreditNoteWFManager.SubmitChanges(cn); } }
public ActionResult OrderWrite(MainOrder mainOrder) { try { HttpFileCollectionBase uploadFile = Request.Files; List <Picture> pInfo = new List <Picture>(); if (uploadFile.Count > 0) { for (int i = 0; i < uploadFile.Count; i++) { HttpPostedFileBase file = uploadFile[i]; string path = ConfigurationManager.AppSettings["repairImgPath"].ToString() + "/" + PhotoType.Device.ToString() + "/"; if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } string fileName = Guid.NewGuid().ToString("N") + "." + file.ContentType.ToString().Split('/')[1]; file.SaveAs(path + "/" + fileName); pInfo.Add(new Picture { Type = PhotoType.Device, Url = PhotoType.Device.ToString() + "/" + fileName, CreateTime = DateTime.Now }); } } mainOrder.ServiceCompanyId = CurrentUser.User.ServiceCompanyId; long deviceId = new DeviceService().DeviceWrite(mainOrder); if (deviceId > 0) { //上传图片 if (pInfo.Count != 0) { using (var db = new LZY.BX.Service.Mb.MbContext()) { foreach (Picture item in pInfo) { item.OuterId = deviceId.ToString(); item.CreateTime = DateTime.Now; db.Picture.Add(item); } db.SaveChanges(); } } //创建新工单 mainOrder.MainOrderId = SequNo.NewId; mainOrder.ServiceCompanyId = CurrentUser.User.ServiceCompanyId; mainOrder.DeviceId = deviceId; if (new OrderService().Create(mainOrder, CurrentUser.User.ServiceCompany)) { return(ResultSuccess("工单已经录入成功", Url.Action("Order", "Order"))); } else { return(ResultSuccess("工单录入失败", Url.Action("Order", "OrderWrite"))); } } else { return(ResultSuccess("工单录入失败", Url.Action("Order", "OrderWrite"))); } } catch (DataExistException ex) { return(ResultError(ex.Message)); } }
OrderReportContainer MapOrder(MainOrder mainorder) { var docData = new OrderReportContainer(); var gross =(mainorder.ItemSummary.Sum(x => (x.Qty*x.Value).GetTruncatedValue() + (x.Qty*x.VatValue).GetTruncatedValue())).GetTotalGross(); var docHeader = new OrderHeader() { AmountPaid = mainorder.PaidAmount, Comment = mainorder.Note, DatePrinted = DateTime.Now, DateRequired = mainorder.DateRequired, DocumentIssuerUserName = mainorder.DocumentIssuerUser.Username, DocumentIssuerCCName = mainorder.DocumentIssuerCostCentre.Name, DocumentReference = mainorder.DocumentReference, IssuedOnBehalfOfName = mainorder.IssuedOnBehalfOf != null ?mainorder.IssuedOnBehalfOf.Name:"", OrderTypeStr = mainorder.OrderType.ToString(), OutstandingAmount = mainorder.OutstandingAmount >0?mainorder.OutstandingAmount:0, ParentId = mainorder.ParentId, SaleDiscount = mainorder.SaleDiscount, SalesmanName = mainorder.DocumentRecipientCostCentre.Name, ShipToAddress = mainorder.ShipToAddress, StatusStr = mainorder.Status.ToString(), TotalGross =gross, //mainorder.TotalGross, TotalNet = (gross-mainorder.SaleDiscount).GetTotalGross(),//mainorder.TotalNet, TotalProductDiscount = mainorder.TotalDiscount, TotalSaleDiscount = mainorder.TotalDiscount, TotalVat = mainorder.TotalVat, ExternalDocumentReference = mainorder.ExternalDocumentReference, }; if (mainorder.IssuedOnBehalfOf is Outlet) docHeader.RouteName = ((Outlet) mainorder.IssuedOnBehalfOf).Route.Name; docHeader.DocumentIssuerDetails = "Generated by: " + docHeader.DocumentIssuerUserName + " ; Cost centre: " + docHeader.DocumentIssuerCCName + "; Date: " + docHeader.DatePrinted.ToShortDateString(); docData.DocumentHeader = docHeader; int i = 0; foreach (var item in mainorder.ItemSummary) { var li = new OrderReportLineItem() { ApprovedQuantity = item.ApprovedQuantity, BackOrderQuantity = item.BackOrderQuantity, DiscountType = StringUtils.BreakUpperCB(item.Product.GetType().ToString().Split('.').Last()), GrossAmount = item.TotalGross, LineItemTypeStr = item.LineItemType.ToString(), LostSaleQuantity = item.LostSaleQuantity, ProductName = item.Product.Description, ProductCode = item.Product.ProductCode, Qty = item.Qty, RowNumber = i + 1, TotalNet = item.TotalNet, TotalVat = item.TotalVat, UnitDiscount = item.ProductDiscount, UnitPrice = item.Value, UnitVat = item.VatValue, }; docData.LineItems.Add(li); i++; } foreach (var payment in mainorder.GetPayments) { string bankinfo = ""; using (StructureMap.IContainer c = NestedContainer) { if (payment.PaymentModeUsed == PaymentMode.Cheque) { var bank = Using<IBankRepository>(c).GetByCode(payment.Bank); var bankbranch = Using<IBankBranchRepository>(c).GetByCode(payment.BankBranch); if (bank != null) bankinfo = bank.Name + "(" + bank.Code + ")" ; if (bankbranch != null) bankinfo +=" -- "+ bankbranch.Name + " (" + bankbranch.Code + ")"; } } docData.PaymentInfoList.Add(new OrderReportPaymentInfo() { Amount = payment.ConfirmedAmount, PaymentModeUsed = payment.PaymentModeUsed.ToString(), PaymentRefId =payment.PaymentRefId, BankInfo = bankinfo, ChequeDueDate= (payment.PaymentModeUsed == PaymentMode.Cheque && payment.DueDate.HasValue)?payment.DueDate.Value.ToShortDateString(): "" }); } return docData; }
public void PrintReceipt(MainOrder order) { decimal calculatedTotal = 0m; decimal priceCalculatedTotal = 0m; foreach (var item in order.ItemSummary) { var vat = item.VatValue; string hasVAT = vat > 0 ? "A" : "B"; double price = (double) Math.Truncate((item.Value + vat)*100)/100; double price2 = (double) (item.Value + vat + item.ProductDiscount); int quantity = (int) item.Qty; calculatedTotal +=Convert.ToDecimal((item.Value+vat)*quantity); priceCalculatedTotal += Convert.ToDecimal(((double)Math.Truncate((item.Value + vat)*quantity) * 100) / 100); } calculatedTotal = calculatedTotal.GetTotalGross(); calculatedTotal=(calculatedTotal-order.SaleDiscount).GetTotalGross(); if (order.PaidAmount != calculatedTotal) { PrintNonFiscalOrderReceipt(order); } else { PrinterOrderReceipt(order); } }
public void PrinterOrderReceipt(MainOrder order) { Log(string.Format("printing order id={0}", order.Id)); var printer = new FiscalPrinterUtility(comPort, comSpeed); if (!FiscalPrinterHelper._isConnected) { printer.ConnectFiscalPrinter(); } if (printer.OpenFiscalPrinter()) { int casesQuantity = 0; double calculatedTotal = 0.0; decimal cumulativeTotal = 0m; int pricePrecision = 0; int quantityPrecision = 0; foreach (var item in order.ItemSummary) { var vat = item.VatValue; string hasVAT = vat> 0 ? "A" : "B"; if (item.Product.ReturnableType == ReturnableType.Returnable && item.Value==0) { continue; } double price = (double)Math.Truncate((item.Value + vat)*100) / 100; var pricecheck = (item.Value + vat).GetTruncatedValue(); cumulativeTotal += Convert.ToDecimal((item.Value + vat) * (int)item.Qty); var bulkQuantity = 0.0m; var calulationPrice = 0.0; using (var container = ObjectFactory.Container.GetNestedContainer()) { var summaryService = container.GetInstance<IProductPackagingSummaryService>(); bulkQuantity = summaryService.GetProductQuantityInBulk(item.Product.Id); var modulo = item.Qty%bulkQuantity; if (modulo != 0) { casesQuantity =(int) item.Qty; calulationPrice = (double) ((pricecheck)); } else { casesQuantity = (int)item.Qty / (int)bulkQuantity; calulationPrice = (double)(pricecheck).GetTruncatedValue(); calulationPrice = (double)((decimal)(calulationPrice * (double)bulkQuantity)).GetTotalGross(); } } double price2 =(double) (item.Value + vat+item.ProductDiscount); int quantity = (int)item.Qty; var line1 = item.Product.ProductCode.Trim(); var line2 = item.Product.Description.Trim(); printer.Sell(line1, line2, hasVAT.Trim(), calulationPrice, pricePrecision, casesQuantity, quantityPrecision); calculatedTotal += quantity * price; } var paidAmount = order.GetPayments.Sum(n => n.Amount); var expectedPayment = order.TotalGross; int subtotal, sumA, sumB, sumC, sumD, sumE, sumF, sumG, sumH; double salediscountValue = Convert.ToDouble(order.SaleDiscount); printer.SaleDiscount(1, 0, -salediscountValue, out subtotal, out sumA, out sumB, out sumC, out sumD, out sumE, out sumF, out sumG, out sumH); cumulativeTotal = cumulativeTotal.GetTotalGross(); cumulativeTotal = (cumulativeTotal - order.SaleDiscount).GetTotalGross(); var value = paidAmount; printer.GetTotalQ((double)value); printer.CloseFiscalPrinter(); } }
private static void MapPaymentInfo(tblDocument tblMainOrder, MainOrder mo) { foreach (var paymentInfo in tblMainOrder.tblOrderPaymentInfo) { var item = new PaymentInfo { Amount = paymentInfo.Amount, ConfirmedAmount = paymentInfo.ConfirmedAmount, Id = paymentInfo.Id, Description = paymentInfo.Description, IsConfirmed = paymentInfo.IsConfirmed.Value, IsProcessed = paymentInfo.IsProcessed.Value, MMoneyPaymentType = paymentInfo.MMoneyPaymentType, NotificationId = paymentInfo.NotificationId, PaymentModeUsed = (PaymentMode) paymentInfo.PaymentMode, PaymentRefId = paymentInfo.PaymentRefId, Bank = paymentInfo.BankCode, BankBranch = paymentInfo.BranchCode, DueDate = paymentInfo.ChequeDueDate }; if (paymentInfo.ChequeDueDate.HasValue) paymentInfo.ChequeDueDate = paymentInfo.ChequeDueDate.Value; mo.AddPayment(item); } }
private MainOrder UpdadateMainOrderIfEdited(MainOrder order) { using (var c = NestedContainer) { var factory = Using<IMainOrderFactory>(c); //update and add line item foreach (var item in LineItem) { SubOrderLineItem existing = order.PendingApprovalLineItems.FirstOrDefault( s => s.Product.Id == item.ProductId && s.LineItemType == item.LineItemType); if (existing != null && existing.Qty != item.Quantity) { existing.Qty = item.Quantity; order.EditLineItem(existing); } else if(existing == null) { if (item.UnitDiscount > 0) { existing = factory.CreateDiscountedLineItem(item.ProductId, item.Quantity, item.UnitPrice, item.ProductType, item.UnitVAT, item.UnitDiscount); } else { existing = factory.CreateLineItem(item.ProductId, item.Quantity, item.UnitPrice, item.ProductType, item.UnitVAT); } order.EditLineItem(existing); } } //remove line item foreach (var item in order.PendingApprovalLineItems) { var existing =LineItem.FirstOrDefault(g => g.LineItemType == item.LineItemType && g.ProductId == item.Product.Id); if(existing==null) { order.RemoveLineItem(item); } } } return order; }
private void HandlePayments(MainOrder order, Guid invoiceId,BasicConfig config) { var orderpaymentInfoitem = order.GetSubOrderCommandsToExecute().OfType<AddOrderPaymentInfoCommand>(); foreach (var paymentInfo in orderpaymentInfoitem) { //TODO AJM resolve this section /* var notification = _notificationRepository.GetById(paymentInfo.InfoId); if (notification != null) { foreach (var paymentNotificationListItem in notification.PaymentNotificationDetails.Where(s => !s.IsUsed)) { _notificationRepository.ConfirmNotificationItem(paymentNotificationListItem.Id); } }*/ } if (orderpaymentInfoitem.Any(s => s.IsConfirmed && !s.IsProcessed)) { if (invoiceId == Guid.Empty) invoiceId = _invoiceRepository.GetInvoiceByOrderId(order.Id).Id; CostCentre recepient = null; if (order.DocumentIssuerCostCentre is DistributorSalesman) recepient = order.DocumentIssuerCostCentre; else recepient = order.DocumentRecipientCostCentre; string receiptRef = _getDocumentReference.GetDocReference("Rpt", recepient.Id,order.IssuedOnBehalfOf.Id); Receipt receipt = _receiptFactory.Create(order.DocumentIssuerCostCentre, order.DocumentIssuerCostCentreApplicationId, order.DocumentRecipientCostCentre, order.DocumentIssuerUser, receiptRef, order.Id, invoiceId, Guid.Empty); foreach (var info in orderpaymentInfoitem.Where(s => s.IsConfirmed && !s.IsProcessed)) { receipt.AddLineItem(_receiptFactory.CreateLineItem(info.ConfirmedAmount, info.PaymentRefId, info.MMoneyPaymentType, info.NotificationId, 0, (PaymentMode)info.PaymentModeId, info.Description, receipt.Id, info.IsConfirmed) ); } receipt.Confirm(); _receiptWorkFlowManager.SubmitChanges(receipt,config); } }
/// <summary> /// 微信手工单 /// 2017-05-26 /// </summary> public ActionResult WxHandWorkOrder(MainOrder mainOrder) { long deviceId = DeviceService.Instance.WxDeviceWrite(mainOrder); if (deviceId > 0) { //创建新工单 var wxUser = Session["WxUser"] as WeiXinUser; var user = new AuthAccountServer().Get(wxUser.openid); mainOrder.MainOrderId = SequNo.NewId; mainOrder.DeviceId = deviceId; mainOrder.UserId = user.User.UserId; ServiceCompany serviceCompany = CompanyService.Instance.GetServiceCompany(mainOrder.ServiceCompanyId); var serviceUsers = UserService.Instance.ServiceCompanyUserList(mainOrder.ServiceCompanyId); //判断RepairImages 是否为空 不为空要更新图片 if (!string.IsNullOrEmpty(mainOrder.RepairImages)) { new PictureService().UpdatePicOuterId(mainOrder.RepairImages, mainOrder.MainOrderId); } var flag = OrderService.Instance.Create(mainOrder, serviceCompany); if (flag) { //判断包修人员信息有没有更改 if (mainOrder.ContactsPhone != user.User.Phone || mainOrder.Contacts != user.User.RealName || mainOrder.UseCompanyName != user.User.CompanyName) { new Task(new Action(() => { user.User.Phone = mainOrder.ContactsPhone; user.User.RealName = mainOrder.Contacts; user.User.CompanyName = mainOrder.UseCompanyName; UserService.Instance.Edit(user.User); })).Start(); } new Task(new Action(() => { if (serviceUsers != null) { foreach (var item in serviceUsers) { if (item.RoleKey == UserType.SvcCompanyUserAdmin || item.RoleKey == (UserType.UseCompanyUserAdmin | UserType.SvcCompanyUserAdmin)) { SMSManager.Instance.SendNotify(item.Phone, mainOrder.MainOrderId.ToString()); } } } //消息推送 var obj = new { title = "新订单提醒", content = string.Format("您有一个新的服务工单:{0}", mainOrder.MainOrderId), orderId = mainOrder.MainOrderId, page = string.Format("/orderDetail/{0}", mainOrder.MainOrderId) }; var tagList = new List <string> { serviceCompany.ServiceCompanyId.ToString(), "1" }; var resultMsg = PushMassageHelper.Push(Newtonsoft.Json.JsonConvert.SerializeObject(obj), tagList, PushMassageHelper.AppType.WX); Logger.InfoFormat("个推推送结果{0}===={1}", serviceCompany.ServiceCompanyId, resultMsg); })).Start(); //发送短信 //判断报修终端 if (mainOrder.RepairType == RepairType.Wx) { //发送公共号消息 new Task(new Action(() => { var resultMsg = os.SendWxTmpMsg(mainOrder.UserId, mainOrder.MainOrderId, OrderState.Created); Logger.InfoFormat("微信消息推送{0}===={1}", mainOrder.UserId, resultMsg); })).Start(); } return(Json(new { success = "创建成功", id = mainOrder.MainOrderId.ToString() }, JsonRequestBehavior.AllowGet)); } else { return(Json(new { error = "服务器繁忙,请稍后再试试" } , JsonRequestBehavior.AllowGet)); } } else { return(Json(new { error = "服务器繁忙,请稍后再试试" } , JsonRequestBehavior.AllowGet)); } }
public void Submit(MainOrder order,BasicConfig config) { int sequence = 0; var envelope = new CommandEnvelope(); envelope.Initialize(order); List<DocumentCommand> commandsToExecute = order.GetSubOrderCommandsToExecute(); var createCommand = commandsToExecute.OfType<CreateCommand>().FirstOrDefault(); if (createCommand != null) envelope.CommandsList.Add(new CommandEnvelopeItem(++sequence, createCommand)); var lineItemCommands = commandsToExecute.OfType<AfterCreateCommand>(); foreach (var _item in lineItemCommands) { envelope.CommandsList.Add(new CommandEnvelopeItem(++sequence, _item)); // _commandRouter.RouteDocumentCommand(_item); } var editlineItemCommands = commandsToExecute.OfType<ChangeMainOrderLineItemCommand>(); foreach (var _editeditem in editlineItemCommands) { envelope.CommandsList.Add(new CommandEnvelopeItem(++sequence, _editeditem)); //_commandRouter.RouteDocumentCommand(_editeditem); } var removedLineitem = commandsToExecute.OfType<RemoveMainOrderLineItemCommand>(); foreach (var _removeditem in removedLineitem) { envelope.CommandsList.Add(new CommandEnvelopeItem(++sequence, _removeditem)); } var co = commandsToExecute.OfType<ConfirmCommand>().FirstOrDefault(); if (co != null) { envelope.CommandsList.Add(new CommandEnvelopeItem(++sequence, co)); //_commandRouter.RouteDocumentCommand(co); _notifyService.SubmitOrderSaleNotification(order); } var rco = commandsToExecute.OfType<RejectMainOrderCommand>().FirstOrDefault(); if (rco != null) envelope.CommandsList.Add(new CommandEnvelopeItem(++sequence, rco)); //adjust inventory from distributor Guid invoiceId; var approvedlineItemCommands = order.GetSubOrderCommandsToExecute().OfType<ApproveOrderLineItemCommand>(); foreach (var _item in approvedlineItemCommands) { envelope.CommandsList.Add(new CommandEnvelopeItem(++sequence, _item)); } HandleApprovedCommand(order,config,out invoiceId); var aop = commandsToExecute.OfType<ApproveCommand>().FirstOrDefault(); if (aop != null) envelope.CommandsList.Add(new CommandEnvelopeItem(++sequence, aop)); var closecommand = commandsToExecute.OfType<CloseOrderCommand>().FirstOrDefault(); if (closecommand != null) envelope.CommandsList.Add(new CommandEnvelopeItem(++sequence, closecommand)); var orderpaymentInfoitem = order.GetSubOrderCommandsToExecute().OfType<AddOrderPaymentInfoCommand>(); foreach (var paymentInfo in orderpaymentInfoitem) { envelope.CommandsList.Add(new CommandEnvelopeItem(++sequence, paymentInfo)); } HandlePayments(order,invoiceId, config); _commandEnvelopeRouter.RouteCommandEnvelope(envelope); }
DocumentReportContainer MapOrder(MainOrder mainorder) { DocumentReportContainer docData = new DocumentReportContainer(); DocumentHeader docHeader = new DocumentHeader() { AmountPaid = mainorder.PaidAmount, Comment = mainorder.Note, DatePrinted = DateTime.Now, DateRequired = mainorder.DateRequired, DocumentIssuerUserName = mainorder.DocumentIssuerUser.Username, DocumentIssuerCCName = mainorder.DocumentIssuerCostCentre.Name, DocumentReference = mainorder.DocumentReference, IssuedOnBehalfOfName = mainorder.IssuedOnBehalfOf.Name, OrderTypeStr = mainorder.OrderType.ToString(), OutstandingAmount = mainorder.OutstandingAmount, ParentId = mainorder.ParentId, RouteName = ((Outlet)mainorder.IssuedOnBehalfOf).Route.Name, SaleDiscount = mainorder.SaleDiscount, SalesmanName = mainorder.DocumentRecipientCostCentre.Name, ShipToAddress = mainorder.ShipToAddress, StatusStr = mainorder.Status.ToString(), TotalGross = mainorder.TotalGross, TotalNet = mainorder.TotalNet, TotalProductDiscount = mainorder.TotalDiscount, TotalSaleDiscount = mainorder.TotalDiscount, TotalVat = mainorder.TotalVat, }; docHeader.DocumentIssuerDetails = "Generated by: " + docHeader.DocumentIssuerUserName + " ; Cost centre: " + docHeader.DocumentIssuerCCName + "; Date: " + docHeader.DatePrinted.ToShortDateString(); docData.DocumentHeader = docHeader; int i = 0; foreach (var item in mainorder.ItemSummary) { OrderReportLineItem li = new DocumentLineItem() { ApprovedQuantity = item.ApprovedQuantity, BackOrderQuantity = item.BackOrderQuantity, DiscountType = StringUtils.BreakUpperCB(item.Product.GetType().ToString().Split('.').Last()), GrossAmount = item.TotalGross, LineItemTypeStr = item.LineItemType.ToString(), LostSaleQuantity = item.LostSaleQuantity, ProductName = item.Product.Description, Qty = item.Qty, RowNumber = i + 1, TotalNet = item.TotalNet, TotalVat = item.TotalVat, UnitDiscount = item.ProductDiscount, UnitPrice = item.Value, UnitVat = item.VatValue, }; docData.LineItems.Add(li); i++; } return docData; }
/// <summary> /// 创建工单 /// </summary> /// <param name="order"></param> /// <returns></returns> public ActionResult Create(MainOrder order) { try { var areaId = ApiUser.Current.AreaId; if (order.DeviceId.HasValue && order.DeviceId > 0) { var device = ds.Get(order.DeviceId.Value); areaId = device != null ? device.AreaId : ApiUser.Current.AreaId; } order.UseCompanyId = ApiUser.Current.UseCompanyId; order.ServiceCompanyId = order.ServiceCompanyId ?? ApiUser.Current.ServiceCompanyId; order.UserId = ApiUser.Current.UserId; order.AreaId = areaId; order.MainOrderId = SequNo.NewId; order.LastEditTime = DateTime.Now; //判断RepairImages 是否为空 不为空要更新图片 if (!string.IsNullOrEmpty(order.RepairImages)) { new PictureService().UpdatePicOuterId(order.RepairImages, order.MainOrderId); } var serviceCompany = cs.GetServiceCompany(order.ServiceCompanyId); var serviceUsers = new UserService().ServiceCompanyUserList(order.ServiceCompanyId); var flag = os.Create(order, ApiUser.Current, serviceCompany); if (flag) { new Task(new Action(() => { if (serviceUsers != null) { foreach (var item in serviceUsers) { if (item.RoleKey == UserType.SvcCompanyUserAdmin || item.RoleKey == (UserType.UseCompanyUserAdmin | UserType.SvcCompanyUserAdmin)) { SMSManager.Instance.SendNotify(item.Phone, order.MainOrderId.ToString()); } } } //消息推送 var obj = new { title = "新订单提醒", content = string.Format("您有一个新的服务工单:{0}", order.MainOrderId), orderId = order.MainOrderId, page = string.Format("/orderDetail/{0}", order.MainOrderId) }; var tagList = new List <string> { serviceCompany.ServiceCompanyId.ToString(), "1" }; var resultMsg = PushMassageHelper.Push(Newtonsoft.Json.JsonConvert.SerializeObject(obj), tagList, PushMassageHelper.AppType.WX); Logger.InfoFormat("个推推送结果{0}===={1}", serviceCompany.ServiceCompanyId, resultMsg); })).Start(); //发送短信 //判断报修终端 if (order.RepairType == RepairType.Wx) { //发送公共号消息 new Task(new Action(() => { var resultMsg = os.SendWxTmpMsg(order.UserId, order.MainOrderId, OrderState.Created); Logger.InfoFormat("微信消息推送{0}===={1}", order.UserId, resultMsg); })).Start(); } return(Json(new { success = "创建成功", id = order.MainOrderId.ToString() }, JsonRequestBehavior.AllowGet)); } else { return(Json(new { error = "服务器繁忙,请稍后再试试" } , JsonRequestBehavior.AllowGet)); } } catch (Exception e) { Logger.Error("创建工单异常", e); return(Json(new { error = "服务器繁忙,请稍后再试试" } , JsonRequestBehavior.AllowGet)); } }