Beispiel #1
0
        /// <summary>
        /// 从淘宝中间表生成系统订单
        /// </summary>
        /// <param name="organ"></param>
        /// <param name="channel"></param>
        /// <see cref=""/>
        /// <returns>0转换成功,数值表示失败计数</returns>
        public int GenerateOrderFromTaobao(MemberOrganization organ, MemberChannel channel)
        {
            string strUserPrefix = Utility.ConfigHelper.GlobalConst.GetSetting("TaobaoUserPrefix");
            int nFailCount = 0;       // 转换失败计数器
            string strFailTids = "";
            var oTbOrders = (from o in dbEntity.ExTaobaoOrders.Include("TaobaoOrderItems")
                             where o.Transfered == false && o.status == "WAIT_SELLER_SEND_GOODS"
                                   && o.OrgID == organ.Gid && o.ChlID == channel.Gid
                             select o).ToList();
            foreach (var oTrade in oTbOrders)
            {
                try
                {
                    // 创建数据库事务
                    using (var scope = new TransactionScope())
                    {
                        string strTid = oTrade.tid.ToString();
                        var oOrder = (from o in dbEntity.OrderInformations
                                      where o.OrgID == organ.Gid && o.ChlID == channel.Gid
                                            && o.LinkCode == strTid
                                      select o).FirstOrDefault();
                        bool bSuccess = false;
                        if (oOrder == null)
                        {
                            // 查询和新建用户
                            string strLoginName = strUserPrefix + oTrade.buyer_nick;
                            var oUser = (from u in dbEntity.MemberUsers
                                         where u.LoginName == strLoginName
                                         select u).FirstOrDefault();
                            if (oUser == null)
                            {
                                oUser = new MemberUser
                                {
                                    Organization = organ,
                                    Role = dbEntity.MemberRoles.Where(r => r.OrgID == organ.Gid && r.Code == "Public").FirstOrDefault(),
                                    Channel = channel,
                                    LoginName = strLoginName,
                                    Ustatus = (byte)ModelEnum.UserStatus.VALID,
                                    NickName = oTrade.buyer_nick,
                                    DisplayName = oTrade.buyer_nick,
                                    Passcode = String.IsNullOrEmpty(oTrade.receiver_mobile) ? oTrade.receiver_phone : oTrade.receiver_mobile,
                                    Culture = dbEntity.GeneralCultureUnits.Where(c => c.Culture == 2052).FirstOrDefault(),
                                    Email = oTrade.buyer_email
                                };
                            }

                            // 匹配地区
                            var oLocation = (from r in dbEntity.GeneralRegions
                                             where r.Code == "CHN"       // 中国
                                             select r).FirstOrDefault();
                            var oProvince = (from r in dbEntity.GeneralRegions
                                             where r.Parent.Code == "CHN"
                                                   && (r.ShortName == oTrade.receiver_state || r.Map01 == oTrade.receiver_state)
                                             select r).FirstOrDefault();
                            if (oProvince != null)
                            {
                                oLocation = oProvince;                   // 匹配到省
                                var oCity = (from r in dbEntity.GeneralRegions
                                             where r.aParent == oProvince.Gid
                                                   && (r.ShortName == oTrade.receiver_city || r.Map01 == oTrade.receiver_city)
                                             select r).FirstOrDefault();
                                if (oCity != null)
                                {
                                    oLocation = oCity;                   // 匹配到市
                                    var oDistrict = (from r in dbEntity.GeneralRegions
                                                     where r.aParent == oCity.Gid
                                                           && (r.ShortName == oTrade.receiver_district || r.Map01 == oTrade.receiver_district)
                                                     select r).FirstOrDefault();
                                    if (oDistrict != null)
                                        oLocation = oDistrict;           // 匹配到区
                                }
                            }

                            // 支付方式 -- 支付宝
                            var oPayType = (from p in dbEntity.FinancePayTypes
                                            where p.Deleted == false && p.OrgID == organ.Gid && p.Code == "alipay"
                                            select p).FirstOrDefault();
                            // 货币 -- 人民币
                            var oCurrency = (from u in dbEntity.GeneralMeasureUnits
                                             where u.Deleted == false && u.Code == "¥"
                                                   && u.Utype == (byte)ModelEnum.MeasureUnit.CURRENCY
                                             select u).FirstOrDefault();

                            // 创建订单主表
                            oOrder = new OrderInformation
                            {
                                Organization = organ,
                                Channel = channel,
                                User = oUser,
                                LinkCode = strTid,
                                Ostatus = (byte)ModelEnum.OrderStatus.NONE,
                                TransType = (oTrade.type == "cod") ? (byte)ModelEnum.TransType.COD : (byte)ModelEnum.TransType.SECURED,
                                PayType = oPayType,
                                PayNote = oTrade.alipay_no,
                                // Pieces = oTrade.num,

                                Currency = oCurrency,
                                SaleAmount = Decimal.Parse(oTrade.total_fee),
                                // ExecuteAmount = Decimal.Parse(oTrade.payment) - Decimal.Parse(oTrade.post_fee),
                                ShippingFee = Decimal.Parse(oTrade.post_fee),
                                MoneyPaid = Decimal.Parse(oTrade.payment),
                                // Differ = 0,

                                PaidTime = new DateTimeOffset(oTrade.pay_time.Value, TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now)),
                                Consignee = oTrade.receiver_name,
                                Location = oLocation,
                                FullAddress = oTrade.receiver_state + oTrade.receiver_city + oTrade.receiver_district + oTrade.receiver_address,
                                PostCode = oTrade.receiver_zip,
                                Telephone = oTrade.receiver_phone,
                                Mobile = oTrade.receiver_mobile,
                                Email = oTrade.buyer_email,
                                PostComment = oTrade.buyer_memo,
                                LeaveWord = oTrade.seller_memo
                            };

                            // 子订单实付金额。精确到2位小数,单位:元。如:200.07,表示:200元7分。计算公式如下:payment = price * num + adjust_fee - discount_fee + post_fee
                            // (邮费,单笔子订单时子订单实付金额包含邮费,多笔子订单时不包含邮费);
                            // 对于退款成功的子订单,由于主订单的优惠分摊金额,会造成该字段可能不为0.00元。建议使用退款前的实付金额减去退款单中的实际退款金额计算。
                            bool bSingleProduct = (oTrade.TaobaoOrderItems.Count() == 1);
                            decimal nTotalQty = 0m;      // 商品总数量,标准计量单位
                            decimal nItemAmount = 0m;    // 商品总金额

                            // 创建订单从表
                            foreach (var item in oTrade.TaobaoOrderItems)
                            {
                                // 先找OnSale.Code确定是否为pu-parts模式,SKU号对应不上时,必须判断转换失败
                                var oParts = (from s in dbEntity.ProductOnSales.Include("Product")
                                              where s.Deleted == false
                                                    && s.OrgID == organ.Gid && s.ChlID == channel.Gid
                                                    && s.Code == item.outer_sku_id
                                                    && s.Mode == (byte)ModelEnum.ProductMode.PU_PARTS
                                              orderby s.Ostatus descending
                                              select s).FirstOrDefault();
                                if (oParts == null)
                                {
                                    // PU-SKU 模式,只导入一个OnItem加入订单
                                    var oOnSku = (from s in dbEntity.ProductOnItems.Include("SkuItem").Include("OnSale")
                                                  where s.OnSale.Deleted == false && s.Deleted == false
                                                        && s.OnSale.Mode == (byte)ModelEnum.ProductMode.PU_SKU
                                                        && s.OnSale.OrgID == organ.Gid
                                                        && s.OnSale.ChlID == channel.Gid
                                                        && s.SkuItem.Code == item.outer_sku_id
                                                  orderby s.OnSale.Ostatus descending, s.OnSale.CreateTime descending
                                                  select s).FirstOrDefault();
                                    var oOnPrice = (from p in dbEntity.ProductOnUnitPrices.Include("MarketPrice").Include("SalePrice")
                                                    where p.Deleted == false
                                                          && p.OnSkuID == oOnSku.Gid       // oOnSku空,则直接到catch记录错误
                                                    orderby p.IsDefault descending, p.CreateTime descending
                                                    select p).FirstOrDefault();
                                    // 计量单位转换,进位法
                                    decimal nQuantity = Decimal.Parse(item.num.ToString());
                                    decimal nPercent = Decimal.Parse("1" + new string('0', oOnPrice.Percision));
                                    nQuantity = Math.Ceiling(nQuantity * oOnPrice.UnitRatio * nPercent) / nPercent;
                                    decimal nPayment = Decimal.Parse(item.payment);
                                    // 单笔子订单时子订单实付金额包含邮费,多笔子订单时不包含邮费
                                    if (bSingleProduct) nPayment -= oOrder.ShippingFee;
                                    OrderItem oOrderItem = new OrderItem
                                    {
                                        OnSkuItem = oOnSku,
                                        SkuItem = oOnSku.SkuItem,
                                        Name = item.title,
                                        Quantity = nQuantity,
                                        MarketPrice = oOnPrice.MarketPrice.GetResource(oOrder.Currency.Gid),
                                        SalePrice = oOnPrice.SalePrice.GetResource(oOrder.Currency.Gid),
                                        ExecutePrice = Math.Round(nPayment / nQuantity, 2),
                                        Remark = String.Format("淘宝:{0} | {1} | {2} | {3}", item.num, item.payment, item.discount_fee, item.adjust_fee)
                                    };
                                    // 统计与误差计算
                                    nTotalQty += nQuantity;
                                    nItemAmount += oOrderItem.ExecutePrice * nQuantity;
                                    oOrder.OrderItems.Add(oOrderItem);
                                }
                                else
                                {
                                    // PU-Parts模式,需要将所有OnItem加入订单,只第一个商品有价格,其他商品价格为零
                                    var oPartItems = (from i in dbEntity.ProductOnItems.Include("SkuItem").Include("OnSale")
                                                      where i.Deleted == false
                                                            && i.OnSaleID == oParts.Gid
                                                      select i).ToList();
                                    bool bIsFirst = true;
                                    decimal nQuantity = Decimal.Parse(item.num.ToString());
                                    decimal nPayment = Decimal.Parse(item.payment);
                                    // 单笔子订单时子订单实付金额包含邮费,多笔子订单时不包含邮费
                                    if (bSingleProduct) nPayment -= oOrder.ShippingFee;
                                    foreach (var oOnSku in oPartItems)
                                    {
                                        var oOnPrice = (from p in dbEntity.ProductOnUnitPrices.Include("MarketPrice").Include("SalePrice")
                                                        where p.Deleted == false && p.OnSkuID == oOnSku.Gid  // oOnSku空,则直接到catch记录错误
                                                        orderby p.IsDefault descending
                                                        select p).FirstOrDefault();
                                        // decimal nItemQty = oOnSku.SetQuantity * nQuantity;          // 不使用套装数量,使用转换算法
                                        // 计量单位转换,进位法
                                        decimal nPercent = Decimal.Parse("1" + new string('0', oOnPrice.Percision));
                                        decimal nItemQty = Math.Ceiling(nQuantity * oOnPrice.UnitRatio * nPercent) / nPercent;
                                        OrderItem oOrderItem = new OrderItem
                                        {
                                            OnSkuItem = oOnSku,
                                            SkuItem = oOnSku.SkuItem,
                                            Name = oOnSku.FullName.GetResource(2052),
                                            Quantity = nItemQty,
                                            MarketPrice = oOnPrice.MarketPrice.GetResource(oOrder.Currency.Gid),
                                            SalePrice = oOnPrice.SalePrice.GetResource(oOrder.Currency.Gid),
                                            ExecutePrice = (bIsFirst) ? Math.Round(nPayment / nItemQty, 2) : 0m,  // 第一个商品有价格,其他商品没有价格
                                            Remark = String.Format("淘宝:{0} | {1} | {2} | {3} | {4}", item.title, item.num, item.payment, item.discount_fee, item.adjust_fee)
                                        };
                                        // 统计与误差计算
                                        nTotalQty += nItemQty;
                                        nItemAmount += oOrderItem.ExecutePrice * nItemQty;
                                        oOrder.OrderItems.Add(oOrderItem);
                                        bIsFirst = false;
                                    }
                                }
                            }
                            oOrder.Pieces = nTotalQty;
                            oOrder.ExecuteAmount = nItemAmount;
                            oOrder.Differ = oOrder.MoneyPaid - oOrder.ShippingFee - nItemAmount;  // 误差
                            dbEntity.OrderInformations.Add(oOrder);
                            dbEntity.SaveChanges();

                            // 更新淘宝订单转换成功状态
                            oTrade.OrderID = oOrder.Gid;
                            oTrade.Transfered = true;
                            dbEntity.SaveChanges();

                            // 创建已收款记录
                            FinancePayment oFinance = new FinancePayment
                            {
                                Organization = organ,
                                PayTo = (byte)ModelEnum.PayDirection.TO_CORPBANK,
                                Pstatus = (byte)ModelEnum.PayStatus.PAID,
                                RefType = (byte)ModelEnum.NoteType.ORDER,
                                RefID = oOrder.Gid,
                                Reason = String.Format("支付宝:{0}", oTrade.alipay_no),
                                PayDate = new DateTimeOffset(oTrade.pay_time.Value, TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now)),
                                Currency = oOrder.Currency,
                                Amount = oOrder.MoneyPaid,
                                Remark = String.Format("淘宝订单:{0}", oTrade.tid)
                            };
                            dbEntity.FinancePayments.Add(oFinance);

                            // 索取发票
                            if (!String.IsNullOrEmpty(oTrade.invoice_name))
                            {
                                FinanceInvoice oInvoice = new FinanceInvoice
                                {
                                    OrderInfo = oOrder,
                                    Code = oOrder.Gid.ToString("N"),
                                    Title = oTrade.invoice_name,
                                    Amount = oOrder.MoneyPaid
                                };
                                dbEntity.FinanceInvoices.Add(oInvoice);
                            }
                            dbEntity.SaveChanges();
                            bSuccess = true;
                        }
                        else
                        {
                            // TODO Warning

                            nFailCount++;
                            strFailTids += String.Format("{0},", oTrade.tid);
                        }
                        scope.Complete();
                        if (bSuccess)
                        {
                            oEventBLL.WriteEvent(String.Format("淘宝订单转换成功: {0}, {1}", oOrder.Code, oTrade.tid),
                                ModelEnum.ActionLevel.GENERIC, ModelEnum.ActionSource.ORDER, this.ToString());
                        }
                    }
                }
                catch
                {
                    nFailCount++;
                    strFailTids += String.Format("{0},", oTrade.tid);
                }
            }
            if (nFailCount > 0)
            {
                oEventBLL.WriteEvent(String.Format("淘宝订单转换失败: {0}", strFailTids),
                    ModelEnum.ActionLevel.ERROR, ModelEnum.ActionSource.ORDER, this.ToString());
            }
            return nFailCount;
        }
