//private string getDistrict(int id)
        //{
        //    if (this._district[id] == null)
        //    {
        //        string name = (from d in this._db.recsys_district
        //                       where d.id == id
        //                       select d.name).FirstOrDefault();
        //        this._district[id] = name;
        //    }
        //    return (this._district[id] != null ? this._district[id].ToString() : String.Empty);
        //}
        public static recsys_relate_customers CopyCustomerData(recsys_relate_customers target)
        {
            recsys_relate_customers result = new recsys_relate_customers();

            if (target != null)
            {
                result.address1 = target.address1;
                result.address2 = target.address2;
                result.center = target.center;
                result.code = target.code;
                result.contact = target.contact;
                result.customer_code = target.customer_code;
                result.customer_id = target.customer_id;
                result.district1 = target.district1;
                result.district2 = target.district2;
                result.email = target.email;
                result.fax1 = target.fax1;
                result.fax2 = target.fax2;
                result.group_id = target.group_id;
                result.name = target.name;
                result.chi_name = target.chi_name;
                result.prefix = target.prefix;
                result.relate_type = target.relate_type;
                result.remark = target.remark;
                result.reference_number = target.reference_number;
                result.tel1 = target.tel1;
                result.tel2 = target.tel2;
                result.title = target.title;
                result.type = target.type;
            }

            return result;
        }
        //
        // GET: /CrmInterfacing/
        public ActionResult CRM_Customer_Booking(
            string customer_code,
            string tel,
            string contact,
            string email,
            string remark,
            string bookings
            )
        {
            if (!string.IsNullOrWhiteSpace(customer_code))
            {
                db _db = new db();
                var customer = (from c in _db.recsys_customers
                                where c.status == 1 && c.customer_code.Contains(customer_code)
                                select c).FirstOrDefault();
                if (customer != null)
                {
                    recsys_relate_customers customer_data = new recsys_relate_customers()
                    {
                        customer_id = customer.id,
                        name = customer.name,
                        customer_code = customer.customer_code,
                        prefix = customer.prefix,
                        code = customer.code,
                        manual_input_code = customer.manual_input_code,
                        contact = contact,
                        relate_type = (int)CustomerDataRelateType.Enquery,
                        tel2 = tel,
                        email = email
                    };

                    _db.recsys_relate_customers.AddObject(customer_data);

                    _db.SaveChanges();

                    _db.Refresh(System.Data.Objects.RefreshMode.StoreWins, customer_data);

                    if (customer_data.id != 0)
                    {
                        recsys_enquery enquery = new recsys_enquery()
                        {
                            create_date = DateTime.Now,
                            customer_id = customer_data.id,
                            last_update = DateTime.Now,
                            remark = remark,
                            sBookingInformation = bookings,
                            status = (int) RecordStatus.Active
                        };

                        _db.recsys_enquery.AddObject(enquery);

                        _db.SaveChanges();

                        return Content("true");
                    }
                }
            }
            return Content("false");
        }
        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 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 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 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
                });
        }
        private ActionResult Add(EnqueryGridRecordBase data, int? masterCustomerID, int Status2)
        {
            bool isSuccess = false;

            Member member = new Member("users");
            recsys_customers masterCustomer = null;
            recsys_relate_customers newCustomerData;
            recsys_enquery newRecord;

            try
            {
                if (masterCustomerID.HasValue)
                    masterCustomer = this._db.recsys_customers.FirstOrDefault(theCustomer => theCustomer.id == masterCustomerID);

                newCustomerData = new recsys_relate_customers()
                {
                    customer_id = masterCustomerID.HasValue ? masterCustomerID.Value : -1,
                    name = masterCustomer == null ? null : masterCustomer.name,
                    manual_input_code = masterCustomer == null ? null : masterCustomer.manual_input_code,
                    code = masterCustomer == null ? null : masterCustomer.code,
                    prefix = masterCustomer == null ? null : masterCustomer.prefix,
                    contact = data.Contact,
                    customer_code = masterCustomer == null ? null : masterCustomer.customer_code,
                    type = masterCustomer == null ? (byte?) null : masterCustomer.type,
                    tel2 = data.Tel,
                    email = data.EMail,
                    relate_type = (int)CustomerDataRelateType.Enquery
                };

                this._db.recsys_relate_customers.AddObject(newCustomerData);
                this._db.SaveChanges();
                this._db.Refresh(System.Data.Objects.RefreshMode.StoreWins, newCustomerData);

                if (newCustomerData.id <= 0)
                    return Json(false, JsonRequestBehavior.AllowGet);

                newRecord = new recsys_enquery()
                {
                    create_date = DateTime.Now,
                    customer_id = newCustomerData.id,
                    last_update = DateTime.Now,
                    remark = data.Remark,
                    sBookingInformation = data.BookingInformation,
                    status = (byte) Status2,
                    update_user_id = (int)member.infoBySession("id")
                };

                this._db.recsys_enquery.AddObject(newRecord);

                this._db.SaveChanges();

                isSuccess = true;
            }
            catch (OptimisticConcurrencyException)
            {
                //# log down
            }

            return Json(isSuccess, JsonRequestBehavior.AllowGet);
        }
        public ActionResult AddSave_Quotation(ECallRecord data)
        {
            Member member;
            recsys_relate_customers masterCustomerData;
            recsys_relate_customers customerData;
            recsys_order ecall;
            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,
                reference_number = masterCustomerData.reference_number,
                tel1 = data.tel1,
                tel2 = data.tel2,
                title = (byte)data.title,
                type = (byte)masterCustomerData.type
            };

            this._db.recsys_relate_customers.AddObject(customerData);

            ecall = new recsys_order()
            {
                by_system = 0,
                completion_date = DateChecking(data.CompleteDate),
                call_pickup_user_id = data.call_pickup_user_id,
                end_time = new TimeSpan(Convert.ToInt32(data.EndTimeHour), Convert.ToInt32(data.EndTimeMinute), 0),
                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 = new TimeSpan(Convert.ToInt32(data.StartTimeHour), Convert.ToInt32(data.StartTimeMinute), 0),
                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 = DateChecking(data.CompleteDate).HasValue ? 3 : (DateChecking(data.repair_date).HasValue ? 2 : 1)
            };

            this._db.recsys_order.AddObject(ecall);

            try
            {
                this._db.SaveChanges();

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

                ecall.customer_id = customerData.id;

                this._db.SaveChanges();

                data.id = ecall.id;

                relation = new recsys_relate()
                {
                    id1 = data.MasterRecordID,
                    id2 = ecall.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(MaintenanceRecord data)
        {
            //# validation
            if (string.IsNullOrEmpty(data.start_date))
            {
                data.SaveResult.WarningMessage = "請填上開始日期";
                data.SaveResult.SavedSuccessfully = false;
                return Json(data);
            }
            if (string.IsNullOrEmpty(data.end_date))
            {
                data.SaveResult.WarningMessage = "請填上完結日期";
                data.SaveResult.SavedSuccessfully = false;
                return Json(data);
            }
            if (DateTime.ParseExact(data.end_date, "dd-MM-yyyy", null) < DateTime.ParseExact(data.start_date, "dd-MM-yyyy", null))
            {
                data.SaveResult.WarningMessage = "完結日期應在開始日期之後";
                data.SaveResult.SavedSuccessfully = false;
                return Json(data);
            }

            if (!data.routine_id.HasValue)
            {
                data.SaveResult.WarningMessage = "請選擇Routine";
                data.SaveResult.SavedSuccessfully = false;
                return Json(data);
            }

            if (!String.IsNullOrEmpty(data.chq_no))
            {
                if (data.chq_no.Length > 50)
                {
                    data.SaveResult.WarningMessage = "請修改Cheque No.至50字以內";
                    data.SaveResult.SavedSuccessfully = false;
                    return Json(data);
                }
            }

            Member member;
            recsys_customers masterCustomer;
            recsys_relate_customers customerData;
            recsys_maintenance maintenance;

            //# 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);
            recsys_routine routine = null;
            if (data.routine_id != null)
            {
                routine = (from r in this._db.recsys_routine
                              where r.id == data.routine_id
                              select r).FirstOrDefault();
            }
            maintenance = new recsys_maintenance()
            {
                amount = data.amount,
                chq_no = data.chq_no,
                chq_receive_date = DateChecking(data.chq_receive_date),
                billing_date = DateChecking(data.billing_date),
                checking_date = DateChecking(data.checking_date),
                confirm_date = DateChecking(data.confirm_date),
                create_date = DateTime.Now,
                end_date = DateChecking(data.end_date),
                invoice = data.invoice,
                invoice_date = DateChecking(data.invoice_date),
                issue_date = DateChecking(data.issue_date),
                last_update = DateTime.Now,
                model = data.model,
                routine = data.routine,
                routine2 = data.routine2,
                lang = data.lang,
                payment = data.payment,
                period = data.period,
                printed = (byte)(data.printed ? 1 : 0),
                remark = routine != null ? "[" + routine.description_chi + "]" + data.remark2 : data.remark2,
                schedule = data.schedule,
                start_date = DateChecking(data.start_date),
                status = (byte)data.status,
                update_user_id = (int)member.infoBySession("id"),
                master_routine_id = data.routine_id
            };

            this._db.recsys_maintenance.AddObject(maintenance);

            try
            {
                this._db.SaveChanges();

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

                maintenance.customer_id = customerData.id;

                this._db.SaveChanges();

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

                data.id = maintenance.id;
                data.center = customerData.center;

                bool generateOrderYet = data.auto_gen_order.HasValue ? data.auto_gen_order.Value : false;
                if (!generateOrderYet && !string.IsNullOrEmpty(data.confirm_date))
                {
                    IEnumerable<recsys_order> orders;

                    //# logic: create orders (定期保養)
                    if (this.TryGenerateOrdersForMaintenance(maintenance, this._db.recsys_routine.FirstOrDefault(theRoutine => theRoutine.id == maintenance.master_routine_id), out orders))
                    {
                        maintenance.period = orders.Count();
                        maintenance.auto_gen_order = true;

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

            return Json(data);
        }
        private bool TryGenerateOrdersForMaintenance(recsys_maintenance maintenance, recsys_routine routine, out IEnumerable<recsys_order> generatedOrders)
        {
            recsys_relate_customers masterCustomerData;
            Member member;
            List<recsys_relate_customers> customerDatas;
            List<recsys_order> orders;
            DateTime? startCalculationDate = null;
            DateTime? endCalculationDate = null;
            HolidaysController holidayController;
            List<DateTime> holidays;
            IEnumerable<DateTime> orderRepairDates;
            bool isSuccessful = false;

            generatedOrders = new List<recsys_order>();

            //# validation
            if (routine == null)
                return false;
            if (maintenance == null)
                return true;
            if (!routine.repair_date_frequency_in_month.HasValue)
                return true;
            if (!maintenance.start_date.HasValue && !maintenance.confirm_date.HasValue)
                return true;        //# start date of the calculation is counting on either the start date or confirm date; if null is given, just return true to indicate no order is generated
            if (!maintenance.end_date.HasValue)
                return true;        //# if maintenace does not have an end date, do not do anything

            //startCalculationDate = maintenance.confirm_date.HasValue ? maintenance.confirm_date.Value : maintenance.start_date;
            startCalculationDate = maintenance.start_date;
            endCalculationDate = maintenance.end_date;

            holidayController = new HolidaysController();
            holidays = holidayController.GetHolidays(startCalculationDate.Value, endCalculationDate.Value, true);

            orderRepairDates = maintenance.GetOrderRepairDatesByRoutine(routine, holidays);

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

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

            member = new Member("users");
            customerDatas = new List<recsys_relate_customers>();

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

                customerDatas.Add(customerData);

                this._db.recsys_relate_customers.AddObject(customerData);
            }

            try
            {
                this._db.SaveChanges();

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

                orders = new List<recsys_order>();

                for (int j = 0; j < customerDatas.Count; j++)
                {
                    recsys_relate_customers theCustomerData = customerDatas[j];

                    recsys_order order = new recsys_order()
                    {
                        by_system = 1,
                        create_date = DateTime.Now,
                        model = maintenance.model,
                        repair_date = orderRepairDates.ElementAt(j),
                        customer_id = theCustomerData.id,
                        fault = "[" + OrderStatus.AppointedWarranty.Name + "]",            //# logic
                        last_update = DateTime.Now,
                        status = (byte) RecordStatus.Active,
                        update_user_id = (int)member.infoBySession("id"),
                        start_time = null,
                        end_time = null,
                        order_status = OrderStatus.AppointedWarranty.ID,
                        call_pickup_user_id = (int) member.infoBySession("id")
                    };

                    orders.Add(order);

                    this._db.recsys_order.AddObject(order);
                }

                this._db.SaveChanges();

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

                foreach (recsys_order theOrder in orders)
                {
                    recsys_relate relation = new recsys_relate()
                    {
                        id1 = maintenance.id,
                        id2 = theOrder.id,
                        table1 = "maintenance",
                        table2 = "order"
                    };

                    this._db.recsys_relate.AddObject(relation);
                }

                this._db.SaveChanges();

                generatedOrders = orders;

                isSuccessful = true;

            }
            catch(OptimisticConcurrencyException)
            {
                //# log down
            }

            return isSuccessful;
        }
        public ActionResult CRM_Customer_Enquery(
            string tel,
            string contact,
            string email,
            string remark,
            string address,
            string company_name
            )
        {
            db _db = new db();
            recsys_relate_customers customer_data = new recsys_relate_customers()
            {
                customer_id = -1,
                contact = contact,
                relate_type = (int)CustomerDataRelateType.Enquery,
                tel2 = tel,
                email = email,
                address2 = address
            };

            _db.recsys_relate_customers.AddObject(customer_data);

            _db.SaveChanges();

            _db.Refresh(System.Data.Objects.RefreshMode.StoreWins, customer_data);

            if (customer_data.id != 0)
            {
                recsys_enquery enquery = new recsys_enquery()
                {
                    create_date = DateTime.Now,
                    customer_id = customer_data.id,
                    last_update = DateTime.Now,
                    remark = (string.IsNullOrEmpty(company_name) ? string.Empty : "[公司名稱] " + company_name + "\r\n") + remark,
                    status = (int)RecordStatus.Active
                };

                _db.recsys_enquery.AddObject(enquery);

                _db.SaveChanges();

                return Content("true");
            }
            return Content("false");
        }
Beispiel #12
0
 /// <summary>
 /// Create a new recsys_relate_customers object.
 /// </summary>
 /// <param name="id">Initial value of the id property.</param>
 /// <param name="customer_id">Initial value of the customer_id property.</param>
 /// <param name="relate_type">Initial value of the relate_type property.</param>
 public static recsys_relate_customers Createrecsys_relate_customers(global::System.Int32 id, global::System.Int32 customer_id, global::System.Byte relate_type)
 {
     recsys_relate_customers recsys_relate_customers = new recsys_relate_customers();
     recsys_relate_customers.id = id;
     recsys_relate_customers.customer_id = customer_id;
     recsys_relate_customers.relate_type = relate_type;
     return recsys_relate_customers;
 }
Beispiel #13
0
 /// <summary>
 /// Deprecated Method for adding a new object to the recsys_relate_customers EntitySet. Consider using the .Add method of the associated ObjectSet&lt;T&gt; property instead.
 /// </summary>
 public void AddTorecsys_relate_customers(recsys_relate_customers recsys_relate_customers)
 {
     base.AddObject("recsys_relate_customers", recsys_relate_customers);
 }