public async Task Get_GetByIdCustomerWithOrders_ReturnsOK()
        {
            // ARRANGE
            CustomerDetailDto customer = TestHelpers.CreateCustomerDetailDto();

            _customerReadService.Stub(x => x.GetByIdAsync(customer.Id)).Return(Task.FromResult(customer));
            _subject.MockRequest(HttpMethod.Get, new HttpRouteValueDictionary {
                { "controller", "Customer" }
            });

            // ACT
            HttpResponseMessage result = await _subject.Get(customer.Id);

            // ASSERT
            Assert.That(result.StatusCode, Is.EqualTo(HttpStatusCode.OK));

            CustomerDetailModel customerResponse = await result.Content.ReadAsAsync <CustomerDetailModel>();

            Assert.That(customerResponse, Is.Not.Null);
            Assert.That(customerResponse.Id, Is.EqualTo(customer.Id));
            Assert.That(customerResponse.Name, Is.EqualTo(customer.Name));
            Assert.That(customerResponse.Email, Is.EqualTo(customer.Email));
            Assert.That(customerResponse.Orders.Any(), Is.True);

            _customerReadService.AssertWasCalled(x => x.GetByIdAsync(customer.Id));
        }
Example #2
0
        /// <summary>
        /// Create a new customer
        /// </summary>
        /// <param name="model"></param>
        public HttpResponseMessage Put(CustomerDetailModel model)
        {
            var customer = this.DataContext.Customers.Find(model.Id);

            if (customer == null)
            {
                return(Request.CreateResponse(HttpStatusCode.NotFound));
            }

            customer.Name    = model.Name;
            customer.Contact = new Contact
            {
                Name  = model.ContactName,
                Title = model.ContactTitle,
            };
            customer.Address    = model.Address;
            customer.City       = model.City;
            customer.Region     = model.Region;
            customer.PostalCode = model.PostalCode;
            customer.Country    = model.Country;
            customer.Phone      = model.Phone;
            customer.Fax        = model.Fax;
            this.DataContext.SaveChanges();

            return(Request.CreateResponse(HttpStatusCode.OK, model));
        }
        public async Task Edit_Customer_Throw_Exception(CustomerDetailModel model)
        {
            IMapper mapper = TestUtilities.GetMapper(new CustomerProfile(), new SharedProfile());
            var     mock   = new Mock <ICustomerService>();

            mock.Setup(x => x.Update(It.IsAny <Customer>())).ThrowsAsync(new Exception("failed"));

            AddressDetailModel address = new Fixture().Create <AddressDetailModel>();

            address.State   = "MO";
            address.ZipCode = "12345";
            model.Addresses.Clear();
            model.Addresses.Add(new CustomerAddressDetailModel()
            {
                Address = address, Type = AddressType.Billing
            });
            model.Addresses.Add(new CustomerAddressDetailModel()
            {
                Address = address, Type = AddressType.Shipping
            });
            model.Contact.Email       = "*****@*****.**";
            model.Contact.Fax         = "123-1234";
            model.Contact.PhoneNumber = "123-1234";
            model.Institutions.Clear();
            model.ItemConfigurations.Clear();
            model.Documents.Clear();
            CustomerManager   manager           = new CustomerManager(_logger, mapper, mock.Object, Mock.Of <IUserService>(), Mock.Of <IIsotopeOrderingAuthorizationService>(), _eventService, Mock.Of <INotificationService>());
            ApplicationResult applicationResult = await manager.Edit(model);

            CustomAssertions.AssertExcpetionErrorsExist(applicationResult);
        }
        public async void Get_Customer_Mapping_Correct(Customer customer, NotificationConfiguration configuration)
        {
            string instanceName = Guid.NewGuid().ToString();

            using (var context = TestUtilities.GetDbContext(instanceName)) {
                customer.Subscriptions.Add(new NotificationSubscription()
                {
                    NotificationConfiguration = configuration,
                    IsDeleted = false
                });
                context.Customers.Add(customer);
                await context.SaveChangesAsync();
            }
            using (var context = TestUtilities.GetDbContext(instanceName)) {
                CustomerService service = new CustomerService(context, TestUtilities.GetMapper());

                CustomerItemModel item = await service.Get <CustomerItemModel>(customer.Id);

                Assert.Equal(customer.Contact.FirstName, item.Contact.FirstName);

                CustomerDetailModel model = await service.Get <CustomerDetailModel>(customer.Id);

                Assert.NotEmpty(model.SubscriptionConfiguration.Subscriptions);
            }
        }
        protected void btnAdd_Click(object sender, EventArgs e)
        {
            CustomerDetailModel customer = new CustomerDetailModel();

            customer.CustomerName = txtCustomerName.Text.ToString();
            customer.EmailAddress = txtEmail.Text.ToString();
            customer.PhoneNo      = Convert.ToInt64(txtPhoneNo.Text.ToString());
            customer.Address      = txtAddress.Text.ToString();


            using (OracleConnection con = new OracleConnection(connectionString))
            {
                using (OracleCommand cmd = new OracleCommand("Insert into customer(FullName, Email, Phone_No, Address)Values('" + customer.CustomerName + "','" + customer.EmailAddress + "','" + customer.PhoneNo + "','" + customer.Address + "')"))
                {
                    cmd.Connection = con;
                    con.Open();
                    cmd.ExecuteNonQuery();
                    con.Close();

                    txtCustomerName.Text = "";
                    txtEmail.Text        = "";
                    txtPhoneNo.Text      = "";
                    txtAddress.Text      = "";
                }



                this.bindGrid();
            }
        }
