Exemple #1
0
        public HttpResponseMessage Post([FromBody] JObject customer_details)
        {
            try
            {
                // Check if a session already exists or if it's expired
                //if (HttpContext.Current.Session["Token"] == null)
                //    return Request.CreateResponse(HttpStatusCode.Unauthorized, new { Success = false, Message = "Session expired! Unable to authenticate user." });


                string name      = customer_details["name"].ToString().Trim();
                string mobile_no = customer_details["mobile_no"].ToString().Trim();
                int    salon_id  = int.Parse(customer_details["salon_id"].ToString());

                using (SalonDbEntities entities = new SalonDbEntities())
                {
                    // Check if the salon id exists
                    if (salon_id != 0 && !entities.tblsalons.Any(e => e.salon_id == salon_id))
                    {
                        return(Messages.GetInstance().HandleException("Retrieve failed! Salon with id = ", salon_id.ToString()));
                    }

                    // Validate customer mobile
                    if (!Utilities.getInstance().ValidateContactNumber(mobile_no))
                    {
                        return(Messages.GetInstance().ValidateFields("Customer", ActionType.INSERT, isContactNumber: true));
                    }

                    // Check if the customer mobile already exists in the particular salon.
                    if (entities.tblcustomers.Any(e => e.mobile_no.ToString().Trim() == mobile_no && e.salon_id == salon_id))
                    {
                        return(Messages.GetInstance().HandleException("Failed to create customer! A customer with the same mobile no exists in salon id = " + salon_id));
                    }

                    else
                    {
                        using (var transaction = entities.Database.BeginTransaction())
                        {
                            tblcustomer obj = new tblcustomer
                            {
                                name       = name,
                                mobile_no  = int.Parse(mobile_no),
                                salon_id   = salon_id,
                                login_time = DateTime.Now
                            };
                            entities.tblcustomers.Add(obj);
                            entities.SaveChanges();

                            Utilities.getInstance().UpdateChanges(entities, transaction, obj.customer_id.ToString(), typeof(tblcustomer).Name, ActionType.INSERT);

                            return(Messages.GetInstance().HandleRequest("Customer", ActionType.INSERT));
                        }
                    }
                }
            }
            catch (Exception)
            {
                return(Messages.GetInstance().HandleException("An error occured! Failed to create customer."));
            }
        }
        // Updates changes in the database
        public void UpdateChanges(SalonDbEntities entities, DbContextTransaction transaction, string id, string table, ActionType actionType)
        {
            if (!actionType.Equals("INSERT"))
            {
                entities.SaveChanges();
            }

            // Update log information
            Log.Update(id, table, actionType);

            transaction.Commit();
        }
Exemple #3
0
        /// <summary>
        /// Save data modification details to the update table
        /// </summary>
        /// <param name="id">Represents references</param>
        /// <param name="table">Represents the reference table</param>
        /// <param name="actionType">Reference the table modification type</param>
        public static void Update(string id, string table, ActionType actionType)
        {
            SalonDbEntities db     = new SalonDbEntities();
            tbllog          update = new tbllog
            {
                ref_table         = table,
                ref_id            = id,
                updated_date_time = DateTime.Now,
                action_type       = System.Enum.GetName(typeof(ActionType), actionType)
            };

            db.tbllogs.Add(update);
            db.SaveChanges();
        }
