Пример #1
0
 /// <summary>
 /// 根據order_id查詢訂單狀態
 /// </summary>
 /// <param name="om"></param>
 /// <returns></returns>
 public OrderMaster GetOrderMaster(OrderMaster om)
 {
     StringBuilder sbSql = new StringBuilder();
     sbSql.Append(@"select order_id,order_status from order_master 
     om where 1=1");
     if (0 != om.Order_Id)
     {
         sbSql.AppendFormat(" and om.order_id={0}", om.Order_Id);
     }
     return _dbAccess.getSinggleObj<OrderMaster>(sbSql.ToString());
 }
Пример #2
0
 public int ReturnAllOrder(OrderMaster om)
 {
     try
     {
         return _orderCancelMaster.ReturnAllOrder(om);
     }
     catch (Exception ex)
     {
         throw new Exception("OrderCancelMasterMgr.ReturnAllOrder-->" + ex.Message, ex);
     }
 }
Пример #3
0
 public int returnMsg(OrderMaster om)
 {
     try
     {
         return _orderCancelMaster.returnMsg(om);
     }
     catch (Exception ex)
     {
         throw new Exception("OrderCancelMasterMgr.returnMsg-->" + ex.Message, ex);
     }
 }
Пример #4
0
 public HttpResponseBase ReturnMsg() 
 {
     string json = string.Empty;
     OrderMaster order = new OrderMaster();
     try
     {
         if (!string.IsNullOrEmpty(Request.Params["order_id"]))
        {
            order.Order_Id = uint.Parse(Request.Params["order_id"]);
        }
          _orderCancelMgr = new OrderCancelMasterMgr(mySqlConnectionString);
          int result = _orderCancelMgr.returnMsg(order);
          int msg =0;
          switch (result)
          {
              case 1:
                  msg = 1;
                break;
              case 99:
                msg = 99;
                break;
           
            case 100:
                msg =100;//操作成功!
                break;
            default:
                break;
          }
          json = "{success:true,msg:\"" + msg + "\"}";
     }
     catch (Exception ex)
     {
         Log4NetCustom.LogMessage logMessage = new Log4NetCustom.LogMessage();
         logMessage.Content = string.Format("TargetSite:{0},Source:{1},Message:{2}", ex.TargetSite.Name, ex.Source, ex.Message);
         logMessage.MethodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
         log.Error(logMessage);
         json = "{success:false,msg:0}";
     }
     this.Response.Clear();
     this.Response.Write(json);
     this.Response.End();
     return this.Response;
 }
Пример #5
0
        public HttpResponseBase ReturnAllOrder()
        {
           string json = string.Empty;
           OrderMaster order = new OrderMaster();
           try{
               if (!string.IsNullOrEmpty(Request.Params["return_order"]))
               {
                   order.Order_Id = uint.Parse(Request.Params["return_order"]);
               }
               if (!string.IsNullOrEmpty(Request.Params["order_note"]))
               {
                   order.Note_Order = Request.Params["order_note"];

               }
               order.User_Id = uint.Parse(((Session["caller"] as Caller).user_id).ToString());
               order.user_name = (Session["caller"] as Caller).user_username;
               System.Net.IPAddress[] addlist = System.Net.Dns.GetHostByName(System.Net.Dns.GetHostName()).AddressList;
               if (addlist.Length > 0)
               {
                   order.Order_Ipfrom = addlist[0].ToString();
               }
               _orderCancelMgr = new OrderCancelMasterMgr(mySqlConnectionString);
               int result = _orderCancelMgr.ReturnAllOrder(order);
               string msg = "等待超時";
               switch (result)
               {
                   case 1:
                       msg = "消費者購物金餘額不足,無法扣除給予購物金!";
                       break;
                   case 2:
                       msg = "error master!";
                       break;
                   case 3:
                       msg = "error slave!";
                       break;
                   case 4:
                       msg = "取得身份證字號失敗!";
                       break;
                   case 5:
                       msg = "bonus type error !";
                       break;
                   case 100:
                       msg = "100";//操作成功!
                       break;
                   default:
                       break;
               }
               json = "{success:true,msg:\"" + msg + "\"}";              
            }
            catch (Exception ex)
            {
                Log4NetCustom.LogMessage logMessage = new Log4NetCustom.LogMessage();
                logMessage.Content = string.Format("TargetSite:{0},Source:{1},Message:{2}", ex.TargetSite.Name, ex.Source, ex.Message);
                logMessage.MethodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
                log.Error(logMessage);
                json = "{success:false,msg:0}";
            }
            this.Response.Clear();
            this.Response.Write(json);
            this.Response.End();
            return this.Response;
        }
Пример #6
0
        /**
         *Add by chaojie1124j 2015/08/20
         *實現訂單內容裡面的<取消整筆訂單>
         */
        public int ReturnAllOrder(OrderMaster om)
        {
            _serialDao = new SerialDao(connString);
            DataTable ordermaster = GetOrderMaster(om.Order_Id);
            StringBuilder sql = new StringBuilder();
            StringBuilder sqlstr = new StringBuilder();
            MySqlCommand mySqlCmd = new MySqlCommand();
            MySqlConnection mySqlConn = new MySqlConnection(connString);
            om.Replace4MySQL();
            int result = 0;
            int accumulated_bonus = 0;
            int accumulated_happygo = 0;
            int deduct_happygo = 0;
            if (ordermaster.Rows.Count <= 0)
            {
                return 0;//Order error;
            }
            try
            {
                if (mySqlConn != null && mySqlConn.State == System.Data.ConnectionState.Closed)
                {
                    mySqlConn.Open();
                }
                mySqlCmd.Connection = mySqlConn;
                mySqlCmd.Transaction = mySqlConn.BeginTransaction();
                mySqlCmd.CommandType = System.Data.CommandType.Text;
                List<OrderSlave> orderSlaveList = new List<OrderSlave>();
                sql.AppendFormat("select slave_id,slave_status from order_slave where order_id='{0}';", om.Order_Id);

                Dictionary<uint, string> SendMail = new Dictionary<uint, string>();
                orderSlaveList = _accessMySql.getDataTableForObj<OrderSlave>(sql.ToString());
                sql.Clear();

                List<OrderDetail> orderDetailList = new List<OrderDetail>();
                sql.Append("select od.detail_id,od.item_id,od.buy_num,od.parent_num,od.item_mode,od.accumulated_bonus,od.accumulated_happygo,od.deduct_happygo");
                sql.AppendFormat("  FROM order_detail od,order_slave os WHERE os.order_id ='{0}' AND os.slave_id = od.slave_id ;", om.Order_Id);
                orderDetailList = _accessMySql.getDataTableForObj<OrderDetail>(sql.ToString());
                sql.Clear();
                 accumulated_bonus =string.IsNullOrEmpty(ordermaster.Rows[0]["accumulated_bonus"].ToString())?0:Convert.ToInt32(ordermaster.Rows[0]["accumulated_bonus"]);
                 accumulated_happygo = string.IsNullOrEmpty(ordermaster.Rows[0]["accumulated_happygo"].ToString()) ? 0 : Convert.ToInt32(ordermaster.Rows[0]["accumulated_happygo"]);
                 deduct_happygo = string.IsNullOrEmpty(ordermaster.Rows[0]["deduct_happygo"].ToString()) ? 0 : Convert.ToInt32(ordermaster.Rows[0]["deduct_happygo"]);

                //for (int i = 0; i < orderDetailList.Count; i++)
                //{
                //    if (orderDetailList[i].item_mode == 2)
                //        continue;
                //    accumulated_bonus += orderDetailList[i].Accumulated_Bonus;
                //    accumulated_happygo += orderDetailList[i].Accumulated_Happygo;
                //    deduct_happygo += orderDetailList[i].Deduct_Happygo;
                //}

                //int user_bonus = GetUserBonus( ordermaster.Rows[0]["user_id"].ToString(), 1);
                //if (accumulated_bonus > user_bonus)
                //{
                //    return 1;//消費者購物金餘額不足,無法扣除給予購物金。
                //}
                if (!check_order_process(Convert.ToInt32(ordermaster.Rows[0]["order_status"]), 90) && Convert.ToInt32(ordermaster.Rows[0]["deduct_card_bonus"]) == 0)
                {
                    return 2;//error master
                }
                for (int i = 0; i < orderSlaveList.Count; i++)
                {
                    if (!check_order_process(Convert.ToInt32(orderSlaveList[i].Slave_Status), 90) && Convert.ToInt32(ordermaster.Rows[0]["deduct_card_bonus"]) == 0)
                    {
                        return 3;//error slave
                    }
                }
                sqlstr.Append(modify_order_master_status(om.Order_Id.ToString(), 90, om.Order_Ipfrom));
                mySqlCmd.CommandText = sqlstr.ToString();
                result = mySqlCmd.ExecuteNonQuery();
                //'Writer : (' . $aUser_Data['user_id'] . ')' . $aUser_Data['user_username'] . "\r\n" . $sDescription;
                om.Note_Order = "Writer : " + om.User_Id + " " + om.user_name + "\r\n" + om.Note_Order;
                sqlstr.Clear();
                sqlstr.Append(order_master_status_record(int.Parse(om.Order_Id.ToString()), 90, om.Note_Order, om.Order_Ipfrom));
                mySqlCmd.CommandText = sqlstr.ToString();
                result = mySqlCmd.ExecuteNonQuery();
                sqlstr.Clear();

                for (int i = 0; i < orderSlaveList.Count; i++)
                {
                    sqlstr.Append(modify_order_slave_status(orderSlaveList[i].Slave_Id, 90, om.Order_Ipfrom));
                    sqlstr.Append(order_slave_status_record(orderSlaveList[i].Slave_Id, 90, om.Order_Ipfrom, om.Note_Order));

                    if (Convert.ToInt32(ordermaster.Rows[0]["order_date_pay"]) > 0)//只要付款了就發郵件&& Convert.ToInt32(ordermaster.Rows[0]["order_amount"]) > 0
                    {
                        if (!SendMail.Keys.Contains(orderSlaveList[i].Slave_Id))
                        {
                            SendMail.Add(orderSlaveList[i].Slave_Id, " ");//發郵件給供應商
                        }
                    }

                }
                if (!string.IsNullOrEmpty(sqlstr.ToString()))
                {
                    mySqlCmd.CommandText = sqlstr.ToString();
                    result = mySqlCmd.ExecuteNonQuery();
                    sqlstr.Clear();
                }
                if (orderDetailList.Count > 0)
                {
                    for (int i = 0; i < orderDetailList.Count; i++)
                    {
                        sqlstr.AppendFormat(" set sql_safe_updates=0;update order_detail SET detail_status ='{0}' WHERE detail_id ='{1}';set sql_safe_updates=1; ", 90, orderDetailList[i].Detail_Id);
                    }
                    mySqlCmd.CommandText = sqlstr.ToString();
                    result = mySqlCmd.ExecuteNonQuery();
                    sqlstr.Clear();
                }

                // 回存庫存量
                for (int i = 0; i < orderDetailList.Count; i++)
                {
                    if (orderDetailList[i].item_mode == 1)
                        continue;
                    uint Buy_Num = orderDetailList[i].Buy_Num;
                    if (orderDetailList[i].item_mode == 2)
                    {
                        Buy_Num = orderDetailList[i].Buy_Num * orderDetailList[i].parent_num;
                    }
                    sqlstr.AppendFormat(" set sql_safe_updates=0;UPDATE product_item SET	item_stock = item_stock +'{0}' WHERE	item_id ='{1}';set sql_safe_updates=1;", Buy_Num, orderDetailList[i].Item_Id);

                }
                if (!string.IsNullOrEmpty(sqlstr.ToString()))
                {
                    mySqlCmd.CommandText = sqlstr.ToString();
                    result = mySqlCmd.ExecuteNonQuery();
                    sqlstr.Clear();
                }
                //取回減免數量

                int[] nums = new int[] { 3, 4, 5, 99 };
                bool or_status = nums.Contains(Convert.ToInt32(ordermaster.Rows[0]["order_status"]));
                if (!or_status)
                {
                    sqlstr.AppendFormat(" set sql_safe_updates=0;UPDATE promotions_amount_reduce_member SET order_status = 0 where order_id ='{0}' ;set sql_safe_updates=1;", om.Order_Id);
                    mySqlCmd.CommandText = sqlstr.ToString();
                    result = mySqlCmd.ExecuteNonQuery();
                    sqlstr.Clear();
                }
                int collect_date = string.IsNullOrEmpty(ordermaster.Rows[0]["money_collect_date"].ToString()) ? 0 : Convert.ToInt32(ordermaster.Rows[0]["money_collect_date"]);//付款日期有null的判斷
                if (collect_date > 0 && (Convert.ToInt32(ordermaster.Rows[0]["order_amount"]) > 0 || Convert.ToInt32(ordermaster.Rows[0]["deduct_card_bonus"]) > 0))
                {
                    int Money_Type = 0;
                    if (Convert.ToInt32(ordermaster.Rows[0]["order_amount"]) == 0)
                    {
                        ordermaster.Rows[0]["order_amount"] = ordermaster.Rows[0]["deduct_card_bonus"];
                    }
                    Money_Type = Convert.ToInt32(ordermaster.Rows[0]["order_payment"]);
                    sqlstr.Append(_serialDao.Update(46));
                    sqlstr.Append(" select serial_value from serial where serial_id=31;");
                    sqlstr.Append(" insert into order_money_return(money_id,order_id,money_type,money_total,money_status,money_note,money_source,money_createdate,money_updatedate,money_ipfrom)value( ");
                    sqlstr.AppendFormat("(select serial_value from serial where serial_id=31),'{0}','{1}', ", om.Order_Id, Money_Type);
                    sqlstr.AppendFormat("'{0}','{1}','{2}', ", Convert.ToInt32(ordermaster.Rows[0]["order_amount"]), 0, "");
                    sqlstr.AppendFormat("'{0}','{1}','{2}', ", "order master cancel", CommonFunction.GetPHPTime(DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss")), CommonFunction.GetPHPTime(DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss")));
                    sqlstr.AppendFormat("'{0}'); ", om.Order_Ipfrom);
                    mySqlCmd.CommandText = sqlstr.ToString();
                    result = mySqlCmd.ExecuteNonQuery();
                    sqlstr.Clear();
                    if (accumulated_happygo > 0)
                    {
                        sql.AppendFormat(" select status,order_id from hg_accumulate where order_id='{0}';", om.Order_Id);
                        DataTable _dtHG = _accessMySql.getDataTable(sql.ToString());
                        sql.Clear();
                        if (_dtHG.Rows.Count > 0 && Convert.ToInt32(_dtHG.Rows[0]["status"]) == 0)
                        {
                            sqlstr.AppendFormat(" set sql_safe_updates=0;update hg_accumulate set error_type='{0}',status='{1}' where order_id='{2}';set sql_safe_updates=1;", "", 2, om.Order_Id);
                        }
                        else
                        {
                            sql.AppendFormat(@"select * from hg_deduct where order_id={0} limit 0,1", om.Order_Id);
                            DataTable hg_deduct = _accessMySql.getDataTable(sql.ToString());
                            sql.Clear();
                            if (hg_deduct.Rows.Count > 0)
                            {
                                sqlstr.Append(Deduct_User_Happy_Go(accumulated_happygo, om.Order_Id.ToString(), hg_deduct));
                                mySqlCmd.CommandText = sqlstr.ToString();
                                result = mySqlCmd.ExecuteNonQuery();
                                sqlstr.Clear();
                            }
                            else
                            {
                                return 4;//取得身分證字號失敗
                            }
                        }
                    }
                }
                //回收購物金在外判斷
                if (accumulated_bonus > 0)
                {
                    sqlstr.Append(Deduct_User_Bonus(accumulated_bonus, om.Order_Id.ToString(), ordermaster.Rows[0]["user_id"].ToString()));
                    if (!string.IsNullOrEmpty(sqlstr.ToString()))
                    {
                        mySqlCmd.CommandText = sqlstr.ToString();
                        result = mySqlCmd.ExecuteNonQuery();
                        sqlstr.Clear();
                    }
                }
                //if (Convert.ToInt32(ordermaster.Rows[0]["order_payment"]) == 8 && Convert.ToInt32(ordermaster.Rows[0]["money_collect_date"]) == 0)
                //{
                //    if(accumulated_bonus > 0)
                //    {
                //        sqlstr.Append(Deduct_User_Bonus(accumulated_bonus, om.Order_Id.ToString(), ordermaster.Rows[0]["user_id"].ToString()));
                //        mySqlCmd.CommandText = sqlstr.ToString();
                //        result = mySqlCmd.ExecuteNonQuery();
                //        sqlstr.Clear();
                //    }
                //}
                if (Convert.ToInt32(ordermaster.Rows[0]["order_amount"]) > 0)
                {
                    sqlstr.AppendFormat(" set sql_safe_updates=0;UPDATE order_master SET money_cancel = '{0}' where order_id = '{1}';set sql_safe_updates=1;", Convert.ToInt32(ordermaster.Rows[0]["order_amount"]), om.Order_Id);
                    mySqlCmd.CommandText = sqlstr.ToString();
                    result = mySqlCmd.ExecuteNonQuery();
                    sqlstr.Clear();
                }
                if (Convert.ToInt32(ordermaster.Rows[0]["priority"]) == 1)
                {
                    sqlstr.AppendFormat(" set sql_safe_updates=0;UPDATE order_master SET priority = 0 WHERE	order_id ='{0}';set sql_safe_updates=1;", om.Order_Id);
                    sqlstr.AppendFormat(" set sql_safe_updates=0;UPDATE users SET first_time = 0 WHERE	user_id ='{0}';set sql_safe_updates=1;", Convert.ToInt32(ordermaster.Rows[0]["user_id"]));
                    mySqlCmd.CommandText = sqlstr.ToString();
                    result = mySqlCmd.ExecuteNonQuery();
                    sqlstr.Clear();
                }
                sql.AppendFormat(" select *from user_recommend  where order_id='{0}';", om.Order_Id);
                DataTable _dtrecom = _accessMySql.getDataTable(sql.ToString());
                sql.Clear();
                if (_dtrecom.Rows.Count > 0)
                {
                    sqlstr.AppendFormat(" set sql_safe_updates=0;UPDATE user_recommend SET is_recommend = 0 WHERE	id ='{0}';set sql_safe_updates=1;", Convert.ToInt32(_dtrecom.Rows[0]["id"]));
                    mySqlCmd.CommandText = sqlstr.ToString();
                    result = mySqlCmd.ExecuteNonQuery();
                    sqlstr.Clear();
                }
                if (deduct_happygo > 0)
                {
                    sqlstr.Append(Deduct_Refund(om.Order_Id, 0, 0, deduct_happygo, om.Order_Ipfrom));
                    if (!string.IsNullOrEmpty(sqlstr.ToString().Trim()))
                    {
                        mySqlCmd.CommandText = sqlstr.ToString();
                        result = mySqlCmd.ExecuteNonQuery();
                        sqlstr.Clear();
                    }
                }
                if (Convert.ToInt32(ordermaster.Rows[0]["deduct_bonus"]) > 0)
                {
                    sqlstr.Append(Deduct_Refund(om.Order_Id, Convert.ToInt32(ordermaster.Rows[0]["deduct_bonus"]), 0, 0, om.Order_Ipfrom));
                    mySqlCmd.CommandText = sqlstr.ToString();
                    result = mySqlCmd.ExecuteNonQuery();
                    sqlstr.Clear();
                }
                if (Convert.ToInt32(ordermaster.Rows[0]["deduct_welfare"]) > 0)
                {
                    sqlstr.Append(Deduct_Refund(om.Order_Id, 0, Convert.ToInt32(ordermaster.Rows[0]["deduct_welfare"]), 0, om.Order_Ipfrom));
                    mySqlCmd.CommandText = sqlstr.ToString();
                    result = mySqlCmd.ExecuteNonQuery();
                    sqlstr.Clear();
                }
                sqlstr.AppendFormat(" set sql_safe_updates=0;UPDATE deliver_master SET delivery_status = 6 WHERE	order_id = '{0}' AND type in (1 , 2);set sql_safe_updates=1;", om.Order_Id);
                if (Convert.ToInt32(ordermaster.Rows[0]["deduct_card_bonus"]) > 0)
                {
                    sqlstr.AppendFormat(" set sql_safe_updates=0;UPDATE order_slave set slave_status=90,slave_date_delivery = 0 where order_id = '{0}';set sql_safe_updates=1;", om.Order_Id);
                }
                mySqlCmd.CommandText = sqlstr.ToString();
                result = mySqlCmd.ExecuteNonQuery();
                sqlstr.Clear();
                sqlstr.Append(check_and_modify_flag(om.Order_Id, 3, om.Order_Ipfrom));
                if (!string.IsNullOrEmpty(sqlstr.ToString()))
                {
                    mySqlCmd.CommandText = sqlstr.ToString();
                    result = mySqlCmd.ExecuteNonQuery();
                    sqlstr.Clear();
                }
                 mySqlCmd.Transaction.Commit();
                // mySqlCmd.Transaction.Rollback();

                send_cancel_mail_for_vendor(SendMail);
                return 100;//完成
            }
            catch (Exception ex)
            {
                mySqlCmd.Transaction.Rollback();
                throw new Exception("OrderCancelMasterDao-->ReturnAllOrder-->" + ex.Message, ex);
            }
            finally
            {
                if (mySqlConn != null && mySqlConn.State == System.Data.ConnectionState.Open)
                {
                    mySqlConn.Close();
                }
            }

        }