Example #6
0
        public bool AddCustomer(CustomerDetailModel customerDetailModel)
        {
            using var connection = _cloudCashDbContextFactory.CreateDbContext();

            connection.Customers.Add(Mapper.MapDetailModelToEntity(customerDetailModel));
            return(connection.SaveChanges() is 1);
        }
Example #7
0
        public async Task <bool> SyncCustomers(string shopifyurl, string token)
        {
            bool response;

            try
            {
                string[]            shosp    = shopifyurl.Split(".");
                string              shopname = shosp[0];
                CustomerDetailModel cdm      = new CustomerDetailModel();
                cdm.token      = token;
                cdm.shopifyurl = shopifyurl;
                List <Customer>            customersList   = await new CustomerHandler().GetAllCustomers(cdm);
                List <CustomerReturnModel> customerReturns = await new CustomerHandler().GetCustomerReturnModel(customersList, shopname);
                var    client    = new HttpClient();
                string json      = JsonConvert.SerializeObject(customerReturns);
                string apiUrl2   = $"{config.Value.ResponseUrl}/api/AddShopifyCustomers";
                var    response2 = client.PostAsJsonAsync(apiUrl2, customerReturns).Result;
                response2.EnsureSuccessStatusCode();
                string responseBody1 = await response2.Content.ReadAsStringAsync();

                var readString = JObject.Parse(responseBody1)["status"];
                response = Convert.ToBoolean(readString);
            }
            catch (Exception)
            {
                return(false);
            }
            return(response);
        }