Beispiel #2
0
 /// <summary>
 /// 生成退款
 /// </summary>
 /// <param name="order"></param>
 /// <returns></returns>
 public bool RefundFromOrder(OrderInformation order)
 {
     if (order.TotalPaid-order.MoneyPaid>0)
     {
         orderBll.ReturnMoney(order);
     }
     if (order.MoneyPaid > 0)
     {
         FinancePayment oFinancePayment = new FinancePayment
         {
             OrgID=order.OrgID,
             Ptype=(from gpc in dbEntity.GeneralPrivateCategorys
                   where gpc.Deleted.Equals(false) && gpc.Ctype==(byte)ModelEnum.PrivateCategoryType.PAY_TYPE
                   select gpc.Gid).FirstOrDefault(),
             PayTo=1,
             Pstatus=0,
             RefType=(byte)ModelEnum.NoteType.ORDER,
             RefID=order.Gid,
             Reason="退",
             Currency=order.Currency,
             Amount=order.MoneyPaid,
             Remark=order.Remark
         };
         dbEntity.FinancePayments.Add(oFinancePayment);
         dbEntity.SaveChanges();
     }
     return true;
 }
Beispiel #3
0
 /// <summary>
 /// 保存添加的应付款
 /// </summary>
 /// <param name="newPayment"></param>
 /// <param name="RefID">页面传回的订单号</param>
 public void SaveNewPayable(FinancePayment newPayment,string RefID)
 {
     try
     {
         byte ptype = newPayment.RefType;    //单据类型,订单或采购单
         switch (ptype)
         {
             case (byte)ModelEnum.NoteType.ORDER:
                 {
                     OrderInformation oOrderInfo = dbEntity.OrderInformations.Include("Currency").Where(o => o.Code == RefID).Single();
                     newPayment.RefID = oOrderInfo.Gid;
                     newPayment.Currency = oOrderInfo.Currency;
                     break;
                 }
             case (byte)ModelEnum.NoteType.PURCHASE:
                 {
                     PurchaseInformation oPurchase = dbEntity.PurchaseInformations.Include("Currency").Where(p => p.Code == RefID).Single();
                     newPayment.RefID = oPurchase.Gid;
                     newPayment.Currency = oPurchase.Currency;
                     break;
                 }
         }
         newPayment.Pstatus = (byte)ModelEnum.FinanceStatus.NONE;
         dbEntity.FinancePayments.Add(newPayment);
         dbEntity.SaveChanges();
     }
     catch (Exception ex)
     {
         RedirectToAction("ErrorPage", "Home", new { message = ex.Message });
     }
 }
