public void MappperTest()
    {
        EntityMapper.Map <UsersBo, Users>();
        EntityMapper.Map <RolesBo, Roles>();
        EntityMapper.Map <AppObjectsBo, AppObjects>();
        var factory = new EntityMapper();
        var entity  = factory.CreateEntity <UsersBo>();

        Assert.IsNotNull(entity);
        Assert.IsInstanceOfType(entity, typeof(Users));
    }
        public override void SaveData <T>(DbContext context, dynamic entity)
        {
            base.SaveData <T>(context, (T)entity);
            CustomersContext DBContext = (CustomersContext)context;
            CU_B_PROFILE     Profile   = DBContext.CU_B_PROFILE.FirstOrDefault(E => E.CUSTOMER_CODE == ID);

            if (Profile == null)
            {
                Profile = EntityMapper.CreateEntity <CU_B_PROFILE>();
                Profile.CUSTOMER_CODE = ID;
                DBContext.CU_B_PROFILE.Add(Profile);
            }
            Profile.FLG_OTHERCONTACT = IsOtherContactPreferred ? "Y" : "N";

            CU_B_PROFILE_ATTRIBUTE_LOOKUP ProfileAttribute = DBContext.CU_B_PROFILE_ATTRIBUTE_LOOKUP.FirstOrDefault(E => E.CUSTOMER_CODE == ID && E.ATTRIBUTE_CODE == "SMF");

            if (ProfileAttribute != null)
            {
                DBContext.CU_B_PROFILE_ATTRIBUTE_LOOKUP.Remove(ProfileAttribute);
            }

            ProfileAttribute = EntityMapper.CreateEntity <CU_B_PROFILE_ATTRIBUTE_LOOKUP>();
            ProfileAttribute.CUSTOMER_CODE  = ID;
            ProfileAttribute.ATTRIBUTE_CODE = "SMF";
            ProfileAttribute.VALUE_CODE     = EnumHelper.GetEnumValue <PreferredContactMethods>(PreferredContactMethod);
            DBContext.CU_B_PROFILE_ATTRIBUTE_LOOKUP.Add(ProfileAttribute);

            CU_B_PROFILE_ATTRIBUTE_LOOKUP OtheContactIsPrimaryAttribute = DBContext.CU_B_PROFILE_ATTRIBUTE_LOOKUP.FirstOrDefault(E => E.CUSTOMER_CODE == ID && E.ATTRIBUTE_CODE == "PCT");

            if (OtheContactIsPrimaryAttribute != null)
            {
                DBContext.CU_B_PROFILE_ATTRIBUTE_LOOKUP.Remove(OtheContactIsPrimaryAttribute);
            }

            OtheContactIsPrimaryAttribute = EntityMapper.CreateEntity <CU_B_PROFILE_ATTRIBUTE_LOOKUP>();
            OtheContactIsPrimaryAttribute.CUSTOMER_CODE  = ID;
            OtheContactIsPrimaryAttribute.ATTRIBUTE_CODE = "PCT";
            OtheContactIsPrimaryAttribute.VALUE_CODE     = IsOtherContactPreferred ? "02" : "01";
            DBContext.CU_B_PROFILE_ATTRIBUTE_LOOKUP.Add(OtheContactIsPrimaryAttribute);

            CU_B_PROFILE_ATTRIBUTE_LOOKUP PreferredTimeOfContactAttribute = DBContext.CU_B_PROFILE_ATTRIBUTE_LOOKUP.FirstOrDefault(E => E.CUSTOMER_CODE == ID && E.ATTRIBUTE_CODE == "CTP");

            if (PreferredTimeOfContactAttribute != null)
            {
                DBContext.CU_B_PROFILE_ATTRIBUTE_LOOKUP.Remove(PreferredTimeOfContactAttribute);
            }

            PreferredTimeOfContactAttribute = EntityMapper.CreateEntity <CU_B_PROFILE_ATTRIBUTE_LOOKUP>();
            PreferredTimeOfContactAttribute.CUSTOMER_CODE  = ID;
            PreferredTimeOfContactAttribute.ATTRIBUTE_CODE = "CTP";
            PreferredTimeOfContactAttribute.VALUE_CODE     = PreferredTimeOfContactCode ?? "06";
            DBContext.CU_B_PROFILE_ATTRIBUTE_LOOKUP.Add(PreferredTimeOfContactAttribute);
        }
        public override void SaveData <T>(DbContext context, dynamic entity)
        {
            base.SaveData <T>(context, (T)entity);

            CustomersContext DBContext = (CustomersContext)context;

            CM_B_ATTACHMENT_ARCHIVE ItemArchive = EntityMapper.CreateEntity <CM_B_ATTACHMENT_ARCHIVE>();

            EntityMapper.UpdateEntity(this, ItemArchive);
            ItemArchive.ATTACHMENT_COUNTER = entity.ATTACHMENT_COUNTER;
            DBContext.CM_B_ATTACHMENT_ARCHIVE.Add(ItemArchive);
        }