Пример #7
0
        /***判斷用戶的購物金是否夠扣除*/
        public int returnMsg(OrderMaster om)
        {
            StringBuilder sb = new StringBuilder();
            try
            {
                _bonus = new BonusMasterDao(connString);
                BonusMasterQuery query = new BonusMasterQuery();
                query.master_note = om.Order_Id.ToString();
                query.bonus_type = 1;
                List<BonusMasterQuery> bonusMasterStore = new List<BonusMasterQuery>();
                bonusMasterStore = _bonus.IsExtendBonus(query);

                if (bonusMasterStore.Count > 0)
                {
                    ///用戶購物金
                    sb.AppendFormat("SELECT sum(od.accumulated_bonus) as accumulated_bonus FROM order_detail od,order_slave os WHERE	os.order_id = '{0}'AND	os.slave_id = od.slave_id and od.item_mode<>2; ", om.Order_Id);
                    DataTable _dtbonus = _accessMySql.getDataTable(sb.ToString());
                    sb.Clear();
                    //訂單購物金
                    sb.AppendFormat("select user_id from order_master where order_id='{0}';", om.Order_Id);
                    DataTable _dtUser = _accessMySql.getDataTable(sb.ToString());
                    int deductuser = 0;
                    if (!string.IsNullOrEmpty(_dtUser.Rows[0]["user_id"].ToString()))
                    {
                        deductuser = GetUserBonus(_dtUser.Rows[0]["user_id"].ToString(), 1);
                    }
                    else
                    {
                        return 1;//訂單錯誤!
                    }
                    int orderbonus = string.IsNullOrEmpty(_dtbonus.Rows[0]["accumulated_bonus"].ToString()) ? 0 : Convert.ToInt32(_dtbonus.Rows[0]["accumulated_bonus"]);
                    if (orderbonus > deductuser)
                    {
                        return 99;//消費者購物金餘額不足,無法扣除給予購物金
                    }
                    else
                    {
                        return 100;//不顯示那個信息
                    }
                }
                else
                {
                    return 100;//不顯示那個信息
                }

            }
            catch (Exception ex)
            {
                throw new Exception("OrderCancelMasterDao-->returnMsg" + ex.Message, ex);
            }
        }
