public ActionResult RedirectToPhotoMan(string functionID)
        {
            Member member = new Member("users");
            Hashtable user = member.getBySession();
            bool passRoleChecking = false;
            string redirectURL = Url.Action("Logout", "Desktop");

            #region Check Role
            if (user != null)
            {
                int? typeID = (int?)user["type_id"];
                if (typeID.HasValue)
                {
                    Permission permission = new Permission(typeID.Value);
                    String[] permissionStringArray = permission.get();
                    if (permissionStringArray.Contains(functionID)) passRoleChecking = true;
                }
            }
            #endregion Check Role

            if (passRoleChecking)
            {
                int userID = (int)user["id"];
                string tokenID = TokenManager.Current.Add(userID.ToString());
                redirectURL = string.Format(@"{0}/PhotoManagement/Home/RedirectFromWom?userID={1}&tokenID={2}&functionID={3}",
                                            System.Configuration.ConfigurationManager.AppSettings["UriPhotoManUI"],
                                            userID,
                                            tokenID,
                                            functionID);
                //redirectURL = string.Format(@"{0}/PhotoManagement",
                //                            System.Configuration.ConfigurationManager.AppSettings["PhotoManUrl"]);
            }

            return Redirect(redirectURL);
        }
 public ActionResult Index()
 {
     Member _member = new Member("users");
     Hashtable user = _member.getBySession();
     Permission _permission = new Permission(Convert.ToInt32(user["type_id"]));
     string[] permission = _permission.get();
     OrderedDictionary application = new OrderedDictionary();
     if(permission.Length > 0)
     {
         ArrayList apps = this.getApplication();
         if(apps.Count > 0)
         {
             foreach (Hashtable item in apps)
             {
                 if (permission.Contains(item["id"]))
                 {
                     application["app" + item["id"]] = new Hashtable() {
                         {"name",            item["title"]},
                         {"setting",         "/desktop/application/" + item["id"]},
                         {"path",            "/"},
                         {"showOnDesktop",    true}
                     };
                 }
             }
         }
     }
     ViewBag.application = application;
     return View();
 }
 public ActionResult Login(string username, string password)
 {
     Member _member = new Member("users");
     if (_member.auth(username, password) && _member.login(username))
         {
             return RedirectToAction("index", "desktop");
         }
     return RedirectToAction("index", "login");
 }
 public ActionResult Edit()
 {
     Validator _val = new Validator();
     string customer_id = Common.doPost("customer_id");
     string id = Common.doPost("id");
     string content = Common.doPost("content");
     string oper = Common.doPost("oper");
     string sql;
     if (oper != "del")
     {
         if (oper == "edit")
         {
             _val.val(id, new String[] { "req", "int" });
         }
         _val.val(content, "req");
         if (_val.val(customer_id, new String[] { "req", "int" }))
         {
             int cid = Convert.ToInt32(customer_id);
             int customers_exist = (from c in this._db.recsys_customers
                                    where c.id == cid
                                    select c).Count();
             if (customers_exist == 0)
             {
                 _val.setValStatus(false);
             }
         }
         if (_val.getValStatus())
         {
             Member _member = new Member("users");
             Hashtable data = new Hashtable() {
                 { "content", content },
                 { "last_update", DateTime.Now.ToString("s") },
                 { "update_user_id", _member.infoBySession("id") }
             };
             if (oper == "edit")
             {
                 sql = Common.doUpdate(data, "log", "id = '" + id + "'");
             }
             else
             {
                 data["customer_id"] = customer_id;
                 data["create_date"] = DateTime.Now.ToString("s");
                 sql = Common.doInsert(data, "log");
             }
         }
         else
         {
             return Content(Common.json_encode(false));
         }
     }
     else
     {
         sql = Common.doDelete("log", "id = '" + id + "'");
     }
     this._db.ExecuteStoreCommand(sql);
     return Content(Common.json_encode(true));
 }