Exemple #4
0
        public HttpResponseMessage Post([FromBody] JObject service_details)
        {
            try
            {
                // Check if a session already exists or if it's expired
                //if (HttpContext.Current.Session["Token"] == null)
                //    return Request.CreateResponse(HttpStatusCode.Unauthorized, new { Success = false, Message = "Session expired! Unable to authenticate user." });


                string  service_name = service_details["service_name"].ToString().Trim();
                int     salon_id     = int.Parse(service_details["salon_id"].ToString());
                Decimal price        = Decimal.Parse(service_details["price"].ToString());
                string  duration     = service_details["duration"].ToString().Trim();

                using (SalonDbEntities entities = new SalonDbEntities())
                {
                    // Validate service - check if the service already exists in that particular salon
                    bool selectedService = entities.tblservices.Any(e => e.service_name.ToUpper().Trim() == service_name.ToUpper().Trim() && e.salon_id == salon_id);

                    // If a service already exists
                    if (selectedService)
                    {
                        return(Messages.GetInstance().HandleRequest("Service", ActionType.INSERT, true));
                    }
                    else
                    {
                        using (var transaction = entities.Database.BeginTransaction())
                        {
                            tblservice obj = new tblservice
                            {
                                service_name = service_name,
                                salon_id     = salon_id,
                                price        = price,
                                duration     = Convert.ToInt32(TimeSpan.Parse(duration).TotalSeconds)
                            };
                            entities.tblservices.Add(obj);
                            entities.SaveChanges();

                            Utilities.getInstance().UpdateChanges(entities, transaction, obj.service_id.ToString(), typeof(tblservice).Name, ActionType.INSERT);

                            return(Messages.GetInstance().HandleRequest("Service", ActionType.INSERT));
                        }
                    }
                }
            }
            catch (Exception)
            {
                return(Messages.GetInstance().HandleException("An error occured! Failed to create service."));
            }
        }
Exemple #5
0
        public HttpResponseMessage GenerateInvoiceAutomatically(int salon_id, int appointment_id, decimal discount = 0)
        {
            try
            {
                // Check if a session already exists or if it's expired
                //if (HttpContext.Current.Session["Token"] == null)
                //    return Request.CreateResponse(HttpStatusCode.Unauthorized, new { Success = false, Message = "Session expired! Unable to authenticate user." });


                using (SalonDbEntities entities = new SalonDbEntities())
                {
                    // Check if an invoice is already existing for the particular appointment
                    if (entities.tblinvoices.Any(e => e.appointment_id == appointment_id))
                    {
                        return(Messages.GetInstance().HandleException("Failed to create invoice! An invoice already exists for appointment id = " + appointment_id));
                    }

                    using (var transaction = entities.Database.BeginTransaction())
                    {
                        int[] requested_services = entities.tblservice_booked.Where(x => x.appointment_id == appointment_id).Select(x => x.service_id).ToArray();

                        decimal    totalPrice = CalculateTotal(salon_id, requested_services);
                        tblinvoice invoice    = new tblinvoice
                        {
                            salon_id       = salon_id,
                            appointment_id = appointment_id,
                            total_price    = totalPrice,
                            discount       = discount,
                            final_price    = CalculateFinalTotal(totalPrice, discount),
                        };
                        entities.tblinvoices.Add(invoice);
                        entities.SaveChanges();

                        Utilities.getInstance().UpdateChanges(entities, transaction, invoice.invoice_id.ToString(), typeof(tblinvoice).Name, ActionType.INSERT);

                        return(Messages.GetInstance().HandleRequest("Invoice", ActionType.INSERT));
                    }
                }
            }
            catch (Exception)
            {
                return(Messages.GetInstance().HandleException("An error occured! Failed to create invoice."));
            }
        }
Exemple #6
0
        public HttpResponseMessage Post([FromBody] JObject barber_service_details)
        {
            try
            {
                // Check if a session already exists or if it's expired
                //if (HttpContext.Current.Session["Token"] == null)
                //    return Request.CreateResponse(HttpStatusCode.Unauthorized, new { Success = false, Message = "Session expired! Unable to authenticate user." });


                using (SalonDbEntities entities = new SalonDbEntities())
                {
                    int barber_id  = int.Parse(barber_service_details["barber_id"].ToString());
                    int service_id = int.Parse(barber_service_details["service_id"].ToString());

                    // Validate barber - check if the barber service already exists
                    if (entities.tblbarber_service.Any(e => e.barber_id == barber_id && e.service_id == service_id))
                    {
                        return(Messages.GetInstance().HandleRequest("Barber Service", ActionType.INSERT, true));
                    }
                    else
                    {
                        using (var transaction = entities.Database.BeginTransaction())
                        {
                            tblbarber_service obj = new tblbarber_service
                            {
                                barber_id  = barber_id,
                                service_id = service_id
                            };
                            entities.tblbarber_service.Add(obj);
                            entities.SaveChanges();

                            Utilities.getInstance().UpdateChanges(entities, transaction, obj.barber_service_id.ToString(), typeof(tblbarber).Name, ActionType.INSERT);

                            return(Messages.GetInstance().HandleRequest("Barber Service", ActionType.INSERT));
                        }
                    }
                }
            }
            catch (Exception)
            {
                return(Messages.GetInstance().HandleException("An error occured! Failed to create barber service."));
            }
        }