Example #4
0
        public void ScreeningPost([FromBody] ScreeningBase value)
        {
            if (value == null)
            {
                throw new ArgumentNullException($"Argument value cannot be null");
            }

            CU_B_SCREENING_EXT_AUS Item = EntityMapper.CreateEntity <CU_B_SCREENING_EXT_AUS>();

            EntityMapper.UpdateEntity(value, Item);

            DBContext.CU_B_SCREENING_EXT_AUS.Add(Item);
            DBContext.SaveChanges();
        }
        public ActionResult <AppointmentListItem> Reschedule(Guid rescheduledAppointmentRowGuid, [FromBody] AppointmentBase value)
        {
            if (value == null)
            {
                throw new ArgumentNullException(nameof(value), $"Argument value cannot be null");
            }

            AG_B_APPOINTMENT oldAppointment = DBContext.AG_B_APPOINTMENT.SingleOrDefault(E => E.ROWGUID == rescheduledAppointmentRowGuid);

            if (oldAppointment == null)
            {
                throw new NotFoundException($"No appointment found with RowGuid:{rescheduledAppointmentRowGuid}");
            }

            if (oldAppointment.AG_B_APPOINTMENT_EXT_AUS.RESCHEDULED_NUMBER.GetValueOrDefault(0) >= 3)
            {
                throw new InvalidOperationException("Appointment reschedule max number exceeded");
            }

            oldAppointment.AG_B_APPOINTMENT_EXT_AUS.RESCHEDULED_NUMBER = oldAppointment.AG_B_APPOINTMENT_EXT_AUS.RESCHEDULED_NUMBER.GetValueOrDefault(0) + 1;

            using (IDbContextTransaction scope = DBContext.Database.BeginTransaction())
            {
                UpdateAppointmentStatus(oldAppointment.ROWGUID, appointmentStatus.Rescheduled);
                AppointmentListItem Result = DoPost(value, rescheduledAppointmentRowGuid: rescheduledAppointmentRowGuid);

                CU_B_ACTIVITY         activity    = EntityMapper.CreateEntity <CU_B_ACTIVITY>();
                CU_B_ACTIVITY_EXT_AUS activityExt = EntityMapper.CreateEntity <CU_B_ACTIVITY_EXT_AUS>();
                activity.ACTIVITY_TYPE_CODE      = "DY";
                activity.ACTIVITY_DATE           = DateTime.Today;
                activity.CUSTOMER_CODE           = activityExt.CUSTOMER_CODE = Result.CustomerCode;
                activity.EMPLOYEE_CODE           = Result.EmployeeCode;
                activity.REFERENCE_DATE          = oldAppointment.DT_APPOINTMENT;
                activity.REFERENCE_NUMBER        = oldAppointment.APPOINTMENT_ID;
                activity.APPOINTMENT_ID          = Result.AppointmentID;
                activityExt.DT_APPOINTEMENT_FROM = oldAppointment.DT_APPOINTMENT;
                activityExt.DT_APPOINTEMENT_TO   = Result.AppointmentDate;
                activity.ACTIVITY_ID             = activityExt.ACTIVITY_ID = FoxDataService.GetNewCounter("CU_B_ACTIVITY", "ACTIVITY_ID", Result.StatusCode, activity.USERINSERT).VALUE.GetValueOrDefault();
                activity.SHOP_CODE = activity.LAPTOP_CODE = activityExt.SHOP_CODE = activityExt.LAPTOP_CODE = Result.ShopCode;
                DBContext.CU_B_ACTIVITY.Add(activity);
                DBContext.CU_B_ACTIVITY_EXT_AUS.Add(activityExt);

                DBContext.SaveChanges();
                scope.Commit();

                return(Result);
            }
        }