Example #8
0
        /// <summary>
        /// Create a new customer
        /// </summary>
        /// <param name="model"></param>
        public HttpResponseMessage Post(CustomerDetailModel model)
        {
            var customer = this.DataContext.Customers.Add(new Customer
            {
                Id      = model.Id,
                Name    = model.Name,
                Contact = new Contact
                {
                    Name  = model.ContactName,
                    Title = model.ContactTitle,
                },
                Address    = model.Address,
                City       = model.City,
                Region     = model.Region,
                PostalCode = model.PostalCode,
                Country    = model.Country,
                Phone      = model.Phone,
                Fax        = model.Fax,
            });

            this.DataContext.SaveChanges();

            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, customer);

            response.Headers.Location = new Uri(Url.Link("Api", new { controller = "Customers", id = customer.Id }));
            return(response);
        }
        public async Task <bool> SyncCustomers(string shopifyurl, string storename, string token)
        {
            bool response = true;

            try
            {
                var client = new HttpClient();
                client.Timeout = TimeSpan.FromMinutes(30);
                CustomerDetailModel cdm = new CustomerDetailModel();
                cdm.token      = token;
                cdm.shopifyurl = shopifyurl;
                List <Customer>            customersList   = await new CustomerHandler().GetAllCustomers(cdm);
                List <CustomerReturnModel> customerReturns = await new CustomerHandler().GetCustomerReturnModel(customersList, storename);
                string json = JsonConvert.SerializeObject(customerReturns);
                foreach (var item in customerReturns)
                {
                    List <CustomerReturnModel> crm = new List <CustomerReturnModel>();
                    crm.Add(item);
                    string apiUrl2   = $"{config.Value.ResponseUrl}/api/AddShopifyCustomers";
                    var    response2 = client.PostAsJsonAsync(apiUrl2, crm).Result;
                    response2.EnsureSuccessStatusCode();
                    string responseBody1 = await response2.Content.ReadAsStringAsync();

                    var readString = JObject.Parse(responseBody1)["status"];
                    response = Convert.ToBoolean(readString.ToString());
                }
            }
            catch (Exception)
            {
                return(false);
            }
            return(response);
        }
Example #10
0
        public static CustomerDetailModel InfoToModel(this CustomerInfo info)
        {
            if (info == null)
            {
                return(null);
            }
            var model = new CustomerDetailModel
            {
                Id            = info.Id,
                CustomerNo    = info.CustomerNo,
                Name          = info.Name,
                Mobile        = info.Mobile,
                Address       = info.Address,
                Gender        = info.Gender,
                Birthday      = info.Birthday,
                WaiterId      = info.WaiterId,
                WaiterName    = info.WaiterName,
                Spend         = info.Spend,
                CreateDate    = info.CreateDate,
                LastUpdatedOn = info.LastUpdatedOn
            };

            if (info.Gender == 0)
            {
                model.GenderString = "女";
            }
            else
            {
                model.GenderString = "男";
            }

            return(model);
        }
 protected void btnSaveCustomer_Click(object sender, EventArgs e)
 {
     try {
         CustomerDetailModel customer = new CustomerDetailModel();
         customer.FirstName    = tbxFirstName.Text;
         customer.LastName     = tbxLastName.Text;
         customer.CompanyName  = tbxCompanyName.Text;
         customer.PrimaryEmail = tbxEmail.Text;
         customer.PrimaryPhone = tbxPhoneNumber.Text;
         string jsonData = new JavaScriptSerializer().Serialize(customer);
         //Json Payload
         //string jsonData = "{'firstName':'"+FullName+"','companyName':'"+Company+"','primaryEmail':'"+EmailId+"'}";
         //Setup API key
         string apiKey = "MDpOeEJEbmpZU0ZESjF3R0xSZ1pIdGMyMjFHVkhPWFczcmxoYUU0Y2xjQUxQZ2VtcHd2MktpTU9wZndvYmU4WkFoA";
         //Configure URI
         WebRequest request = WebRequest.Create("HTTPS://stg-secure.fusebill.com/v1/customers");
         //Add Content type
         request.ContentType = "application/json";
         //Add Api key authorization
         request.Headers.Add(HttpRequestHeader.Authorization, "Basic " + apiKey);
         //Set request method
         request.Method = "POST";
         //Add the json data to request
         using (var streamWriter = new StreamWriter(request.GetRequestStream()))
         {
             streamWriter.Write(jsonData);
             streamWriter.Flush();
             streamWriter.Close();
         }
         //Perform the request
         var httpResponse = (HttpWebResponse)request.GetResponse();
         //Record the response from our request
         var result = "";
         using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
         {
             result = streamReader.ReadToEnd();
         }
         var response = ((int)httpResponse.StatusCode).GetResponse();
         if (response.StatusCode == (int)HttpStatusCode.OK)
         {
             Response.Redirect("PlanSelection.aspx");
         }
         else
         {
             divContent.Visible   = false;
             divError.Visible     = true;
             lblErrorMessage.Text = response.ApiMessage;
         }
     }
     catch (Exception ex)
     {
         var response = (HttpWebResponse)((WebException)ex).Response;
         var result   = ((int)response.StatusCode).GetResponse();
         divContent.Visible   = false;
         divError.Visible     = true;
         lblErrorMessage.Text = result.ApiMessage;
     }
 }