Пример #8
0
        public string modify_order_master_status(string order_id, int order_status, string ip)
        {
            StringBuilder sb = new StringBuilder();
            try
            {
                OrderMaster om = new OrderMaster();
                om.Order_Status = uint.Parse(order_status.ToString());
                om.Order_Updatedate = uint.Parse(CommonFunction.GetPHPTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")).ToString());
                om.Order_Ipfrom = ip;
                om.Order_Date_Cancel = 0;
                om.Order_Date_Close = 0;
                if (order_status == 90)
                {
                    om.Order_Date_Cancel = uint.Parse(CommonFunction.GetPHPTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")).ToString());
                }
                else if (order_status == 99)
                {
                    om.Order_Date_Close = uint.Parse(CommonFunction.GetPHPTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")).ToString());
                }
                sb.AppendFormat("set sql_safe_updates=0;update order_master set order_status='{0}',order_updatedate='{1}',order_ipfrom='{2}' ", om.Order_Status, om.Order_Updatedate, om.Order_Ipfrom);
                if (om.Order_Date_Cancel != 0)
                {
                    sb.AppendFormat(" ,order_date_cancel='{0}' ", om.Order_Date_Cancel);
                }
                if (om.Order_Date_Close != 0)
                {
                    sb.AppendFormat(" ,order_date_close='{0}' ", om.Order_Date_Close);
                }
                sb.AppendFormat(" where order_id='{0}';set sql_safe_updates=1; ", order_id);
                return sb.ToString();

            }
            catch (Exception ex)
            {

                throw new Exception("OrderCancelMasterDao-->check_order_process" + ex.Message + sb.ToString(), ex);
            }
        }
Пример #9
0
        public string OrderWaitClick(OrderMasterStatusQuery query)
        {
            string json = "";
            Serial s = new Serial();//流水號
            ArrayList sql = new ArrayList();
            OrderMaster om = new OrderMaster();
            OrderSlave os = new OrderSlave();
            OrderMasterStatusQuery oms = new OrderMasterStatusQuery();
            
            List<OrderSlaveQuery> vendor = new List<OrderSlaveQuery>();
            try
            {
                vendor = _orderSlaveDao.GetVendor(query.order_id);
                if (vendor.Count > 0)
                {
                    uint a = 1;
                    om.Order_Id = query.order_id;
                    om.Order_Status = query.order_status;
                    om.Order_Ipfrom = query.status_ipfrom;
                    //獲取變更order_master.status和付款money的sql
                    sql.Add(_orderMaterDao.UpdateOrderMasterStatus(om));

                    s = _serial.GetSerialById(29);//獲取訂單主檔狀態流水號 
                    sql.Add(_serial.Update(29));//變更流水號+1   
                    query.serial_id = s.Serial_Value+a;
                    //往訂單記錄表插入一條等待付款的狀態數據
                    sql.Add(_orderMaterStatusDao.Insert(query));
                    //
                    foreach (var item in vendor)
                    {
                        os.Slave_Id = item.Slave_Id;
                        os.Slave_Ipfrom = query.status_ipfrom;
                        sql.Add(_orderSlaveDao.UpdOrderSlaveStatus(os));
                        //往order_slave_status表插入數據
                        s = _serial.GetSerialById(31);//獲取slaver狀態表流水號 
                        sql.Add(_serial.Update(31));//變更流水號+1 
                        oms.serial_id = s.Serial_Value + a;
                        oms.slave_id = item.Slave_Id;
                        oms.order_status = query.order_status;
                        oms.status_description = query.status_description;
                        oms.status_ipfrom = query.status_ipfrom;
                        sql.Add(_orderMaterStatusDao.InsertSlave(oms));
                        a++;
                    }
                    if (_mySqlDao.ExcuteSqlsThrowException(sql))
                    {
                        json = "{success:true}";
                    }
                    else
                    {
                        json = "{success:true,msg:2}";//執行sql報錯
                    }   
                }
                else
                {
                    json = "{success:flase,msg:3}";//slave沒有數據
                }
                return json;
            }
            catch (Exception ex)
            {
                throw new Exception("OrderDetailMgr-->OrderWaitClick-->sql:" + sql + ",Message:" + ex.Message, ex);
            }
        }
Пример #10
0
        public bool SelfThingsMethod( DataTable _dtSms ,OrderDeliver query, string Descriptions)
        {
             Description = Descriptions;
           
            StringBuilder sb = new StringBuilder();
            MySqlCommand mySqlCmd = new MySqlCommand();
            MySqlConnection mySqlConn = new MySqlConnection(connStr);
            try
            {
                if (mySqlConn != null && mySqlConn.State == System.Data.ConnectionState.Closed)
                {
                    mySqlConn.Open();
                }
                mySqlCmd.Connection = mySqlConn;
                mySqlCmd.Transaction = mySqlConn.BeginTransaction();
                mySqlCmd.CommandType = System.Data.CommandType.Text;
                sb.AppendFormat(@"select order_id from order_slave  where slave_id='{0}';", query.slave_id);
                mySqlCmd.CommandText = sb.ToString();
                string Order_Id = mySqlCmd.ExecuteScalar().ToString();//--訂單編號,後面會用來修改付款單狀態和查詢訂單流水號詳情
                sb.Clear();

                SerialDao serial = new SerialDao(connStr);
           
                sb.AppendFormat(serial.Update(41));  // 出貨單流水號參考自vendor.gigade100.com/order/orerd_deliver.php第226行
                sb.Append(@"insert into order_deliver(deliver_id,slave_id,deliver_status,deliver_store,deliver_code,deliver_time,deliver_note");
                sb.Append(",deliver_createdate,deliver_updatedate,deliver_ipfrom)value((select serial_value from serial where serial_id=41),");
                sb.AppendFormat(" '{0}','{1}','{2}','{3}','{4}',",query.slave_id,1,query.deliver_store,query.deliver_code,query.deliver_time);
                sb.AppendFormat(" '{0}','{1}',", query.deliver_note, CommonFunction.GetPHPTime(DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")));
                sb.AppendFormat(" '{0}','{1}');", CommonFunction.GetPHPTime(DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")), query.deliver_ipfrom);
                mySqlCmd.CommandText = sb.ToString();
                mySqlCmd.ExecuteNonQuery();
                sb.Clear();
                int[] Product_Mode = { 1 };
                //參考自vendor.gigade100.com/order/orerd_deliver.php第246行
                sb.Append(update_detail_for_product_mode(query.slave_id.ToString(), Product_Mode,query.deliver_time));
                mySqlCmd.CommandText = sb.ToString();
                mySqlCmd.ExecuteNonQuery();
                sb.Clear();
                //參考自vendor.gigade100.com/order/orerd_deliver.php第252行
                string Modify_Master_Order_Status = check_vendor_deliver_order_master_status(Order_Id);
                if (Modify_Master_Order_Status == "false")//參考自(vendor.gigade100.com/order/order_deliver.php第253行方法)
                {
                    mySqlCmd.Transaction.Rollback();
                }

                // 修改付款單狀態參考自(vendor.gigade100.com/order/order_deliver.php第259行方法)
                sb.Append(modify_order_master_status(Order_Id, Modify_Master_Order_Status));
                mySqlCmd.CommandText = sb.ToString();
                mySqlCmd.ExecuteNonQuery();
                sb.Clear();
                // 新增付款單狀態參考自(vendor.gigade100.com/order/order_deliver.php第263行方法)
                sb.Append(order_master_status_record(Order_Id, Modify_Master_Order_Status,Descriptions));
                mySqlCmd.CommandText = sb.ToString();
                mySqlCmd.ExecuteNonQuery();
                sb.Clear();

                // 異動商品明細狀態為已出貨態 參考自(vendor.gigade100.com/order/order_deliver.php第266行方法)
                //簡訊通知
                //參考自(vendor.gigade100.com/order/order_deliver.php第269行方法)
             List<OrderDetailQuery> OrderDetailList=new List<OrderDetailQuery>();
             sb.AppendFormat(@"select item_id,product_name from order_detail where slave_id='{0}';", query.slave_id);
             OrderDetailList = _dbAccess.getDataTableForObj<OrderDetailQuery>(sb.ToString());
             sb.Clear();
             //參考自(vendor.gigade100.com/order/order_deliver.php第281行方法)
             sb.AppendFormat(@"select delivery_mobile from order_master where order_id='{0}';", Order_Id);
             OrderMaster ordermaster = new OrderMaster();
             ordermaster=_dbAccess.getSinggleObj<OrderMaster>(sb.ToString());
             sb.Clear();

                 foreach (var item in OrderDetailList)
                 {//參考自(vendor.gigade100.com/order/order_deliver.php第276行方法)
                     DataRow[] rows = _dtSms.Select("sms_id='" + item.Item_Id + "'");
                     foreach (DataRow row in rows)//篩選出的最多只有一條數據,
                     {
                         if (!string.IsNullOrEmpty(row["sms_id"].ToString()))
                         {
                             string content = "您好,您所訂購的商品 " + item.Product_Name + " 已於今天送出,到貨前會由宅配人員與您確認到貨時段, 謝謝您.吉甲地";
                             sb.AppendFormat(@"insert into sms(type,order_id,mobile,subject,content,estimated_send_time)value(4,'{0}',", Order_Id);
                             sb.AppendFormat(" '{0}','','{1}','{2}');", ordermaster.Delivery_Mobile, content, "00-00-00 00:00:00");
                             mySqlCmd.CommandText = sb.ToString();
                             mySqlCmd.ExecuteNonQuery();
                             sb.Clear();
                             break;
                         }
                     }
                 }
                 //---------------------------------------------這個PHP傳入的是Slave_id那個是錯誤的,但是我先傳入Order_id以便實現現在的功能
                 #region 參考自(vendor.gigade100.com/order/order_deliver.php第364行方法)


                 sb.AppendFormat(@"select user_id,order_name from order_master where order_id='{0}';", Order_Id);
                 ordermaster = _dbAccess.getSinggleObj<OrderMaster>(sb.ToString());
                 sb.Clear();
                 sb.AppendFormat(@"select user_email from users where user_id='{0}';", ordermaster.user_id);
                 Users user = new Users();
                 user = _dbAccess.getSinggleObj<Users>(sb.ToString());
                 sb.Clear();
            //    $aParamenter['s_username']	= $sOrder_Username;-----------------ordermaster.Order_Name;
            //$aParamenter['s_deliver_time']	= $sDeliver_Time;-----------------query.deliver_time
            //$aParamenter['s_deliver_store']	= $aLang['Deliver_Store'][$nDeliver_Store];----------------地圖,需要查詢
            //$aParamenter['s_deliver_code']	= $sDeliver_Code;-------------------query.deliver_code
            //$sFrom_Name			= $amego_config->get_single_config('system_mail_from_name');
            //$sFrom_Email			= $amego_config->get_single_config('system_mail_from_email');
            //$sMailer_Root			= MAIL_TEMPLATE_ROOT;
                 Config conf = new Config();
                 sb.AppendFormat(@"select *from config where config_name='system_mail_from_name';");
                 conf = _dbAccess.getSinggleObj<Config>(sb.ToString());
                 sb.Clear();
                 string From_Name = conf.config_value;//--------------------有了
                 sb.AppendFormat(@"select *from config where config_name='system_mail_from_email';");
                 conf = _dbAccess.getSinggleObj<Config>(sb.ToString());
                 sb.Clear();
                 string From_Email = conf.config_value;//--------------------有了
                 //出貨單通知信_新增
                 int Mailer_Number = 406;
                //----------------------------------下面的不知道怎麼賦值啊!!
                 string Mailer_Root = "";////define('MAIL_TEMPLATE_ROOT',			GIGADE_WWW_DIR . '/mailer/');			// 郵件版型位置,在各實體目錄中的相對位置
                 #endregion




                 mySqlCmd.Transaction.Rollback();
            return true;
            }
            catch (Exception ex)
            {
                mySqlCmd.Transaction.Rollback();
                throw new Exception("OrderDao.SelfThingsMethod -->" + ex.Message + sb.ToString(), ex);
            }
            finally
            {
                if (mySqlConn != null && mySqlConn.State == System.Data.ConnectionState.Open)
                {
                    mySqlConn.Close();
                }
            }

        }
Пример #11
0
        /// <summary>
        /// 更新訂單狀態sql
        /// </summary>
        /// <param name="om"></param>
        /// <returns></returns>
        public string UpdateOrderMasterStatus(OrderMaster om)
        {
            StringBuilder sql = new StringBuilder();

            sql.AppendFormat("set sql_safe_updates = 0; ");
            sql.AppendFormat("UPDATE order_master SET order_date_pay = 0,order_status='{0}',order_updatedate ='{1}',order_ipfrom='{2}' ", om.Order_Status, CommonFunction.GetPHPTime(DateTime.Now.ToString()), om.Order_Ipfrom);
            sql.AppendFormat(" WHERE order_id={0} ; ", om.Order_Id);
            sql.Append(" set sql_safe_updates = 1;");
            try
            {
                return sql.ToString();
            }
            catch (Exception ex)
            {
                throw new Exception("OrderMasterDao-->UpdateOrderMasterStatus-->" + ex.Message + sql.ToString(), ex);
            }
        }
Пример #12
0
        public void Deduct_Refund(OrderMaster om, int deductbonus, int deductcash, int deducthg, OrderReturnMasterQuery query)
        {
            #region 購金
            int expireDay = 90;
            BonusMaster bm = new BonusMaster();
            bm.user_id = om.User_Id;
            bm.type_id = 4;
            bm.bonus_type = 1;
            DateTime master_start = DateTime.Now;
            bm.master_start = Convert.ToUInt32(CommonFunction.GetPHPTime(master_start.ToString("yyyy-MM-dd 00:00:00")));
            bm.master_createdate = Convert.ToUInt32(CommonFunction.GetPHPTime(DateTime.Now.ToString()));
            bm.master_updatedate = Convert.ToUInt32(CommonFunction.GetPHPTime(DateTime.Now.ToString()));
            bm.master_ipfrom = System.Net.Dns.GetHostByName(System.Net.Dns.GetHostName()).AddressList.FirstOrDefault().ToString();
            bm.master_note = om.Order_Id.ToString();
            bm.master_writer = "system";
            if (deductbonus > 0)
            {

                List<VipUserGroup> vipuserLi = _vipuserGroupDao.GetVipUserByOrderId(om.User_Id, 0, 1);
                if (vipuserLi.Count!=0)
                {
                    VipUserGroup vug = vipuserLi.FirstOrDefault();
                    expireDay = vug.bonus_expire_day;
                    om.Accumulated_Bonus = om.Accumulated_Bonus * vug.bonus_rate;
                }
                #region BonusMaster Model
                bm.master_total = Convert.ToUInt32(deductbonus);
                bm.master_balance = Convert.ToInt32(deductbonus);
                DateTime master_end = master_start.AddDays(Convert.ToDouble(expireDay));
                bm.master_end = Convert.ToUInt32(CommonFunction.GetPHPTime(master_end.ToString("yyyy-MM-dd 23:59:59")));
                #endregion
                bm.master_writer = "訂單退貨返還購物金";
                Bonus_Master_Add(bm);
            }
            #endregion
            #region 抵用券
            if (deductcash > 0)
            {
                bm.bonus_type = 2;
                bm.master_total = Convert.ToUInt32(deductcash);
                bm.master_balance = Convert.ToInt32(deductcash);
                DateTime master_end = master_start.AddDays(Convert.ToDouble(expireDay));
                bm.master_end = Convert.ToUInt32(CommonFunction.GetPHPTime(master_end.ToString("yyyy-MM-dd 23:59:59")));
                bm.master_writer = "訂單退貨返還抵用券";
                Bonus_Master_Add(bm);
            }
            #endregion
            #region HG點
            if (deducthg > 0)
            {
                //hg_deduct_reverse(deducthg, om.Order_Id, query);
            }
            #endregion


        }
Пример #13
0
 public void Deduct_User_Bonus(int accumulated_bonus, OrderMaster om)
 {
     StringBuilder sql = new StringBuilder();
     MySqlCommand mySqlCmd = new MySqlCommand();
     SerialDao serialDao = new SerialDao(connStr);
     MySqlConnection mySqlConn = new MySqlConnection(connStr);
     try
     {
         if (mySqlConn != null && mySqlConn.State == System.Data.ConnectionState.Closed)
         {
             mySqlConn.Open();
         }
         mySqlCmd.Connection = mySqlConn;
         mySqlCmd.Transaction = mySqlConn.BeginTransaction();
         mySqlCmd.CommandType = System.Data.CommandType.Text;
         int userbonus = GetUserBonus(om.User_Id, 1);
         if (userbonus >= accumulated_bonus)
         {
             string ip = System.Net.Dns.GetHostByName(System.Net.Dns.GetHostName()).AddressList.FirstOrDefault().ToString();
             mySqlCmd.CommandText = CheckBonusTypeExist(32);//32代表 退貨產生的購物金
             //判斷type_id是否存在
             if (mySqlCmd.ExecuteScalar().ToString() == null)
             {
                 mySqlCmd.Transaction.Rollback();
             }
             int bonusnum = accumulated_bonus;
             // 會員目前可用購物金
             if (bonusnum < 0)
             {
                 bonusnum = bonusnum * -1;
             }
             if (bonusnum > userbonus)
             {
                 mySqlCmd.Transaction.Rollback();
             }
             // 找出目前可用購物金,以到期日排序
             List<BonusMaster> bmList = QueryBonusById(om.User_Id);
             foreach (var item in bmList)
             {
                 if (bonusnum > 0)
                 {
                     // 記錄點數數量
                     int tempNum = bonusnum > item.master_balance ? item.master_balance : bonusnum;
                     // 取得下一個流水號
                     mySqlCmd.CommandText = serialDao.Update(28);//28 // 購物金使用記錄流水號
                     BonusRecord brModel = new BonusRecord();
                     brModel.record_id = Convert.ToUInt32(mySqlCmd.ExecuteScalar());
                     brModel.master_id = item.master_id;
                     brModel.type_id = 32;
                     brModel.order_id = om.Order_Id;
                     brModel.record_ipfrom = ip;
                     brModel.record_use = uint.Parse(tempNum.ToString());
                     // 更新購物金結餘
                     mySqlCmd.CommandText += UpdateBonusMaster(tempNum, item.master_id);
                     bonusnum -= tempNum;
                 }
                 else
                 {
                     break;
                 }
             }
         }
         else
         {
             sql.AppendFormat(" insert into  users_deduct_bonus (deduct_bonus,user_id,createdate,order_id) values ('{0}','{1}','{2}','{3}');",
               accumulated_bonus, om.User_Id, CommonFunction.GetPHPTime(DateTime.Now.ToString()), om.Order_Id);
             mySqlCmd.CommandText += sql;
            
         }
         mySqlCmd.ExecuteNonQuery();
         mySqlCmd.Transaction.Commit();
     }
     catch (Exception ex)
     {
         mySqlCmd.Transaction.Rollback();
         throw new Exception("OrderReturnStatusDao-->Deduct_User_Bonus-->" + ex.Message, ex);
     }
     finally
     {
         if (mySqlConn != null && mySqlConn.State == System.Data.ConnectionState.Open)
         {
             mySqlConn.Close();
         }
     }
 }
Пример #14
0
        public HttpResponseBase OrderSave()
        {
            int orderType = Request.UrlReferrer.AbsolutePath == "/Order/InteriorOrderAdd" ? 2 : 1;//訂單類型,:1為普通訂單輸入,2為內部訂單輸入
            string jsonStr = "{success:false,msg:'" + Resources.OrderAdd.ORDER_ADD_FAIL + "'}";
            try
            {
                Caller _caller = (Session["caller"] as Caller);

                uint normalFright = 0, lowFright = 0, receipt_to = 0, productTotalPrice = 0, combChannelId = 0, combPayMent = 0, combStoreMode = 0, combOrderStatus = 0, storeType = 0, retrieve_mode = 0;
                string combOrderDate = "", combLatestDeliverDate = "", txtAdminNote = "", txtCartNote = "", txtTradeNumber = "", txtOrderId = "", txtDeliverNumber = "";
                uint.TryParse(Request.Params["retrieve_mode"] ?? "0", out retrieve_mode);
                uint.TryParse(Request.Params["receipt_to"] ?? "0", out receipt_to);
                uint.TryParse(Request.Params["normalFright"] ?? "0", out normalFright);
                uint.TryParse(Request.Params["lowFright"] ?? "0", out lowFright);
                uint.TryParse(Request.Params["comboPrice"] ?? "0", out productTotalPrice);
                uint.TryParse(Request.Params["combChannelId"] ?? "0", out combChannelId);
                uint.TryParse(Request.Params["combPayMent"] ?? "0", out combPayMent);//付款方式
                uint.TryParse(Request.Params["combStoreMode"] ?? "0", out combStoreMode);
                uint.TryParse(Request.Params["combOrderStatus"] ?? "0", out combOrderStatus);//訂單狀態
                uint.TryParse(Request.Params["storeType"] ?? "0", out storeType);

                combOrderDate = Request.Params["combOrderDate"];
                //txtOrderDateHour = Request.Params["txtOrderDateHour"];
                //txtOrderDateMinute = Request.Params["txtOrderDateMinute"];
                combLatestDeliverDate = Request.Params["combLatestDeliverDate"];
                txtAdminNote = Request.Params["txtareAdminNote"];
                txtCartNote = Request.Params["txtareCartNote"];
                txtTradeNumber = Request.Params["txtTradeNumber"];
                txtOrderId = Request.Params["txtOrderId"];
                txtDeliverNumber = Request.Params["txtDeliverNumber"];
                //combOrderDate += " " + txtOrderDateHour + ":" + txtOrderDateMinute;

                if (!string.IsNullOrEmpty(txtAdminNote))
                {
                    txtAdminNote = Resources.OrderAdd.NOTE + ":" + txtAdminNote;
                }

                #region 訂購人信息
                string b_txtName = "", b_txtMobil = "", b_txtPhoneHead = "", b_txtPhoneContent = "", b_txtAddress = "";
                uint b_combZip = 0;
                b_txtName = Request.Params["b_txtName"];
                b_txtMobil = Request.Params["b_txtMobel"];
                b_txtPhoneHead = Request.Params["b_txtPhoneHead"];
                b_txtPhoneContent = Request.Params["b_txtPhoneContent"];
                b_txtAddress = Request.Params["b_txtAddress"];
                uint.TryParse(Request.Params["b_combZip"] ?? "0", out b_combZip);
                #endregion

                #region 收件人信息
                string r_txtCNFullName = "", r_txtActionPhone = "", r_txtContactPhoneHead = "", r_txtContactPhoneContent = "", r_txtContactAddress = "";
                uint r_combZip = 0;
                r_txtCNFullName = Request.Params["r_txtCNFullName"];
                r_txtActionPhone = Request.Params["r_txtActionPhone"];
                r_txtContactPhoneHead = Request.Params["r_txtContactPhoneHead"];
                r_txtContactPhoneContent = Request.Params["r_txtContactPhoneContent"];
                r_txtContactAddress = Request.Params["r_txtContactAddress"];
                uint.TryParse(Request.Params["r_combZip"] ?? "0", out r_combZip);
                #endregion

                string dataStr = Request.Params["gridData"];

                OrderAddCustom odc = new OrderAddCustom();
                JavaScriptSerializer jss = new JavaScriptSerializer();

                List<OrderAddCustom> errorOrder = new List<OrderAddCustom>();
                List<CooperatorOrderCustom> coopErrorList = new List<CooperatorOrderCustom>();
                //添加總和 抵用金 和 購物金  add by zhuoqin0830w
                uint productTotal = 0, deduct_bonusTotal = 0, deduct_welfareTotal = 0, acc_bonusTotal = 0;

                OrderImportMgr orderImportMgr = new OrderImportMgr(connectionString, 0);
                Resource.CoreMessage = new CoreResource("OrderImport");
                List<OrderSlave> slaves = new List<OrderSlave>();
                List<ChannelOrder> channelList = new List<ChannelOrder>();
                //add by zhuoqin0830w  2015/02/26  公關單與報廢單功能  獲取前臺傳來的單據類型
                string billtype = orderType == 1 ? "" : Request.Form["BillType"];
                string dep = orderType == 1 ? "" : Request.Form["dep"];
                //獲取前臺傳來 的 Cart_Delivery 和 Site_Id  add by zhuoqin0830w  2015/07/03
                uint Cart_Delivery = uint.Parse(Request.Params["Cart_Delivery"]);
                uint Site_Id = orderType == 1 ? 0 : uint.Parse(Request.Form["Site_Id"]);

                switch (storeType)
                {
                    case 1:
                        #region 合作外站新增訂單
                        List<CooperatorOrderCustom> odcList1 = jss.Deserialize<List<CooperatorOrderCustom>>(dataStr);
                        IPriceMasterImplMgr _priceMgr = new PriceMasterMgr(connectionString);
                        var parentList1 = from rec in odcList1 where rec.parent_id == "0" && rec.Item_Id == 0 select rec;//rec.price_type!=2:各自定價的價格是從表中讀取的,所以到後臺不需要重新計算價格
                        var singleList1 = from rec in odcList1 where rec.Item_Id != 0 && rec.parent_id == "0" select rec;

                        foreach (var item in parentList1)
                        {
                            var totalPrice = item.Event_Item_Money == 0 ? item.product_cost : item.Event_Item_Money;//add by zhuoqin0830w 2015/12/02  判斷是否使用活動價
                            productTotal += uint.Parse((totalPrice * item.buynum).ToString());

                            productItemMapMgr = new ProductItemMapMgr(connectionString);
                            ProductItemMap pMap = productItemMapMgr.QueryAll(new ProductItemMap { channel_id = uint.Parse(combChannelId.ToString()), channel_detail_id = item.coop_product_id }).FirstOrDefault();

                            PriceMaster pMaster = _priceMgr.QueryPriceMaster(new PriceMaster
                            {
                                product_id = uint.Parse(pMap.product_id.ToString()),
                                //user_id = 0,
                                //user_level = 1,
                                //site_id = 1,
                                price_master_id = pMap.price_master_id,
                                child_id = int.Parse(pMap.product_id.ToString())
                            });
                            odcList1.Find(rec => rec.Product_Id == item.Product_Id && rec.group_id == item.group_id).price_master_id = pMaster.price_master_id;

                            ////查找該父商品下的子商品
                            var childList = from rec in odcList1 where rec.parent_id == item.coop_product_id select rec;
                            foreach (var child in childList)
                            {
                                IItemPriceImplMgr iPMgr = new ItemPriceMgr(connectionString);
                                PriceMaster query = new PriceMaster { user_id = pMaster.user_id, user_level = pMaster.user_level, site_id = pMaster.site_id };
                                if (item.price_type == 1)
                                {
                                    query.product_id = uint.Parse(child.coop_product_id);
                                    query.child_id = 0;
                                }
                                else if (item.price_type == 2)
                                {
                                    query.product_id = uint.Parse(pMap.product_id.ToString());
                                    query.child_id = int.Parse(child.coop_product_id);
                                }
                                PriceMaster pM = _priceMgr.QueryPriceMaster(query);
                                List<ItemPriceCustom> ipList = new List<ItemPriceCustom>();
                                if (pM != null)
                                {
                                    odcList1.Find(rec => rec.coop_product_id == child.coop_product_id && rec.group_id == child.group_id).price_master_id = pM.price_master_id;
                                    ipList = iPMgr.Query(new ItemPrice
                                    {
                                        item_id = child.Item_Id,
                                        price_master_id = pM.price_master_id
                                    });
                                    if ((item.price_type == 1 && pM.same_price == 1) || (item.price_type == 2 && pMaster.same_price == 1))
                                    {
                                        odcList1.Find(rec => rec.coop_product_id == child.coop_product_id && rec.group_id == child.group_id).Item_Money = uint.Parse(pM.price.ToString());
                                        //odcList1.Find(rec => rec.coop_product_id == child.coop_product_id && rec.group_id == child.group_id).Item_Cost = uint.Parse(pM.cost.ToString());
                                        odcList1.Find(rec => rec.coop_product_id == child.coop_product_id && rec.group_id == child.group_id).Event_Item_Cost = uint.Parse(pM.event_cost.ToString());
                                    }
                                    else
                                    {
                                        odcList1.Find(rec => rec.coop_product_id == child.coop_product_id && rec.group_id == child.group_id).Item_Money = ipList[0].item_money;
                                        //odcList1.Find(rec => rec.coop_product_id == child.coop_product_id && rec.group_id == child.group_id).Item_Cost = ipList[0].item_cost;
                                        odcList1.Find(rec => rec.coop_product_id == child.coop_product_id && rec.group_id == child.group_id).Event_Item_Cost = ipList[0].event_cost;
                                    }
                                }

                            }
                        }
                        //單一商品
                        #region Channel_Order 資料
                        ChannelOrder chOrd;
                        foreach (CooperatorOrderCustom coop in odcList1)
                        {
                            ChannelOrder existChl = channelList.Where(m => m.Channel_Detail_Id == coop.coop_product_id).FirstOrDefault();
                            if (existChl != null)
                            {
                                continue;
                            }
                            chOrd = new ChannelOrder();
                            chOrd.Channel_Detail_Id = coop.coop_product_id;
                            chOrd.Channel_Id = int.Parse(combChannelId.ToString());
                            chOrd.Createtime = DateTime.Now;
                            if (!string.IsNullOrEmpty(combOrderDate))
                            {
                                chOrd.Ordertime = Convert.ToDateTime(combOrderDate);
                            }
                            chOrd.Order_Id = txtTradeNumber;
                            if (!string.IsNullOrEmpty(combLatestDeliverDate))
                            {
                                chOrd.Latest_Deliver_Date = Convert.ToDateTime(combLatestDeliverDate);
                            }
                            chOrd.Dispatch_Seq = txtDeliverNumber;
                            channelList.Add(chOrd);
                        }
                        #endregion

                        slaves = orderImportMgr.FillSlaveCooperator(odcList1, coopErrorList, combChannelId, combOrderStatus, txtOrderId);

                        foreach (var item in singleList1)
                        {
                            var totalPrice = item.Event_Item_Money == 0 ? item.product_cost : item.Event_Item_Money;//add by zhuoqin0830w 2015/12/02  判斷是否使用活動價
                            productTotal += uint.Parse((totalPrice * item.buynum).ToString());
                        }
                        #endregion
                        break;
                    case 2:     //Gigade新增訂單
                        List<OrderAddCustom> odcList2 = jss.Deserialize<List<OrderAddCustom>>(dataStr);
                        //將前臺傳來的 Site_Id 的值傳入到後臺 并插入數據庫  add by zhuoqin0830w  2015/07/03
                        odcList2.ForEach(m =>
                        {
                            m.Site_Id = Site_Id;
                        });

                        if (orderType == 1)
                        {
                            #region 重新計算組合商品價格
                            IPriceMasterImplMgr priceMgr = new PriceMasterMgr(connectionString);

                            var parentList = from rec in odcList2 where rec.parent_id == 0 && rec.Item_Id == 0 && rec.price_type != 2 select rec;  //rec.price_type!=2:各自定價的價格是從表中讀取的,所以到後臺不需要重新計算價格

                            var singleList = from rec in odcList2 where rec.Item_Id != 0 && rec.parent_id == 0 select rec;

                            var priceSelfList = from rec in odcList2 where rec.Item_Id == 0 && rec.parent_id == 0 && rec.price_type == 2 select rec;

                            //單一商品計算價格
                            foreach (var item in singleList)
                            {
                                //使 總價  減去 抵用金 和 購物金  edit by zhuoqin0830w  2015/05/14
                                var totalPrice = item.Event_Item_Money == 0 ? item.product_cost : item.Event_Item_Money;//add by zhuoqin0830w 2015/12/02  判斷是否使用活動價
                                productTotal += uint.Parse((totalPrice * item.buynum - item.deduct_bonus - item.deduct_welfare).ToString());
                                // 計算 購物金 和 抵用金  的 總和  add by zhuoqin0830w  2015/05/14
                                deduct_bonusTotal += uint.Parse(item.deduct_bonus.ToString());
                                deduct_welfareTotal += uint.Parse(item.deduct_welfare.ToString());
                                PriceMaster pM = priceMgr.QueryPriceMaster(new PriceMaster
                                {
                                    product_id = uint.Parse(item.Product_Id.ToString()),
                                    user_id = 0,
                                    user_level = 1,
                                    site_id = Site_Id,
                                    child_id = 0
                                });
                                if (pM != null)
                                {
                                    odcList2.Find(rec => rec.Product_Id == item.Product_Id).price_master_id = pM.price_master_id;
                                }
                            }

                            //組合商品各自定價計算價格
                            foreach (var item in priceSelfList)
                            {
                                //使 總價  減去 抵用金 和 購物金  edit by zhuoqin0830w  2015/05/14
                                var totalPrice = item.Event_Item_Money == 0 ? item.product_cost : item.Event_Item_Money;//add by zhuoqin0830w 2015/12/02  判斷是否使用活動價
                                productTotal += uint.Parse((totalPrice * item.buynum - item.deduct_bonus - item.deduct_welfare).ToString());

                                // 計算 購物金 和 抵用金  的 總和  add by zhuoqin0830w  2015/05/14
                                deduct_bonusTotal += uint.Parse(item.deduct_bonus.ToString());
                                deduct_welfareTotal += uint.Parse(item.deduct_welfare.ToString());

                                PriceMaster pM = priceMgr.QueryPriceMaster(new PriceMaster { product_id = item.Product_Id, user_id = 0, user_level = 1, site_id = 1, child_id = Convert.ToInt32(item.Product_Id) });
                                if (pM != null)
                                {
                                    odcList2.Find(rec => rec.Product_Id == item.Product_Id && rec.group_id == item.group_id).price_master_id = pM.price_master_id;
                                }
                                //找出當前父商品的子商品
                                var childList = from rec in odcList2 where rec.parent_id == item.Product_Id && rec.group_id == item.group_id select rec;
                                foreach (var child in childList)
                                {
                                    pM = priceMgr.QueryPriceMaster(new PriceMaster { product_id = item.Product_Id, user_id = 0, user_level = 1, site_id = 1, child_id = Convert.ToInt32(child.Product_Id) });
                                    if (pM != null)
                                    {
                                        IItemPriceImplMgr iPMgr = new ItemPriceMgr(connectionString);
                                        ItemPrice price = iPMgr.Query(new ItemPrice { item_id = child.Item_Id, price_master_id = pM.price_master_id }).FirstOrDefault();
                                        if (price != null)
                                        {
                                            odcList2.Find(rec => rec.Product_Id == child.Product_Id && rec.group_id == item.group_id).Item_Cost = price.item_cost;       //成本
                                            odcList2.Find(rec => rec.Product_Id == child.Product_Id && rec.group_id == item.group_id).Event_Item_Cost = price.event_cost;//活動成本
                                            odcList2.Find(rec => rec.Product_Id == child.Product_Id && rec.group_id == item.group_id).Item_Money = price.item_money;//售價
                                        }
                                    }
                                }
                            }

                            //組合商品按比例拆分計算價格
                            foreach (var item in parentList)
                            {
                                var TotalPrice = 0.0;
                                var TotalCost = 0.0;
                                //使 總價  減去 抵用金 和 購物金  edit by zhuoqin0830w  2015/05/14
                                var totalPrice = item.Event_Item_Money == 0 ? item.product_cost : item.Event_Item_Money;//add by zhuoqin0830w 2015/12/02  判斷是否使用活動價
                                productTotal += uint.Parse((totalPrice * item.buynum - item.deduct_bonus - item.deduct_welfare).ToString());

                                // 計算 購物金 和 抵用金  的 總和  add by zhuoqin0830w  2015/05/14
                                deduct_bonusTotal += uint.Parse(item.deduct_bonus.ToString());
                                deduct_welfareTotal += uint.Parse(item.deduct_welfare.ToString());

                                PriceMaster pMaster = priceMgr.QueryPriceMaster(new PriceMaster
                                {
                                    product_id = uint.Parse(item.Product_Id.ToString()),
                                    user_id = 0,
                                    user_level = 1,
                                    site_id = Site_Id,
                                    child_id = int.Parse(item.Product_Id.ToString())
                                });
                                odcList2.Find(rec => rec.Product_Id == item.Product_Id && rec.group_id == item.group_id).price_master_id = pMaster.price_master_id;

                                //找出當前父商品的子商品
                                var childList = from rec in odcList2 where rec.parent_id == item.Product_Id && rec.group_id == item.group_id select rec;

                                var parentPrice = item.product_cost;
                                var parentCost = pMaster != null ? pMaster.cost : 0;

                                //子商品總價
                                foreach (var child in childList)
                                {
                                    //價格
                                    IItemPriceImplMgr iPMgr = new ItemPriceMgr(connectionString);

                                    PriceMaster pM = priceMgr.QueryPriceMaster(new PriceMaster
                                    {
                                        product_id = uint.Parse(child.Product_Id.ToString()),
                                        user_id = 0,
                                        user_level = 1,
                                        site_id = Site_Id,
                                        child_id = 0
                                    });
                                    List<ItemPriceCustom> ipList = new List<ItemPriceCustom>();
                                    if (pM != null)
                                    {
                                        //必購數量
                                        _prodCombMgr = new ProductComboMgr(connectionString);
                                        List<ProductComboCustom> prodComList = _prodCombMgr.combQuery(new ProductComboCustom
                                        {
                                            Parent_Id = int.Parse(item.Product_Id.ToString()),
                                            Child_Id = child.Product_Id.ToString() //add by wangwei02016w 2014/9/24 
                                        });
                                        var s_must_buy = prodComList[0].S_Must_Buy == 0 ? child.s_must_buy : prodComList[0].S_Must_Buy;

                                        if (pM.same_price == 1)//同價
                                        {
                                            TotalPrice += pM.price * s_must_buy;
                                            TotalCost += pM.cost * s_must_buy;
                                        }
                                        else
                                        {
                                            ipList = iPMgr.Query(new ItemPrice
                                            {
                                                item_id = child.Item_Id,
                                                price_master_id = pM.price_master_id
                                            });

                                            if (ipList.Count != 0)
                                            {
                                                TotalPrice += ipList[0].item_money * s_must_buy;
                                                TotalCost += ipList[0].item_cost * s_must_buy;
                                            }
                                        }
                                    }
                                }

                                //子商品按比例拆分后的價格
                                foreach (var child in childList)
                                {
                                    _prodCombMgr = new ProductComboMgr(connectionString);
                                    List<ProductComboCustom> prodComList = _prodCombMgr.combQuery(new ProductComboCustom
                                    {
                                        Parent_Id = int.Parse(item.Product_Id.ToString()),
                                        Child_Id = child.Product_Id.ToString() //add by wangwei02016w 2014/9/24 
                                    });
                                    var s_must_buy = prodComList[0].S_Must_Buy == 0 ? child.s_must_buy : prodComList[0].S_Must_Buy;

                                    IItemPriceImplMgr iPMgr = new ItemPriceMgr(connectionString);

                                    PriceMaster pM = priceMgr.QueryPriceMaster(new PriceMaster
                                    {
                                        product_id = uint.Parse(child.Product_Id.ToString()),
                                        user_id = 0,
                                        user_level = 1,
                                        site_id = Site_Id,
                                        child_id = 0
                                    });
                                    List<ItemPriceCustom> ipList = new List<ItemPriceCustom>();
                                    if (pM != null)
                                    {
                                        odcList2.Find(rec => rec.Product_Id == child.Product_Id && rec.group_id == item.group_id).price_master_id = pM.price_master_id;
                                        if (pM.same_price == 1)
                                        {
                                            odcList2.Find(rec => rec.Product_Id == child.Product_Id && rec.group_id == item.group_id).Item_Cost = uint.Parse(pM.cost.ToString());       //成本
                                            odcList2.Find(rec => rec.Product_Id == child.Product_Id && rec.group_id == item.group_id).Event_Item_Cost = uint.Parse(pM.event_cost.ToString());//活動成本

                                            var afterPrice = 0;
                                            var afterCost = 0;
                                            if (TotalPrice <= 0)
                                            {
                                                afterPrice = 0;
                                            }
                                            else
                                            {
                                                afterPrice = Convert.ToInt16(Math.Round(parentPrice * (Convert.ToDouble(pM.price * s_must_buy) / TotalPrice / s_must_buy)));
                                            }
                                            if (TotalCost <= 0)
                                            {
                                                afterCost = 0;
                                            }
                                            else
                                            {
                                                afterCost = Convert.ToInt16(Math.Round(parentCost * (Convert.ToDouble(pM.cost * s_must_buy) / TotalCost / s_must_buy)));
                                            }

                                            //var singleTotal = afterPrice * s_must_buy;
                                            var singleTotal = afterPrice;
                                            parentPrice -= uint.Parse(singleTotal.ToString());
                                            TotalPrice -= Convert.ToDouble(pM.price) * s_must_buy;
                                            odcList2.Find(rec => rec.Product_Id == child.Product_Id && rec.group_id == item.group_id).product_cost = uint.Parse(afterPrice.ToString());

                                            //var singleCostTotal = afterCost * s_must_buy;
                                            var singleCostTotal = afterCost;
                                            parentCost -= singleCostTotal;
                                            TotalCost -= Convert.ToDouble(pM.cost) * s_must_buy;
                                            odcList2.Find(rec => rec.Product_Id == child.Product_Id && rec.group_id == item.group_id).Item_Cost = uint.Parse(afterCost.ToString());
                                        }
                                        else
                                        {
                                            ipList = iPMgr.Query(new ItemPrice { item_id = child.Item_Id, price_master_id = pM.price_master_id });
                                            if (ipList.Count != 0)
                                            {
                                                odcList2.Find(rec => rec.Product_Id == child.Product_Id && rec.group_id == item.group_id).Item_Cost = ipList[0].item_cost;       //成本
                                                odcList2.Find(rec => rec.Product_Id == child.Product_Id && rec.group_id == item.group_id).Event_Item_Cost = ipList[0].event_cost;//活動成本

                                                //var afterPrice = CommonFunction.Math4Cut5Plus(parentPrice * ipList[0].item_money * s_must_buy / TotalPrice / s_must_buy);
                                                //beforePrice += afterPrice * s_must_buy;

                                                //new logic
                                                var afterPrice = 0;
                                                var afterCost = 0;
                                                if (TotalPrice <= 0)
                                                {
                                                    afterPrice = 0;
                                                }
                                                else
                                                {
                                                    afterPrice = Convert.ToInt16(Math.Round(parentPrice * (Convert.ToDouble(ipList[0].item_money * s_must_buy) / TotalPrice / s_must_buy)));

                                                }

                                                if (TotalCost <= 0)
                                                {
                                                    afterCost = 0;
                                                }
                                                else
                                                {
                                                    afterCost = Convert.ToInt16(Math.Round(parentCost * (Convert.ToDouble(ipList[0].item_cost * s_must_buy) / TotalCost / s_must_buy)));
                                                }

                                                //var singleTotal = afterPrice * s_must_buy;
                                                var singleTotal = afterPrice;
                                                parentPrice -= uint.Parse(singleTotal.ToString());
                                                TotalPrice -= Convert.ToDouble(ipList[0].item_money) * s_must_buy;
                                                // beforePrice += singleTotal;

                                                //var singleCostTotal = afterCost * s_must_buy;
                                                var singleCostTotal = afterCost;
                                                parentCost -= singleCostTotal;
                                                TotalCost -= Convert.ToDouble(ipList[0].item_cost) * s_must_buy;
                                                odcList2.Find(rec => rec.Product_Id == child.Product_Id && rec.group_id == item.group_id).product_cost = uint.Parse(afterPrice.ToString());
                                                odcList2.Find(rec => rec.Product_Id == child.Product_Id && rec.group_id == item.group_id).Item_Cost = uint.Parse(afterCost.ToString());
                                                odcList2.Find(rec => rec.Product_Id == child.Product_Id && rec.group_id == item.group_id).s_must_buy = s_must_buy;
                                            }
                                        }
                                    }

                                }
                            }
                            #endregion
                        }
                        else
                        {
                            foreach (var item in odcList2.FindAll(m => (m.parent_id == 0 && m.Item_Id == 0) || (m.Item_Id != 0 && m.parent_id == 0)))
                            {
                                //使 總價  減去 抵用金 和 購物金  edit by zhuoqin0830w  2015/05/14
                                var totalPrice = item.Event_Item_Money == 0 ? item.product_cost : item.Event_Item_Money;//add by zhuoqin0830w 2015/12/02  判斷是否使用活動價
                                productTotal += uint.Parse((totalPrice * item.buynum - item.deduct_bonus - item.deduct_welfare).ToString());
                                // 計算 購物金 和 抵用金  的 總和  add by zhuoqin0830w  2015/05/14
                                deduct_bonusTotal += uint.Parse(item.deduct_bonus.ToString());
                                deduct_welfareTotal += uint.Parse(item.deduct_welfare.ToString());
                                acc_bonusTotal += uint.Parse(item.accumulated_bonus.ToString());
                            }
                        }

                        slaves = orderImportMgr.FillSlave(odcList2, errorOrder, combOrderStatus, txtOrderId);
                        break;
                    default:
                        break;
                }

                if (slaves != null && errorOrder.Count() == 0 && coopErrorList.Count() == 0)
                {
                    channelMgr = new ChannelMgr(connectionString);

                    #region OrderMaster 信息
                    #region receipt_to 發票開立方式
                    switch (receipt_to)
                    {
                        case 1: receipt_to = 2; break;
                        case 2: receipt_to = 0; break;
                        case 3: receipt_to = 2; break;
                    }
                    #endregion

                    #region retrieve_mode 取貨方式
                    channelShipMgr = new ChannelShippingMgr(connectionString);
                    ChannelShipping chip = new ChannelShipping();
                    chip.channel_id = int.Parse(combChannelId.ToString());
                    chip.shipping_carrior = int.Parse(combStoreMode.ToString());
                    retrieve_mode = uint.Parse(channelShipMgr.Query(chip)[0].retrieve_mode.ToString());
                    #endregion

                    OrderMaster ordermaster = new OrderMaster();
                    //ordermaster.Order_Id = Convert.ToUInt32(orderImportMgr.NextOrderId());
                    ordermaster.Channel_Order_Id = txtTradeNumber;
                    ordermaster.Invoice_Status = receipt_to;
                    ordermaster.Order_Freight_Normal = normalFright;
                    ordermaster.Order_Freight_Low = lowFright;
                    ordermaster.Delivery_Store = combStoreMode;
                    ordermaster.Channel = combChannelId;
                    ordermaster.Order_Status = combOrderStatus;
                    //orderType=2為内部订单输入 edit by xiangwang0413w 2014/10/29
                    ordermaster.User_Id = (orderType == 1) ? (uint)channelMgr.GetUserIdByChannelId((int)combChannelId) : uint.Parse(Request.Params["userId"]);//订单人的user_id
                    ordermaster.Order_Product_Subtotal = productTotal;
                    ordermaster.Order_Amount = productTotal + normalFright + lowFright;
                    ordermaster.Order_Payment = combPayMent;
                    //向 order_master 裱中 添加 從前臺獲取的 Cart_Delivery  edit by zhuoqin0830w  2015/07/03
                    ordermaster.Cart_Id = Cart_Delivery;
                    ordermaster.Note_Admin = string.Format(Resources.OrderAdd.NOTE_CONTENT, _caller.user_username, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), txtAdminNote);
                    ordermaster.Note_Order = txtCartNote;
                    ordermaster.Order_Date_Pay = Convert.ToUInt32(BLL.gigade.Common.CommonFunction.GetPHPTime());
                    ordermaster.Order_Createdate = Convert.ToUInt32(BLL.gigade.Common.CommonFunction.GetPHPTime(combOrderDate));
                    ordermaster.Import_Time = DateTime.Now;
                    ordermaster.Retrieve_Mode = retrieve_mode;
                    //向 order_master 裱中 添加 抵用金 和 購物金  add by zhuoqin0830w  2015/05/14
                    ordermaster.Deduct_Welfare = deduct_welfareTotal;
                    ordermaster.Deduct_Bonus = deduct_bonusTotal;
                    //向 order_master 表中 添加 返還購物金  add by zhuoqin0830w  2015/09/01
                    ordermaster.Accumulated_Bonus = (int)acc_bonusTotal;
                    #endregion

                    #region 出貨時間
                    if (orderType == 2)//內部訂單輸入
                    {
                        ordermaster.Holiday_Deliver = Convert.ToInt32(Request.Form["HolidayDeliver"]);
                        ordermaster.Estimated_Arrival_Period = Convert.ToInt32(Request.Form["EstimatedArrivalPeriod"]);
                    }
                    #endregion

                    #region 訂購人信息
                    ordermaster.Order_Name = b_txtName;
                    ordermaster.Order_Mobile = b_txtMobil;
                    b_txtPhoneHead = !string.IsNullOrEmpty(b_txtPhoneHead) ? b_txtPhoneHead + "-" : b_txtPhoneHead;
                    ordermaster.Order_Phone = b_txtPhoneHead + b_txtPhoneContent;
                    ordermaster.Order_Zip = b_combZip;
                    ordermaster.Order_Address = b_txtAddress;
                    ordermaster.Order_Gender = Request.Params["ServiceSex"] == "1" ? true : false; //add by wwei0216w 2015/1/21 訂購人性別
                    #endregion

                    #region 收件人信息
                    ordermaster.Delivery_Name = r_txtCNFullName;
                    ordermaster.Delivery_Mobile = r_txtActionPhone;
                    ordermaster.Delivery_Phone = r_txtContactPhoneHead + "-" + r_txtContactPhoneContent;
                    ordermaster.Delivery_Zip = r_combZip;
                    ordermaster.Delivery_Address = r_txtContactAddress;
                    ordermaster.Delivery_Gender = Request.Params["AddresseeSex"] == "1" ? true : false; //add by wwei0216w 收件人性別
                    #endregion

                    #region add by zhuoqin0830w  2015/02/26  公關單與報廢單功能   判斷單據類型是否為空值 如果不為空則執行添加功能
                    OrderMasterPattern op = null;
                    if (!string.IsNullOrEmpty(billtype))
                    {
                        op = new OrderMasterPattern { Pattern = int.Parse(billtype), Dep = int.Parse(dep) };
                    }
                    #endregion

                    #region add by zhuoqin0830w 2015/08/24  在內部訂單輸入時 同時將 輸入的 購物金 和 返還購物金 以及 抵用券 添加至 bonus_master 和 bonus_record 表中
                    BonusMaster bm = null; BonusRecord brBonus = null; BonusRecord brWelfare = null;
                    //判斷返還購物金 是否 大於0 如果大於 0 表示需要在 bonus_master 新增一筆數據 
                    if (acc_bonusTotal > 0)
                    {
                        bm = new BonusMaster
                        {
                            user_id = ordermaster.User_Id,
                            type_id = 30,// 默認為 商品回饋購物金
                            master_writer = "商品回饋購物金",
                            master_total = acc_bonusTotal,
                            master_balance = (int)acc_bonusTotal,
                            master_start = Convert.ToUInt32(BLL.gigade.Common.CommonFunction.GetPHPTime()),
                            master_end = Convert.ToUInt32(BLL.gigade.Common.CommonFunction.GetPHPTime(DateTime.Now.AddDays(90).ToString())),//默認過期時間是當前時間+90天
                            master_createdate = Convert.ToUInt32(BLL.gigade.Common.CommonFunction.GetPHPTime()),
                            master_updatedate = Convert.ToUInt32(BLL.gigade.Common.CommonFunction.GetPHPTime()),
                            bonus_type = 1//默認為  購物金
                        };
                    }
                    //判斷購物金是否大於 0 如果是 則表示 需要在 bonus_record 增加一筆數據 
                    //並且需要 在 bonus_master 中 按照 過期日期 減去 相應的 參數
                    if (deduct_bonusTotal > 0)
                    {
                        brBonus = new BonusRecord
                        {
                            user_id = ordermaster.User_Id,
                            record_use = deduct_bonusTotal,
                            record_createdate = Convert.ToUInt32(BLL.gigade.Common.CommonFunction.GetPHPTime()),
                            record_updatedate = Convert.ToUInt32(BLL.gigade.Common.CommonFunction.GetPHPTime())
                        };
                        //判斷購物金是否小於或等於數據庫中的購物金
                        _bonusMasterMgr = new BonusMasterMgr(connectionString);
                        int userBonusTotal = _bonusMasterMgr.GetSumBouns(brBonus);
                        if (deduct_bonusTotal > userBonusTotal)
                        {
                            jsonStr = "{success:false,msg:'" + Resources.OrderAdd.BONUS_PRICE_NULL + "'}";
                            this.Response.Clear();
                            this.Response.Write(jsonStr);
                            this.Response.End();
                            return this.Response;
                        }
                    }
                    //判斷 抵用卷 金額 是否 大於 0 
                    if (deduct_welfareTotal > 0)
                    {
                        brWelfare = new BonusRecord
                        {
                            user_id = ordermaster.User_Id,
                            record_use = deduct_welfareTotal,
                            record_createdate = Convert.ToUInt32(BLL.gigade.Common.CommonFunction.GetPHPTime()),
                            record_updatedate = Convert.ToUInt32(BLL.gigade.Common.CommonFunction.GetPHPTime())
                        };
                        //判斷購物金是否小於或等於數據庫中的購物金
                        _bonusMasterMgr = new BonusMasterMgr(connectionString);
                        int userWelfateTotal = _bonusMasterMgr.GetSumWelfare(brWelfare);
                        if (deduct_welfareTotal > userWelfateTotal)
                        {
                            jsonStr = "{success:false,msg:'" + Resources.OrderAdd.WELFARE_PRICE_NULL + "'}";
                            this.Response.Clear();
                            this.Response.Write(jsonStr);
                            this.Response.End();
                            return this.Response;
                        }
                    }
                    #endregion

                    #region 保存至數據庫
                    bool result = orderImportMgr.Save2DB(ordermaster, slaves, channelList, null, op, bm, brBonus, brWelfare);
                    #endregion

                    if (result)
                    {
                        jsonStr = "{success:true,msg:'" + Resources.OrderAdd.ORDER_ADD_SUCCESS + "'}";
                    }
                }
                else
                {
                    StringBuilder stb = new StringBuilder();
                    if (storeType == 1)
                    {
                        foreach (CooperatorOrderCustom item in coopErrorList)
                        {
                            stb.Append(item.coop_product_id + "\\n");
                        }
                        stb.Append("\\n" + Resources.OrderAdd.EMPTY_NULL_FAIL);
                    }
                    else if (storeType == 2)
                    {
                        foreach (OrderAddCustom item in errorOrder)
                        {
                            stb.Append(item.Product_Id + item.Spec_Name_1 + item.Spec_Name_2 + "\\n");
                        }
                        stb.Append("\\n" + Resources.OrderAdd.EMPTY_NULL_FAIL);
                    }
                    jsonStr = "{success:false,msg:'" + stb.ToString() + "'}";
                }
            }
            catch (Exception ex)
            {
                Log4NetCustom.LogMessage logMessage = new Log4NetCustom.LogMessage();
                logMessage.Content = string.Format("TargetSite:{0},Source:{1},Message:{2}", ex.TargetSite.Name, ex.Source, ex.Message);
                logMessage.MethodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
                log.Error(logMessage);
            }

            this.Response.Clear();
            this.Response.Write(jsonStr);
            this.Response.End();
            return this.Response;
        }
Пример #15
0
 /// <summary>
 /// 更改付款單狀態代號:方法參考自(includes/order/order.php第355行方法)
 /// </summary>
 /// <param name="Order_Id"></param>
 /// <param name="Modify_Master_Order_Status"></param>
 public string modify_order_master_status(string Order_Id, string Modify_Master_Order_Status)
 {
     OrderMaster master = new OrderMaster();
     master.Order_Status = uint.Parse(Modify_Master_Order_Status);
     master.Order_Updatedate = uint.Parse(CommonFunction.GetPHPTime(DateTime.Now.ToString()).ToString());
     master.Order_Ipfrom = IPAddress;
     StringBuilder sb = new StringBuilder();
     try
     {
         if (Modify_Master_Order_Status == "90")//訂單取消
         {
             master.Order_Date_Cancel = uint.Parse(CommonFunction.GetPHPTime(DateTime.Now.ToString()).ToString());
         }
         else if (Modify_Master_Order_Status == "99")//訂單歸檔
         {
             master.Order_Date_Close = uint.Parse(CommonFunction.GetPHPTime(DateTime.Now.ToString()).ToString());
         }
         sb.Append("set sql_safe_updates = 0;");
         sb.AppendFormat(@"UPDATE	order_master set order_status = '{0}', order_updatedate ='{1}', ", master.Order_Status, master.Order_Updatedate);
         sb.AppendFormat(" order_ipfrom = '{0}' WHERE	order_id = '{1}';", IPAddress, Order_Id);
         sb.Append("set sql_safe_updates = 1;");
         return sb.ToString();
     }
     catch (Exception ex)
     {
         throw new Exception("OrderDao.modify_order_master_status -->" + ex.Message + sb.ToString(), ex);
     }
 }
Пример #16
0
 public List<OrderMaster> Selpay(OrderMaster store)
 {
     try
     {
         return _iordertempreturnlistdao.Selpay(store);
     }
     catch (Exception ex)
     {
         throw new Exception(" ReturnMasterMgr-->Selpay-->" + ex.Message, ex);
     }
     
 }
Пример #17
0
        /// <summary>
        /// 將文件內容存儲到數據庫
        /// </summary>
        /// <param name="all"></param>
        /// <param name="pdfFile"></param>
        /// <param name="importType"></param>
        /// <param name="chkRecord"></param>
        /// <param name="totalCount"></param>
        /// <returns></returns>
        public int Import2DB(List<OrdersImport> all, string pdfFile, string importType, string chkRecord, int siteId, ref int totalCount)
        {
            orderImportMgr = new OrderImportMgr(MySqlConnStr, CurChannel.channel_id);
            int successCount = 0;
            try
            {
                List<OrdersImport> chks = orderImportMgr.SplitChkData(chkRecord).FindAll(m => m.chlitpdno != "0");//移除廠商商品編號為0的
                if (chks != null && all != null && all.Count > 0)
                {
                    #region 篩選出選中數據資訊

                    //所有選中商品
                    var result = from h in chks
                                 join o in all on new { h.dmtshxuid, h.chlitpdno } equals new { o.dmtshxuid, o.chlitpdno } into cs
                                 from c in cs.DefaultIfEmpty()
                                 select c;
                    #endregion

                    //所有訂單編號
                    List<string> master = chks.GroupBy(m => m.dmtshxuid).Select(m => m.Key).ToList();
                    totalCount = master == null ? 0 : master.Count;

                    //外站物流業者
                    channelShippingMgr = new ChannelShippingMgr(MySqlConnStr);
                    List<ChannelShipping> shippings = channelShippingMgr.QueryByChannelId(new ChannelShipping { channel_id = CurChannel.channel_id });

                    foreach (var om in master)
                    {
                        //單個訂單下所有商品
                        var product = (from p in result
                                       where p.dmtshxuid == om
                                       select p).ToList();

                        all.FindAll(m => m.dmtshxuid == om && product.Exists(n => n.chlitpdno == m.chlitpdno)).ForEach(m => m.IsSel = true);

                        #region 訂單物流業者

                        ChannelShipping cShipping = null;
                        if (shippings != null)
                        {
                            //查詢該訂單物流業者 取貨方式
                            cShipping = shippings.Where(m => m.shipco.Trim().ToLower() == product.FirstOrDefault().shipco.Trim().ToLower()).FirstOrDefault();
                        }
                        if (shippings == null || cShipping == null)
                        {
                            all.FindAll(m => m.dmtshxuid == om && m.IsSel).ForEach(m => m.Msg = Resource.CoreMessage.GetResource("DELIVERY_MAP_NOT_EXISTS"));
                            continue;
                        }
                        #endregion

                        #region 生成OrderSlave

                        List<OrderSlave> slaves = orderImportMgr.GetSlave(product, all);
                        //訂單內商品有問題(商品對照不存在,商品不存在,商品庫存不足),跳過處理下筆訂單
                        if (slaves == null || slaves.Count == 0)
                        {
                            continue;
                        }
                        #endregion

                        #region OrderMaster

                        OrderMaster newMaster = new OrderMaster();

                        #region 其他信息

                        newMaster.Order_Status = 2;
                        //newMaster.Order_Id = uint.Parse(orderImportMgr.NextOrderId());
                        channelMgr = new ChannelMgr(MySqlConnStr);
                        newMaster.User_Id = Convert.ToUInt32(channelMgr.GetUserIdByChannelId(CurChannel.channel_id));

                        //備註
                        if (!string.IsNullOrEmpty(product.FirstOrDefault().xrem))
                        {
                            newMaster.Note_Order = "購買備註:" + product.FirstOrDefault().xrem;
                        }
                        if (!string.IsNullOrEmpty(product.FirstOrDefault().shipxrem))
                        {
                            newMaster.Note_Order = string.IsNullOrEmpty(newMaster.Note_Order) ? "配送備註:" + product.FirstOrDefault().shipxrem : newMaster.Note_Order + ",配送備註:" + product.FirstOrDefault().shipxrem;
                        }
                        string name = (System.Web.HttpContext.Current.Session["caller"] as Caller).user_username;
                        newMaster.Note_Admin = name + " 於" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "建立";
                        if (!string.IsNullOrEmpty(product.FirstOrDefault().orddat))
                        {
                            newMaster.Order_Createdate = Convert.ToUInt32(CommonFunction.GetPHPTime(product.FirstOrDefault().orddat));
                        }
                        else
                        {
                            newMaster.Order_Createdate = Convert.ToUInt32(CommonFunction.GetPHPTime());
                        }
                        newMaster.Order_Date_Pay = Convert.ToUInt32(CommonFunction.GetPHPTime());
                        newMaster.Import_Time = DateTime.Now;
                        newMaster.Channel = Convert.ToUInt32(CurChannel.channel_id);
                        newMaster.Channel_Order_Id = product.FirstOrDefault().dmtshxuid;
                        if (!string.IsNullOrEmpty(product.FirstOrDefault().agpesadrzip))
                        {
                            newMaster.Order_Zip = Convert.ToUInt32(product.FirstOrDefault().agpesadrzip);
                        }
                        #endregion

                        #region 发票状态

                        if (CurChannel.receipt_to != 2)
                        {
                            newMaster.Invoice_Status = 2;
                        }
                        #endregion

                        #region 物流方式

                        newMaster.Delivery_Store = Convert.ToUInt32(cShipping.shipping_carrior);
                        newMaster.Retrieve_Mode = Convert.ToUInt32(cShipping.retrieve_mode);

                        #endregion

                        #region 運費

                        var freight = product.Where(m => m.dsr.Contains("物流服務費")).FirstOrDefault();
                        if (freight != null && !string.IsNullOrEmpty(freight.sumup))
                        {
                            if (freight.chlitpdno == "6727_13743")//若廠商商品編號為"6727_13743"是低溫運費
                            {
                                newMaster.Order_Freight_Low = uint.Parse(freight.sumup);
                            }
                            else//若廠商商品編號為"6727_13742"是常溫運費
                            {
                                newMaster.Order_Freight_Normal = uint.Parse(freight.sumup);
                            }
                        }
                        #endregion

                        #region 訂單價格

                        product.Where(m => !m.dsr.Contains("物流服務費")).ToList().ForEach(m => newMaster.Order_Product_Subtotal += uint.Parse(string.IsNullOrEmpty(m.sumup) ? "0" : m.sumup));
                        product.ForEach(m => newMaster.Order_Amount += uint.Parse(string.IsNullOrEmpty(m.sumup) ? "0" : m.sumup));
                        #endregion

                        #region 支付方式
                        //若是外站類型為”合作外站”的,匯入訂單時的 payment = 15
                        newMaster.Order_Payment = 15;
                        //switch (product.FirstOrDefault().Payment)
                        //{
                        //    case "信用卡一次":
                        //        newMaster.Order_Payment = 1;
                        //        break;
                        //    case "7-11貨到付款":
                        //        newMaster.Order_Payment = 15;
                        //        break;
                        //    default:
                        //        newMaster.Order_Payment = 1;
                        //        break;
                        //}
                        #endregion

                        #region 訂購人信息

                        newMaster.Order_Name = product.FirstOrDefault().ordpesnm;
                        newMaster.Order_Mobile = product.FirstOrDefault().ordpesnacttel.Replace("'", "");//去掉電話中的單引號
                        if (string.IsNullOrEmpty(newMaster.Order_Mobile))
                        {
                            newMaster.Order_Mobile = product.FirstOrDefault().agpesacttel.Replace("'", "");//去掉電話中的單引號
                        }
                        newMaster.Order_Address = product.FirstOrDefault().agpesadr;//order_address與delivery_address相同
                        #endregion

                        #region 發貨信息

                        newMaster.Delivery_Name = product.FirstOrDefault().agpesnm;
                        newMaster.Delivery_Mobile = product.FirstOrDefault().agpesacttel.Replace("'", "");//去掉電話中的單引號
                        newMaster.Delivery_Phone = product.FirstOrDefault().agpestel1.Replace("'", "");//去掉電話中的單引號
                        if (!string.IsNullOrEmpty(product.FirstOrDefault().agpesadrzip))
                        {
                            newMaster.Delivery_Zip = uint.Parse(product.FirstOrDefault().agpesadrzip);
                        }
                        newMaster.Delivery_Address = product.FirstOrDefault().agpesadr;
                        #endregion

                        #endregion

                        #region ChannelOrder

                        List<ChannelOrder> cOrder = new List<ChannelOrder>();
                        ChannelOrder channelOrder;
                        foreach (var slave in slaves)
                        {
                            foreach (var detail in slave.Details)
                            {
                                detail.Site_Id = siteId;//add xw 2014/02/03
                                //ChannelOrder
                                channelOrder = new ChannelOrder { Channel_Id = CurChannel.channel_id, Order_Id = newMaster.Channel_Order_Id.ToString() };
                                var p = product.Where(m => m.chlitpdno == detail.Channel_Detail_Id).FirstOrDefault();
                                if (p != null)
                                {
                                    //if (importType == "2")
                                    //{
                                    //    //channelOrder.Store_Dispatch_File = pdfFile;
                                    //}
                                    channelOrder.Dispatch_Seq = p.shipno;
                                    channelOrder.Channel_Detail_Id = detail.Channel_Detail_Id;
                                    if (!string.IsNullOrEmpty(p.orddat))
                                    {
                                        channelOrder.Createtime = Convert.ToDateTime(p.orddat);
                                    }
                                    channelOrder.Ordertime = channelOrder.Createtime;
                                    if (!string.IsNullOrEmpty(p.prndldat))
                                    {
                                        channelOrder.Latest_Deliver_Date = Convert.ToDateTime(p.prndldat);
                                    }
                                    cOrder.Add(channelOrder);
                                }
                            }
                        }
                        #endregion

                        #region 寫入數據庫

                        if (orderImportMgr.Save2DB(newMaster, slaves, cOrder, all))
                        {
                            all.FindAll(m => m.dmtshxuid == om && m.IsSel).ForEach(m => m.Msg = Resource.CoreMessage.GetResource("IMPORT_SUCCESS"));
                            successCount++;
                        }

                        #endregion
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("OrderImportPayEasy-->Import2DB-->" + ex.Message, ex);
            }
            return successCount;
        }
Пример #18
0
 }//
 public List<OrderMaster> Selpay(OrderMaster store)
 {//查詢付款單
     StringBuilder sql = new StringBuilder();
     try
     {
         List<OrderMaster> list = new List<OrderMaster>();
         sql.AppendFormat(@" SELECT * from order_master where order_deliver_success = 1 amd order_status<>'' AND order_id='{0}' ", store.Order_Id);
         list = _accessMySql.getDataTableForObj<OrderMaster>(sql.ToString());
         return list;
     }
     catch (Exception ex)
     {
         throw new Exception("OrderTempReturnListDao.Selpay-->" + sql.ToString() + ex.Message, ex);
     }
    
 }