Exemple #7
0
        public HttpResponseMessage Post([FromBody] JObject invoice_details)
        {
            try
            {
                // Check if a session already exists or if it's expired
                //if (HttpContext.Current.Session["Token"] == null)
                //    return Request.CreateResponse(HttpStatusCode.Unauthorized, new { Success = false, Message = "Session expired! Unable to authenticate user." });


                using (SalonDbEntities entities = new SalonDbEntities())
                {
                    int     salon_id       = int.Parse(invoice_details["salon_id"].ToString());
                    int     appointment_id = int.Parse(invoice_details["appointment_id"].ToString());
                    decimal discount       = decimal.Parse(invoice_details["discount"].ToString());

                    int[] requested_services = new int[invoice_details["requested_services"].Count()];
                    int   count = 0;
                    foreach (var service in invoice_details["requested_services"])
                    {
                        requested_services[count] = int.Parse(invoice_details["requested_services"][count].ToString());
                        count++;
                    }

                    // Check if an invoice is already existing for the particular appointment
                    if (entities.tblinvoices.Any(e => e.appointment_id == appointment_id))
                    {
                        return(Messages.GetInstance().HandleException("Failed to create invoice! An invoice already exists for appointment id = " + appointment_id));
                    }

                    // Check if the requested services exist in the given salon
                    foreach (int service in requested_services)
                    {
                        if (!entities.tblservices.Any(x => x.salon_id == salon_id && x.service_id == service))
                        {
                            return(Messages.GetInstance().HandleException("Failed to create invoice! Requested service doesn't exist in the given salon."));
                        }
                    }

                    // Check if the services have been requested in the given appointment
                    foreach (int service in requested_services)
                    {
                        if (!entities.tblservice_booked.Any(x => x.appointment_id == appointment_id && x.service_id == service))
                        {
                            return(Messages.GetInstance().HandleException("Failed to create invoice! Service id = " + service + " has not been requested, in the given appointment."));
                        }
                    }


                    using (var transaction = entities.Database.BeginTransaction())
                    {
                        decimal    totalPrice = CalculateTotal(salon_id, requested_services);
                        tblinvoice invoice    = new tblinvoice
                        {
                            salon_id       = salon_id,
                            appointment_id = appointment_id,
                            total_price    = CalculateTotal(salon_id, requested_services),
                            discount       = discount,
                            final_price    = CalculateFinalTotal(totalPrice, discount)
                        };
                        entities.tblinvoices.Add(invoice);
                        entities.SaveChanges();

                        Utilities.getInstance().UpdateChanges(entities, transaction, invoice.invoice_id.ToString(), typeof(tblinvoice).Name, ActionType.INSERT);

                        return(Messages.GetInstance().HandleRequest("Invoice", ActionType.INSERT));
                    }
                }
            }
            catch (Exception)
            {
                return(Messages.GetInstance().HandleException("An error occured! Failed to create invoice."));
            }
        }