Example #12
0
        // GET:
        public ActionResult SelectPlan(int id)
        {
            CustomerDetailModel customerDetailModel = new CustomerDetailModel();
            var modelDB = new PlanDBModel();
            var list    = modelDB.getListPlan();

            customerDetailModel.Plans      = list;
            customerDetailModel.customerId = id;
            return(View(customerDetailModel));
        }
Example #13
0
        public async Task <IActionResult> Edit(CustomerDetailModel model)
        {
            if (ModelState.IsValid)
            {
                ApplicationResult result = await _customerManager.Edit(model);

                SetApplicationResult(result);
                return(RedirectToAction(nameof(Edit), new { id = model.Id }));
            }
            return(View(model));
        }
 public ActionResult AddCustomer(CustomerDetailModel model)
 {
     try
     {
         return(Json(new { Success = _customerService.AddCustomer(model), }));
     }
     catch (Exception ex)
     {
         return(Json(new { Success = false, Messages = ex.Message }));
     }
 }
        public async void Edit_Customer_With_Validation_Errors(CustomerDetailModel model)
        {
            IMapper         mapper  = TestUtilities.GetMapper(new CustomerProfile());
            CustomerManager manager = new CustomerManager(_logger, mapper, Mock.Of <ICustomerService>(), Mock.Of <IUserService>(), Mock.Of <IIsotopeOrderingAuthorizationService>(), _eventService, Mock.Of <INotificationService>());

            model.Addresses.Clear();

            ApplicationResult applicationResult = await manager.Edit(model);

            _output.WriteLine(applicationResult.Message);
            CustomAssertions.AssertValidationErrorsExist(applicationResult);
        }
 public async Task <IActionResult> SearchAllCustomers([FromBody] CustomerDetailModel model)
 {
     try
     {
         dynamic response = await new CustomerManager().SearchCustomerDetails(model);
         return(Ok(response));
     }
     catch (Exception ex)
     {
         return(BadRequest(ex.Message));
     }
 }
        public ActionResult Detail(int id)
        {
            TempData.Remove("Outgoing");
            Customer            C   = db.Customers.Find(id);
            CustomerDetailModel CDM = new CustomerDetailModel()
            {
                customer = new Customer()
                {
                    Id               = C.Id,
                    UserName         = C.UserName,
                    AuthorizedPerson = C.AuthorizedPerson,
                    Email            = C.Email,
                    Phone            = C.Phone,
                    MobilePhone      = C.MobilePhone,
                    Budget           = C.Budget,
                    CustomerActive   = true,

                    BankName = C.BankName,
                    IBANno   = C.IBANno,

                    CompanyTitle = C.CompanyTitle,
                    TaxOffice    = C.TaxOffice,
                    TaxorTCNo    = C.TaxorTCNo,
                    CompanyPhone = C.CompanyPhone,
                    FaxNo        = C.FaxNo,
                    Address      = C.Address,
                    Province     = C.Province,
                    District     = C.District,
                    WebAddress   = C.WebAddress,
                    CreateTime   = DateTime.Now,

                    CompanyId = 1,
                },

                InterViews   = db.InterViews.Where(w => w.CustomerId == C.Id).ToList(), // görüşmeler
                Incomings    = db.Invoices.OfType <Incoming>().Where(w => w.CustomerId == C.Id).ToList(),
                OutGoings    = db.Invoices.OfType <OutGoing>().Where(w => w.CustomerId == C.Id).ToList(),
                PIncomings   = db.Payments.OfType <PIncoming>().Where(w => w.CustomerId == C.Id).ToList(),
                POutGoings   = db.Payments.OfType <POutGoing>().Where(w => w.CustomerId == C.Id).ToList(),
                projects     = db.Projects.Where(w => w.CustomerId == C.Id).ToList(),
                reminds      = db.Reminds.Where(w => w.CustomerId == C.Id).ToList(),
                CashAccounts = db.CashAccounts.ToList(),
                //PaymentIncome = db.Payments.OfType<PIncoming>().Where(w=>w.CustomerId == C.Id).Sum(s=>s.Total),
                //PaymentOutgoing = db.Payments.OfType<POutGoing>().Where(w => w.CustomerId == C.Id).Sum(s=>s.Total),
                //InvoiceOutgoing = db.Invoices.OfType<OutGoing>().Where(w=>w.CustomerId == C.Id).Sum(s=>s.Total),//satış faturasıları toplamı için
                //InvoiceIncome = db.Invoices.OfType<Incoming>().Where(w=>w.CustomerId == C.Id).Sum(s=>s.Total),
                //Sum() ?? 0
            };

            return(View(CDM));
        }
        public virtual ActionResult SaveCustomerDetail(CustomerDetailModel model)
        {
            if (!ModelState.IsValid)
            {
                return(JsonValidationError());
            }

            //if (_sessionContext.CurrentUser.Email != model.Email)
            //{
            //    ModelState.AddModelError("Error", "You cannot save detail to this Email!");
            //    return JsonValidationError();
            //}

            var customerModel = new CustomerModel
            {
                UserId               = Guid.Parse(model.UserId),
                BirthDate            = Sanitizer.GetSafeHtmlFragment(model.BirthDate),
                DayOfBirth           = Sanitizer.GetSafeHtmlFragment(model.DayOfBirth),
                Email                = Sanitizer.GetSafeHtmlFragment(model.Email),
                FirstName            = Sanitizer.GetSafeHtmlFragment(model.FirstName),
                Gender               = Sanitizer.GetSafeHtmlFragment(model.Gender),
                LastName             = Sanitizer.GetSafeHtmlFragment(model.LastName),
                Mobile               = Sanitizer.GetSafeHtmlFragment(model.Mobile),
                MonthOfBirth         = Sanitizer.GetSafeHtmlFragment(model.MonthOfBirth),
                PostCode             = Sanitizer.GetSafeHtmlFragment(model.PostCode),
                Telephone            = Sanitizer.GetSafeHtmlFragment(model.Telephone),
                Title                = Sanitizer.GetSafeHtmlFragment(model.Title),
                YearOfBirth          = Sanitizer.GetSafeHtmlFragment(model.YearOfBirth),
                NewsLetterSubscribed = model.NewsLetterSubscribed,
                NotifyByEmail        = model.NotifyByEmail,
                NotifyByPost         = model.NotifyByPost,
                NotifyBySMS          = model.NotifyBySMS,
                SourceProcess        = SourceProcessType.SITE_MYACCOUNT.ToString(),
                CompanyId            = model.CompanyId
            };

            customerModel.DayOfBirth   = "00";
            customerModel.MonthOfBirth = "00";
            customerModel.YearOfBirth  = "00";
            if (customerModel.BirthDate.Split('/').Length == 3)
            {
                customerModel.DayOfBirth   = customerModel.BirthDate.Split('/')[0];
                customerModel.MonthOfBirth = customerModel.BirthDate.Split('/')[1];
                customerModel.YearOfBirth  = customerModel.BirthDate.Split('/')[2];
            }

            var result = _customerRepository.UpdateCustomerDetail(customerModel.UserId.ToString(), customerModel);

            return(JsonSuccess(result.Result, JsonRequestBehavior.AllowGet));
        }