Example #6
0
        public void AttachmentPost([FromBody] Attachment value)
        {
            if (value == null)
            {
                throw new ArgumentNullException($"Argument value cannot be null");
            }

            long   WEIGHT_MAX            = 363520;
            string ATTACHMENT_WEIGHT_MAX = FoxDataService.GetGlobalParameterValue <string>("CM_B_ATTACHMENT_WEIGHT_MAX", "5120");

            if (!string.IsNullOrEmpty(ATTACHMENT_WEIGHT_MAX))
            {
                WEIGHT_MAX = Convert.ToInt64(ATTACHMENT_WEIGHT_MAX) * 1024;
                if (value.AttachmentData?.LongLength > WEIGHT_MAX)
                {
                    throw new InvalidOperationException($"Max attachment size is {WEIGHT_MAX}Kb");
                }
            }

            CM_B_ATTACHMENT Item = EntityMapper.CreateEntity <CM_B_ATTACHMENT>();

            EntityMapper.UpdateEntity(value, Item);

            Item.REASON_ID          = Item.ROWGUID;
            Item.ATTACHMENT_COUNTER = Convert.ToInt64(FoxDataService.GetNewCounter("CM_B_ATTACHMENT", "ATTACHMENT_COUNTER", value.ShopCode, Item.USERINSERT).FORMATTEDVALUE);

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

            //Update customer's privacy flags
            if (value.AttachmentTypeCode == "PCF")
            {
                CU_B_ADDRESS_BOOK customer = DBContext.CU_B_ADDRESS_BOOK.Where(E => E.CUSTOMER_CODE == Item.CUSTOMER_CODE).FirstOrDefault();
                customer.FLG_PRIVACYPERSDATA = "Y";
                customer.CU_B_ADDRESS_BOOK_EXT_AUS.FLG_TO_CALL = "Y";
                EntityMapper.UpdateEntityStandardFields(customer);
                EntityMapper.UpdateEntityStandardFields(customer.CU_B_ADDRESS_BOOK_EXT_AUS);
            }

            DBContext.CM_B_ATTACHMENT.Add(Item);
            DBContext.SaveChanges();
        }
Example #7
0
        private void CreateAddressEntity(Address value, ref int?addressCounter, string customerCode = null)
        {
            CU_B_ADDRESS         Item    = EntityMapper.CreateEntity <CU_B_ADDRESS>();
            CU_B_ADDRESS_EXT_AUS ItemExt = EntityMapper.CreateEntity <CU_B_ADDRESS_EXT_AUS>();

            Item.CUSTOMER_CODE = ItemExt.CUSTOMER_CODE = value.CustomerCode ?? customerCode;

            IQueryable <CU_B_ADDRESS> qryAddresses = DBContext.CU_B_ADDRESS.Where(E => E.CUSTOMER_CODE == Item.CUSTOMER_CODE);

            addressCounter = qryAddresses.Any() ? Math.Max(qryAddresses.Max(E => E.ADDRESS_COUNTER) + 1, addressCounter.GetValueOrDefault(1)) : addressCounter.GetValueOrDefault(1);

            Item.ADDRESS_COUNTER = ItemExt.ADDRESS_COUNTER = addressCounter.Value;
            addressCounter       = addressCounter.Value + 1;
            Item.ROWGUID         = ItemExt.ROWGUID = Guid.NewGuid();

            EntityMapper.UpdateEntity(value, Item, ItemExt);
            CheckAddressData(Item, ItemExt);

            DBContext.CU_B_ADDRESS.Add(Item);
            DBContext.CU_B_ADDRESS_EXT_AUS.Add(ItemExt);
        }
Example #8
0
        public ActionResult <NoteListItem> NotePost([FromBody] NoteBase value)
        {
            if (value == null)
            {
                throw new ArgumentNullException($"Argument value cannot be null");
            }

            CU_B_NOTE Item = EntityMapper.CreateEntity <CU_B_NOTE>();

            EntityMapper.UpdateEntity(value, Item);

            Item.NOTE_DATE = DateTime.Today;
            CU_B_NOTE LastNote = DBContext.CU_B_NOTE.Where(E => E.CUSTOMER_CODE == Item.CUSTOMER_CODE && E.NOTE_DATE == Item.NOTE_DATE).OrderByDescending(E => E.NOTE_COUNTER).FirstOrDefault();

            Item.NOTE_COUNTER = LastNote != null ? LastNote.NOTE_COUNTER + 1 : 1;

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

            DBContext.CU_B_NOTE.Add(Item);
            DBContext.SaveChanges();

            return(NoteGet(Item.ROWGUID));
        }
Example #9
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);
        }