Exemple #8
0
        public HttpResponseMessage Get(int salon_id, int barber_id)
        {
            try
            {
                using (SalonDbEntities entities = new SalonDbEntities())
                {
                    // Check if the barber exists, in the given salon
                    if (!entities.tblbarbers.Any(e => e.salon_id == salon_id && e.barber_id == barber_id))
                    {
                        return(Request.CreateResponse(HttpStatusCode.NotFound, new { Success = false, Message = "Retrieve failed! Barber doesn't exist in the given salon." }));
                    }

                    DateTime      currentDate = DateTime.Now.Date;
                    List <Object> response    = new List <Object>();

                    // Check if the barber has any appointment(s) for today
                    List <tblappointment> appointmentsForToday = entities.tblappointments.Where(x => x.due_date.Equals(currentDate) && x.salon_id == salon_id && x.barber_Id == barber_id).ToList();
                    if (appointmentsForToday.Count == 0)
                    {
                        response.Add(new
                        {
                            Success = true,
                            Message = "No appointments scheduled for today.",
                            Current_appointment_no = 0
                        });
                        return(Request.CreateResponse(HttpStatusCode.OK, response));
                    }


                    // Check if the barber has started his appointment(s) for today
                    var allAppointmentsMade = entities.tblcurrent_appointments.Where(x => x.current_date.Equals(currentDate) && x.salon_id == salon_id && x.barber_id == barber_id).FirstOrDefault();
                    int nextAppointment     = 0;

                    if (!entities.tblappointments.Any(x => x.due_date.Equals(currentDate) && x.salon_id == salon_id && x.barber_Id == barber_id && x.status == AppointmentStatus.TO_DO.ToString()))
                    {
                        return(Request.CreateResponse(HttpStatusCode.OK, new
                        {
                            Success = true,
                            Message = "All appointments made to barber id = " + barber_id + " in salon id = " + salon_id + ", which are scheduled for today, have been completed!",
                            Current_appointment_no = 0
                        }));
                    }


                    if (allAppointmentsMade != null)
                    {
                        nextAppointment = allAppointmentsMade.last_appointment_no + 1;
                    }

                    // If the barber has any appointment(s) scheduled for today, but if they have not started yet
                    else
                    {
                        nextAppointment = 1;
                    }


                    response.Add(new
                    {
                        Success = true,
                        Message = "Current appointment no for barber id = " + barber_id + " in salon id = " + salon_id + " retrieved successfully!",
                        Current_appointment_no = nextAppointment
                    });

                    using (var transaction = entities.Database.BeginTransaction())
                    {
                        // Update the status of the appointment
                        tblappointment entity = entities.tblappointments.Where(x => x.due_date.Equals(currentDate) && x.salon_id == salon_id && x.barber_Id == barber_id && x.appointment_no_for_day == nextAppointment).FirstOrDefault();
                        if (entity != null)
                        {
                            entity.status = AppointmentStatus.IN_PROGRESS.ToString();
                            entities.SaveChanges();
                            Log.Update(entity.appointment_id.ToString(), typeof(tblappointment).Name, ActionType.UPDATE);
                        }

                        // Update the availability of barber
                        var barber = entities.tblbarbers.Where(x => x.salon_id == salon_id && x.barber_id == barber_id).FirstOrDefault();
                        if (barber != null)
                        {
                            barber.is_available = false;
                            entities.SaveChanges();
                            Log.Update(barber.barber_id.ToString(), typeof(tblbarber).Name, ActionType.UPDATE);
                        }
                        transaction.Commit();
                    }

                    return(Request.CreateResponse(HttpStatusCode.OK, response));
                }
            }
            catch (Exception)
            {
                return(Messages.GetInstance().HandleException("An error occured! Failed to retrieve current appointment number."));
            }
        }
