Exemplo n.º 1
0
        public ActionResult <CustomerExtended> Post([FromBody] Customer value, string XID, string campaignCode, string mediaTypeCode)
        {
            CheckCustomerAge(value?.Birthday);
            CU_B_ADDRESS_BOOK         Item        = EntityMapper.CreateEntity <CU_B_ADDRESS_BOOK>();
            CU_B_ADDRESS_BOOK_EXT_AUS ItemExt     = EntityMapper.CreateEntity <CU_B_ADDRESS_BOOK_EXT_AUS>();
            CU_B_ACTIVITY             activity    = EntityMapper.CreateEntity <CU_B_ACTIVITY>();
            CU_B_ACTIVITY_EXT_AUS     activityExt = EntityMapper.CreateEntity <CU_B_ACTIVITY_EXT_AUS>();

            EntityMapper.UpdateEntity(value, Item, ItemExt);

            CM_B_SHOP shop = DBContext.CM_B_SHOP.FirstOrDefault(E => E.SHOP_CODE == ItemExt.SHOP_CODE);

            //Add default values
            Item.CUSTOMER_TYPE_CODE = "QL";
            Item.COUNTRY_CODE       = Settings.Value.CountryCode;
            //Item.GENDER_CODE = Item.GENDER_CODE ?? "U";
            Item.STATUS_CODE = "00";                    //Force status to Active to avoid FOX issues
            ItemExt.CURRENT_FILE_LOCATION      = "000"; //Head office
            ItemExt.CURRENT_LOCATION_TYPE_CODE = "00";  //Head office
            ItemExt.SHOP_CODE = "000";                  //Head office
            Item.CUSTOMER_ID  = XID;
            //
            Item.CUSTOMER_CODE        = FoxDataService.GetNewCounter("CU_B_ADDRESS_BOOK", "CUSTOMER_CODE", ItemExt.SHOP_CODE, Item.USERINSERT).FORMATTEDVALUE;
            activityExt.CUSTOMER_CODE = activity.CUSTOMER_CODE = value.ID = ItemExt.CUSTOMER_CODE = Item.CUSTOMER_CODE;
            EntityMapper.InitializeEntityStandardFields(activity);
            EntityMapper.InitializeEntityStandardFields(activityExt);
            activity.ACTIVITY_TYPE_CODE = "RR";
            activity.ACTIVITY_DATE      = DateTime.Today;
            activity.LAPTOP_CODE        = activityExt.LAPTOP_CODE = activity.SHOP_CODE = activityExt.SHOP_CODE = ItemExt.SHOP_CODE;
            activity.LOCATION_CODE      = ItemExt.SHOP_CODE;
            activity.LOCATION_TYPE_CODE = ItemExt.SHOP_CODE == "000" ? "03" : "01";
            activity.ACTIVITY_ID        = activityExt.ACTIVITY_ID = FoxDataService.GetNewCounter("CU_B_ACTIVITY", "ACTIVITY_ID", ItemExt.SHOP_CODE, Item.USERINSERT).VALUE.GetValueOrDefault();
            EntityMapper.CheckEntityRowId(activity, activityExt, Guid.NewGuid());

            /* Disabled FK check
             * //Check for valid campaign
             * if (!string.IsNullOrWhiteSpace(campaignCode))
             * {
             *      CM_S_CAMPAIGN campaign = DBContext.CM_S_CAMPAIGN.FirstOrDefault(E => E.CAMPAIGN_CODE == campaignCode);
             *      activity.CAMPAIGN_CODE = campaign?.CAMPAIGN_CODE;
             * }
             * //Check for valid mediatype
             * if (!string.IsNullOrWhiteSpace(mediaTypeCode))
             * {
             *      CM_S_MEDIATYPE mediaType = DBContext.CM_S_MEDIATYPE.FirstOrDefault(E => E.MEDIATYPE_CODE == mediaTypeCode);
             *      activity.MEDIATYPE_CODE = mediaType?.MEDIATYPE_CODE;
             * }
             */
            activity.CAMPAIGN_CODE  = campaignCode;
            activity.MEDIATYPE_CODE = mediaTypeCode;

            DBContext.CU_B_ADDRESS_BOOK.Add(Item);
            DBContext.CU_B_ADDRESS_BOOK_EXT_AUS.Add(ItemExt);
            DBContext.CU_B_ACTIVITY.Add(activity);
            DBContext.CU_B_ACTIVITY_EXT_AUS.Add(activityExt);

            value.SaveData <CU_B_ADDRESS_BOOK>(DBContext, Item);

            if (value.Addresses != null)
            {
                int?    AddressCounter = null;
                Address Addr           = value.Addresses.FirstOrDefault(E => E.IsHomeAddress);
                if (Addr != null)
                {
                    CreateAddressEntity(Addr, ref AddressCounter, Item.CUSTOMER_CODE);
                }

                Addr = value.Addresses.FirstOrDefault(E => !E.IsHomeAddress && E.IsInvoiceDefault);
                if (Addr != null)
                {
                    CreateAddressEntity(Addr, ref AddressCounter, Item.CUSTOMER_CODE);
                }

                Addr = value.Addresses.FirstOrDefault(E => !E.IsHomeAddress && E.IsMailingDefault);
                if (Addr != null)
                {
                    CreateAddressEntity(Addr, ref AddressCounter, Item.CUSTOMER_CODE);
                }

                Addr = value.Addresses.FirstOrDefault(E => !E.IsHomeAddress && E.IsOtherContact);
                if (Addr != null)
                {
                    CreateAddressEntity(Addr, ref AddressCounter, Item.CUSTOMER_CODE);
                }

                Addr = value.Addresses.FirstOrDefault(E => !E.IsHomeAddress && E.IsHomeVisitDefault);
                if (Addr != null)
                {
                    CreateAddressEntity(Addr, ref AddressCounter, Item.CUSTOMER_CODE);
                }
            }

            if (!string.IsNullOrWhiteSpace(XID))            //Creating customer from lead
            {
                CU_B_LEAD_EXT_AUS Lead = DBContext.CU_B_LEAD_EXT_AUS.FirstOrDefault(E => E.XID == XID);
                if (Lead != null)
                {
                    Lead.CUSTOMER_CODE = Item.CUSTOMER_CODE;
                    Lead.STATUS_CODE   = "30";
                    EntityMapper.UpdateEntityStandardFields(Lead);
                }
            }

            DBContext.Database.GetDbConnection().Open();
            try
            {
                var Transaction = DBContext.Database.GetDbConnection().BeginTransaction();
                try
                {
                    DBContext.Database.UseTransaction(Transaction);
                    DBContext.SaveChanges();
                    StringBuilder SQL = new StringBuilder("p_CU_B_CUSTOMER_MAPPING_getxidfrom_Customer_Code");

                    /*
                     * SQL.Append("@COMPANY_CODE = {0} ");
                     * SQL.Append(", @DIVISION_CODE = {1}");
                     * SQL.Append(", @CUSTOMER_CODE = {2}");
                     * SQL.Append(", @DT_INSERT = {3}");
                     * SQL.Append(", @USERINSERT = {4}");
                     * SQL.Append(", @DT_UPDATE = {5}");
                     * SQL.Append(", @USERUPDATE = {6}");
                     */
                    object[] parameters = new object[] { Settings.Value.CompanyCode, Settings.Value.CompanyCode, Item.CUSTOMER_CODE, Item.DT_INSERT, Item.USERINSERT, Item.DT_UPDATE, Item.USERUPDATE };
                    var      Connection = DBContext.Database.GetDbConnection();
                    var      Command    = Connection.CreateCommand();
                    Command.Transaction = Transaction;
                    Command.CommandType = CommandType.StoredProcedure;
                    Command.CommandText = SQL.ToString();
                    Command.Parameters.Add(new SqlParameter("@COMPANY_CODE", Settings.Value.CompanyCode));
                    Command.Parameters.Add(new SqlParameter("@DIVISION_CODE", Settings.Value.DivisionCode));
                    Command.Parameters.Add(new SqlParameter("@CUSTOMER_CODE", Item.CUSTOMER_CODE));
                    Command.Parameters.Add(new SqlParameter("@DT_INSERT", Item.DT_INSERT));
                    Command.Parameters.Add(new SqlParameter("@USERINSERT", Item.USERINSERT));
                    Command.Parameters.Add(new SqlParameter("@DT_UPDATE", Item.DT_UPDATE));
                    Command.Parameters.Add(new SqlParameter("@USERUPDATE", Item.USERUPDATE));
                    Command.ExecuteNonQuery();
                    //DBContext.Database.ExecuteSqlCommand(SQL.ToString(), parameters: parameters);
                    Transaction.Commit();
                }
                catch (Exception E)
                {
                    Transaction.Rollback();
                    throw E;
                }
                return(Get(Item.CUSTOMER_CODE));
            }
            finally
            {
                DBContext.Database.GetDbConnection().Close();
            }
        }
        private AppointmentListItem DoPost(AppointmentBase value, string campaignCode = null, string mediaTypeCode = null, string callID = null, Guid?rescheduledAppointmentRowGuid = null)
        {
            if (value == null)
            {
                throw new ArgumentNullException(nameof(value), "Argument 'value' cannot be null");
            }

            OperationResult <bool> check = CheckCanBookAppointment(value.CustomerCode, value.AppointmentShopCode, value.ServiceCode, value.AppointmentDate, rescheduledAppointmentRowGuid.GetValueOrDefault(Guid.Empty));

            if (!check.Result)
            {
                throw new InvalidOperationException(check.Message);
            }

            AG_B_APPOINTMENT         Item    = EntityMapper.CreateEntity <AG_B_APPOINTMENT>();
            AG_B_APPOINTMENT_EXT_AUS ItemExt = EntityMapper.CreateEntity <AG_B_APPOINTMENT_EXT_AUS>();

            CU_B_ACTIVITY         activity    = EntityMapper.CreateEntity <CU_B_ACTIVITY>();
            CU_B_ACTIVITY_EXT_AUS activityExt = EntityMapper.CreateEntity <CU_B_ACTIVITY_EXT_AUS>();

            AG_B_APPOINTMENT_STATUS_HISTORY history = EntityMapper.CreateEntity <AG_B_APPOINTMENT_STATUS_HISTORY>();

            if ((string.IsNullOrWhiteSpace(value.StatusCode) || value.StatusCode == appointmentStatus.Open) && value.AppointmentDate >= DateTime.Today && value.AppointmentDate < DateTime.Today.AddDays(2))
            {
                value.StatusCode = appointmentStatus.Confirmed;
            }

            EntityMapper.UpdateEntity(value, Item, ItemExt);

            //Add default or other values
            Item.APPOINTMENT_ID = ItemExt.APPOINTMENT_ID = string.Format("{0}00{1}", Item.APPOINTMENT_SHOP_CODE, FoxDataService.GetNewCounter("AG_B_APPOINTMENT", "APPOINTMENT_ID", "*", Item.USERINSERT).FORMATTEDVALUE);
            if (string.IsNullOrEmpty(Item.SHOP_CODE))
            {
                Item.SHOP_CODE = ItemExt.SHOP_CODE = Item.LAPTOP_CODE = ItemExt.LAPTOP_CODE = Item.APPOINTMENT_SHOP_CODE;
            }

            string[] specialAvailabilityServiceCodes = FoxDataService.GetSpecialAvailabilityServiceCodes(Item.SHOP_CODE);

            CM_B_SHOP shop = DBContext.CM_B_SHOP.FirstOrDefault(E => E.SHOP_CODE == Item.SHOP_CODE);

            activity.ACTIVITY_TYPE_CODE = "PR";
            activity.ACTIVITY_DATE      = DateTime.Today;
            activity.CUSTOMER_CODE      = activityExt.CUSTOMER_CODE = Item.CUSTOMER_CODE;
            activity.EMPLOYEE_CODE      = Item.EMPLOYEE_CODE;
            Item.LOCATION_CODE          = activity.LOCATION_CODE = shop?.OBJ_CODE;
            Item.LOCATION_TYPE_CODE     = activity.LOCATION_TYPE_CODE = Item.SHOP_CODE == "000" ? "03" : "01";
            Item.STATUS_CODE            = Item.STATUS_CODE ?? appointmentStatus.Open;
            activity.REFERENCE_DATE     = Item.DT_APPOINTMENT;
            activity.REFERENCE_NUMBER   = Item.APPOINTMENT_ID;
            history.APPOINTMENT_ID      = activity.APPOINTMENT_ID = Item.APPOINTMENT_ID;
            history.SHOP_CODE           = history.LAPTOP_CODE = activity.SHOP_CODE = activity.LAPTOP_CODE = activityExt.SHOP_CODE = activityExt.LAPTOP_CODE = Item.SHOP_CODE;
            activity.ACTIVITY_ID        = activityExt.ACTIVITY_ID = FoxDataService.GetNewCounter("CU_B_ACTIVITY", "ACTIVITY_ID", Item.SHOP_CODE, Item.USERINSERT).VALUE.GetValueOrDefault();
            history.CONFIRMATION_STATUS = Item.STATUS_CODE;
            history.REASON_CODE         = Item.REASON_CODE;
            history.ROWGUID             = Item.ROWGUID;


            /* Disabled FK check
             * //Check for valid campaign
             * if (!string.IsNullOrWhiteSpace(campaignCode))
             * {
             *      CM_S_CAMPAIGN campaign = DBContext.CM_S_CAMPAIGN.FirstOrDefault(E => E.CAMPAIGN_CODE == campaignCode);
             *      ItemExt.CAMPAIGN_CODE = activity.CAMPAIGN_CODE = campaign?.CAMPAIGN_CODE;
             * }
             * //Check for valid mediatype
             * if (!string.IsNullOrWhiteSpace(mediaTypeCode))
             * {
             *      CM_S_MEDIATYPE mediaType = DBContext.CM_S_MEDIATYPE.FirstOrDefault(E => E.MEDIATYPE_CODE == mediaTypeCode);
             *      ItemExt.MEDIATYPE_CODE = activity.MEDIATYPE_CODE = mediaType?.MEDIATYPE_CODE;
             * }
             */

            ItemExt.CAMPAIGN_CODE  = activity.CAMPAIGN_CODE = campaignCode;
            ItemExt.MEDIATYPE_CODE = activity.MEDIATYPE_CODE = mediaTypeCode;

            ItemExt.SOURCE_TRACKING_ID = callID;

            EntityMapper.CheckEntityRowId(activity, activityExt, Guid.NewGuid());

            value.SaveData <AG_B_APPOINTMENT>(DBContext, Item);
            value.SaveData <CU_B_ACTIVITY>(DBContext, activity);

            // Set proper customer shop code if needed
            CU_B_ADDRESS_BOOK customer = DBContext.CU_B_ADDRESS_BOOK.FirstOrDefault(E => E.CUSTOMER_CODE == Item.CUSTOMER_CODE && E.CU_B_ADDRESS_BOOK_EXT_AUS.SHOP_CODE == "000");

            if (customer != null)
            {
                customer.CU_B_ADDRESS_BOOK_EXT_AUS.SHOP_CODE = Item.APPOINTMENT_SHOP_CODE;
            }


            DBContext.AG_B_APPOINTMENT.Add(Item);
            DBContext.AG_B_APPOINTMENT_EXT_AUS.Add(ItemExt);
            DBContext.CU_B_ACTIVITY.Add(activity);
            DBContext.CU_B_ACTIVITY_EXT_AUS.Add(activityExt);
            DBContext.AG_B_APPOINTMENT_STATUS_HISTORY.Add(history);


            IDbContextTransaction scope = DBContext.Database.CurrentTransaction;
            bool ownTransaction         = (scope == null);

            if (scope == null)
            {
                scope = DBContext.Database.BeginTransaction();
            }

            try
            {
                //Lock the table during this transaction
                DBContext.AG_B_APPOINTMENT.FromSql("SELECT TOP 1 * FROM AG_B_APPOINTMENT WITH (TABLOCKX, HOLDLOCK)");

                //Check for overlap
                DateTime appointmentStart = Item.DT_APPOINTMENT;
                DateTime appointmentEnd   = Item.DT_APPOINTMENT.AddMinutes(Item.DURATION.GetValueOrDefault());

                int overlappedAppointmentCount = DBContext.AG_B_APPOINTMENT.Where(E => AllowedAppointmentStatus.Contains(E.STATUS_CODE) &&
                                                                                  (E.ROOM_CODE == Item.ROOM_CODE || E.EMPLOYEE_CODE == Item.EMPLOYEE_CODE) &&
                                                                                  !specialAvailabilityServiceCodes.Contains(E.AG_S_SERVICE.SERVICE_TYPE_CODE) &&
                                                                                  ((E.DT_APPOINTMENT >= appointmentStart && E.DT_APPOINTMENT < appointmentEnd) ||
                                                                                   (E.DT_APPOINTMENT.AddMinutes(E.DURATION.GetValueOrDefault()) > appointmentStart && E.DT_APPOINTMENT.AddMinutes(E.DURATION.GetValueOrDefault()) < appointmentEnd) ||
                                                                                   (E.DT_APPOINTMENT <= appointmentStart && E.DT_APPOINTMENT.AddMinutes(E.DURATION.GetValueOrDefault()) > appointmentEnd))).Count();
                if (overlappedAppointmentCount > 0)
                {
                    throw new Exception("There is already an appointment for the given time slot");
                }

                //Complete the scope here to commit, otherwise it will rollback
                //The table lock will be released after we exit the TransactionScope block
                DBContext.SaveChanges();
                if (ownTransaction)
                {
                    scope.Commit();
                }
            }
            catch (Exception E)
            {
                if (ownTransaction)
                {
                    scope.Rollback();
                }
                throw E;
            }

            return(Get(Item.ROWGUID).Value);
        }