Example #19
0
 public CustomerDetailViewModel(CustomerDto operation)
 {
     CustomerServiceAdapter = new ServiceAdapter <ICustomerService>();
     Model = new CustomerDetailModel {
         Customer = new CustomerDto()
     };
     if (operation != null)
     {
         Model.Customer = operation;
     }
     View = new CustomerDetailView {
         DataContext = this
     };
 }
Example #20
0
 public CustomerDetailViewModel(CustomerDto operation)
 {
     CustomerServiceInstance = ClientServiceLocator.Instance().ContractLocator.CustomerServices;
     Model = new CustomerDetailModel {
         Customer = new CustomerDto()
     };
     if (operation != null)
     {
         Model.Customer = operation;
     }
     View = new CustomerDetailView {
         DataContext = this
     };
 }
Example #21
0
        public async Task <IActionResult> CreateCustomer([FromBody] CustomerDetailModel model)
        {
            var response = "";

            try
            {
                //model.token = new HomeController().ReturnToken();
                var service = new CustomerService(model.shopifyurl, model.token);
                for (int i = 0; i < 10; i++)
                {
                    var customer = new Customer()
                    {
                        FirstName = "John",
                        LastName  = "Doe",
                        Email     = $"john.doe200{i}@example.com",
                        Addresses = new List <Address>()
                        {
                            new Address()
                            {
                                Address1     = "123 4th Street",
                                City         = "Minneapolis",
                                Province     = "Minnesota",
                                ProvinceCode = "MN",
                                Zip          = "55401",
                                Phone        = "555-555-5555",
                                FirstName    = "John",
                                LastName     = "Doe",
                                Company      = "Tomorrow Corporation",
                                Country      = "United States",
                                CountryCode  = "US",
                                Default      = true,
                            }
                        },

                        VerifiedEmail = true,
                        Note          = "Test note about the customer.",
                        State         = "enabled"
                    };
                    customer = await service.CreateAsync(customer);
                }

                response = "Customer is added successfuly!";
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
            return(Ok(response));
        }
Example #22
0
        public ActionResult Detail(string id, string name, string groupId, int page = 1)
        {
            Customer            entity = this.customerService.Select(id);
            CustomerDetailModel model  = new CustomerDetailModel(entity);

            model.Group = this.GetCustomerGroupName(model.Group);
            if (string.IsNullOrWhiteSpace(model.WeChatId))
            {
                model.WeChatId = WebResource.Common_None;
            }
            model.QueryName    = name;
            model.QueryGroupId = groupId;
            model.PageIndex    = page;
            return(View(model));
        }
Example #23
0
        public ActionResult CRCreate(CustomerDetailModel model)
        {
            Remind remind = new Remind()
            {
                CustomerId  = model.customer.Id,
                Description = model.remind.Description,
                CreateTime  = DateTime.Now,
                Title       = model.remind.Title,
                WhoUser     = "******",
            };

            db.Reminds.Add(remind);
            db.SaveChanges();
            return(RedirectToAction("Detail", "Customer", new { id = model.customer.Id }));
        }
        /// <summary>
        /// 客户详情页面
        /// </summary>
        /// <returns></returns>
        public ActionResult Detail(Guid id)
        {
            CustomerDetailModel model = null;

            if (id != Guid.Empty)
            {
                model = _customerService.GetCustomerById(id);
                if (model != null)
                {
                    var selectlist = _employeeService.GetSelectlist();
                    ViewBag.Selectlist = selectlist.Where(x => x.Id != model.WaiterId);
                }
            }
            return(View(model));
        }
Example #25
0
 public static CustomerDetail MapCustomerDetail(CustomerDetailModel detail)
 {
     return(new CustomerDetail
     {
         Email = detail.Email,
         Phone = detail.Phone,
         PrimaryAddress = detail.PrimaryAddress,
         AlternateAddress = detail.AlternateAddress,
         City = detail.City,
         State = detail.State,
         PostalCode = detail.PostalCode,
         Country = detail.Country,
         CreatedAt = DateTime.UtcNow,
         UpdatedAt = DateTime.UtcNow,
     });
 }
Example #26
0
        public async Task <IActionResult> GetCustomer([FromBody] CustomerDetailModel model)
        {
            dynamic response;

            try
            {
                //model.token = new HomeController().ReturnToken();
                long cid     = Convert.ToInt64(model.customerId);
                var  service = new CustomerService(model.shopifyurl, model.token);
                response = await service.GetAsync(cid);
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
            return(Ok(response));
        }
 public async Task <IActionResult> SearchCustomersWithPagination([FromBody] CustomerDetailModel model)
 {
     try
     {
         if (string.IsNullOrEmpty(model.pageno.ToString()) && string.IsNullOrEmpty(model.pagesize.ToString()))
         {
             string msg = "pageNo & pageSize should not be null or empty";
             return(BadRequest(msg));
         }
         dynamic response = await new CustomerManager().SearchCustomersWithPagination(model);
         return(Ok(response));
     }
     catch (Exception ex)
     {
         return(BadRequest(ex.Message));
     }
 }
 public async Task <IActionResult> GetCustomer([FromBody] CustomerDetailModel model)
 {
     try
     {
         if (string.IsNullOrEmpty(model.customerId))
         {
             string msg = "customerId should not be null or empty";
             return(BadRequest(msg));
         }
         dynamic response = await new CustomerManager().GetCustomerDetails(model);
         return(Ok(response));
     }
     catch (Exception ex)
     {
         return(BadRequest(ex.Message));
     }
 }
Example #29
0
        public bool EditCustomer(CustomerDetailModel customerDetailModel)
        {
            using var connection = _cloudCashDbContextFactory.CreateDbContext();

            var entityCustomer       = connection.Customers.First(x => x.ID == customerDetailModel.ID);
            var mappedEntityCustomer = Mapper.MapEntityToDetailModel(entityCustomer);

            if (mappedEntityCustomer != customerDetailModel)
            {
                entityCustomer = Mapper.MapDetailModelToEntity(customerDetailModel);
                return(connection.SaveChanges() is 1);
            }
            else
            {
                return(false);
            }
        }
Example #30
0
        /// <summary>
        /// 添加客户
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool AddCustomer(CustomerDetailModel model)
        {
            var _session     = HttpContext.Current.Session;
            var employeeId   = Guid.Parse(_session["EmployeeId"]?.ToString());
            var employeeInfo = _employeeInfoRepository.GetById(employeeId);

            if (employeeInfo == null)
            {
                throw new Exception("登录信息有误,请重新登录!");
            }
            Assert.IsNotNullOrEmpty(model.Name, "客户姓名不可为空");
            Assert.IsTrue((model.Gender == 1 || model.Gender == 0), "用户性别设置错误!");
            Assert.IsNotNullOrEmpty(model.Mobile, "客户联系电话不可为空!");
            Assert.IsTrue(_customerInfoRepository.CheckMobile(model.Mobile, Guid.Empty), "客户联系电话重复!");
            var info = new CustomerInfo
            {
                Id       = Guid.NewGuid(),
                Name     = model.Name,
                Gender   = model.Gender,
                Mobile   = model.Mobile,
                Address  = model.Address,
                Birthday = model.Birthday,
                //info.WaiterId
                //info.WaiterName
                Spend = 0
            };

            if (model.WaiterId.HasValue)
            {
                var waiterInfo = _employeeInfoRepository.GetById(model.WaiterId.Value);
                Assert.IsNotNull(waiterInfo, "服务人员设置错误!");
                info.WaiterId   = waiterInfo.Id;
                info.WaiterName = waiterInfo.Name;
            }
            _customerInfoRepository.Insert(info);
            var recordInfo = new RecordInfo
            {
                CustomerId   = info.Id,
                EmployeeId   = employeeInfo.Id,
                EmployeeName = employeeInfo.Name,
                Message      = "添加新客户"
            };

            _recordInfoRepository.Insert(recordInfo);
            return(true);
        }