Exemple #9
0
        public HttpResponseMessage Put(int salon_id, int barber_id, int current_appointment_no)
        {
            try
            {
                using (SalonDbEntities entities = new SalonDbEntities())
                {
                    if (!entities.tblappointments.Any(e => e.salon_id == salon_id && e.barber_Id == barber_id && e.appointment_no_for_day == current_appointment_no))
                    {
                        return(Request.CreateResponse(HttpStatusCode.NotFound, new { Success = false, Message = "Update failed! No matching entry found." }));
                    }

                    using (var transaction = entities.Database.BeginTransaction())
                    {
                        DateTime currentDate = DateTime.Now.Date;

                        // Check if the barber has started any of his appointment(s) for today
                        tblcurrent_appointments currentAppointment = entities.tblcurrent_appointments.Where(x => x.current_date.Equals(currentDate) && x.salon_id == salon_id && x.barber_id == barber_id).FirstOrDefault();

                        // If no current appointments for the current date
                        if (currentAppointment == null)
                        {
                            int appointment_id = entities.tblappointments.Where(x => x.due_date.Equals(currentDate) && x.salon_id == salon_id && x.barber_Id == barber_id && x.appointment_no_for_day == 1).Select(x => x.appointment_id).FirstOrDefault();
                            tblcurrent_appointments appointment = new tblcurrent_appointments
                            {
                                appointment_id      = appointment_id,
                                salon_id            = salon_id,
                                barber_id           = barber_id,
                                current_date        = currentDate,
                                last_appointment_no = current_appointment_no
                            };
                            entities.tblcurrent_appointments.Add(appointment);
                            entities.SaveChanges();
                            Log.Update(appointment.current_appointment_id.ToString(), typeof(tblcurrent_appointments).Name, ActionType.INSERT);


                            // Update the appointment status as completed
                            var entity = entities.tblappointments.FirstOrDefault(e => e.appointment_id == appointment_id);
                            if (entity != null)
                            {
                                entity.end_time = DateTime.Now.TimeOfDay;
                                entity.status   = AppointmentStatus.COMPLETED.ToString();
                                entities.SaveChanges();
                                Log.Update(appointment_id.ToString(), typeof(tblappointment).Name, ActionType.UPDATE);
                            }


                            // Update the availability of barber
                            var barber = entities.tblbarbers.Where(x => x.salon_id == salon_id && x.barber_id == barber_id).FirstOrDefault();
                            if (barber != null)
                            {
                                barber.is_available = true;
                                entities.SaveChanges();
                                Log.Update(barber.barber_id.ToString(), typeof(tblbarber).Name, ActionType.UPDATE);
                            }

                            transaction.Commit();

                            return(Request.CreateResponse(HttpStatusCode.OK, new { Success = true, Message = "Appointment details updated successfully!" }));
                        }
                        else
                        {
                            List <Object> response          = new List <Object>();
                            int           mainAppointmentId = entities.tblappointments.Where(x => x.due_date.Equals(currentDate) && x.salon_id == salon_id && x.barber_Id == barber_id && x.appointment_no_for_day == current_appointment_no).Select(x => x.appointment_id).FirstOrDefault();

                            // Update necessary fields
                            currentAppointment.last_appointment_no = current_appointment_no;
                            currentAppointment.appointment_id      = mainAppointmentId;
                            entities.SaveChanges();
                            Log.Update(currentAppointment.current_appointment_id.ToString(), typeof(tblcurrent_appointments).Name, ActionType.UPDATE);


                            // Update the appointment status as completed
                            var entity = entities.tblappointments.FirstOrDefault(e => e.appointment_id == mainAppointmentId);
                            if (entity != null)
                            {
                                entity.end_time = DateTime.Now.TimeOfDay;
                                entity.status   = AppointmentStatus.COMPLETED.ToString();
                                entities.SaveChanges();
                                Log.Update(mainAppointmentId.ToString(), typeof(tblappointment).Name, ActionType.UPDATE);
                            }


                            // Update the availability of barber
                            var barber = entities.tblbarbers.Where(x => x.salon_id == salon_id && x.barber_id == barber_id).FirstOrDefault();
                            if (barber != null)
                            {
                                barber.is_available = true;
                                entities.SaveChanges();
                                Log.Update(barber.barber_id.ToString(), typeof(tblbarber).Name, ActionType.UPDATE);
                            }

                            transaction.Commit();

                            return(Request.CreateResponse(HttpStatusCode.OK, new { Success = true, Message = "Appointment details updated successfully!" }));
                        }
                    }
                }
            }
            catch (Exception)
            {
                return(Messages.GetInstance().HandleException("An error occured! Failed to update current appointment details."));
            }
        }