Beispiel #4
0
 /// <summary>
 /// 保存编辑的应付款
 /// </summary>
 /// <param name="newPayable"></param>
 /// <param name="RefID">页面传回的订单号</param>
 public void SaveEditPayable(FinancePayment newPayable)
 {
     try
     {
         FinancePayment oldPayment = dbEntity.FinancePayments.Include("Organization").Include("PaymentType").Include("Currency").Where(p => p.Gid == newPayable.Gid).Single();
         oldPayment.OrgID = newPayable.OrgID;
         oldPayment.Ptype = newPayable.Ptype;
         oldPayment.PayTo = newPayable.PayTo;
         oldPayment.PayDate = newPayable.PayDate;
         oldPayment.Reason = newPayable.Reason;
         oldPayment.Currency = newPayable.Currency;
         oldPayment.Amount = newPayable.Amount;
         oldPayment.Remark = newPayable.Remark;
         if (ModelState.IsValid)
         {
             dbEntity.Entry(oldPayment).State = EntityState.Modified;
             dbEntity.SaveChanges();
         }
     }
     catch (Exception ex)
     {
         RedirectToAction("ErrorPage", "Home", new { message = ex.Message });
     }
 }
Beispiel #5
0
 public ActionResult GetPayToText()
 {
     StringBuilder s = new StringBuilder();
     List<ListItem> list = new FinancePayment().PayToList;
     foreach (ListItem item in list)
     {
         s.Append(item.Value + ":" + item.Text + ";");
     }
     return Json(s.ToString(), JsonRequestBehavior.AllowGet);
 }
Beispiel #6
0
 /// <summary>
 /// 获取退款方向的下拉框列表
 /// </summary>
 /// <returns></returns>
 public List<SelectListItem> GetPayToSelectList()
 {
     List<SelectListItem> oList = new List<SelectListItem>();
     List<ListItem> PayToList = new FinancePayment().PayToList;
     foreach (var item in PayToList)
     {
         oList.Add(new SelectListItem { Text = item.Text, Value = item.Value });
     }
     return oList;
 }