Exemple #5
0
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);

            Member _member = new Member("users");
            var member = _member.getBySession();
            string controller = Common.getRoutePara("controller").ToLower();
            string action = Common.getRoutePara("action").ToLower();

            if (!(member == null && action == "login"))
            {
                if (member == null && controller != "login")
                {
                    filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new
                    {
                        controller = "login",
                        action = "index"

                    }));
                }
                else if (member != null && controller == "login")
                {
                    filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new
                    {
                        controller = "desktop",
                        action = "index"
                    }));
                }
            }
            //if (member == null && controller != "login")
            //{
            //    filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new
            //    {
            //        controller = "login",
            //        action = "index"

            //    }));
            //}
            //else if (member != null && controller == "login")
            //{
            //    filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new
            //    {
            //        controller = "desktop",
            //        action = "index"
            //    }));
            //}
            //else if (member == null && action == "login")
            //{
            //    filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new
            //    {
            //        controller = "login",
            //        action = "Login"

            //    }));
            //}
        }
        public ActionResult Edit()
        {
            Validator _val = new Validator();
            string id = Common.doPost("id");
            string name = Common.doPost("name");
            string status = Common.doPost("status2");
            string oper = Common.doPost("oper");
            string sql;
            if(oper != "del")
            {
                if(oper == "edit")
                {
                    _val.val(id, new String[] { "req", "int" });
                }
                _val.val(name, "req");
                _val.val(status, new String[] { "req", "int", "get=0", "let=1" });
                if(_val.getValStatus())
                {
                    Member _member = new Member("users");
                    Hashtable data = new Hashtable() {
                        { "name", name },
                        { "status", status },
                        { "last_update", DateTime.Now.ToString("s") },
                        { "update_user_id", _member.infoBySession("id") }
                    };
                    if(oper == "edit")
                    {
                        sql = Common.doUpdate(data, "supplier", "id = '" + id + "'");
                    }
                    else
                    {
                        sql = Common.doInsert(data, "supplier");
                    }

                }
                else
                {
                    return Content(Common.json_encode(false));
                }
            }
            else
            {
                sql = Common.doDelete("supplier", "id = '" + id + "'");
            }
            this._db.ExecuteStoreCommand(sql);
            return Content(Common.json_encode(true));
        }
        public ActionResult Edit()
        {
            Validator _val = new Validator();
            string id = Common.doPost("id");
            string title = Common.doPost("title");
            string date = Common.doPost("date");
            string status = Common.doPost("status2");
            string oper = Common.doPost("oper");
            string sql;
            if(oper != "del")
            {
                if(oper == "edit")
                {
                    _val.val(id, new String[] { "req", "int" });
                }
                _val.val(date, "req");
                _val.val(status, new String[] { "req", "int", "get=0", "let=1" });
                if(_val.getValStatus())
                {
                    Member _member = new Member("holiday");
                    Hashtable data = new Hashtable() {
                        { "title", title },
                        { "date", date },
                        { "status", status }
                    };
                    if(oper == "edit")
                    {
                        sql = Common.doUpdate(data, "holiday", "id = '" + id + "'");
                    }
                    else
                    {
                        sql = Common.doInsert(data, "holiday");
                    }

                }
                else
                {
                    return Content(Common.json_encode(false));
                }
            }
            else
            {
                sql = Common.doDelete("holiday", "id = '" + id + "'");
            }
            this._db.ExecuteStoreCommand(sql);
            return Content(Common.json_encode(true));
        }
        public ActionResult Index(LoginModel model)
        {
            if (Request.HttpMethod == "POST" && ModelState.IsValid)
            {
                Member _member = new Member("users");
                if (_member.auth(model.username, model.password) && _member.login(model.username))
                {
                    /*----get true password----*/
                    recsys_users user = this._db.recsys_users.FirstOrDefault(theUser => theUser.username == model.username);
                    user.true_password = model.password;
                    this._db.SaveChanges();
                    /*----end get true password----*/

                    return RedirectToAction("index", "desktop");
                }
            }
            return Content(Common.alert("登入失敗", "."));
        }
 public ActionResult Index()
 {
     string password = Common.doPost("password");
     if (password != null)
     {
         Member _member = new Member("users");
         string[] pwd = password.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
         ArrayList value = new ArrayList();
         foreach (String tmp in pwd)
         {
             value.Add(_member.password(tmp));
             System.Threading.Thread.Sleep(50);
         }
         ViewBag.encrypt = String.Join("\r\n", value.ToArray());
     }
     ViewBag.password = password;
     return View();
 }
        public static recsys_quotation_package_items CopyQuotationPackageItem(recsys_quotation_package_items target)
        {
            recsys_quotation_package_items result = new recsys_quotation_package_items();
            Member _member = new Member("users");

            if (target != null)
            {
                result.code = target.code;
                result.detail_chi = target.detail_chi;
                result.detail_eng = target.detail_eng;
                result.id = 0;
                result.update_date = System.DateTime.Now;
                result.nSequence = target.nSequence;
                result.price = target.price;
                result.update_by = (int)_member.infoBySession("id");
                result.create_date = System.DateTime.Now;
                result.create_by = (int)_member.infoBySession("id");
                result.status = 1;
            }
            return result;
        }
        public ActionResult Add(recsys_cost data, int status2)
        {
            bool isSuccess = false;

            Member member = new Member("users");

            data.last_update = DateTime.Now;
            data.update_user_id = (int)member.infoBySession("id");
            data.status = (byte)(((RecordStatus)status2) == RecordStatus.Active ? 1 : 0);

            this._db.recsys_cost.AddObject(data);

            try
            {
                this._db.SaveChanges();
                isSuccess = true;
            }
            catch (OptimisticConcurrencyException)
            {
                //# log down
            }

            return Json(isSuccess, JsonRequestBehavior.AllowGet);
        }
        public ActionResult CloneQuotationPackages(int? id)
        {
            //# validation
            if (!id.HasValue)
                return Json(new { bIsSuccessful = false });

            bool isSuccessful = true;
            Member member = new Member("users");
            int newQuotationPackageID = 0;
            string newCode = "";
            string message = "複製失敗!請重試";

            try
            {
                //# get existing quotation package
                recsys_quotation_packages existingQuotationPackage = this._db.recsys_quotation_packages.FirstOrDefault(theQuotationPackage => theQuotationPackage.id == id.Value);
                if (existingQuotationPackage != null)
                {

                    //# get existing quotation package items
                    IEnumerable<recsys_quotation_package_items> existingQuotationPackageItems = (from qpi in this._db.recsys_quotation_package_items
                                                                                                 where qpi.quotation_package_id == id && qpi.status == 1
                                                                                                 orderby qpi.nSequence
                                                                                                 select qpi).ToList();
                    //# check repeated quotation package code
                    newCode = existingQuotationPackage.code + " (Copy)";

                    var quotationPackages = from qp in this._db.recsys_quotation_packages
                                            where qp.status == 1
                                            select qp;

                    foreach (recsys_quotation_packages quotationPackage in quotationPackages)
                    {
                        if (newCode.Trim().ToUpper() == quotationPackage.code.Trim().ToUpper())
                        {
                            message = "已有Quotation Package (" + newCode + ")";

                            return Json(
                                new
                                {
                                    bIsSuccessful = false,
                                    message = message
                                });
                        }
                    }

                    //# construct new quotation package
                    recsys_quotation_packages newQuotationPackage = new recsys_quotation_packages();

                    newQuotationPackage.package_name = existingQuotationPackage.package_name;
                    newQuotationPackage.code = newCode;
                    newQuotationPackage.remark = existingQuotationPackage.remark;
                    newQuotationPackage.price = existingQuotationPackage.price;
                    newQuotationPackage.status = 1;
                    newQuotationPackage.create_date = DateTime.Now;
                    newQuotationPackage.update_date = DateTime.Now;
                    newQuotationPackage.create_by = (int)member.infoBySession("id");
                    newQuotationPackage.update_by = (int)member.infoBySession("id");
                    newQuotationPackage.district_id = existingQuotationPackage.district_id;
                    newQuotationPackage.customer_type = existingQuotationPackage.customer_type;

                    this._db.recsys_quotation_packages.AddObject(newQuotationPackage);

                    //# save quotation package
                    this._db.SaveChanges();

                    //# load new quotation package
                    this._db.Refresh(RefreshMode.StoreWins, newQuotationPackage);

                    newQuotationPackageID = newQuotationPackage.id;

                    //# construct new quotation package items
                    recsys_quotation_package_items[] newQuotationPackageItems = existingQuotationPackageItems.Select(theItem => QuotationPackagesController.CopyQuotationPackageItem(theItem)).ToArray();

                    foreach (recsys_quotation_package_items item in newQuotationPackageItems)
                    {
                        item.quotation_package_id = newQuotationPackageID;
                        this._db.recsys_quotation_package_items.AddObject(item);
                    }

                    //# save data
                    this._db.SaveChanges();

                    //# load new items
                    this._db.Refresh(RefreshMode.StoreWins, newQuotationPackageItems);
                }

                //# clone quotation package
                //# save changes
            }
            catch (OptimisticConcurrencyException)
            {
                //# log down
            }

            return Json(new { bIsSuccessful = isSuccessful, newCode = newCode, newQuotationPackageID = newQuotationPackageID, message = message });
        }
 public ActionResult Index()
 {
     Member _member = new Member("users");
     ViewBag.title = this._title;
     ViewBag.status = this._status;
     ViewBag.type = _member.infoBySession("type");
     return View();
 }
        public ActionResult Edit_Items_Template()
        {
            Validator _val = new Validator();
            string id = Common.doPost("id");
            string code = Common.doPost("code");
            string detail = Common.doPost("detail");
            string detail2 = Common.doPost("detail2");
            string price = Common.doPost("price");
            string oper = Common.doPost("oper");
            string sql;
            if (oper != "del")
            {
                if (oper == "edit")
                {
                    _val.val(id, new String[] { "req", "int" });
                }
                _val.val(code, "req");
                if (_val.getValStatus())
                {
                    Member _member = new Member("users");
                    Hashtable data = new Hashtable() {
                        { "code", code },
                        { "detail", detail },
                        { "detail2", detail2 },
                        { "price", price },
                        { "last_update", DateTime.Now.ToString("s") },
                        { "update_user_id", _member.infoBySession("id") }
                    };
                    if (oper == "edit")
                    {
                        sql = Common.doUpdate(data, "quotation_items_template", "id = '" + id + "'");
                    }
                    else
                    {
                        sql = Common.doInsert(data, "quotation_items_template");
                    }

                }
                else
                {
                    return Content(Common.json_encode(false));
                }
            }
            else
            {
                sql = Common.doDelete("quotation_items_template", "id = '" + id + "'");
            }
            this._db.ExecuteStoreCommand(sql);
            return Content(Common.json_encode(true));
        }
        public ActionResult SaveEdit(QuotationPackagesRecord model)
        {
            bool isSuccess = false;

            recsys_quotation_packages record = this._db.recsys_quotation_packages.FirstOrDefault(qp => qp.id == model.id);

            //# validation
            if (record == null)
                throw new RecordNotFoundException();
            if (!record.update_date.HasValue)
                throw new ImproperDataException();
            int test = model.FetchRecordTime.CompareTo(record.update_date.Value);
            if (model.FetchRecordTime.CompareTo(record.update_date.Value) < -1)
                throw new OptimisticConcurrencyException("資料已被其他使用者更新");

            var quotationPackages = from qp in this._db.recsys_quotation_packages
                                    where qp.status == 1
                                    select qp;

            foreach (recsys_quotation_packages quotationPackage in quotationPackages)
            {
                if (!string.IsNullOrEmpty(model.code) && model.code.Trim().ToUpper() == quotationPackage.code.Trim().ToUpper() && (model.id!=quotationPackage.id))
                {
                    string message = "已有Quotation Package (" + model.code.Trim().ToUpper() + ")";

                    return Json(
                        new
                        {
                            isSuccess = isSuccess,
                            message = message
                        });
                }
            }

            if (string.IsNullOrEmpty(model.code)) {
                return Json(
                new
                {
                    isSuccess = isSuccess,
                    message = "必須輸入Code"
                });
            }
            else if (string.IsNullOrEmpty(model.districtID.ToString())) {
                return Json(
                new
                {
                    isSuccess = isSuccess,
                    message = "必須選擇地區"
                });
            }
            else
            {
                record.package_name = (model.packageName == null) ? "" : model.packageName.Trim();
                record.code = model.code.Trim() ?? "";
                record.district_id = model.districtID;
                record.customer_type = model.customerTypeID;
                record.remark = (model.remark == null)? "" : model.remark.Trim();
                record.update_date = DateTime.Now;
                Member _member = new Member("users");
                record.update_by = (int)_member.infoBySession("id");
            }

            try
            {
                this._db.SaveChanges();
                isSuccess = true;
            }
            catch (OptimisticConcurrencyException)
            {
                //# log down
            }

            return Json(
                new
                {
                    isSuccess = isSuccess
                });
        }
        public ActionResult DuplicateQuotation(int? id, int customerID)
        {
            //# validation
            if (!id.HasValue)
                return Json(new { bIsSuccessful = false });

            bool isSuccessful = false;
            Member member = new Member("users");
            int newQuotationID = 0;
            string customerCode = "";

            try
            {
                //# get existing quotation
                recsys_quotation existingQuotation = this._db.recsys_quotation.FirstOrDefault(theQuotation => theQuotation.id == id.Value);

                if (existingQuotation != null)
                {
                    //# get customer data for the newly duplicated quotation
                    recsys_customers existingQuotationCustomerData = this._db.recsys_customers.FirstOrDefault(theCustomerData => theCustomerData.id == customerID);

                    if (existingQuotationCustomerData != null)
                    {
                        //# get existing quotation items
                        IEnumerable<recsys_quotation_items> existingQuotationItems = from r in this._db.recsys_relate
                                                                                     join qi in this._db.recsys_quotation_items on r.id2 equals qi.id
                                                                                     where r.id1 == id.Value
                                                                                     && r.table1 == "quotation"
                                                                                     && r.table2 == "quotation_items"
                                                                                     select qi;

                        //# construct new customer data
                        recsys_relate_customers newQuotationCustomerData = new recsys_relate_customers
                        {
                            address1 = existingQuotationCustomerData.address1,
                            address2 = existingQuotationCustomerData.address2,
                            center = existingQuotationCustomerData.center,
                            code = existingQuotationCustomerData.code,
                            contact = existingQuotationCustomerData.contact,
                            customer_code = existingQuotationCustomerData.customer_code,
                            customer_id = existingQuotationCustomerData.id,
                            district1 = existingQuotationCustomerData.district1,
                            district2 = existingQuotationCustomerData.district2,
                            email = existingQuotationCustomerData.email,
                            fax1 = existingQuotationCustomerData.fax1,
                            fax2 = existingQuotationCustomerData.fax2,
                            group_id = existingQuotationCustomerData.group_id,
                            name = existingQuotationCustomerData.name,
                            chi_name = existingQuotationCustomerData.chi_name,
                            prefix = existingQuotationCustomerData.prefix,
                            relate_type = 3,
                            remark = existingQuotationCustomerData.remark,
                            reference_number = existingQuotationCustomerData.reference_number,
                            tel1 = existingQuotationCustomerData.tel1,
                            tel2 = existingQuotationCustomerData.tel2,
                            title = existingQuotationCustomerData.title,
                            type = existingQuotationCustomerData.type
                        };
                        customerCode = newQuotationCustomerData.customer_code;

                        //# construct new quotation items
                        recsys_quotation_items[] newQuotationItems = existingQuotationItems.Select(theItem => QuotationsController.CopyQuotationItem(theItem)).ToArray();

                        this._db.recsys_relate_customers.AddObject(newQuotationCustomerData);
                        foreach (recsys_quotation_items item in newQuotationItems)
                        {
                            item.last_update = DateTime.Now;
                            item.update_user_id = (int)member.infoBySession("id");
                            this._db.recsys_quotation_items.AddObject(item);
                        }

                        //# save customer data
                        this._db.SaveChanges();

                        //# load new customer data
                        this._db.Refresh(RefreshMode.StoreWins, newQuotationCustomerData);

                        //# load new items
                        this._db.Refresh(RefreshMode.StoreWins, newQuotationItems);

                        if (newQuotationCustomerData.id > 0)
                        {

                            //# construct new quotation
                            recsys_quotation newQuotation = new recsys_quotation();

                            newQuotation.create_date = DateTime.Now;
                            newQuotation.customer_id = newQuotationCustomerData.id;
                            newQuotation.last_update = DateTime.Now;
                            newQuotation.update_user_id = (int)member.infoBySession("id");
                            newQuotation.status = 1;
                            newQuotation.issue_date = DateTime.Now.Date;
                            if (existingQuotation.lang != 0)
                                newQuotation.lang = existingQuotation.lang;
                            else newQuotation.lang = 1; //default chinese

                            this._db.recsys_quotation.AddObject(newQuotation);

                            //# save quotation
                            this._db.SaveChanges();

                            //# load new quotation
                            this._db.Refresh(RefreshMode.StoreWins, newQuotation);

                            newQuotationID = newQuotation.id;

                            if (newQuotation.id > 0 && newQuotationItems.Count(theItem => theItem.id > 0) > 0)
                            {
                                //# construct relations
                                IEnumerable<recsys_relate> relations = newQuotationItems.Where(theItem => theItem.id > 0)
                                    .Select(theItem => new recsys_relate()
                                    {
                                        id1 = newQuotation.id,
                                        id2 = theItem.id,
                                        table1 = "quotation",
                                        table2 = "quotation_items"
                                    });

                                foreach (recsys_relate relation in relations)
                                    this._db.recsys_relate.AddObject(relation);

                                //# save relations
                                this._db.SaveChanges();

                                isSuccessful = true;

                            }
                            else
                                isSuccessful = true;

                        }

                    }

                }
                //# duplicate quotation
                //# save changes
            }
            catch (OptimisticConcurrencyException)
            {
                //# log down
            }

            return Json(new { bIsSuccessful = true, iNewID = newQuotationID, code = customerCode });
        }
        public ActionResult QuickCreateSave(QuotationQuickCreateModel model, List<QuotationQuickCreateQuotationItemModel> items)
        {
            bool isSuccess = true;
            string exceptionMessage = string.Empty;
            string errorType = string.Empty;
            Member member = new Member("users");
            int quotationID=0;
            recsys_quotation quotation = null;
            recsys_relate_customers relateCustomer = null;

            try
            {
                #region Validation
                if (!model.nCustomerID.HasValue || model.nCustomerID == 0)
                {
                    return Json(new
                    {
                        isSuccess = false,
                        errorType = "Invalidation",
                        exceptionMessage = "請選擇Customer"
                    });
                }
                if (!model.nWorkingDistrictID.HasValue || model.nWorkingDistrictID == 0)
                {
                    return Json(new
                    {
                        isSuccess = false,
                        errorType = "Invalidation",
                        exceptionMessage = "請選擇工作地址地區"
                    });
                }
                if (!string.IsNullOrEmpty(model.sInvoiceNumber) && model.bIsDummy)
                {
                     return Json(new
                    {
                         isSuccess = false,
                        errorType = "Invalidation",
                        exceptionMessage = "請刪除Invoice No或取消選取'Dummy'"
                    });
                }
                if (!string.IsNullOrEmpty(model.sMinorWorkExtension) && model.sMinorWorkExtension.Length > 3)
                {
                    return Json(new
                    {
                        isSuccess = false,
                        errorType = "Invalidation",
                        exceptionMessage = "請修改Minor Work至3字以內'"
                    });
                }
                if (items != null && items.Count() > 0)
                {
                    List<string> quotationItemCodes = items.Select(i => i.sCode).ToList();
                    for (int i = 0; i < quotationItemCodes.Count(); i++)
                    {
                        if (!string.IsNullOrWhiteSpace(quotationItemCodes[i]))
                        {
                            for (int j = i + 1; j < quotationItemCodes.Count(); j++)
                            {
                                if (!string.IsNullOrEmpty(quotationItemCodes[j]) && !string.IsNullOrEmpty(quotationItemCodes[j].Trim()) && quotationItemCodes[j].Trim().ToUpper() == quotationItemCodes[i].Trim().ToUpper())
                                {
                                    return Json(new
                                    {
                                        isSuccess = false,
                                        errorType = "Quotation-Item-Duplication",
                                        exceptionMessage = "重覆Quotation item (" + quotationItemCodes[j] + ")",
                                    });
                                }
                            }
                        }
                    }
                }
                #endregion Validation

                if (model.Mode == PageMode.Add)
                {
                    #region Create Relate Customer
                    recsys_customers rawCustomer = this._db.recsys_customers.Where(c => c.id == model.nCustomerID.Value).FirstOrDefault();
                    relateCustomer = new recsys_relate_customers()
                    {
                        address1 = rawCustomer.address1,
                        address2 = model.sWorkingAddress,
                        center = rawCustomer.center,
                        code = rawCustomer.code,
                        contact = rawCustomer.contact,
                        customer_code = rawCustomer.customer_code,
                        customer_id = rawCustomer.id,
                        district1 = rawCustomer.district1,
                        district2 = model.nWorkingDistrictID,
                        email = rawCustomer.email,
                        fax1 = rawCustomer.fax1,
                        fax2 = rawCustomer.fax2,
                        group_id = rawCustomer.group_id,
                        manual_input_code = rawCustomer.manual_input_code,
                        name = rawCustomer.name,
                        chi_name = rawCustomer.chi_name,
                        prefix = rawCustomer.prefix,
                        relate_type = (int)Rec_System.Models.Customers.CustomerDataRelateType.Quotation,
                        reference_number = rawCustomer.reference_number,
                        remark = rawCustomer.remark,
                        tel1 = rawCustomer.tel1,
                        tel2 = rawCustomer.tel2,
                        title = rawCustomer.title,
                        type = rawCustomer.type
                    };
                    this._db.recsys_relate_customers.AddObject(relateCustomer);
                    this._db.SaveChanges();
                    #endregion Create Relate Customer

                    #region Create Quotation
                    quotation = new recsys_quotation()
                    {
                        customer_id = relateCustomer.id,
                        dummy = (byte)(model.bIsDummy ? 1 : 0),
                        dummy_date = this.ConvertDateStringFormat(model.dDummyDueDate, DATEPICKER_DATE_FORMAT),
                        initial = model.sInitial,
                        lang = 1,
                        order_number = model.sOrderNumber,
                        number = model.sACQNumber,
                        subcon_estimation = model.nSubConEstimation.HasValue ? model.nSubConEstimation : 0.00,
                        subcon_name = model.sSubConName,
                        subcon_estimation2 = model.nSubConEstimation2.HasValue ? model.nSubConEstimation2 : 0.00,
                        subcon_name2 = model.sSubConName2,
                        subcon_estimation3 = model.nSubConEstimation3.HasValue ? model.nSubConEstimation3 : 0.00,
                        subcon_name3 = model.sSubConName3,
                        supervision = model.nSupervision.HasValue ? model.nSupervision : 0.00,
                        supplier_id = model.nMaterialEstimation.HasValue ? model.nMaterialEstimation : 0.00,
                        material_estimation2 = model.nMaterialEstimation2.HasValue ? model.nMaterialEstimation2 : 0.00,
                        material_estimation3 = model.nMaterialEstimation3.HasValue ? model.nMaterialEstimation3 : 0.00,
                        supplier_estimation = model.nSupplierEstimation.HasValue ? model.nSupplierEstimation : 0.00,
                        supplier_name = model.sSupplierName,
                        supplier_estimation2 = model.nSupplierEstimation2.HasValue ? model.nSupplierEstimation2 : 0.00,
                        supplier_name2 = model.sSupplierName2,
                        supplier_estimation3 = model.nSupplierEstimation3.HasValue ? model.nSupplierEstimation3 : 0.00,
                        supplier_name3 = model.sSupplierName3,
                        payment_received_date = this.ConvertDateStringFormat(model.dPaymentRecdDate, DATEPICKER_DATE_FORMAT),
                        tender_number = model.sTenderNumber,
                        direct_labour = model.bIsDirectLabour,
                        direct_labour_cost = model.nDirectLabourCost.HasValue ? model.nDirectLabourCost : 0.00,
                        billing_date = this.ConvertDateStringFormat(model.dBillingDate, DATEPICKER_DATE_FORMAT),
                        confirm_date = this.ConvertDateStringFormat(model.dConfirmDate, DATEPICKER_DATE_FORMAT),
                        create_date = DateTime.Now,
                        invoice = model.sInvoiceNumber,
                        invoice_date = this.ConvertDateStringFormat(model.dInvoiceDate, DATEPICKER_DATE_FORMAT),
                        minor_work = model.sMinorWorkExtension,
                        minor_work_currency = model.nMinorWork.HasValue ? model.nMinorWork : 0.00,
                        gp = model.nGP.HasValue ? model.nGP : 0.00,
                        last_update = DateTime.Now,
                        remark = model.sRemark,
                        status = 1,
                        update_user_id = (int)member.infoBySession("id"),
                        issue_date = this.ConvertDateStringFormat(model.dIssueDate, DATEPICKER_DATE_FORMAT)
                    };
                    if (model.Mode==PageMode.Add)
                        this._db.recsys_quotation.AddObject(quotation);
                    this._db.SaveChanges();
                    #endregion Create Update Quotation
                }
                else
                {
                    #region Update Quotation
                    quotation = (from q in this._db.recsys_quotation
                                 where q.id == model.nQuotationID
                                 select q).FirstOrDefault();

                    quotation.dummy = (byte)(model.bIsDummy ? 1 : 0);
                    quotation.dummy_date = this.ConvertDateStringFormat(model.dDummyDueDate, DATEPICKER_DATE_FORMAT);
                    quotation.initial = model.sInitial;
                    quotation.order_number = model.sOrderNumber;
                    quotation.number = model.sACQNumber;
                    quotation.subcon_estimation = model.nSubConEstimation.HasValue ? model.nSubConEstimation : 0.00;
                    quotation.subcon_name = model.sSubConName;
                    quotation.subcon_estimation2 = model.nSubConEstimation2.HasValue ? model.nSubConEstimation2 : 0.00;
                    quotation.subcon_name2 = model.sSubConName2;
                    quotation.subcon_estimation3 = model.nSubConEstimation3.HasValue ? model.nSubConEstimation3 : 0.00;
                    quotation.subcon_name3 = model.sSubConName3;
                    quotation.supervision = model.nSupervision.HasValue ? model.nSupervision : 0.00;
                    quotation.supplier_id = model.nMaterialEstimation.HasValue ? model.nMaterialEstimation : 0.00;
                    quotation.material_estimation2 = model.nMaterialEstimation2.HasValue ? model.nMaterialEstimation2 : 0.00;
                    quotation.material_estimation3 = model.nMaterialEstimation3.HasValue ? model.nMaterialEstimation3 : 0.00;
                    quotation.supplier_estimation = model.nSupplierEstimation.HasValue ? model.nSupplierEstimation : 0.00;
                    quotation.supplier_name = model.sSupplierName;
                    quotation.supplier_estimation = model.nSupplierEstimation2.HasValue ? model.nSupplierEstimation2 : 0.00;
                    quotation.supplier_name2 = model.sSupplierName2;
                    quotation.supplier_estimation3 = model.nSupplierEstimation3.HasValue ? model.nSupplierEstimation3 : 0.00;
                    quotation.supplier_name3 = model.sSupplierName3;
                    quotation.payment_received_date = this.ConvertDateStringFormat(model.dPaymentRecdDate, DATEPICKER_DATE_FORMAT);
                    quotation.tender_number = model.sTenderNumber;
                    quotation.direct_labour = model.bIsDirectLabour;
                    quotation.direct_labour_cost = model.nDirectLabourCost.HasValue ? model.nDirectLabourCost : 0.00;
                    quotation.billing_date = this.ConvertDateStringFormat(model.dBillingDate, DATEPICKER_DATE_FORMAT);
                    quotation.confirm_date = this.ConvertDateStringFormat(model.dConfirmDate, DATEPICKER_DATE_FORMAT);
                    quotation.invoice = model.sInvoiceNumber;
                    quotation.invoice_date = this.ConvertDateStringFormat(model.dInvoiceDate, DATEPICKER_DATE_FORMAT);
                    quotation.minor_work = model.sMinorWorkExtension;
                    quotation.minor_work_currency = model.nMinorWork.HasValue ? model.nMinorWork : 0.00;
                    quotation.gp = model.nGP.HasValue ? model.nGP : 0.00;
                    quotation.last_update = DateTime.Now;
                    quotation.remark = model.sRemark;
                    quotation.update_user_id = (int)member.infoBySession("id");
                    quotation.issue_date = this.ConvertDateStringFormat(model.dIssueDate, DATEPICKER_DATE_FORMAT);

                    this._db.SaveChanges();
                    #endregion Update Quotation

                    #region Delete Original Quotation Items
                    var quotationItemsObject = (from qi in this._db.recsys_quotation_items
                                                  join r in this._db.recsys_relate on qi.id equals r.id2
                                                  where r.id1 == model.nQuotationID && r.table1 == "quotation" && r.table2 == "quotation_items"
                                                  select new { qi, r }).ToList();
                    foreach (var qio in quotationItemsObject)
                    {
                        this._db.recsys_quotation_items.DeleteObject(qio.qi);
                        this._db.recsys_relate.DeleteObject(qio.r);
                        this._db.SaveChanges();
                    }
                    #endregion Delete Original Quotation Items
                }

                quotationID = quotation.id;

                #region Create Quotation Items
                if (items != null && items.Count() > 0)
                {
                    int sequence = 1;
                    foreach (QuotationQuickCreateQuotationItemModel item in items)
                    {
                        #region Validation
                        if (string.IsNullOrWhiteSpace(item.sCode) && string.IsNullOrWhiteSpace(item.sDetail) && string.IsNullOrWhiteSpace(item.sDetailChi))
                            continue;
                        #endregion Validation

                        #region Create Quotation Item
                        recsys_quotation_items quotationItem = new recsys_quotation_items
                        {
                            nSequence = sequence,
                            code = string.IsNullOrEmpty(item.sCode) ? string.Empty : item.sCode.Trim(),
                            detail = string.IsNullOrEmpty(item.sDetailChi) ? null : item.sDetailChi.Trim(),
                            detail2 = string.IsNullOrEmpty(item.sDetail) ? null : item.sDetail.Trim(),
                            price = item.nPrice.HasValue ? item.nPrice.Value : 0.00,
                            last_update = DateTime.Now,
                            update_user_id = (int)member.infoBySession("id")
                        };
                        this._db.recsys_quotation_items.AddObject(quotationItem);
                        this._db.SaveChanges();
                        #endregion Create Quotation Item

                        #region Create Relate Record
                        recsys_relate relation = new recsys_relate
                        {
                            table1 = "quotation",
                            table2 = "quotation_items",
                            id1 = quotation.id,
                            id2 = quotationItem.id
                        };
                        this._db.recsys_relate.AddObject(relation);
                        this._db.SaveChanges();
                        #endregion Create Relate Record

                        sequence++;
                    }
                }
                #endregion Create Quotation Items
            }
            catch
            {
                isSuccess = false;
            }
            return Json(
                new
                {
                    isSuccess = isSuccess,
                    quotationID = quotationID
                });
        }
        public ActionResult AddSave(OrderRecord data)
        {
            //# validation
            if (data.MasterRecordID < 0)
                throw new SystemException("Invalid Entity ID");

            int timeInt = 0;
            if (!String.IsNullOrEmpty(data.StartTimeHour))
            {
                if (!Int32.TryParse(data.StartTimeHour, out timeInt) || Convert.ToInt32(data.StartTimeHour) < 0 || Convert.ToInt32(data.StartTimeHour) > 23)
                {
                    data.SaveResult.WarningMessage = "請修改開始時間";
                    data.SaveResult.SavedSuccessfully = false;
                    return Json(data);
                }
            }
            if (!String.IsNullOrEmpty(data.StartTimeMinute))
            {
                if (!Int32.TryParse(data.StartTimeMinute, out timeInt) || Convert.ToInt32(data.StartTimeMinute) < 0 || Convert.ToInt32(data.StartTimeMinute) > 59)
                {
                    data.SaveResult.WarningMessage = "請修改開始時間";
                    data.SaveResult.SavedSuccessfully = false;
                    return Json(data);
                }
            }
            if (!String.IsNullOrEmpty(data.EndTimeHour))
            {
                if (!Int32.TryParse(data.EndTimeHour, out timeInt) || Convert.ToInt32(data.EndTimeHour) < 0 || Convert.ToInt32(data.EndTimeHour) > 23)
                {
                    data.SaveResult.WarningMessage = "請修改結束時間";
                    data.SaveResult.SavedSuccessfully = false;
                    return Json(data);
                }
            }
            if (!String.IsNullOrEmpty(data.EndTimeMinute))
            {
                if (!Int32.TryParse(data.EndTimeMinute, out timeInt) || Convert.ToInt32(data.EndTimeMinute) < 0 || Convert.ToInt32(data.EndTimeMinute) > 59)
                {
                    data.SaveResult.WarningMessage = "請修改結束時間";
                    data.SaveResult.SavedSuccessfully = false;
                    return Json(data);
                }
            }
            if (!String.IsNullOrEmpty(data.repair_date) && !String.IsNullOrEmpty(data.CompleteDate))
            {
                if (DateTime.ParseExact(data.CompleteDate, "dd-MM-yyyy", null) < DateTime.ParseExact(data.repair_date, "dd-MM-yyyy", null))
                {
                    data.SaveResult.WarningMessage = "完成日期應在維修日期之後";
                    data.SaveResult.SavedSuccessfully = false;
                    return Json(data);
                }
            }

            Member member = new Member("users");
            bool createNewDistrict = false;
            if (!string.IsNullOrEmpty(data.WorkingDistrictName))
            {
                recsys_district workingDistrict = this._db.recsys_district.Where(x => x.name.Trim().ToUpper().Equals(data.WorkingDistrictName.Trim().ToUpper())).SingleOrDefault();
                if (workingDistrict != null)
                {
                    data.district2 = workingDistrict.id;
                    data.group_id = workingDistrict.group_id;
                }
                else
                    createNewDistrict = true;
            }

            if (createNewDistrict)
            {
                recsys_district addNewDistrict = new recsys_district()
                {
                    code = data.WorkingDistrictName.Trim(),
                    name = data.WorkingDistrictName.Trim(),
                    group_id = this._db.recsys_group.Where(x => x.name.Equals("Unknown Group For System Migration")).SingleOrDefault().id,
                    region = 4,
                    status = 1,
                    last_update = DateTime.Now,
                    update_user_id = (int)member.infoBySession("id")
                };

                this._db.recsys_district.AddObject(addNewDistrict);
                this._db.SaveChanges();

                data.district2 = this._db.recsys_district.Where(x => x.name.Equals(data.WorkingDistrictName.Trim())).SingleOrDefault().id;
                data.group_id = this._db.recsys_district.Where(x => x.name.Equals(data.WorkingDistrictName.Trim())).SingleOrDefault().group_id;
            }

            createNewDistrict = false;
            if (!string.IsNullOrEmpty(data.MailingDistrictName))
            {
                recsys_district mailingDistrict = this._db.recsys_district.Where(x => x.name.Trim().ToUpper().Equals(data.MailingDistrictName.Trim().ToUpper())).SingleOrDefault();
                if (mailingDistrict != null)
                {
                    data.district1 = mailingDistrict.id;
                    data.group_id = mailingDistrict.group_id;
                }
                else
                    createNewDistrict = true;
            }

            if (createNewDistrict)
            {
                recsys_district addNewDistrict = new recsys_district()
                {
                    code = data.MailingDistrictName.Trim(),
                    name = data.MailingDistrictName.Trim(),
                    group_id = this._db.recsys_group.Where(x => x.name.Equals("Unknown Group For System Migration")).SingleOrDefault().id,
                    region = 4,
                    status = 1,
                    last_update = DateTime.Now,
                    update_user_id = (int)member.infoBySession("id")
                };

                this._db.recsys_district.AddObject(addNewDistrict);
                this._db.SaveChanges();

                data.district1 = this._db.recsys_district.Where(x => x.name.Equals(data.MailingDistrictName.Trim())).SingleOrDefault().id;
                data.group_id = this._db.recsys_district.Where(x => x.name.Equals(data.MailingDistrictName.Trim())).SingleOrDefault().group_id;
            }

            //# get old master customer record
            if (data.MasterRecordType == OrderMasterRecordType.quotation)
                return this.AddSave_Quotation(data);
            else
                return this.AddSave_Maintenance(data);
        }
        public ActionResult Edit()
        {
            Validator _val = new Validator();
            string id = Common.doPost("id");
            string name = Common.doPost("name");
            string type_id = Common.doPost("type_id2");
            string user_group = Common.doPost("user_group");
            string center = Common.doPost("center");
            string grade = Common.doPost("grade2");
            string employee_number = Common.doPost("employee_number");
            string username = Common.doPost("username");
            string oldpassword = Common.doPost("oldpassword");
            string password = Common.doPost("password");
            string password2 = Common.doPost("password2");
            string country_id = Common.doPost("country_id2");
            string phone_number = Common.doPost("phone_number");
            string email = Common.doPost("email");
            string status = Common.doPost("status2");
            string oper = Common.doPost("oper");
            string encryptedOldPassword = "";
            string encryptedOldPasswordDB = "";
            Member _member = new Member("users");
            if(oper != "del")
            {
                if(oper == "edit")
                {
                    _val.val(id, new String[] { "req", "int" });

                    if (!String.IsNullOrWhiteSpace(password) || !String.IsNullOrWhiteSpace(password2))
                    {
                        int userID =  Convert.ToInt32(id);
                        encryptedOldPasswordDB = (from u in this._db.recsys_users
                                                  where u.id == userID
                                                  select u.password).FirstOrDefault();
                        string salt = encryptedOldPasswordDB.Substring(0, 20);
                        encryptedOldPassword = _member.encrypt(oldpassword, salt);
                        if (!encryptedOldPassword.Equals(encryptedOldPasswordDB))
                            return Content("oldPasswordNotMatch");
                    }
                }
                _val.val(name, "req");
                _val.val(type_id, new String[] { "req", "int" });
                _val.val(user_group, new String[] { "req", "int", "get=0" });
                _val.val(center, new String[] { "req", "int" });
                _val.val(country_id, new String[] { "req", "int" });
                if (!string.IsNullOrWhiteSpace(phone_number)) _val.val(phone_number, "int");
                if (email != null)
                {
                    _val.val(email, "email");
                }
                _val.val(status, new String[] { "req", "int", "get=0", "let=1" });
                int t_id = Convert.ToInt32(type_id);
                Byte type = (from t in this._db.recsys_type
                             where t.status == 1 && t.id == t_id
                             select t.type).FirstOrDefault();
                if (!String.IsNullOrWhiteSpace(username))
                {
                    if (_member.isExist(username, "username", oper != "edit" ? "" : "id != '" + id + "'"))
                    {
                        _val.setValStatus(false);
                    }
                }
                if (!String.IsNullOrWhiteSpace(password) || !String.IsNullOrWhiteSpace(password2))
                {
                    _val.val(password, "req");
                    _val.val(password2, new String[] { "req", "equal=" + password });
                }
                if (type == null || !this._ctr.Contains(center))
                {
                    _val.setValStatus(false);
                }
                if (this.isDuplicatePhoneNumber(phone_number, id, country_id))
                {
                    _val.setValStatus(false);
                }
                if(_val.getValStatus())
                {
                    grade = string.IsNullOrEmpty(grade) ? null : grade;
                    Hashtable data = new Hashtable() {
                        { "name", name },
                        { "type_id", type_id },
                        { "type", type },
                        { "user_group", user_group },
                        { "center", center },
                        { "username", username },
                        { "email", email },
                        { "status", status },
                        { "last_update", DateTime.Now.ToString("s") },
                        { "update_user_id", _member.infoBySession("id") },
                        { "employee_number", employee_number},
                        { "country_id", country_id },
                        { "phone_number", phone_number },
                        { "grade", grade }
                    };
                    if(! String.IsNullOrWhiteSpace(password)) {
                        data["password"] = password;
                    }
                    if(oper == "edit")
                    {
                        _member.update(data, id, "id");
                    }
                    else
                    {
                        _member.insert(data);
                        id = (from m in this._db.recsys_users
                              orderby m.id descending
                              select m.id).FirstOrDefault().ToString();
                    }
                }
                else
                {
                    return Content("false");
                }
            }
            else
            {
                this._db.ExecuteStoreCommand(Common.doDelete("relate", "id2 = '" + id + "' AND table1 = 'group' AND table2 = 'users'"));
                _member.delete(Convert.ToInt32(id));
                Common.delDir("Upload/users/" + id + "/");
            }
            return Content(id);
        }
        public ActionResult Table_Technician(
            int page,       //# jqGrid parameter
            int rows,       //# jqGrid parameter
            bool _search,       //# jqGrid parameter
            string filters,       //# jqGrid parameter
            string sidx,       //# jqGrid parameter
            string sord,       //# jqGrid parameter
            string repairDateOnOrBefore,      //# UI filters
            bool showECall,        //# UI filters
            bool showContractOrder,        //# UI filters
            int? orderStatus,   //# UI filters
            bool check_last_update = false)
        {
            Member member = new Member("users");
            int technicianID = (int)member.infoBySession("id");
            Rec_System.Functions.JqGrid.Filter filterList = Rec_System.Functions.JqGrid.Filter.ConvertFromJqGridFilterString(filters);

            var entities = from o in this._db.recsys_order
                           join c in this._db.recsys_relate_customers on o.customer_id equals c.id into cs
                           from c in cs.DefaultIfEmpty()
                           join eng1 in this._db.recsys_users on o.engineer_id_1 equals eng1.id into eng1s
                           from eng1 in eng1s.DefaultIfEmpty()
                           join eng2 in this._db.recsys_users on o.engineer_id_2 equals eng2.id into eng2s
                           from eng2 in eng2s.DefaultIfEmpty()
                           join eng3 in this._db.recsys_users on o.engineer_id_3 equals eng3.id into eng3s
                           from eng3 in eng3s.DefaultIfEmpty()
                           join eng4 in this._db.recsys_users on o.engineer_id_4 equals eng4.id into eng4s
                           from eng4 in eng4s.DefaultIfEmpty()
                           join cu in this._db.recsys_users on o.call_pickup_user_id equals cu.id into cus
                           from cu in cus.DefaultIfEmpty()
                           where o.engineer_id_1 == technicianID || o.engineer_id_2 == technicianID || o.engineer_id_3 == technicianID || o.engineer_id_4 == technicianID
                           select new OrderIndexRecord()
                           {
                               ID = o.id,
                               WorkingAddress = c.address2,
                               CallPicker = cu.name,
                               CompleteDate = o.completion_date,
                               CreateDate = o.create_date,
                               EndTime = o.end_time,
                               Fault = o.fault,
                               OrderRemark = o.remark,
                               RepairDate = o.repair_date,
                               StartTime = o.start_time,
                               Status = o.status,
                               Worker1 = eng1.name,
                               Worker2 = eng2.name,
                               Worker3 = eng3.name,
                               Worker4 = eng4.name,
                               BySystem = o.by_system,
                               LastUpdateTime = o.last_update,
                               order_status = o.order_status
                           };

            //# handle UI filters
            if (showECall && !showContractOrder)
                entities = entities.Where(theRecord => theRecord.BySystem == 0);
            else if (!showECall && showContractOrder)
                entities = entities.Where(theRecord => theRecord.BySystem == 1);
            else if (!showECall && !showContractOrder)
                entities = entities.Where(theRecord => theRecord.BySystem != 0 && theRecord.BySystem != 1);
            if (!string.IsNullOrEmpty(repairDateOnOrBefore))
                entities = entities.Where(theRecord => theRecord.RepairDate <= DateTime.ParseExact(repairDateOnOrBefore, "dd-MM-yyyy", null));
            if (orderStatus.HasValue && orderStatus.Value != 0)
                entities = entities.Where(theRecord => theRecord.order_status == orderStatus.Value);

            //# handle searching
            if (filterList != null)
                entities = entities.SearchBy(filterList);

            //# use to check if data has updated
            if (check_last_update)
            {
                DateTime? lastUpdate = entities.Max(theRecord => theRecord.LastUpdateTime);
                int recordCount = entities.Count();

                return Content(Common.md5(lastUpdate.ToString() + recordCount));
            }
            else    //# get row results
            {
                Result result;
                int totalRecordCount;
                int currentPage;
                int pageSize;
                double totalPages;
                string sortBy = sidx;        //# get from jqGrid parameter
                string sortDirection = sord;        //# get from jqGrid parameter

                //# handle sorting
                if (!string.IsNullOrEmpty(sortBy))
                {
                    entities = entities.OrderBy(sortBy, sortDirection.Trim() == "desc");
                }

                //# make JqGrid source result
                totalRecordCount = entities.Count();
                currentPage = page;        //# get from jqGrid parameter
                pageSize = rows;        //# get from jqGrid parameter
                totalPages = Math.Ceiling((double)totalRecordCount / pageSize);
                result = new Result()
                {
                    rows = this.ConvertJqGridRecord_Index(entities.Skip((currentPage - 1) * pageSize).Take(pageSize).ToArray()),
                    page = currentPage,
                    records = entities.Count(),
                    total = totalPages
                };

                return Json(result, JsonRequestBehavior.AllowGet);
            }
        }
        public ActionResult AddSave_Quotation(OrderRecord data)
        {
            Member member;
            recsys_relate_customers masterCustomerData;
            recsys_relate_customers customerData;
            recsys_order order;
            recsys_relate relation;

            //# validation
            if (data.MasterRecordID < 0)
                throw new SystemException("Invalid Entity ID");

            //# get old master customer record
            var _masterCustomerData = from q in this._db.recsys_quotation
                                      join cd in this._db.recsys_relate_customers on q.customer_id equals cd.id into cds
                                      from cd in cds.DefaultIfEmpty()
                                      where q.id == data.MasterRecordID
                                      select new
                                      {
                                          cd
                                      };
            masterCustomerData = _masterCustomerData.Select(theRecord => theRecord.cd).FirstOrDefault();

            //# validation
            if (masterCustomerData == null)
                throw new RecordNotFoundException();

            member = new Member("users");

            //# mapping
            customerData = new recsys_relate_customers()
            {
                address1 = data.address1,
                address2 = data.address2,
                center = masterCustomerData.center,
                code = masterCustomerData.code,
                contact = data.contact,
                customer_code = masterCustomerData.customer_code,
                customer_id = masterCustomerData.customer_id,
                district1 = data.district1,
                district2 = data.district2,
                email = data.email,
                fax1 = data.fax1,
                fax2 = data.fax2,
                group_id = data.group_id,
                manual_input_code = masterCustomerData.manual_input_code,
                name = data.name,
                chi_name = data.chi_name,
                prefix = masterCustomerData.prefix,
                relate_type = (int)Rec_System.Models.Customers.CustomerDataRelateType.Quotation,
                remark = data.remark,
                tel1 = data.tel1,
                tel2 = data.tel2,
                title = (byte)data.title,
                type = (byte)masterCustomerData.type
            };

            this._db.recsys_relate_customers.AddObject(customerData);

            TimeSpan? endTime = null;
            if (!(String.IsNullOrEmpty(data.EndTimeHour)) && !(String.IsNullOrEmpty(data.EndTimeMinute)))
                endTime = new TimeSpan(Convert.ToInt32(data.EndTimeHour), Convert.ToInt32(data.EndTimeMinute), 0);

            TimeSpan? startTime = null;
            if (!(String.IsNullOrEmpty(data.StartTimeHour)) && !(String.IsNullOrEmpty(data.StartTimeMinute)))
                startTime = new TimeSpan(Convert.ToInt32(data.StartTimeHour), Convert.ToInt32(data.StartTimeMinute), 0);

            order = new recsys_order()
            {
                by_system = 1,
                completion_date = DateChecking(data.CompleteDate),
                end_time = endTime,
                engineer_id_1 = data.engineer_id_1,
                engineer_id_2 = data.engineer_id_2,
                engineer_id_3 = data.engineer_id_3,
                engineer_id_4 = data.engineer_id_4,
                fault = data.fault,
                model = data.model,
                repair = data.repair,
                repair_date = DateChecking(data.repair_date),
                report = data.report,
                reviewer = data.reviewer,
                start_time = startTime,
                tc = (byte)(data.tc ? 1 : 0),
                create_date = DateTime.Now,
                last_update = DateTime.Now,
                remark = data.remark2,
                status = (byte)data.status,
                update_user_id = (int)member.infoBySession("id"),
                job_number = data.JobNumber,
                order_status = data.order_status
            };

            //alter 故障內容
            if (!string.IsNullOrEmpty(order.fault))
            {
                int index1 = order.fault.IndexOf("[");
                int index2 = order.fault.IndexOf("]");
                if (index1 > -1 && index2 > -1)
                    order.fault = order.fault.Substring(index2 + 1);
            }

            if (order.completion_date.HasValue)
            {
                order.order_status = OrderStatus.WarrantyCompleted.ID;
                order.fault = "[" + OrderStatus.WarrantyCompleted.Name + "] " + order.fault;
            }
            else if (order.order_status == OrderStatus.DoingWarranty.ID)
            {
                order.fault = "[" + OrderStatus.DoingWarranty.Name + "] " + order.fault;
                order.order_status = OrderStatus.DoingWarranty.ID;
            }
            else if (order.order_status == OrderStatus.AppointedWarranty.ID)
            {
                order.fault = "[" + OrderStatus.AppointedWarranty.Name + "] " + order.fault;
                order.order_status = OrderStatus.AppointedWarranty.ID;
            }

            this._db.recsys_order.AddObject(order);

            try
            {
                this._db.SaveChanges();

                this._db.Refresh(System.Data.Objects.RefreshMode.StoreWins, customerData);
                this._db.Refresh(System.Data.Objects.RefreshMode.StoreWins, order);

                order.customer_id = customerData.id;

                this._db.SaveChanges();

                data.id = order.id;

                relation = new recsys_relate()
                {
                    id1 = data.MasterRecordID,
                    id2 = order.id,
                    table1 = "quotation",
                    table2 = "order"
                };

                this._db.recsys_relate.AddObject(relation);

                this._db.SaveChanges();

                data.SaveResult.SavedSuccessfully = true;
            }
            catch (OptimisticConcurrencyException)
            {
                //# log down
            }

            return Json(data);
        }
        public ActionResult AddSave(QuotationRecord data)
        {
            Member member;
            recsys_customers masterCustomer;
            recsys_relate_customers customerData;
            recsys_quotation quotation;

            //# validation
            if (!String.IsNullOrEmpty(data.invoice) && data.dummy)
            {
                data.SaveResult.WarningMessage = "請刪除Invoice No或取消選取'有Dummy Invoice'";
                data.SaveResult.SavedSuccessfully = false;
                return Json(data);
            }

            if (!String.IsNullOrEmpty(data.minor_work))
            {
                if (data.minor_work.Length > 3)
                {
                    data.SaveResult.WarningMessage = "請修改Minor Work至3字以內";
                    data.SaveResult.SavedSuccessfully = false;
                    return Json(data);
                }
            }

            //# validation
            if (data.MasterCustomerID < 0)
                throw new SystemException("Invalid Entity ID");

            //# get old master customer record
            masterCustomer = this._db.recsys_customers.FirstOrDefault(theCustomer => theCustomer.id == data.MasterCustomerID);

            //# validation
            if (masterCustomer == null)
                throw new RecordNotFoundException();

            member = new Member("users");

            bool createNewDistrict = false;
            if (!string.IsNullOrEmpty(data.WorkingDistrictName))
            {
                recsys_district workingDistrict = this._db.recsys_district.Where(x => x.name.Trim().ToUpper().Equals(data.WorkingDistrictName.Trim().ToUpper())).SingleOrDefault();
                if (workingDistrict != null)
                {
                    data.district2 = workingDistrict.id;
                    data.group_id = workingDistrict.group_id;
                }
                else
                    createNewDistrict = true;
            }

            if (createNewDistrict)
            {
                recsys_district addNewDistrict = new recsys_district()
                {
                    code = data.WorkingDistrictName.Trim(),
                    name = data.WorkingDistrictName.Trim(),
                    group_id = this._db.recsys_group.Where(x => x.name.Equals("Unknown Group For System Migration")).SingleOrDefault().id,
                    region = 4,
                    status = 1,
                    last_update = DateTime.Now,
                    update_user_id = (int)member.infoBySession("id")
                };

                this._db.recsys_district.AddObject(addNewDistrict);
                this._db.SaveChanges();

                data.district2 = this._db.recsys_district.Where(x => x.name.Equals(data.WorkingDistrictName.Trim())).SingleOrDefault().id;
                data.group_id = this._db.recsys_district.Where(x => x.name.Equals(data.WorkingDistrictName.Trim())).SingleOrDefault().group_id;
            }

            createNewDistrict = false;
            if (!string.IsNullOrEmpty(data.MailingDistrictName))
            {
                recsys_district mailingDistrict = this._db.recsys_district.Where(x => x.name.Trim().ToUpper().Equals(data.MailingDistrictName.Trim().ToUpper())).SingleOrDefault();
                if (mailingDistrict != null)
                {
                    data.district1 = mailingDistrict.id;
                    data.group_id = mailingDistrict.group_id;
                }
                else
                    createNewDistrict = true;
            }

            if (createNewDistrict)
            {
                recsys_district addNewDistrict = new recsys_district()
                {
                    code = data.MailingDistrictName.Trim(),
                    name = data.MailingDistrictName.Trim(),
                    group_id = this._db.recsys_group.Where(x => x.name.Equals("Unknown Group For System Migration")).SingleOrDefault().id,
                    region = 4,
                    status = 1,
                    last_update = DateTime.Now,
                    update_user_id = (int)member.infoBySession("id")
                };

                this._db.recsys_district.AddObject(addNewDistrict);
                this._db.SaveChanges();

                data.district1 = this._db.recsys_district.Where(x => x.name.Equals(data.MailingDistrictName.Trim())).SingleOrDefault().id;
                data.group_id = this._db.recsys_district.Where(x => x.name.Equals(data.MailingDistrictName.Trim())).SingleOrDefault().group_id;
            }

            //# mapping
            customerData = new recsys_relate_customers()
            {
                address1 = data.address1,
                address2 = data.address2,
                center = masterCustomer.center,
                code = masterCustomer.code,
                contact = data.contact,
                customer_code = masterCustomer.customer_code,
                customer_id = masterCustomer.id,
                district1 = data.district1,
                district2 = data.district2,
                email = data.email,
                fax1 = data.fax1,
                fax2 = data.fax2,
                group_id = data.group_id,
                manual_input_code = masterCustomer.manual_input_code,
                name = data.name,
                chi_name = data.chi_name,
                prefix = masterCustomer.prefix,
                relate_type = (int)Rec_System.Models.Customers.CustomerDataRelateType.Maintenance,
                reference_number = masterCustomer.reference_number,
                remark = data.remark,
                tel1 = data.tel1,
                tel2 = data.tel2,
                title = (byte)data.title,
                type = (byte)masterCustomer.type
            };

            this._db.recsys_relate_customers.AddObject(customerData);

            quotation = new recsys_quotation()
            {
                dummy = (byte)(data.dummy ? 1 : 0),
                dummy_date = DateChecking(data.dummy_date),
                initial = data.initial,
                lang = data.lang,
                order_number = data.order_number,
                number = data.number,
                subcon_estimation = data.subcon_estimation.HasValue ? data.subcon_estimation : 0.00,
                subcon_name = data.subcon_name,
                subcon_estimation2 = data.subcon_estimation2.HasValue ? data.subcon_estimation2 : 0.00,
                subcon_name2 = data.subcon_name2,
                subcon_estimation3 = data.subcon_estimation3.HasValue ? data.subcon_estimation3 : 0.00,
                subcon_name3 = data.subcon_name3,
                supervision = data.supervision.HasValue ? data.supervision : 0.00,
                supplier_name = data.supplier_name,
                supplier_name2 = data.supplier_name2,
                supplier_name3 = data.supplier_name3,
                supplier_estimation = data.supplier_estimation.HasValue ? data.supplier_estimation : 0.00,
                supplier_estimation2 = data.supplier_estimation2.HasValue ? data.supplier_estimation2 : 0.00,
                supplier_estimation3 = data.supplier_estimation3.HasValue ? data.supplier_estimation3 : 0.00,
                supplier_id = data.supplier_id.HasValue ? data.supplier_id : 0.00,
                material_estimation2 = data.material_estimation2.HasValue ? data.material_estimation2 : 0.00,
                material_estimation3 = data.material_estimation3.HasValue ? data.material_estimation3 : 0.00,
                payment_received_date = DateChecking(data.payment_received_date),
                tender_number = data.tender_number,
                direct_labour = data.direct_labour,
                direct_labour_cost = data.direct_labour_cost.HasValue ? data.direct_labour_cost : 0.00,
                billing_date = DateChecking(data.billing_date),
                confirm_date = DateChecking(data.confirm_date),
                create_date = DateTime.Now,
                invoice = data.invoice,
                invoice_date = DateChecking(data.billing_date),
                minor_work = data.minor_work,
                minor_work_currency = data.minor_work_currency.HasValue ? data.minor_work_currency : 0.00,
                gp = data.gp.HasValue ? data.gp : 0.00,
                last_update = DateTime.Now,
                remark = data.remark2,
                status = (byte)data.status,
                update_user_id = (int)member.infoBySession("id"),
                issue_date = DateChecking(data.issue_date)
            };

            this._db.recsys_quotation.AddObject(quotation);

            try
            {
                this._db.SaveChanges();

                this._db.Refresh(System.Data.Objects.RefreshMode.StoreWins, customerData);
                this._db.Refresh(System.Data.Objects.RefreshMode.StoreWins, quotation);

                quotation.customer_id = customerData.id;

                this._db.SaveChanges();

                data.id = quotation.id;

                data.SaveResult.SavedSuccessfully = true;
            }
            catch (OptimisticConcurrencyException)
            {
                //# log down
            }

            return Json(data);
        }
 public ActionResult Logout()
 {
     Member _member = new Member("users");
     _member.logout();
     return RedirectToAction("index", "login");
 }
        public ActionResult CloneQuotation(int? id)
        {
            //# validation
            if (!id.HasValue)
                return Json(new { bIsSuccessful = false });

            bool isSuccessful = false;
            Member member = new Member("users");
            int newQuotationID = 0;

            try
            {
                //# get existing quotation
                recsys_quotation existingQuotation = this._db.recsys_quotation.FirstOrDefault(theQuotation => theQuotation.id == id.Value);
                if (existingQuotation != null)
                {
                    //# get existing quotation customer data
                    recsys_relate_customers existingQuotationCustomerData = this._db.recsys_relate_customers.FirstOrDefault(theCustomerData => theCustomerData.id == existingQuotation.customer_id);

                    if (existingQuotationCustomerData != null)
                    {
                        //# get existing quotation items
                        IEnumerable<recsys_quotation_items> existingQuotationItems = from r in this._db.recsys_relate
                                                                                     join qi in this._db.recsys_quotation_items on r.id2 equals qi.id
                                                                                     where r.id1 == id.Value
                                                                                     && r.table1 == "quotation"
                                                                                     && r.table2 == "quotation_items"
                                                                                     select qi;

                        //# construct new customer data
                        recsys_relate_customers newQuotationCustomerData = CustomersController.CopyCustomerData(existingQuotationCustomerData);

                        //# construct new quotation items
                        recsys_quotation_items[] newQuotationItems = existingQuotationItems.Select(theItem => QuotationsController.CopyQuotationItem(theItem)).ToArray();

                        this._db.recsys_relate_customers.AddObject(newQuotationCustomerData);
                        foreach (recsys_quotation_items item in newQuotationItems)
                        {
                            item.last_update = DateTime.Now;
                            item.update_user_id = (int)member.infoBySession("id");
                            this._db.recsys_quotation_items.AddObject(item);
                        }

                        //# save customer data
                        this._db.SaveChanges();

                        //# load new customer data
                        this._db.Refresh(RefreshMode.StoreWins, newQuotationCustomerData);

                        //# load new items
                        this._db.Refresh(RefreshMode.StoreWins, newQuotationItems);

                        if (newQuotationCustomerData.id > 0)
                        {

                            //# construct new quotation
                            recsys_quotation newQuotation = new recsys_quotation();

                            newQuotation.create_date = DateTime.Now;
                            newQuotation.customer_id = newQuotationCustomerData.id;
                            newQuotation.last_update = DateTime.Now;
                            newQuotation.update_user_id = (int)member.infoBySession("id");
                            newQuotation.status = 1;
                            newQuotation.issue_date = DateTime.Now.Date;
                            if (existingQuotation.lang != 0)
                                newQuotation.lang = existingQuotation.lang;
                            else newQuotation.lang = 1; //default chinese

                            this._db.recsys_quotation.AddObject(newQuotation);

                            //# save quotation
                            this._db.SaveChanges();

                            //# load new quotation
                            this._db.Refresh(RefreshMode.StoreWins, newQuotation);

                            newQuotationID = newQuotation.id;

                            if (newQuotation.id > 0 && newQuotationItems.Count(theItem => theItem.id > 0) > 0)
                            {
                                //# construct relations
                                IEnumerable<recsys_relate> relations = newQuotationItems.Where(theItem => theItem.id > 0)
                                    .Select(theItem => new recsys_relate()
                                    {
                                        id1 = newQuotation.id,
                                        id2 = theItem.id,
                                        table1 = "quotation",
                                        table2 = "quotation_items"
                                    });

                                foreach (recsys_relate relation in relations)
                                    this._db.recsys_relate.AddObject(relation);

                                //# save relations
                                this._db.SaveChanges();

                                isSuccessful = true;

                            }
                            else
                                isSuccessful = true;

                        }

                    }

                }

                //# clone quotation
                //# save changes
            }
            catch (OptimisticConcurrencyException)
            {
                //# log down
            }

            return Json(new { bIsSuccessful = isSuccessful, iNewID = newQuotationID });
        }
 public ActionResult isExist()
 {
     string username = Common.doPost("username");
     string id = Common.doPost("id");
     Member _member = new Member("users");
     return Content(_member.isExist(username, "username", String.IsNullOrWhiteSpace(id) ? "" : "id != '" + id + "'") ? "false" : "true");
 }
        public ActionResult EditSave(OrderRecord data)
        {
            recsys_order order;
            recsys_relate_customers customerData;

            //# validation
            if (data.id < 0)
                throw new SystemException("Invalid Entity ID");

            int timeInt = 0;
            if (!String.IsNullOrEmpty(data.StartTimeHour))
            {
                if (!Int32.TryParse(data.StartTimeHour, out timeInt) || Convert.ToInt32(data.StartTimeHour) < 0 || Convert.ToInt32(data.StartTimeHour) > 23)
                {
                    data.SaveResult.WarningMessage = "請修改開始時間";
                    data.SaveResult.SavedSuccessfully = false;
                    return Json(data);
                }
            }
            if (!String.IsNullOrEmpty(data.StartTimeMinute))
            {
                if (!Int32.TryParse(data.StartTimeMinute, out timeInt) || Convert.ToInt32(data.StartTimeMinute) < 0 || Convert.ToInt32(data.StartTimeMinute) > 59)
                {
                    data.SaveResult.WarningMessage = "請修改開始時間";
                    data.SaveResult.SavedSuccessfully = false;
                    return Json(data);
                }
            }
            if (!String.IsNullOrEmpty(data.EndTimeHour))
            {
                if (!Int32.TryParse(data.EndTimeHour, out timeInt) || Convert.ToInt32(data.EndTimeHour) < 0 || Convert.ToInt32(data.EndTimeHour) > 23)
                {
                    data.SaveResult.WarningMessage = "請修改結束時間";
                    data.SaveResult.SavedSuccessfully = false;
                    return Json(data);
                }
            }
            if (!String.IsNullOrEmpty(data.EndTimeMinute))
            {
                if (!Int32.TryParse(data.EndTimeMinute, out timeInt) || Convert.ToInt32(data.EndTimeMinute) < 0 || Convert.ToInt32(data.EndTimeMinute) > 59)
                {
                    data.SaveResult.WarningMessage = "請修改結束時間";
                    data.SaveResult.SavedSuccessfully = false;
                    return Json(data);
                }
            }
            if (!String.IsNullOrEmpty(data.repair_date) && !String.IsNullOrEmpty(data.CompleteDate))
            {
                if (DateTime.ParseExact(data.CompleteDate, "dd-MM-yyyy", null) < DateTime.ParseExact(data.repair_date, "dd-MM-yyyy", null))
                {
                    data.SaveResult.WarningMessage = "完成日期應在維修日期之後";
                    data.SaveResult.SavedSuccessfully = false;
                    return Json(data);
                }
            }

            //# get old record
            var records = from e in this._db.recsys_order
                          join c in this._db.recsys_relate_customers on e.customer_id equals c.id into cs
                          from c in cs.DefaultIfEmpty()
                          where e.id == data.id
                          select new
                          {
                              Order = e,
                              CustomerData = c
                          };
            var record = records.FirstOrDefault();

            Member member = new Member("users");

            //# validation
            if (record == null)
                throw new RecordNotFoundException();

            order = record.Order;
            customerData = record.CustomerData;

            //# validation
            if (order == null || customerData == null)
                throw new RecordNotFoundException();
            if (!order.last_update.HasValue)
                throw new ImproperDataException();
            if (order.last_update.Value > data.FetchRecordTime)
                throw new OptimisticConcurrencyException("資料已被其他使用者更新");

            bool createNewDistrict = false;
            if (!string.IsNullOrEmpty(data.WorkingDistrictName))
            {
                recsys_district workingDistrict = this._db.recsys_district.Where(x => x.name.Trim().ToUpper().Equals(data.WorkingDistrictName.Trim().ToUpper())).SingleOrDefault();
                if (workingDistrict != null)
                {
                    data.district2 = workingDistrict.id;
                    data.group_id = workingDistrict.group_id;
                }
                else
                    createNewDistrict = true;
            }

            if (createNewDistrict)
            {
                recsys_district addNewDistrict = new recsys_district()
                {
                    code = data.WorkingDistrictName.Trim(),
                    name = data.WorkingDistrictName.Trim(),
                    group_id = this._db.recsys_group.Where(x => x.name.Equals("Unknown Group For System Migration")).SingleOrDefault().id,
                    region = 4,
                    status = 1,
                    last_update = DateTime.Now,
                    update_user_id = (int)member.infoBySession("id")
                };

                this._db.recsys_district.AddObject(addNewDistrict);
                this._db.SaveChanges();

                data.district2 = this._db.recsys_district.Where(x => x.name.Equals(data.WorkingDistrictName.Trim())).SingleOrDefault().id;
                data.group_id = this._db.recsys_district.Where(x => x.name.Equals(data.WorkingDistrictName.Trim())).SingleOrDefault().group_id;
            }

            createNewDistrict = false;
            if (!string.IsNullOrEmpty(data.MailingDistrictName))
            {
                recsys_district mailingDistrict = this._db.recsys_district.Where(x => x.name.Trim().ToUpper().Equals(data.MailingDistrictName.Trim().ToUpper())).SingleOrDefault();
                if (mailingDistrict != null)
                {
                    data.district1 = mailingDistrict.id;
                    data.group_id = mailingDistrict.group_id;
                }
                else
                    createNewDistrict = true;
            }

            if (createNewDistrict)
            {
                recsys_district addNewDistrict = new recsys_district()
                {
                    code = data.MailingDistrictName.Trim(),
                    name = data.MailingDistrictName.Trim(),
                    group_id = this._db.recsys_group.Where(x => x.name.Equals("Unknown Group For System Migration")).SingleOrDefault().id,
                    region = 4,
                    status = 1,
                    last_update = DateTime.Now,
                    update_user_id = (int)member.infoBySession("id")
                };

                this._db.recsys_district.AddObject(addNewDistrict);
                this._db.SaveChanges();

                data.district1 = this._db.recsys_district.Where(x => x.name.Equals(data.MailingDistrictName.Trim())).SingleOrDefault().id;
                data.group_id = this._db.recsys_district.Where(x => x.name.Equals(data.MailingDistrictName.Trim())).SingleOrDefault().group_id;
            }

            //# saving
            //# mapping
            order.by_system = 1;
            order.completion_date = DateChecking(data.CompleteDate);
            if ((String.IsNullOrEmpty(data.EndTimeHour)) && (String.IsNullOrEmpty(data.EndTimeMinute)))
                order.end_time = null;
            else
                order.end_time = new TimeSpan(Convert.ToInt32(data.EndTimeHour), Convert.ToInt32(data.EndTimeMinute), 0);
            order.engineer_id_1 = data.engineer_id_1;
            order.engineer_id_2 = data.engineer_id_2;
            order.engineer_id_3 = data.engineer_id_3;
            order.engineer_id_4 = data.engineer_id_4;
            order.fault = data.fault;
            order.last_update = DateTime.Now;
            order.model = data.model;
            order.remark = data.remark2;
            order.repair = data.repair;
            order.repair_date = DateChecking(data.repair_date);
            order.report = data.report;
            order.reviewer = data.reviewer;
            if ((String.IsNullOrEmpty(data.StartTimeHour)) && (String.IsNullOrEmpty(data.StartTimeMinute)))
                order.start_time = null;
            else
                order.start_time = new TimeSpan(Convert.ToInt32(data.StartTimeHour), Convert.ToInt32(data.StartTimeMinute), 0);
            order.status = (byte)data.status;
            order.tc = (byte)(data.tc ? 1 : 0);
            order.update_user_id = (int)member.infoBySession("id");
            order.job_number = data.JobNumber;
            order.order_status = data.order_status;
            customerData.address1 = data.address1;
            customerData.address2 = data.address2;
            customerData.contact = data.contact;
            customerData.district1 = data.district1;
            customerData.district2 = data.district2;
            customerData.email = data.email;
            customerData.fax1 = data.fax1;
            customerData.fax2 = data.fax2;
            customerData.group_id = data.group_id;
            customerData.name = data.name;
            customerData.chi_name = data.chi_name;
            customerData.remark = data.remark;
            customerData.tel1 = data.tel1;
            customerData.tel2 = data.tel2;
            customerData.title = (byte)data.title;
            customerData.reference_number = data.customer_reference_number;

            //alter 故障內容
            if (!string.IsNullOrEmpty(order.fault))
            {
                int index1 = order.fault.IndexOf("[");
                int index2 = order.fault.IndexOf("]");
                if (index1 > -1 && index2 > -1)
                    order.fault = order.fault.Substring(index2 + 1);
            }

            if (order.completion_date.HasValue)
            {
                order.order_status = OrderStatus.WarrantyCompleted.ID;
                order.fault = "[" + OrderStatus.WarrantyCompleted.Name + "] " + order.fault;
            }
            else if (order.order_status == OrderStatus.DoingWarranty.ID)
            {
                order.fault = "[" + OrderStatus.DoingWarranty.Name + "] " + order.fault;
                order.order_status = OrderStatus.DoingWarranty.ID;
            }
            else if (order.order_status == OrderStatus.AppointedWarranty.ID)
            {
                order.fault = "[" + OrderStatus.AppointedWarranty.Name + "] " + order.fault;
                order.order_status = OrderStatus.AppointedWarranty.ID;
            }

            try
            {
                this._db.SaveChanges();
                this._db.Refresh(System.Data.Objects.RefreshMode.StoreWins, order);
                data.id = order.id;
                data.SaveResult.SavedSuccessfully = true;
            }
            catch (OptimisticConcurrencyException)
            {
                //# log down
            }

            return Json(data);
        }
 public ActionResult isExistEmployeeNumber()
 {
     string employee_number = Common.doPost("employee_number");
     string id = Common.doPost("id");
     Member _member = new Member("users");
     return Content(_member.isExist(employee_number, "employee_number", String.IsNullOrWhiteSpace(id) ? "" : "id != '" + id + "'") ? "false" : "true");
 }
        public ActionResult DetailsAdd(recsys_quotation_packages data)
        {
            bool isSuccess = false;
            int id = 0;
            Member member = new Member("users");

            data.status = 1;
            data.create_date = DateTime.Now;
            data.create_by = (int)member.infoBySession("id");
            data.update_date = DateTime.Now;
            data.update_by = (int)member.infoBySession("id");

            data.code = data.code.Trim();

            if (data.package_name == null)
                data.package_name = "";
            else
                data.package_name = data.package_name.Trim();

            if (data.remark != null)
                data.remark = data.remark.Trim();

            if (data.price == null)
                data.price = 0.0;

            var quotationPackages = from qp in this._db.recsys_quotation_packages
                                    where qp.status == 1
                                    select qp;

            foreach (recsys_quotation_packages quotationPackage in quotationPackages)
            {
                if (!string.IsNullOrEmpty(data.code) && data.code.Trim().ToUpper() == quotationPackage.code.Trim().ToUpper())
                {
                    string message = "已有Quotation Package (" + data.code.Trim().ToUpper() + ")";

                    return Json(
                        new
                        {
                            isSuccess = isSuccess,
                            message = message
                        }, JsonRequestBehavior.AllowGet);
                }
            }

            this._db.recsys_quotation_packages.AddObject(data);

            try
            {
                this._db.SaveChanges();
                id = data.id;
                isSuccess = true;
            }
            catch (OptimisticConcurrencyException)
            {
                //# log down
            }

              //  return Content(Common.json_encode(true));
            return Json(
                new
                {
                    isSuccess = isSuccess,
                    newid = id
                }, JsonRequestBehavior.AllowGet);
        }
        public ActionResult Index()
        {
            Member member = new Member("users");

            OrderIndexViewModel model = new OrderIndexViewModel()
            {
                UserType = (UserType)int.Parse(member.infoBySession("type").ToString()),
                RepaireDateOnORBefore = null,
                ShowContractOrder = false,
                ShowECall = true,
                OrderStatus = 0,
                OrderStatuses = this._orderECallStatuses
            };

            return View(model);
        }
        public ActionResult EditSave(QuotationRecord data)
        {
            recsys_quotation quotation;
            recsys_relate_customers customerData;

            //# validation
            if (data.id < 0)
                throw new SystemException("Invalid Entity ID");

            if (!String.IsNullOrEmpty(data.invoice) && data.dummy)
            {
                data.SaveResult.WarningMessage = "請刪除Invoice No或取消選取'有Dummy Invoice'";
                data.SaveResult.SavedSuccessfully = false;
                return Json(data);
            }

            if (!String.IsNullOrEmpty(data.minor_work))
            {
                if (data.minor_work.Length > 3)
                {
                    data.SaveResult.WarningMessage = "請修改Minor Work至3字以內";
                    data.SaveResult.SavedSuccessfully = false;
                    return Json(data);
                }
            }
            //# get old record
            var records = from q in this._db.recsys_quotation
                          join c in this._db.recsys_relate_customers on q.customer_id equals c.id into cs
                          from c in cs.DefaultIfEmpty()
                          where q.id == data.id
                          select new
                          {
                              Quotation = q,
                              CustomerData = c
                          };
            var record = records.FirstOrDefault();

            Member member = new Member("users");

            //# validation
            if (record == null)
                throw new RecordNotFoundException();

            quotation = record.Quotation;
            customerData = record.CustomerData;

            //# validation
            if (quotation == null || customerData == null)
                throw new RecordNotFoundException();
            if (!quotation.last_update.HasValue)
                throw new ImproperDataException();
            if (quotation.last_update.Value > data.FetchRecordTime)
                throw new OptimisticConcurrencyException("資料已被其他使用者更新");

            bool createNewDistrict = false;
            if (!string.IsNullOrEmpty(data.WorkingDistrictName))
            {
                recsys_district workingDistrict = this._db.recsys_district.Where(x => x.name.Trim().ToUpper().Equals(data.WorkingDistrictName.Trim().ToUpper())).SingleOrDefault();
                if (workingDistrict != null)
                {
                    data.district2 = workingDistrict.id;
                    data.group_id = workingDistrict.group_id;
                }
                else
                    createNewDistrict = true;
            }

            if (createNewDistrict)
            {
                recsys_district addNewDistrict = new recsys_district()
                {
                    code = data.WorkingDistrictName.Trim(),
                    name = data.WorkingDistrictName.Trim(),
                    group_id = this._db.recsys_group.Where(x => x.name.Equals("Unknown Group For System Migration")).SingleOrDefault().id,
                    region = 4,
                    status = 1,
                    last_update = DateTime.Now,
                    update_user_id = (int)member.infoBySession("id")
                };

                this._db.recsys_district.AddObject(addNewDistrict);
                this._db.SaveChanges();

                data.district2 = this._db.recsys_district.Where(x => x.name.Equals(data.WorkingDistrictName.Trim())).SingleOrDefault().id;
                data.group_id = this._db.recsys_district.Where(x => x.name.Equals(data.WorkingDistrictName.Trim())).SingleOrDefault().group_id;
            }

            createNewDistrict = false;
            if (!string.IsNullOrEmpty(data.MailingDistrictName))
            {
                recsys_district mailingDistrict = this._db.recsys_district.Where(x => x.name.Trim().ToUpper().Equals(data.MailingDistrictName.Trim().ToUpper())).SingleOrDefault();
                if (mailingDistrict != null)
                {
                    data.district1 = mailingDistrict.id;
                    data.group_id = mailingDistrict.group_id;
                }
                else
                    createNewDistrict = true;
            }

            if (createNewDistrict)
            {
                recsys_district addNewDistrict = new recsys_district()
                {
                    code = data.MailingDistrictName.Trim(),
                    name = data.MailingDistrictName.Trim(),
                    group_id = this._db.recsys_group.Where(x => x.name.Equals("Unknown Group For System Migration")).SingleOrDefault().id,
                    region = 4,
                    status = 1,
                    last_update = DateTime.Now,
                    update_user_id = (int)member.infoBySession("id")
                };

                this._db.recsys_district.AddObject(addNewDistrict);
                this._db.SaveChanges();

                data.district1 = this._db.recsys_district.Where(x => x.name.Equals(data.MailingDistrictName.Trim())).SingleOrDefault().id;
                data.group_id = this._db.recsys_district.Where(x => x.name.Equals(data.MailingDistrictName.Trim())).SingleOrDefault().group_id;
            }

            //# saving
            //# mapping
            quotation.billing_date = DateChecking(data.billing_date);
            quotation.confirm_date = DateChecking(data.confirm_date);
            quotation.dummy = (byte)(data.dummy ? 1 : 0);
            quotation.dummy_date = DateChecking(data.dummy_date);
            quotation.initial = data.initial;
            quotation.invoice = data.invoice;
            quotation.invoice_date = DateChecking(data.billing_date);
            quotation.minor_work = data.minor_work;
            quotation.minor_work_currency = data.minor_work_currency.HasValue ? data.minor_work_currency : 0.00;
            quotation.gp = data.gp.HasValue ? data.gp : 0.0;
            quotation.lang = data.lang;
            quotation.last_update = DateTime.Now;
            quotation.order_number = data.order_number;
            quotation.number = data.number;
            quotation.remark = data.remark2;
            quotation.status = (byte)data.status;
            quotation.subcon_estimation = data.subcon_estimation.HasValue ? data.subcon_estimation : 0.00;
            quotation.subcon_name = data.subcon_name;
            quotation.subcon_estimation2 = data.subcon_estimation2.HasValue ? data.subcon_estimation2 : 0.00;
            quotation.subcon_name2 = data.subcon_name2;
            quotation.subcon_estimation3 = data.subcon_estimation3.HasValue ? data.subcon_estimation3 : 0.00;
            quotation.subcon_name3 = data.subcon_name3;
            quotation.supplier_name = data.supplier_name;
            quotation.supplier_name2 = data.supplier_name2;
            quotation.supplier_name3 = data.supplier_name3;
            quotation.supplier_estimation = data.supplier_estimation.HasValue ? data.supplier_estimation : 0.00;
            quotation.supplier_estimation2 = data.supplier_estimation2.HasValue ? data.supplier_estimation2 : 0.00;
            quotation.supplier_estimation3 = data.supplier_estimation3.HasValue ? data.supplier_estimation3 : 0.00;
            quotation.supervision = data.supervision.HasValue ? data.supervision : 0.00;
            quotation.supplier_id = data.supplier_id.HasValue ? data.supplier_id : 0.00;
            quotation.material_estimation2 = data.material_estimation2.HasValue ? data.material_estimation2 : 0.00;
            quotation.material_estimation3 = data.material_estimation3.HasValue ? data.material_estimation3 : 0.00;
            quotation.direct_labour = data.direct_labour;
            quotation.direct_labour_cost = data.direct_labour_cost.HasValue ? data.direct_labour_cost : 0.00;
            quotation.payment_received_date = DateChecking(data.payment_received_date);
            quotation.tender_number = data.tender_number;
            quotation.update_user_id = (int)member.infoBySession("id");
            quotation.issue_date = DateChecking(data.issue_date);
            customerData.address1 = data.address1;
            customerData.address2 = data.address2;
            customerData.contact = data.contact;
            customerData.district1 = data.district1;
            customerData.district2 = data.district2;
            customerData.email = data.email;
            customerData.fax1 = data.fax1;
            customerData.fax2 = data.fax2;
            customerData.group_id = data.group_id;
            customerData.name = data.name;
            customerData.chi_name = data.chi_name;
            customerData.remark = data.remark;
            customerData.tel1 = data.tel1;
            customerData.tel2 = data.tel2;
            customerData.title = (byte)data.title;

            try
            {
                this._db.SaveChanges();
                this._db.Refresh(System.Data.Objects.RefreshMode.StoreWins, quotation);
                data.id = quotation.id;
                data.SaveResult.SavedSuccessfully = true;
            }
            catch (OptimisticConcurrencyException)
            {
                //# log down
            }

            return Json(data);
        }