Exemple #10
0
        public HttpResponseMessage Post([FromBody] JObject salon_details)
        {
            try
            {
                // Check if a session already exists or if it's expired
                //if (HttpContext.Current.Session["Token"] == null)
                //    return Request.CreateResponse(HttpStatusCode.Unauthorized, new { Success = false, Message = "Session expired! Unable to authenticate user." });


                int    owner_id     = int.Parse(salon_details["owner_id"].ToString());
                string name         = salon_details["name"].ToString();
                string location     = salon_details["location"].ToString();
                string contact_no   = salon_details["contact_no"].ToString().Trim();
                string email        = salon_details["email"].ToString();
                int    no_of_seats  = int.Parse(salon_details["no_of_seats"].ToString());
                string opening_time = salon_details["opening_time"].ToString();
                string closing_time = salon_details["closing_time"].ToString();

                using (SalonDbEntities entities = new SalonDbEntities())
                {
                    // Validate salon - check if the salon already exists
                    bool selectedSalon = entities.tblsalons.Any(e => e.contact_no.ToString().Trim() == contact_no || e.email.ToUpper().Trim() == email.ToUpper().Trim());

                    // If a salon already exists
                    if (selectedSalon)
                    {
                        return(Messages.GetInstance().HandleRequest("Salon", ActionType.INSERT, true));
                    }
                    else
                    {
                        // Validates the contact no
                        if (!Utilities.getInstance().ValidateContactNumber(contact_no))
                        {
                            return(Messages.GetInstance().ValidateFields("Salon", ActionType.INSERT, isContactNumber: true));
                        }

                        // Validates the email
                        if (email != null && !Utilities.getInstance().ValidateEmail(email))
                        {
                            return(Messages.GetInstance().ValidateFields("Salon", ActionType.INSERT, isEmail: true));
                        }

                        // Validates the no of seats
                        if (no_of_seats <= 0)
                        {
                            return(Messages.GetInstance().HandleException("Failed to create salon! No of seats should be > 0."));
                        }

                        using (var transaction = entities.Database.BeginTransaction())
                        {
                            tblsalon obj = new tblsalon
                            {
                                owner_id         = owner_id,
                                salon_name       = name.Trim(),
                                salon_location   = location.Trim(),
                                contact_no       = int.Parse(contact_no),
                                email            = email.Trim(),
                                seating_capacity = no_of_seats,
                                opening_time     = DateTime.Parse(opening_time, System.Globalization.CultureInfo.CurrentCulture).TimeOfDay,
                                closing_time     = DateTime.Parse(closing_time, System.Globalization.CultureInfo.CurrentCulture).TimeOfDay
                            };
                            entities.tblsalons.Add(obj);
                            entities.SaveChanges();

                            Utilities.getInstance().UpdateChanges(entities, transaction, obj.salon_id.ToString(), typeof(tblsalon).Name, ActionType.INSERT);

                            return(Messages.GetInstance().HandleRequest("Salon", ActionType.INSERT));
                        }
                    }
                }
            }
            catch (Exception)
            {
                return(Messages.GetInstance().HandleException("An error occured! Failed to create salon."));
            }
        }
        public HttpResponseMessage Post([FromBody] JObject barber_details)
        {
            try
            {
                // Check if a session already exists or if it's expired
                //if (HttpContext.Current.Session["Token"] == null)
                //    return Request.CreateResponse(HttpStatusCode.Unauthorized, new { Success = false, Message = "Session expired! Unable to authenticate user." });


                string barber_name       = barber_details["barber_name"].ToString().Trim();
                int    salon_id          = int.Parse(barber_details["salon_id"].ToString());
                int    allocated_seat_no = int.Parse(barber_details["allocated_seat_no"].ToString());

                using (SalonDbEntities entities = new SalonDbEntities())
                {
                    // Check if the barber name already exists in the particular salon. Otherwise there will be confusions.
                    if (entities.tblbarbers.Any(e => e.barber_name.ToUpper().Trim() == barber_name.ToUpper().Trim() && e.salon_id == salon_id))
                    {
                        return(Messages.GetInstance().HandleException("Failed to create barber! A barber with the same name already exists in salon id = " + salon_id + ". Please enter another name."));
                    }


                    // Check if the user entered seat no exists in the salon
                    // 1. Get the no of seats available in the salon
                    // 2. Check if the entered seat no is within that range
                    var obj = entities.tblsalons.Where(p => p.salon_id.Equals(salon_id)).Select(p => new { seating_capacity = p.seating_capacity }).FirstOrDefault();
                    if (1 <= allocated_seat_no && allocated_seat_no <= obj.seating_capacity)
                    {
                        // If the seat no exists, then check if a barber in that salon, has already been assigned to that particular seat no
                        if (entities.tblbarbers.Any(e => e.salon_id == salon_id && e.allocated_seat_no == allocated_seat_no))
                        {
                            return(Messages.GetInstance().HandleException("Failed to create barber! A barber has already been assigned to seat no = " + allocated_seat_no + " in salon id = " + salon_id + ". Please enter another seat number."));
                        }
                        else
                        {
                            // Add the new barber, & allocate the entered seat no to him
                            using (var transaction = entities.Database.BeginTransaction())
                            {
                                tblbarber barber = new tblbarber
                                {
                                    barber_name       = barber_name,
                                    salon_id          = salon_id,
                                    allocated_seat_no = allocated_seat_no,
                                    is_available      = true
                                };
                                entities.tblbarbers.Add(barber);
                                entities.SaveChanges();

                                Utilities.getInstance().UpdateChanges(entities, transaction, barber.barber_id.ToString(), typeof(tblbarber).Name, ActionType.INSERT);

                                return(Messages.GetInstance().HandleRequest("Barber", ActionType.INSERT));
                            }
                        }
                    }
                    else
                    {
                        return(Messages.GetInstance().HandleException("Failed to create barber! The entered seat number is not found in the salon. Please enter a valid seat number."));
                    }
                }
            }
            catch (Exception)
            {
                return(Messages.GetInstance().HandleException("An error occured! Failed to create barber."));
            }
        }
Exemple #12
0
        public HttpResponseMessage Post([FromBody] JObject owner_details)
        {
            try
            {
                string name       = owner_details["name"].ToString().Trim();
                string contact_no = owner_details["contact_no"].ToString().Trim();
                string pin        = owner_details["pin"].ToString().Trim();
                string password   = owner_details["password"].ToString().Trim();

                string email = null;
                if (owner_details["email"] != null)
                {
                    email = owner_details["email"].ToString().Trim();
                }

                using (SalonDbEntities entities = new SalonDbEntities())
                {
                    // Validate the contact no
                    if (!Utilities.getInstance().ValidateContactNumber(contact_no))
                    {
                        return(Messages.GetInstance().ValidateFields("Shop owner", ActionType.INSERT, isContactNumber: true));
                    }

                    // Validates the email
                    if (email != null && !Utilities.getInstance().ValidateEmail(email))
                    {
                        return(Messages.GetInstance().ValidateFields("Shop owner", ActionType.INSERT, isEmail: true));
                    }

                    // Validates the pin
                    if (pin.Count() != 5 || !Regex.IsMatch(pin, @"^\d{5}$"))
                    {
                        return(Request.CreateResponse(HttpStatusCode.BadRequest, new { Success = false, Message = "Failed to create shop owner! Received invalid pin. Hint: Pin should contain only 5 digits." }));
                    }

                    // Validates the password
                    if (!Utilities.getInstance().ValidatePassword(password))
                    {
                        return(Messages.GetInstance().ValidateFields("Shop owner", ActionType.INSERT, isPassword: true));
                    }

                    // Check if another shop owner already exists with the same contact no or email or username
                    if (entities.tblshop_owner.Any(e => e.contact_no.ToString() == contact_no))
                    {
                        return(Messages.GetInstance().HandleException("Failed to create shop owner! Contact number already exists."));
                    }

                    // Checks if the user pin alreeady exists
                    var userPins = entities.tblshop_owner.Select(x => x.pin).ToList();
                    foreach (string o in userPins)
                    {
                        if (Utilities.getInstance().DecodeFrom64(o) == pin)
                        {
                            return(Messages.GetInstance().HandleException("Failed to create shop owner! Pin already exists."));
                        }
                    }


                    if (email != null && entities.tblshop_owner.Any(e => e.email != null && e.email == email))
                    {
                        return(Messages.GetInstance().HandleException("Failed to create shop owner! Email already exists."));
                    }

                    else
                    {
                        // Add the new shop owner
                        using (var transaction = entities.Database.BeginTransaction())
                        {
                            tblshop_owner owner = new tblshop_owner
                            {
                                name       = name,
                                contact_no = int.Parse(contact_no),
                                email      = email,
                                password   = Utilities.getInstance().CalculateHash(password),
                                pin        = Utilities.getInstance().CalculateHash(pin)
                            };
                            entities.tblshop_owner.Add(owner);
                            entities.SaveChanges();

                            Utilities.getInstance().UpdateChanges(entities, transaction, owner.owner_id.ToString(), typeof(tblshop_owner).Name, ActionType.INSERT);

                            return(Messages.GetInstance().HandleRequest("Shop owner", ActionType.INSERT));
                            //return Request.CreateResponse(HttpStatusCode.Created, new { Login = true, Pin = pin });
                        }
                    }
                }
            }
            catch (Exception)
            {
                return(Messages.GetInstance().HandleException("An error occured! Failed to create shop owner."));
            }
        }