protected static FR_Guid Execute(DbConnection Connection, DbTransaction Transaction, P_L5PI_CDPfC_1134 Parameter, CSV2Core.SessionSecurity.SessionSecurityTicket securityTicket = null)
        {
            #region UserCode
            var returnValue = new FR_Guid();

            #region get company tenant

            ORM_CMN_BPT_BusinessParticipant.Query tenantBPQuery = new ORM_CMN_BPT_BusinessParticipant.Query();
            tenantBPQuery.IsTenant = true;
            tenantBPQuery.IfTenant_Tenant_RefID = securityTicket.TenantID;
            tenantBPQuery.IsDeleted             = false;
            ORM_CMN_BPT_BusinessParticipant tenantBP = ORM_CMN_BPT_BusinessParticipant.Query.Search(Connection, Transaction, tenantBPQuery).First();

            #endregion

            #region check if tenant need default person

            Boolean needDefaultPerson = tenantBP.IsNaturalPerson;
            if (needDefaultPerson)
            {
                ORM_CMN_BPT_BusinessParticipant_AssociatedBusinessParticipant.Query associatedBPQuery = new ORM_CMN_BPT_BusinessParticipant_AssociatedBusinessParticipant.Query();
                associatedBPQuery.AssociatedBusinessParticipant_RefID = tenantBP.CMN_BPT_BusinessParticipantID;
                associatedBPQuery.IsDeleted = false;
                List <ORM_CMN_BPT_BusinessParticipant_AssociatedBusinessParticipant> association = ORM_CMN_BPT_BusinessParticipant_AssociatedBusinessParticipant.Query.Search(Connection, Transaction, associatedBPQuery);
                if (association.Count > 0)
                {
                    foreach (var item in association)
                    {
                        if ((item.BusinessParticipant_RefID != null) || (item.BusinessParticipant_RefID != Guid.Empty))
                        {
                            needDefaultPerson = false;
                        }
                        break;
                    }
                }
            }

            #endregion

            if (needDefaultPerson)
            {
                #region create personalInfo

                ORM_CMN_PER_PersonInfo personInfo = new ORM_CMN_PER_PersonInfo();
                personInfo.CMN_PER_PersonInfoID = Guid.NewGuid();
                personInfo.Tenant_RefID         = securityTicket.TenantID;
                personInfo.IsDeleted            = false;
                personInfo.FirstName            = tenantBP.DisplayName;
                personInfo.LastName             = tenantBP.DisplayName;
                personInfo.Creation_Timestamp   = DateTime.Now;
                personInfo.Save(Connection, Transaction);

                #endregion

                #region create new businessParticipiant

                ORM_CMN_BPT_BusinessParticipant bParticipant = new ORM_CMN_BPT_BusinessParticipant();
                bParticipant.CMN_BPT_BusinessParticipantID = Guid.NewGuid();
                bParticipant.Tenant_RefID    = securityTicket.TenantID;
                bParticipant.IsNaturalPerson = true;
                bParticipant.IfNaturalPerson_CMN_PER_PersonInfo_RefID = personInfo.CMN_PER_PersonInfoID;
                bParticipant.DisplayName        = tenantBP.DisplayName;
                bParticipant.Creation_Timestamp = DateTime.Now;
                bParticipant.Save(Connection, Transaction);

                #endregion

                #region create associated businessParticipant table

                ORM_CMN_BPT_BusinessParticipant_AssociatedBusinessParticipant associatedBP = new ORM_CMN_BPT_BusinessParticipant_AssociatedBusinessParticipant();
                associatedBP.CMN_BPT_BusinessParticipant_AssociatedBusinessParticipantID = Guid.NewGuid();
                associatedBP.IsDeleted = false;
                associatedBP.BusinessParticipant_RefID           = bParticipant.CMN_BPT_BusinessParticipantID;
                associatedBP.AssociatedBusinessParticipant_RefID = tenantBP.CMN_BPT_BusinessParticipantID;
                associatedBP.Creation_Timestamp = DateTime.Now;
                associatedBP.Tenant_RefID       = securityTicket.TenantID;
                associatedBP.Save(Connection, Transaction);
                #endregion

                returnValue.Result = bParticipant.CMN_BPT_BusinessParticipantID;
            }

            //Put your code here

            return(returnValue);

            #endregion UserCode
        }
Beispiel #2
0
        protected static FR_Guid Execute(DbConnection Connection, DbTransaction Transaction, P_L5AC_SA_1046 Parameter, CSV2Core.SessionSecurity.SessionSecurityTicket securityTicket = null)
        {
            #region UserCode
            var returnValue = new FR_Guid();

            var bp = new ORM_CMN_BPT_BusinessParticipant()
            {
                CMN_BPT_BusinessParticipantID = Guid.NewGuid(),
                Tenant_RefID    = securityTicket.TenantID,
                IsNaturalPerson = true,
                IfNaturalPerson_CMN_PER_PersonInfo_RefID = Guid.NewGuid(),
                DisplayName = Parameter.Title + " " + Parameter.FirstName + " " + Parameter.LastName
            };
            bp.Save(Connection, Transaction);

            var personInfo = new ORM_CMN_PER_PersonInfo()
            {
                CMN_PER_PersonInfoID = bp.IfNaturalPerson_CMN_PER_PersonInfo_RefID,
                Tenant_RefID         = securityTicket.TenantID,
                Title         = Parameter.Title,
                FirstName     = Parameter.FirstName,
                LastName      = Parameter.LastName,
                PrimaryEmail  = Parameter.Email,
                Address_RefID = Guid.NewGuid()
            };
            personInfo.Save(Connection, Transaction);

            var address = new ORM_CMN_Address()
            {
                CMN_AddressID   = personInfo.Address_RefID,
                Tenant_RefID    = securityTicket.TenantID,
                Street_Name     = Parameter.StreetName,
                Street_Number   = Parameter.StreetNumber,
                City_Name       = Parameter.CityName,
                City_PostalCode = Parameter.CityPostalCode,
                Country_Name    = Parameter.CountryName
            };
            address.Save(Connection, Transaction);

            var bptUser = new ORM_CMN_BPT_USR_User()
            {
                CMN_BPT_USR_UserID        = Guid.NewGuid(),
                Tenant_RefID              = securityTicket.TenantID,
                BusinessParticipant_RefID = bp.CMN_BPT_BusinessParticipantID,
                Username = Parameter.Email
            };

            bptUser.Save(Connection, Transaction);

            var    cryptoUtils = new CryptoUtils();
            string passSalt    = cryptoUtils.GenerateRandomSalt(32);

            var bptUserPass = new ORM_CMN_BPT_USR_User_Password()
            {
                CMN_BPT_USR_User_PasswordID = Guid.NewGuid(),
                CMN_BPT_USR_User_RefID      = bptUser.CMN_BPT_USR_UserID,
                Tenant_RefID       = securityTicket.TenantID,
                Password_Salt      = passSalt,
                Password_Hash      = cryptoUtils.GenerateSaltedHash(Parameter.Password, passSalt),
                Password_Algorithm = cryptoUtils.GetHashAlgorithName(),
                IsActive           = Parameter.IsActivated
            };

            bptUserPass.Save(Connection, Transaction);

            var community = ORM_HEC_CMT_Community.Query.Search(Connection, Transaction, new ORM_HEC_CMT_Community.Query()
            {
                Tenant_RefID = securityTicket.TenantID,
                IsDeleted    = false,
                IsCommunityOperatedByThisTenant = true
            }).Single();


            var membershipType = ORM_HEC_CMT_Community_OfferedMembershipType.Query.Search(Connection, Transaction, new ORM_HEC_CMT_Community_OfferedMembershipType.Query()
            {
                Tenant_RefID           = securityTicket.TenantID,
                IsDeleted              = false,
                IsAvailableFor_Tenants = Parameter.IsTenant,
                IsAvailableFor_Doctors = !Parameter.IsTenant
            }).Single();

            var member = new ORM_HEC_CMT_Membership()
            {
                CommunityMembershipITL    = Guid.NewGuid().ToString(),
                HEC_CMT_MembershipID      = Guid.NewGuid(),
                Tenant_RefID              = securityTicket.TenantID,
                Community_RefID           = community.HEC_CMT_CommunityID,
                MembershipType_RefID      = membershipType.HEC_CMT_Community_OfferedMembershipTypeID,
                BusinessParticipant_RefID = bp.CMN_BPT_BusinessParticipantID
            };
            member.Save(Connection, Transaction);

            returnValue.Result = bptUser.CMN_BPT_USR_UserID;

            return(returnValue);

            #endregion UserCode
        }
Beispiel #3
0
        protected static FR_Guid Execute(DbConnection Connection, DbTransaction Transaction, P_L3MD_SDBI_1349 Parameter, CSV2Core.SessionSecurity.SessionSecurityTicket securityTicket = null)
        {
            #region UserCode
            var returnValue = new FR_Guid();

            var doctor = new ORM_HEC_Doctor();

            if (Parameter.DoctorID != Guid.Empty)
            {
                var result = doctor.Load(Connection, Transaction, Parameter.DoctorID);
                if (result.Status != FR_Status.Success || doctor.HEC_DoctorID == Guid.Empty)
                {
                    var error = new FR_Guid();
                    error.ErrorMessage = "No Such ID";
                    error.Status       = FR_Status.Error_Internal;
                    return(error);
                }
                #region Edit

                bool bopAccIsChenged = (doctor.Account_RefID == Parameter.Account_RefID) ? false : true;

                doctor.Account_RefID = Parameter.Account_RefID;
                if (Parameter.isLucentisSave)
                {
                    doctor.DoctorIDNumber = Parameter.ifLucentis_LANR;
                }
                doctor.Save(Connection, Transaction);

                //bussinessParticipant
                var query1 = new ORM_CMN_BPT_BusinessParticipant.Query();
                query1.CMN_BPT_BusinessParticipantID = doctor.BusinessParticipant_RefID;

                var bussinessParticipant = ORM_CMN_BPT_BusinessParticipant.Query.Search(Connection, Transaction, query1).First();

                if (!bopAccIsChenged)
                {
                    //personInfo
                    var query2 = new ORM_CMN_PER_PersonInfo.Query();
                    query2.CMN_PER_PersonInfoID = bussinessParticipant.IfNaturalPerson_CMN_PER_PersonInfo_RefID;

                    var personInfo = ORM_CMN_PER_PersonInfo.Query.Search(Connection, Transaction, query2).First();
                    personInfo.FirstName = Parameter.FirstName;
                    personInfo.LastName  = Parameter.LastName;
                    personInfo.Title     = Parameter.Title;
                    if (Parameter.isOphthalSave)
                    {
                        personInfo.Salutation_General = Parameter.ifOphthal_Salutation_General;
                        personInfo.Salutation_Letter  = Parameter.ifOphthal_Salutation_Letter;
                    }
                    if (Parameter.isLucentisSave)
                    {
                        personInfo.PrimaryEmail = Parameter.ifLucentis_LoginEmail;
                    }
                    personInfo.Save(Connection, Transaction);

                    var query4 = new ORM_CMN_PER_CommunicationContact.Query();
                    query4.PersonInfo_RefID = personInfo.CMN_PER_PersonInfoID;

                    var communicationContactsList = ORM_CMN_PER_CommunicationContact.Query.Search(Connection, Transaction, query4).ToList();

                    if (Parameter.Contacts != null)
                    {
                        foreach (var parContact in Parameter.Contacts)
                        {
                            ORM_CMN_PER_CommunicationContact communicationContacts = communicationContactsList.FirstOrDefault(c => c.Contact_Type == parContact.CMN_PER_CommunicationContact_TypeID);
                            if (communicationContacts != null)
                            {
                                communicationContacts.Tenant_RefID = securityTicket.TenantID;
                                communicationContacts.Content      = parContact.Content;
                                communicationContacts.Save(Connection, Transaction);
                            }
                            else
                            {
                                communicationContacts = new ORM_CMN_PER_CommunicationContact();
                                communicationContacts.CMN_PER_CommunicationContactID = Guid.NewGuid();
                                communicationContacts.PersonInfo_RefID   = personInfo.CMN_PER_PersonInfoID;
                                communicationContacts.Contact_Type       = parContact.CMN_PER_CommunicationContact_TypeID;
                                communicationContacts.Content            = parContact.Content;
                                communicationContacts.Creation_Timestamp = DateTime.Now;
                                communicationContacts.Tenant_RefID       = securityTicket.TenantID;
                                communicationContacts.Save(Connection, Transaction);
                            }
                        }
                    }
                }
                else
                {
                    var account2personInfoQuery = new ORM_CMN_PER_PersonInfo_2_Account.Query();
                    account2personInfoQuery.USR_Account_RefID = Parameter.Account_RefID;
                    account2personInfoQuery.Tenant_RefID      = securityTicket.TenantID;
                    account2personInfoQuery.IsDeleted         = false;
                    var account2personInfo = ORM_CMN_PER_PersonInfo_2_Account.Query.Search(Connection, Transaction, account2personInfoQuery).First();

                    var query2 = new ORM_CMN_PER_PersonInfo.Query();
                    query2.CMN_PER_PersonInfoID = account2personInfo.CMN_PER_PersonInfo_RefID;

                    var personInfo = ORM_CMN_PER_PersonInfo.Query.Search(Connection, Transaction, query2).First();
                    personInfo.FirstName = Parameter.FirstName;
                    personInfo.LastName  = Parameter.LastName;
                    personInfo.Title     = Parameter.Title;
                    personInfo.Save(Connection, Transaction);

                    var query4 = new ORM_CMN_PER_CommunicationContact.Query();
                    query4.PersonInfo_RefID = bussinessParticipant.IfNaturalPerson_CMN_PER_PersonInfo_RefID;
                    var communicationContactsList = ORM_CMN_PER_CommunicationContact.Query.Search(Connection, Transaction, query4).ToList();

                    if (communicationContactsList != null)
                    {
                        foreach (var c in communicationContactsList)
                        {
                            c.PersonInfo_RefID = personInfo.CMN_PER_PersonInfoID;
                            c.Save(Connection, Transaction);
                        }
                    }

                    if (Parameter.Contacts != null)
                    {
                        foreach (var parContact in Parameter.Contacts)
                        {
                            ORM_CMN_PER_CommunicationContact communicationContacts = communicationContactsList.FirstOrDefault(c => c.Contact_Type == parContact.CMN_PER_CommunicationContact_TypeID);
                            if (communicationContacts != null)
                            {
                                communicationContacts.Tenant_RefID = securityTicket.TenantID;
                                communicationContacts.Content      = parContact.Content;
                                communicationContacts.Save(Connection, Transaction);
                            }
                            else
                            {
                                communicationContacts = new ORM_CMN_PER_CommunicationContact();
                                communicationContacts.CMN_PER_CommunicationContactID = Guid.NewGuid();
                                communicationContacts.PersonInfo_RefID   = personInfo.CMN_PER_PersonInfoID;
                                communicationContacts.Contact_Type       = parContact.CMN_PER_CommunicationContact_TypeID;
                                communicationContacts.Content            = parContact.Content;
                                communicationContacts.Creation_Timestamp = DateTime.Now;
                                communicationContacts.Tenant_RefID       = securityTicket.TenantID;
                                communicationContacts.Save(Connection, Transaction);
                            }
                        }
                    }

                    bussinessParticipant.IfNaturalPerson_CMN_PER_PersonInfo_RefID = personInfo.CMN_PER_PersonInfoID;
                    bussinessParticipant.Save(Connection, Transaction);
                }
                if (Parameter.isLucentisSave)
                {
                    foreach (var practice in Parameter.Practices)
                    {
                        //if (practice.PracticeID != Guid.Empty) {

                        var medPract = new ORM_HEC_MedicalPractis.Query();
                        medPract.HEC_MedicalPractiseID = practice.PracticeID;

                        var medicalPractice = ORM_HEC_MedicalPractis.Query.Search(Connection, Transaction, medPract).First();

                        var queryCompanyInfo = new ORM_CMN_COM_CompanyInfo.Query();
                        queryCompanyInfo.CMN_COM_CompanyInfoID = medicalPractice.Ext_CompanyInfo_RefID;

                        var companyInfo = ORM_CMN_COM_CompanyInfo.Query.Search(Connection, Transaction, queryCompanyInfo).First();

                        var practiceQuery = new ORM_CMN_BPT_BusinessParticipant.Query();
                        practiceQuery.IfCompany_CMN_COM_CompanyInfo_RefID = companyInfo.CMN_COM_CompanyInfoID;

                        var practiceBPT = ORM_CMN_BPT_BusinessParticipant.Query.Search(Connection, Transaction, practiceQuery).First();

                        var query3 = new ORM_CMN_BPT_BusinessParticipant_AssociatedBusinessParticipant.Query();
                        query3.BusinessParticipant_RefID           = bussinessParticipant.CMN_BPT_BusinessParticipantID;
                        query3.AssociatedBusinessParticipant_RefID = practiceBPT.CMN_BPT_BusinessParticipantID;
                        query3.IsDeleted = false;

                        var associatedbusinessparticipantsOriginal = ORM_CMN_BPT_BusinessParticipant_AssociatedBusinessParticipant.Query.Search(Connection, Transaction, query3).FirstOrDefault();
                        if (associatedbusinessparticipantsOriginal != null)
                        {
                            associatedbusinessparticipantsOriginal.IsDeleted = practice.isDeleted;
                            associatedbusinessparticipantsOriginal.Save(Connection, Transaction);
                        }
                        else
                        {
                            var associatedbusinessparticipants = new ORM_CMN_BPT_BusinessParticipant_AssociatedBusinessParticipant();
                            associatedbusinessparticipants.BusinessParticipant_RefID           = bussinessParticipant.CMN_BPT_BusinessParticipantID;
                            associatedbusinessparticipants.AssociatedBusinessParticipant_RefID = practiceBPT.CMN_BPT_BusinessParticipantID;
                            associatedbusinessparticipants.AssociatedParticipant_FunctionName  = practice.AssociatedParticipant_FunctionName;
                            associatedbusinessparticipants.Creation_Timestamp = DateTime.Now;
                            associatedbusinessparticipants.Tenant_RefID       = securityTicket.TenantID;
                            associatedbusinessparticipants.Save(Connection, Transaction);


                            // }
                        }
                    }
                }
                if (Parameter.isOphthalSave && Parameter.Practices.Length == 1)
                {
                    var query3 = new ORM_CMN_BPT_BusinessParticipant_AssociatedBusinessParticipant.Query();
                    query3.BusinessParticipant_RefID = bussinessParticipant.CMN_BPT_BusinessParticipantID;
                    query3.IsDeleted = false;
                    var associatedbusinessparticipantsRes = ORM_CMN_BPT_BusinessParticipant_AssociatedBusinessParticipant.Query.Search(Connection, Transaction, query3);
                    ORM_CMN_BPT_BusinessParticipant_AssociatedBusinessParticipant firstPractice;

                    var medPract = new ORM_HEC_MedicalPractis.Query();
                    medPract.HEC_MedicalPractiseID = Parameter.Practices[0].PracticeID;
                    var medicalPractice  = ORM_HEC_MedicalPractis.Query.Search(Connection, Transaction, medPract).First();
                    var queryCompanyInfo = new ORM_CMN_COM_CompanyInfo.Query();
                    queryCompanyInfo.CMN_COM_CompanyInfoID = medicalPractice.Ext_CompanyInfo_RefID;
                    var companyInfo   = ORM_CMN_COM_CompanyInfo.Query.Search(Connection, Transaction, queryCompanyInfo).First();
                    var practiceQuery = new ORM_CMN_BPT_BusinessParticipant.Query();
                    practiceQuery.IfCompany_CMN_COM_CompanyInfo_RefID = companyInfo.CMN_COM_CompanyInfoID;
                    var practiceBPT = ORM_CMN_BPT_BusinessParticipant.Query.Search(Connection, Transaction, practiceQuery).First();

                    if (associatedbusinessparticipantsRes.Count > 0)
                    {
                        associatedbusinessparticipantsRes = associatedbusinessparticipantsRes.OrderBy(a => a.Creation_Timestamp).ToList();
                        firstPractice = associatedbusinessparticipantsRes.First();
                        foreach (var item in associatedbusinessparticipantsRes)
                        {
                            if (item != firstPractice && item.CMN_BPT_BusinessParticipant_AssociatedBusinessParticipantID == practiceBPT.CMN_BPT_BusinessParticipantID)
                            {
                                item.IsDeleted = true;
                                item.Save(Connection, Transaction);
                            }
                        }
                    }
                    else
                    {
                        firstPractice = new ORM_CMN_BPT_BusinessParticipant_AssociatedBusinessParticipant();
                        firstPractice.CMN_BPT_BusinessParticipant_AssociatedBusinessParticipantID = Guid.NewGuid();
                        firstPractice.Tenant_RefID = securityTicket.TenantID;
                        firstPractice.BusinessParticipant_RefID = bussinessParticipant.CMN_BPT_BusinessParticipantID;
                    }
                    firstPractice.AssociatedParticipant_FunctionName  = Parameter.Practices[0].AssociatedParticipant_FunctionName;
                    firstPractice.AssociatedBusinessParticipant_RefID = practiceBPT.CMN_BPT_BusinessParticipantID;
                    firstPractice.Save(Connection, Transaction);
                }
                #endregion
            }
            else
            {
                #region Save

                //personInfo
                Guid personInfoID;
                if (Parameter.Account_RefID == Guid.Empty)
                {
                    var personInfo = new ORM_CMN_PER_PersonInfo();
                    personInfo.CMN_PER_PersonInfoID = Guid.NewGuid();
                    personInfo.FirstName            = Parameter.FirstName;
                    personInfo.LastName             = Parameter.LastName;
                    if (Parameter.isLucentisSave)
                    {
                        personInfo.PrimaryEmail = Parameter.ifLucentis_LoginEmail;
                    }
                    personInfo.Title = Parameter.Title;
                    personInfo.Creation_Timestamp = DateTime.Now;
                    personInfo.Tenant_RefID       = securityTicket.TenantID;
                    if (Parameter.isOphthalSave)
                    {
                        personInfo.Salutation_Letter  = Parameter.ifOphthal_Salutation_Letter;
                        personInfo.Salutation_General = Parameter.ifOphthal_Salutation_General;
                    }
                    personInfo.Save(Connection, Transaction);
                    personInfoID = personInfo.CMN_PER_PersonInfoID;
                }
                else
                {
                    var account2personInfoQuery = new ORM_CMN_PER_PersonInfo_2_Account.Query();
                    account2personInfoQuery.USR_Account_RefID = Parameter.Account_RefID;
                    account2personInfoQuery.Tenant_RefID      = securityTicket.TenantID;
                    account2personInfoQuery.IsDeleted         = false;
                    var account2personInfo = ORM_CMN_PER_PersonInfo_2_Account.Query.Search(Connection, Transaction, account2personInfoQuery).First();

                    var query2 = new ORM_CMN_PER_PersonInfo.Query();
                    query2.CMN_PER_PersonInfoID = account2personInfo.CMN_PER_PersonInfo_RefID;

                    var personInfo = ORM_CMN_PER_PersonInfo.Query.Search(Connection, Transaction, query2).First();
                    personInfo.FirstName = Parameter.FirstName;
                    personInfo.LastName  = Parameter.LastName;
                    personInfo.Title     = Parameter.Title;
                    personInfo.Save(Connection, Transaction);

                    personInfoID = personInfo.CMN_PER_PersonInfoID;
                }
                //bussinessParticipants
                var bussinessParticipantTable = new ORM_CMN_BPT_BusinessParticipant();
                bussinessParticipantTable.CMN_BPT_BusinessParticipantID = Guid.NewGuid();
                bussinessParticipantTable.IsNaturalPerson    = true;
                bussinessParticipantTable.IsTenant           = false;
                bussinessParticipantTable.IsCompany          = false;
                bussinessParticipantTable.IsDeleted          = false;
                bussinessParticipantTable.Creation_Timestamp = DateTime.Now;
                bussinessParticipantTable.Tenant_RefID       = securityTicket.TenantID;
                bussinessParticipantTable.IfNaturalPerson_CMN_PER_PersonInfo_RefID = personInfoID;
                bussinessParticipantTable.Save(Connection, Transaction);

                doctor.HEC_DoctorID = Guid.NewGuid();
                if (Parameter.isLucentisSave)
                {
                    doctor.DoctorIDNumber = Parameter.ifLucentis_LANR;
                }
                doctor.Creation_Timestamp        = DateTime.Now;
                doctor.Tenant_RefID              = securityTicket.TenantID;
                doctor.BusinessParticipant_RefID = bussinessParticipantTable.CMN_BPT_BusinessParticipantID;
                doctor.Account_RefID             = Parameter.Account_RefID;
                doctor.Save(Connection, Transaction);

                if (Parameter.Contacts != null)
                {
                    foreach (var contact in Parameter.Contacts)
                    {
                        ORM_CMN_PER_CommunicationContact communicationContacts = new ORM_CMN_PER_CommunicationContact();
                        communicationContacts.CMN_PER_CommunicationContactID = Guid.NewGuid();
                        communicationContacts.PersonInfo_RefID   = personInfoID;
                        communicationContacts.Contact_Type       = contact.CMN_PER_CommunicationContact_TypeID;
                        communicationContacts.Content            = contact.Content;
                        communicationContacts.Creation_Timestamp = DateTime.Now;
                        communicationContacts.Tenant_RefID       = securityTicket.TenantID;
                        communicationContacts.Save(Connection, Transaction);
                    }
                }

                foreach (var practice in Parameter.Practices)
                {
                    if (practice.isDeleted == true)
                    {
                        continue;
                    }

                    var medPract = new ORM_HEC_MedicalPractis.Query();
                    medPract.HEC_MedicalPractiseID = practice.PracticeID;
                    var medicalPractice = ORM_HEC_MedicalPractis.Query.Search(Connection, Transaction, medPract).First();

                    var queryCompanyInfo = new ORM_CMN_COM_CompanyInfo.Query();
                    queryCompanyInfo.CMN_COM_CompanyInfoID = medicalPractice.Ext_CompanyInfo_RefID;
                    var companyInfo = ORM_CMN_COM_CompanyInfo.Query.Search(Connection, Transaction, queryCompanyInfo).First();

                    var practiceQuery = new ORM_CMN_BPT_BusinessParticipant.Query();
                    practiceQuery.IfCompany_CMN_COM_CompanyInfo_RefID = companyInfo.CMN_COM_CompanyInfoID;
                    var practiceBPT = ORM_CMN_BPT_BusinessParticipant.Query.Search(Connection, Transaction, practiceQuery).First();

                    //associatedbusinessparticipants
                    var associatedbusinessparticipants = new ORM_CMN_BPT_BusinessParticipant_AssociatedBusinessParticipant();
                    associatedbusinessparticipants.BusinessParticipant_RefID           = bussinessParticipantTable.CMN_BPT_BusinessParticipantID;
                    associatedbusinessparticipants.AssociatedBusinessParticipant_RefID = practiceBPT.CMN_BPT_BusinessParticipantID;
                    associatedbusinessparticipants.AssociatedParticipant_FunctionName  = practice.AssociatedParticipant_FunctionName;
                    associatedbusinessparticipants.Creation_Timestamp = DateTime.Now;
                    associatedbusinessparticipants.Tenant_RefID       = securityTicket.TenantID;
                    associatedbusinessparticipants.Save(Connection, Transaction);
                }
                #endregion
            }

            returnValue.Result = doctor.HEC_DoctorID;
            return(returnValue);

            #endregion UserCode
        }
        protected static FR_Base Execute(DbConnection Connection, DbTransaction Transaction, P_L3_ALTT_1558 Parameter, CSV2Core.SessionSecurity.SessionSecurityTicket securityTicket = null)
        {
            //Leave UserCode region to enable user code saving
            #region UserCode
            var returnValue = new FR_Base();

            if (Parameter == null)
            {
                returnValue.Status       = FR_Status.Error_Internal;
                returnValue.ErrorMessage = "Assign_Languages_To_Tenant method returned error message: Parameter is null.";
                return(returnValue);
            }

            ORM_CMN_Language[] languages = null;

            #region Retrieve all languages for tenant

            languages = ORM_CMN_Language.Query.Search(Connection, Transaction, new ORM_CMN_Language.Query()
            {
                Tenant_RefID = securityTicket.TenantID
            }).ToArray();


            #endregion

            #region Assign/deassign languages

            foreach (var languageToAssign in Parameter.AssignedLanguages)
            {
                var language = languages.FirstOrDefault(l => l.ISO_639_1.ToLower() == languageToAssign.LanguageISoCode.ToLower());
                if (language == null)
                {
                    language = new ORM_CMN_Language();
                    language.CMN_LanguageID     = Guid.NewGuid();
                    language.Creation_Timestamp = DateTime.Now;
                    language.IsDeleted          = false;
                    language.ISO_639_1          = languageToAssign.LanguageISoCode;
                    language.Name         = languageToAssign.LanguageName;
                    language.Tenant_RefID = securityTicket.TenantID;
                    language.Save(Connection, Transaction);
                }

                if (language.IsDeleted == true)
                {
                    language.IsDeleted = false;
                    language.Save(Connection, Transaction);
                }
            }

            foreach (var language in languages.Where(l => l.IsDeleted == false))
            {
                var languageToAssign = Parameter.AssignedLanguages.FirstOrDefault(lta => lta.LanguageISoCode.ToLower() == language.ISO_639_1.ToLower());
                if (languageToAssign == null)
                {
                    language.IsDeleted = true;
                    language.Save(Connection, Transaction);
                }
            }

            #endregion

            #region Set default language for tenant

            if (Parameter.DefaultLanguage != null)
            {
                ORM_CMN_BPT_BusinessParticipant businesParticipant = ORM_CMN_BPT_BusinessParticipant.Query.Search(Connection, Transaction, new ORM_CMN_BPT_BusinessParticipant.Query()
                {
                    IsDeleted             = false,
                    Tenant_RefID          = securityTicket.TenantID,
                    IfTenant_Tenant_RefID = securityTicket.TenantID
                }).FirstOrDefault();

                if (businesParticipant != null)
                {
                    var defaultLanguage = languages.FirstOrDefault(l => l.ISO_639_1.ToLower() == Parameter.DefaultLanguage.LanguageISoCode.ToLower());
                    if (defaultLanguage != null)
                    {
                        businesParticipant.DefaultLanguage_RefID = defaultLanguage.CMN_LanguageID;
                        businesParticipant.Save(Connection, Transaction);
                    }
                }
            }

            #endregion

            returnValue.Status = FR_Status.Success;

            return(returnValue);

            #endregion UserCode
        }
Beispiel #5
0
        protected static FR_Guid Execute(DbConnection Connection, DbTransaction Transaction, P_L6DR_SD_1537 Parameter, CSV2Core.SessionSecurity.SessionSecurityTicket securityTicket = null)
        {
            //Leave UserCode region to enable user code saving
            #region UserCode
            var returnValue = new FR_Guid();
            //Put your code here
            if (Parameter.CMN_BPT_BusinessParticipantID == Guid.Empty)
            {
                #region Create Mode

                #region BusinessParticipant


                ORM_CMN_BPT_BusinessParticipant bParticipant = new ORM_CMN_BPT_BusinessParticipant();
                bParticipant.CMN_BPT_BusinessParticipantID            = Guid.NewGuid();
                bParticipant.IfNaturalPerson_CMN_PER_PersonInfo_RefID = Guid.NewGuid();
                bParticipant.IsNaturalPerson    = true;
                bParticipant.Tenant_RefID       = securityTicket.TenantID;
                bParticipant.Creation_Timestamp = DateTime.Now;
                bParticipant.Save(Connection, Transaction);

                #endregion

                #region Account

                ORM_USR_Account account = new ORM_USR_Account();

                account.Username    = Parameter.FirstName + "_" + Parameter.LastName;
                account.AccountType = 3;
                account.BusinessParticipant_RefID = bParticipant.CMN_BPT_BusinessParticipantID;
                account.Tenant_RefID       = securityTicket.TenantID;
                account.Creation_Timestamp = DateTime.Now;
                account.Save(Connection, Transaction);

                P_L2DC_GUDCfT_1505 codeParam = new P_L2DC_GUDCfT_1505();
                codeParam.codeLength = 8;
                var checkCodeValue = cls_GetUniqueDeviceCodeForTenant.Invoke(Connection, Transaction, codeParam, securityTicket).Result;

                ORM_USR_Device_AccountCode accountCode = new ORM_USR_Device_AccountCode();
                accountCode.Account_RefID                   = account.USR_AccountID;
                accountCode.AccountCode_Value               = checkCodeValue.CodeValue;
                accountCode.AccountCode_ValidFrom           = DateTime.Now;
                accountCode.AccountCode_CurrentStatus_RefID = Guid.NewGuid();
                accountCode.IsAccountCode_Expirable         = false;
                accountCode.Tenant_RefID       = securityTicket.TenantID;
                accountCode.Creation_Timestamp = DateTime.Now;
                accountCode.Save(Connection, Transaction);

                ORM_USR_Device_AccountCode_StatusHistory Device_AccountCode_StatusHistory = new ORM_USR_Device_AccountCode_StatusHistory();
                Device_AccountCode_StatusHistory.USR_Device_AccountCode_StatusHistoryID = accountCode.AccountCode_CurrentStatus_RefID;
                Device_AccountCode_StatusHistory.IsAccountCode_Active     = true;
                Device_AccountCode_StatusHistory.Device_AccountCode_RefID = accountCode.USR_Device_AccountCodeID;
                Device_AccountCode_StatusHistory.Tenant_RefID             = securityTicket.TenantID;
                Device_AccountCode_StatusHistory.Creation_Timestamp       = DateTime.Now;
                Device_AccountCode_StatusHistory.Save(Connection, Transaction);


                ORM_USR_Device_AccountCode_UsageHistory USR_Device_AccountCode_UsageHistory = new ORM_USR_Device_AccountCode_UsageHistory();
                USR_Device_AccountCode_UsageHistory.USR_Device_AccountCode_UsageHistoryID = Guid.NewGuid();
                USR_Device_AccountCode_UsageHistory.Tenant_RefID             = securityTicket.TenantID;
                USR_Device_AccountCode_UsageHistory.Device_AccountCode_RefID = accountCode.USR_Device_AccountCodeID;
                USR_Device_AccountCode_UsageHistory.Creation_Timestamp       = DateTime.Now;
                USR_Device_AccountCode_UsageHistory.Save(Connection, Transaction);


                #endregion

                #region PersonInfo and Adresses

                ORM_CMN_PER_PersonInfo personInfo = new ORM_CMN_PER_PersonInfo();
                personInfo.CMN_PER_PersonInfoID = bParticipant.IfNaturalPerson_CMN_PER_PersonInfo_RefID;
                personInfo.Salutation_General   = Parameter.Salutation_General;
                personInfo.FirstName            = Parameter.FirstName;
                personInfo.LastName             = Parameter.LastName;
                personInfo.PrimaryEmail         = Parameter.PrimaryMail;
                personInfo.Address_RefID        = Guid.NewGuid();
                personInfo.Tenant_RefID         = securityTicket.TenantID;
                personInfo.Save(Connection, Transaction);

                ORM_CMN_PER_PersonInfo_2_Address personAdress = new ORM_CMN_PER_PersonInfo_2_Address();
                personAdress.AssignmentID             = Guid.NewGuid();
                personAdress.CMN_PER_PersonInfo_RefID = personInfo.CMN_PER_PersonInfoID;
                personAdress.CMN_Address_RefID        = personInfo.Address_RefID;
                personAdress.IsPrimary    = true;
                personAdress.Tenant_RefID = securityTicket.TenantID;
                personAdress.Save(Connection, Transaction);

                ORM_CMN_Address adress = new ORM_CMN_Address();
                adress.CMN_AddressID   = personInfo.Address_RefID;
                adress.City_Name       = Parameter.City_Name;
                adress.Province_Name   = Parameter.Province_Name;
                adress.Street_Name     = Parameter.Street_Name;
                adress.Street_Number   = Parameter.Street_Number;
                adress.City_PostalCode = Parameter.City_PostalCode;
                adress.Tenant_RefID    = securityTicket.TenantID;
                adress.Save(Connection, Transaction);

                #endregion

                #region Contacts

                foreach (var parContact in Parameter.Contacts)
                {
                    ORM_CMN_PER_CommunicationContact contact = new ORM_CMN_PER_CommunicationContact();
                    contact.Content          = parContact.Content;
                    contact.Contact_Type     = parContact.CMN_PER_CommunicationContact_TypeID;
                    contact.Tenant_RefID     = securityTicket.TenantID;
                    contact.PersonInfo_RefID = personInfo.CMN_PER_PersonInfoID;
                    contact.Save(Connection, Transaction);
                }

                #endregion

                #region Driver To Employer

                ORM_CMN_BPT_BusinessParticipant_AssociatedBusinessParticipant bpt_asBP = new ORM_CMN_BPT_BusinessParticipant_AssociatedBusinessParticipant();
                bpt_asBP.CMN_BPT_BusinessParticipant_AssociatedBusinessParticipantID = Guid.NewGuid();
                bpt_asBP.BusinessParticipant_RefID          = bParticipant.CMN_BPT_BusinessParticipantID;
                bpt_asBP.AssociatedParticipant_FunctionName = "Driver";
                bpt_asBP.Tenant_RefID = securityTicket.TenantID;
                bpt_asBP.AssociatedBusinessParticipant_RefID = Parameter.CMN_BPT_BusinessParticipantID_Of_Employer;
                bpt_asBP.Save(Connection, Transaction);

                #endregion

                #endregion
            }
            else
            {
                ORM_CMN_BPT_BusinessParticipant bParticipant = new ORM_CMN_BPT_BusinessParticipant();
                bParticipant.Load(Connection, Transaction, Parameter.CMN_BPT_BusinessParticipantID);

                var personInfo = new ORM_CMN_PER_PersonInfo();
                personInfo.Load(Connection, Transaction, bParticipant.IfNaturalPerson_CMN_PER_PersonInfo_RefID);
                personInfo.Salutation_General = Parameter.Salutation_General;
                personInfo.FirstName          = Parameter.FirstName;
                personInfo.LastName           = Parameter.LastName;
                personInfo.PrimaryEmail       = Parameter.PrimaryMail;
                personInfo.Save(Connection, Transaction);

                ORM_CMN_Address adress = new ORM_CMN_Address();
                adress.Load(Connection, Transaction, personInfo.Address_RefID);
                adress.City_Name     = Parameter.City_Name;
                adress.Province_Name = Parameter.Province_Name;
                adress.Street_Name   = Parameter.Street_Name;
                adress.Street_Number = Parameter.Street_Number;
                adress.Save(Connection, Transaction);

                foreach (var parContact in Parameter.Contacts)
                {
                    var query = new ORM_CMN_PER_CommunicationContact.Query();
                    query.Contact_Type     = parContact.CMN_PER_CommunicationContact_TypeID;
                    query.IsDeleted        = false;
                    query.PersonInfo_RefID = personInfo.CMN_PER_PersonInfoID;

                    var contact = ORM_CMN_PER_CommunicationContact.Query.Search(Connection, Transaction, query).First();
                    contact.Content      = parContact.Content;
                    contact.Contact_Type = parContact.CMN_PER_CommunicationContact_TypeID;
                    contact.Save(Connection, Transaction);
                }

                var associationQuery = new ORM_CMN_BPT_BusinessParticipant_AssociatedBusinessParticipant.Query();
                associationQuery.BusinessParticipant_RefID = Parameter.CMN_BPT_BusinessParticipantID;
                associationQuery.IsDeleted = false;

                var bpt_asBP = ORM_CMN_BPT_BusinessParticipant_AssociatedBusinessParticipant.Query.Search(Connection, Transaction, associationQuery).First();
                bpt_asBP.AssociatedBusinessParticipant_RefID = Parameter.CMN_BPT_BusinessParticipantID_Of_Employer;
                bpt_asBP.Save(Connection, Transaction);
            }
            return(returnValue);

            #endregion UserCode
        }
        protected static FR_Guid Execute(DbConnection Connection, DbTransaction Transaction, P_DO_SAHD_1815 Parameter, CSV2Core.SessionSecurity.SessionSecurityTicket securityTicket = null)
        {
            #region UserCode
            var returnValue = new FR_Guid();
            //Put your code here

            #region EMAIL
            Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("de-DE");

            string        urlMM        = System.Configuration.ConfigurationManager.AppSettings["mmdocconnect.dashboard.url"];
            List <String> mailToL      = new List <String>();
            var           accountMails = cls_Get_All_Account_LoginEmails_Who_Receive_Notifications.Invoke(Connection, Transaction, securityTicket).Result.ToList();
            foreach (var mail in accountMails)
            {
                mailToL.Add(mail.LoginEmail);
            }

            string appName  = WebConfigurationManager.AppSettings["mmAppUrl"];
            var    prefix   = HttpContext.Current.Request.Url.AbsoluteUri.Contains("https") ? "https://" : "http://";
            var    imageUrl = HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.IndexOf("api")) + "Content/images/logo.png";

            var     email_template = File.ReadAllText(HttpContext.Current.Server.MapPath("~/EmailTemplates/NewTemporaryDoctorEmailTemplate.html"));
            var     subjectsJson   = File.ReadAllText(HttpContext.Current.Server.MapPath("~/EmailTemplates/EmailSubjects.json"));
            dynamic subjects       = Newtonsoft.Json.JsonConvert.DeserializeObject(subjectsJson);
            var     subjectMail    = subjects["NewTemporaryDoctorSubject"].ToString();

            email_template = EmailTemplater.SetTemplateData(email_template, new
            {
                name                    = Parameter.name,
                street                  = String.IsNullOrEmpty(Parameter.street) ? "-" : Parameter.street,
                house_number            = String.IsNullOrEmpty(Parameter.house_number) ? "-" : Parameter.house_number,
                zip                     = String.IsNullOrEmpty(Parameter.zip) ? "-" : Parameter.zip,
                city                    = String.IsNullOrEmpty(Parameter.city) ? "-" : Parameter.city,
                phone                   = String.IsNullOrEmpty(Parameter.phone) ? "-" : Parameter.phone,
                fax                     = String.IsNullOrEmpty(Parameter.fax) ? "-" : Parameter.fax,
                email                   = String.IsNullOrEmpty(Parameter.email) ? "-" : Parameter.email,
                comment                 = String.IsNullOrEmpty(Parameter.comment) ? "-" : Parameter.comment,
                doc_app_url             = prefix + HttpContext.Current.Request.Url.Authority + "/" + appName,
                medios_connect_logo_url = imageUrl
            }, "{{", "}}");

            try
            {
                // string mailFrom = cls_Get_Company_Settings.Invoke(Connection, Transaction, securityTicket).Result.Email;
                string mailFrom      = WebConfigurationManager.AppSettings["mailFrom"];
                var    mailsDistinct = mailToL.Distinct().ToList();
                foreach (var mailTo in mailsDistinct)
                {
                    EmailNotificationSenderUtil.SendEmail(mailFrom, mailTo, subjectMail, email_template);
                }
            }
            catch (Exception ex)
            {
                LogUtils.Logger.LogDocAppInfo(new LogUtils.LogEntry(System.Reflection.MethodInfo.GetCurrentMethod(), ex, null, "Temporary doctor creation: Email sending failed."), "EmailExceptions");
            }
            #endregion

            #region PERSON INFO
            ORM_CMN_PER_PersonInfo temporary_doctor_person_info = new ORM_CMN_PER_PersonInfo();
            temporary_doctor_person_info.LastName = Parameter.name;
            temporary_doctor_person_info.Modification_Timestamp = DateTime.Now;
            temporary_doctor_person_info.Tenant_RefID           = securityTicket.TenantID;

            temporary_doctor_person_info.Save(Connection, Transaction);

            ORM_CMN_PER_CommunicationContact_Type temporary_doctor_communication_contact_type_email = new ORM_CMN_PER_CommunicationContact_Type();
            temporary_doctor_communication_contact_type_email.Tenant_RefID = securityTicket.TenantID;
            temporary_doctor_communication_contact_type_email.Type         = "Email";

            temporary_doctor_communication_contact_type_email.Save(Connection, Transaction);

            ORM_CMN_PER_CommunicationContact temporary_doctor_communication_contact_email = new ORM_CMN_PER_CommunicationContact();
            temporary_doctor_communication_contact_email.Tenant_RefID           = securityTicket.TenantID;
            temporary_doctor_communication_contact_email.Modification_Timestamp = DateTime.Now;
            temporary_doctor_communication_contact_email.PersonInfo_RefID       = temporary_doctor_person_info.CMN_PER_PersonInfoID;
            temporary_doctor_communication_contact_email.Content      = Parameter.email;
            temporary_doctor_communication_contact_email.Contact_Type = temporary_doctor_communication_contact_type_email.CMN_PER_CommunicationContact_TypeID;

            temporary_doctor_communication_contact_email.Save(Connection, Transaction);

            ORM_CMN_PER_CommunicationContact_Type temporary_doctor_communication_contact_type_phone = new ORM_CMN_PER_CommunicationContact_Type();
            temporary_doctor_communication_contact_type_phone.Tenant_RefID = securityTicket.TenantID;
            temporary_doctor_communication_contact_type_phone.Type         = "Phone";

            temporary_doctor_communication_contact_type_phone.Save(Connection, Transaction);

            ORM_CMN_PER_CommunicationContact temporary_doctor_communication_contact_phone = new ORM_CMN_PER_CommunicationContact();
            temporary_doctor_communication_contact_phone.Tenant_RefID           = securityTicket.TenantID;
            temporary_doctor_communication_contact_phone.Modification_Timestamp = DateTime.Now;
            temporary_doctor_communication_contact_phone.PersonInfo_RefID       = temporary_doctor_person_info.CMN_PER_PersonInfoID;
            temporary_doctor_communication_contact_phone.Content      = Parameter.phone;
            temporary_doctor_communication_contact_phone.Contact_Type = temporary_doctor_communication_contact_type_phone.CMN_PER_CommunicationContact_TypeID;

            temporary_doctor_communication_contact_phone.Save(Connection, Transaction);
            #endregion

            #region BPT
            ORM_CMN_BPT_BusinessParticipant temporary_doctor_bpt = new ORM_CMN_BPT_BusinessParticipant();
            temporary_doctor_bpt.IfNaturalPerson_CMN_PER_PersonInfo_RefID = temporary_doctor_person_info.CMN_PER_PersonInfoID;
            temporary_doctor_bpt.IsNaturalPerson        = true;
            temporary_doctor_bpt.Modification_Timestamp = DateTime.Now;
            temporary_doctor_bpt.Tenant_RefID           = securityTicket.TenantID;

            temporary_doctor_bpt.Save(Connection, Transaction);
            #endregion

            #region DOCTOR
            ORM_HEC_Doctor temporary_doctor = new ORM_HEC_Doctor();
            // account ref. id = guid empty means that this is a temporary doctor with no account
            temporary_doctor.Account_RefID                     = Guid.Empty;
            temporary_doctor.BusinessParticipant_RefID         = temporary_doctor_bpt.CMN_BPT_BusinessParticipantID;
            temporary_doctor.DoctorIDNumber                    = "";
            temporary_doctor.IsDoctorForFollowupTreatmentsOnly = true;
            temporary_doctor.Tenant_RefID = securityTicket.TenantID;

            temporary_doctor.Save(Connection, Transaction);

            ORM_HEC_Doctor_UniversalProperty temporary_doctor_universal_property = new ORM_HEC_Doctor_UniversalProperty();
            temporary_doctor_universal_property.GlobalPropertyMatchingID = "mm.docconnect.temporary.aftercare.doctor.comment";
            temporary_doctor_universal_property.IsValue_String           = true;
            temporary_doctor_universal_property.Modification_Timestamp   = DateTime.Now;
            temporary_doctor_universal_property.PropertyName             = "Comment";
            temporary_doctor_universal_property.Tenant_RefID             = securityTicket.TenantID;

            temporary_doctor_universal_property.Save(Connection, Transaction);

            ORM_HEC_Doctor_UniversalPropertyValue temporary_doctor_universal_property_value = new ORM_HEC_Doctor_UniversalPropertyValue();
            temporary_doctor_universal_property_value.HEC_Doctor_RefID        = temporary_doctor.HEC_DoctorID;
            temporary_doctor_universal_property_value.Modification_Timestamp  = DateTime.Now;
            temporary_doctor_universal_property_value.Value_String            = Parameter.comment;
            temporary_doctor_universal_property_value.UniversalProperty_RefID = temporary_doctor_universal_property.HEC_Doctor_UniversalPropertyID;
            temporary_doctor_universal_property_value.Tenant_RefID            = securityTicket.TenantID;

            temporary_doctor_universal_property_value.Save(Connection, Transaction);
            #endregion

            #region IMPORT TO ELASTIC

            Practice_Doctors_Model temporary_doctor_elastic_model = new Practice_Doctors_Model();
            temporary_doctor_elastic_model.autocomplete_name = Parameter.name;
            temporary_doctor_elastic_model.name                   = Parameter.name;
            temporary_doctor_elastic_model.name_untouched         = Parameter.name;
            temporary_doctor_elastic_model.address                = Parameter.street + " " + Parameter.house_number;
            temporary_doctor_elastic_model.zip                    = Parameter.zip;
            temporary_doctor_elastic_model.city                   = Parameter.city;
            temporary_doctor_elastic_model.email                  = Parameter.email;
            temporary_doctor_elastic_model.phone                  = Parameter.phone;
            temporary_doctor_elastic_model.account_status         = "temp";
            temporary_doctor_elastic_model.id                     = temporary_doctor.HEC_DoctorID.ToString();
            temporary_doctor_elastic_model.practice_for_doctor_id = Parameter.practice_id.ToString();
            temporary_doctor_elastic_model.tenantid               = securityTicket.TenantID.ToString();
            temporary_doctor_elastic_model.type                   = "Doctor";

            Add_New_Practice.Import_Practice_Data_to_ElasticDB(new List <Practice_Doctors_Model>()
            {
                temporary_doctor_elastic_model
            }, securityTicket.TenantID.ToString());
            #endregion

            returnValue.Result = temporary_doctor.HEC_DoctorID;
            return(returnValue);

            #endregion UserCode
        }
        protected static FR_L3CCfTaIC_1526_Array Execute(DbConnection Connection, DbTransaction Transaction, P_L3CCfTaIC_1526 Parameter, CSV2Core.SessionSecurity.SessionSecurityTicket securityTicket = null)
        {
            #region UserCode
            var returnValue = new FR_L3CCfTaIC_1526_Array();
            //Put your code here
            List <L3CCfTaIC_1526> ProductList = new List <L3CCfTaIC_1526>();
            returnValue.Result = ProductList.ToArray();
            var _service = CatalogServiceFactory.GetSubscriptionService();

            //make data to send to Architecture so that they will know which catalog to update
            var subscriptionRequest = new SubscriptionRequest();
            subscriptionRequest.CatalogCode = Parameter.CatalogCodeITL;
            Customer customer = new Customer();

            // for only Tenant specific cases add Business Participant ID
            if (Parameter.SubscribedBy_BusinessParticipant_RefID != Guid.Empty)
            {
                customer.BusinessParticipantITL = Parameter.SubscribedBy_BusinessParticipant_RefID.ToString();
            }
            else
            {
                customer.BusinessParticipantITL = securityTicket.TenantID.ToString();
            }
            customer.TenantITL = securityTicket.TenantID.ToString();
            customer.Name      = Parameter.ClientName;
            // customer.SourceRealm = BOp.Infrastructure.PropertyRepository.Instance.RealmID.ToString();

            subscriptionRequest.Customer = customer;

            /*
             * @see if catalog with the same ITL for that bussinessParticipant exists
             * */
            var subscribedCatalogQuery = new ORM_CMN_PRO_SubscribedCatalog.Query();
            subscribedCatalogQuery.Tenant_RefID   = securityTicket.TenantID;
            subscribedCatalogQuery.CatalogCodeITL = Parameter.CatalogCodeITL;
            if (Parameter.SubscribedBy_BusinessParticipant_RefID != Guid.Empty)
            {
                subscribedCatalogQuery.SubscribedBy_BusinessParticipant_RefID = Parameter.SubscribedBy_BusinessParticipant_RefID;
            }
            subscribedCatalogQuery.IsDeleted = false;

            var subscribedCatalog = ORM_CMN_PRO_SubscribedCatalog.Query.Search(Connection, Transaction, subscribedCatalogQuery).FirstOrDefault();

            #region Get VAT

            var defaultCountryISOCode = cls_Get_DefaultCountryISOCode_for_TenantID.Invoke(Connection, Transaction, securityTicket).Result;

            var param = new P_L3TX_GTfCICaT_1359();
            param.CountryISOCode = "DE";



            var taxes = cls_Get_Taxes_for_CountryISOCode_and_TenantID.Invoke(Connection, Transaction, param, securityTicket).Result;
            //if there are no taxes for tenant
            Guid countryID = Guid.Empty;
            if (taxes.Length == 0)
            {
                var country = cls_Get_AllCountries_for_TenantID.Invoke(Connection, Transaction, securityTicket).Result.FirstOrDefault();

                if (country != null)
                {
                    countryID = country.CMN_CountryID;
                }
            }
            else
            {
                countryID = taxes.First().CMN_CountryID; // ti slucajni posmatracu ovog koda nemoj zameriti na ovakvom resenju.
            }

            #endregion

            #region save

            if (subscribedCatalog == null)
            {
                /*
                 * @save ORM_CMN_PRO_SubscribedCatalog
                 * */
                subscribedCatalog = new ORM_CMN_PRO_SubscribedCatalog();
                subscribedCatalog.CMN_PRO_SubscribedCatalogID = Guid.NewGuid();
                subscribedCatalog.CatalogCodeITL         = Parameter.CatalogCodeITL;
                subscribedCatalog.SubscribedCatalog_Name = Parameter.CatalogName;
                subscribedCatalog.SubscribedBy_BusinessParticipant_RefID = Parameter.SubscribedBy_BusinessParticipant_RefID;
                subscribedCatalog.Tenant_RefID = securityTicket.TenantID;
                subscribedCatalog.SubscribedCatalog_ValidFrom    = Parameter.ValidFrom_Date;
                subscribedCatalog.SubscribedCatalog_ValidThrough = Parameter.ValidTo_Date;
                subscribedCatalog.SubscribedCatalog_Description  = Parameter.CatalogDescription;
                subscribedCatalog.Creation_Timestamp             = DateTime.Now;
                subscribedCatalog.IsDeleted = false;
                subscribedCatalog.SubscribedCatalog_CurrentRevision = Parameter.CatalogVersion;
                subscribedCatalog.IsCatalogPublic = Parameter.IsCatalogPublic;

                // check if language with that ISO exists for Tenant (Lower, exmpl de)
                var languageQuery = new ORM_CMN_Language.Query();
                languageQuery.ISO_639_1    = Parameter.CatalogLanguage_ISO_639_1_codes.ToLower();
                languageQuery.Tenant_RefID = securityTicket.TenantID;
                languageQuery.IsDeleted    = false;

                var language = ORM_CMN_Language.Query.Search(Connection, Transaction, languageQuery).FirstOrDefault();

                // if language does not exist for that Tenant
                if (language == null)
                {
                    //check if language with that ISO exists for Tenant (Upper exmpl DE)
                    languageQuery              = new ORM_CMN_Language.Query();
                    languageQuery.ISO_639_1    = Parameter.CatalogLanguage_ISO_639_1_codes.ToUpper();
                    languageQuery.Tenant_RefID = securityTicket.TenantID;
                    languageQuery.IsDeleted    = false;

                    language = ORM_CMN_Language.Query.Search(Connection, Transaction, languageQuery).FirstOrDefault();

                    // if language does not exist for that Tenant
                    if (language == null)
                    {
                        ORM_CMN_Language newLanguage = new ORM_CMN_Language();
                        newLanguage.CMN_LanguageID     = Guid.NewGuid();
                        newLanguage.ISO_639_1          = Parameter.CatalogLanguage_ISO_639_1_codes;
                        newLanguage.Creation_Timestamp = DateTime.Now;
                        newLanguage.Tenant_RefID       = securityTicket.TenantID;
                        newLanguage.IsDeleted          = false;
                        newLanguage.Save(Connection, Transaction);

                        subscribedCatalog.SubscribedCatalog_Language_RefID = newLanguage.CMN_LanguageID;
                    }
                    else
                    {
                        subscribedCatalog.SubscribedCatalog_Language_RefID = language.CMN_LanguageID;
                    }
                }
                else
                {
                    subscribedCatalog.SubscribedCatalog_Language_RefID = language.CMN_LanguageID;
                }

                // check if currency with that ISO exists for Tenant

                var currencyQuery = new ORM_CMN_Currency.Query();
                currencyQuery.ISO4127      = Parameter.CatalogCurrency_ISO_4217;
                currencyQuery.Tenant_RefID = securityTicket.TenantID;
                currencyQuery.IsDeleted    = false;

                var currency = ORM_CMN_Currency.Query.Search(Connection, Transaction, currencyQuery).FirstOrDefault();

                if (currency == null)
                {
                    ORM_CMN_Currency newCurrency = new ORM_CMN_Currency();
                    newCurrency.CMN_CurrencyID     = Guid.NewGuid();
                    newCurrency.ISO4127            = Parameter.CatalogCurrency_ISO_4217;
                    newCurrency.Tenant_RefID       = securityTicket.TenantID;
                    newCurrency.Creation_Timestamp = DateTime.Now;
                    newCurrency.Save(Connection, Transaction);

                    subscribedCatalog.SubscribedCatalog_Currency_RefID = newCurrency.CMN_CurrencyID;
                }
                else
                {
                    subscribedCatalog.SubscribedCatalog_Currency_RefID = currency.CMN_CurrencyID;
                }

                #region product group

                /*
                 * @Search product group
                 * */
                ORM_CMN_PRO_ProductGroup productGroup = new ORM_CMN_PRO_ProductGroup();

                var productGroupQuery = new ORM_CMN_PRO_ProductGroup.Query();
                productGroupQuery.Tenant_RefID             = securityTicket.TenantID;
                productGroupQuery.GlobalPropertyMatchingID = EnumUtils.GetEnumDescription(EProductGroup.Treatment);

                //if (Parameter.IsCatalogPublic == false)
                //{
                //    productGroupQuery.GlobalPropertyMatchingID = EnumUtils.GetEnumDescription(EProductGroup.HauseList);
                //}
                //else
                //{
                //    productGroupQuery.GlobalPropertyMatchingID = EnumUtils.GetEnumDescription(EProductGroup.ABDA);
                //}
                // for only Tenant specific cases add Business Participant ID
                if (Parameter.SubscribedBy_BusinessParticipant_RefID != Guid.Empty)
                {
                    productGroupQuery.GlobalPropertyMatchingID += Parameter.SubscribedBy_BusinessParticipant_RefID;
                }
                productGroupQuery.IsDeleted = false;

                productGroup = ORM_CMN_PRO_ProductGroup.Query.Search(Connection, Transaction, productGroupQuery).FirstOrDefault();

                if (productGroup == null)
                {
                    /*
                     * @Create product group for products if product group for that BP and Tenent does not exist
                     * */
                    productGroup = new ORM_CMN_PRO_ProductGroup();
                    productGroup.Tenant_RefID                  = securityTicket.TenantID;
                    productGroup.Creation_Timestamp            = DateTime.Now;
                    productGroup.CMN_PRO_ProductGroupID        = Guid.NewGuid();
                    productGroup.ProductGroup_Name             = new Dict(ORM_CMN_PRO_ProductGroup.TableName);
                    productGroupQuery.GlobalPropertyMatchingID = EnumUtils.GetEnumDescription(EProductGroup.Treatment);
                    productGroup.ProductGroup_Name.AddEntry(language.CMN_LanguageID, "Treatment Group");

                    //if (Parameter.IsCatalogPublic == false)
                    //{
                    //    productGroup.GlobalPropertyMatchingID = EnumUtils.GetEnumDescription(EProductGroup.HauseList);
                    //    productGroup.ProductGroup_Name.AddEntry(language.CMN_LanguageID, "HauseList Group");
                    //}
                    //else
                    //{
                    //    productGroup.GlobalPropertyMatchingID = EnumUtils.GetEnumDescription(EProductGroup.ABDA);
                    //    productGroup.ProductGroup_Name.AddEntry(language.CMN_LanguageID, "ABDA Group");
                    //}

                    // for only Tenant specific cases add Business Participant ID
                    if (Parameter.SubscribedBy_BusinessParticipant_RefID != Guid.Empty)
                    {
                        productGroup.GlobalPropertyMatchingID += Parameter.SubscribedBy_BusinessParticipant_RefID;
                        productGroup.ProductGroup_Name.AddEntry(language.CMN_LanguageID, "Treatment Group");
                    }
                    productGroup.Save(Connection, Transaction);
                }
                #endregion

                #region create priceList for Catalog

                /*
                 * @create pricelist_Release
                 * */
                ORM_CMN_SLS_Pricelist_Release pricelist_Release = new ORM_CMN_SLS_Pricelist_Release();
                pricelist_Release.CMN_SLS_Pricelist_ReleaseID = Guid.NewGuid();
                pricelist_Release.Release_Version             = "v1";
                if (Parameter.IsCatalogPublic == false)
                {
                    pricelist_Release.PricelistRelease_ValidFrom = Parameter.ValidFrom_Date;
                    pricelist_Release.PricelistRelease_ValidTo   = Parameter.ValidTo_Date;
                }
                else
                {
                    pricelist_Release.IsPricelistAlwaysActive = true;
                }
                pricelist_Release.Tenant_RefID       = securityTicket.TenantID;
                pricelist_Release.Creation_Timestamp = DateTime.Now;
                pricelist_Release.Pricelist_RefID    = Guid.NewGuid();//priceList.CMN_SLS_PricelistID
                pricelist_Release.Save(Connection, Transaction);

                /*
                 * @create pricelist
                 * */
                ORM_CMN_SLS_Pricelist priceList = new ORM_CMN_SLS_Pricelist();
                priceList.CMN_SLS_PricelistID = pricelist_Release.Pricelist_RefID;

                var DBLanguages = cls_Get_All_Languages.Invoke(Connection, Transaction, securityTicket).Result.ToList();

                Dict nameDict = new Dict("cmn_sls_pricelist");
                if (Parameter.IsCatalogPublic == false)
                {
                    for (int i = 0; i < DBLanguages.Count; i++)
                    {
                        nameDict.AddEntry(DBLanguages[i].CMN_LanguageID, Parameter.CatalogName + "_" + Parameter.ValidFrom_Date.ToShortDateString() + "_" + Parameter.ValidTo_Date.ToShortDateString());
                    }
                }
                else
                {
                    for (int i = 0; i < DBLanguages.Count; i++)
                    {
                        nameDict.AddEntry(DBLanguages[i].CMN_LanguageID, "ABDA_PriceList");
                    }
                }
                priceList.Pricelist_Name     = nameDict;
                priceList.Tenant_RefID       = securityTicket.TenantID;
                priceList.Creation_Timestamp = DateTime.Now;
                priceList.Save(Connection, Transaction);

                #endregion

                if (Parameter.IsCatalogPublic == false)
                {
                    #region create and save products in product group and give product its price , product amout and measure unit

                    /*
                     * @create and save products in product group
                     * */

                    bool isAlreadyInABDA = false;
                    foreach (var item in Parameter.Products)
                    {
                        ORM_CMN_PRO_Product product = new ORM_CMN_PRO_Product();

                        // only for Tenant specific cases add Business Participant ID (!Lucentis)
                        if (Parameter.SubscribedBy_BusinessParticipant_RefID == Guid.Empty)
                        {
                            var productQuery = new ORM_CMN_PRO_Product.Query();
                            productQuery.ProductITL   = item.ProductITL;
                            productQuery.Tenant_RefID = securityTicket.TenantID;
                            productQuery.IsDeleted    = false;
                            productQuery.IsProductAvailableForOrdering = true;

                            product = ORM_CMN_PRO_Product.Query.Search(Connection, Transaction, productQuery).FirstOrDefault();

                            //if it is not in ABDA
                            if (product == null)
                            {
                                product = new ORM_CMN_PRO_Product();
                                product.CMN_PRO_ProductID             = Guid.NewGuid();
                                product.Creation_Timestamp            = DateTime.Now;
                                product.Tenant_RefID                  = securityTicket.TenantID;
                                product.ProductITL                    = item.ProductITL;
                                product.Product_Name                  = item.Product_Name;
                                product.Product_Description           = item.Product_Description;
                                product.Product_Number                = item.Product_Number;
                                product.IsProduct_Article             = item.IsProduct_Article;
                                product.IsProductAvailableForOrdering = true;
                                product.PackageInfo_RefID             = Guid.NewGuid();//packageInfo.CMN_PRO_PAC_PackageInfoID

                                isAlreadyInABDA = false;
                            }
                            else
                            {
                                isAlreadyInABDA = true;
                            }
                        }
                        else
                        {
                            product.CMN_PRO_ProductID             = Guid.NewGuid();
                            product.Creation_Timestamp            = DateTime.Now;
                            product.Tenant_RefID                  = securityTicket.TenantID;
                            product.ProductITL                    = item.ProductITL;
                            product.Product_Name                  = item.Product_Name;
                            product.Product_Description           = item.Product_Description;
                            product.Product_Number                = item.Product_Number;
                            product.IsProduct_Article             = item.IsProduct_Article;
                            product.IsProductAvailableForOrdering = true;
                            product.PackageInfo_RefID             = Guid.NewGuid();//packageInfo.CMN_PRO_PAC_PackageInfoID

                            isAlreadyInABDA = false;
                        }

                        product.IfImportedFromExternalCatalog_CatalogSubscription_RefID = subscribedCatalog.CMN_PRO_SubscribedCatalogID;
                        product.Save(Connection, Transaction);

                        L3CCfTaIC_1526 pro = new L3CCfTaIC_1526();
                        pro.ProductID = product.CMN_PRO_ProductID;
                        if (product.IsProduct_Article)
                        {
                            pro.Dosage = item.Dosage;
                        }
                        pro.isEdit = false;
                        ProductList.Add(pro);

                        ORM_CMN_PRO_Product_2_ProductGroup product_2_productGroup = new ORM_CMN_PRO_Product_2_ProductGroup();
                        product_2_productGroup.CMN_PRO_Product_RefID      = product.CMN_PRO_ProductID;
                        product_2_productGroup.CMN_PRO_ProductGroup_RefID = productGroup.CMN_PRO_ProductGroupID;
                        product_2_productGroup.Tenant_RefID       = securityTicket.TenantID;
                        product_2_productGroup.Creation_Timestamp = DateTime.Now;
                        product_2_productGroup.Save(Connection, Transaction);

                        if (isAlreadyInABDA == false)
                        {
                            ORM_CMN_SLS_Price price = new ORM_CMN_SLS_Price();
                            price.CMN_SLS_PriceID        = Guid.NewGuid();
                            price.Tenant_RefID           = securityTicket.TenantID;
                            price.Creation_Timestamp     = DateTime.Now;
                            price.PricelistRelease_RefID = pricelist_Release.CMN_SLS_Pricelist_ReleaseID;
                            price.CMN_PRO_Product_RefID  = product.CMN_PRO_ProductID;
                            price.PriceAmount            = item.Price;
                            price.CMN_Currency_RefID     = subscribedCatalog.SubscribedCatalog_Currency_RefID;
                            price.Save(Connection, Transaction);

                            //add amount and Measure
                            ORM_CMN_PRO_PAC_PackageInfo packageInfo = new ORM_CMN_PRO_PAC_PackageInfo();
                            packageInfo.CMN_PRO_PAC_PackageInfoID = product.PackageInfo_RefID;
                            packageInfo.Tenant_RefID          = securityTicket.TenantID;
                            packageInfo.Creation_Timestamp    = DateTime.Now;
                            packageInfo.PackageContent_Amount = item.Amount;

                            //check if MeasureUnit exists for this Tenant
                            var unitsQuery = new ORM_CMN_Unit.Query();
                            unitsQuery.Tenant_RefID = securityTicket.TenantID;
                            unitsQuery.ISOCode      = item.MeasuredInUnit_ISO_um_ums;
                            unitsQuery.IsDeleted    = false;

                            var measuredInUnit = ORM_CMN_Unit.Query.Search(Connection, Transaction, unitsQuery).FirstOrDefault();
                            if (measuredInUnit == null)
                            {
                                ORM_CMN_Unit newMeasuredInUnit = new ORM_CMN_Unit();
                                newMeasuredInUnit.Tenant_RefID       = securityTicket.TenantID;
                                newMeasuredInUnit.Creation_Timestamp = DateTime.Now;
                                newMeasuredInUnit.ISOCode            = item.MeasuredInUnit_ISO_um_ums;
                                newMeasuredInUnit.CMN_UnitID         = Guid.NewGuid();
                                newMeasuredInUnit.Save(Connection, Transaction);

                                packageInfo.PackageContent_MeasuredInUnit_RefID = newMeasuredInUnit.CMN_UnitID;
                            }
                            else
                            {
                                packageInfo.PackageContent_MeasuredInUnit_RefID = measuredInUnit.CMN_UnitID;
                            }

                            packageInfo.Save(Connection, Transaction);

                            if (countryID != Guid.Empty)// if there is a country for this Tenant
                            {
                                #region Create Taxes

                                double productVAT = 0;
                                Double.TryParse(item.VAT, out productVAT);

                                var tax = taxes.Where(i => i.TaxRate == productVAT).SingleOrDefault();

                                if (tax == default(L3TX_GTfCICaT_1359))
                                {
                                    #region CreateTax

                                    var saveTaxParam = new P_L3TX_STX_1119();
                                    saveTaxParam.ACC_TAX_TaxeID = Guid.Empty;
                                    saveTaxParam.TaxName        = new Dict(ORM_ACC_TAX_Tax.TableName);
                                    saveTaxParam.TaxName.AddEntry(language.CMN_LanguageID, productVAT.ToString());
                                    saveTaxParam.TaxRate = productVAT;
                                    if (taxes.Length != 0)
                                    {
                                        saveTaxParam.EconomicRegion_RefID = taxes.First().CMN_EconomicRegionID;
                                        saveTaxParam.Country_RefID        = taxes.First().CMN_CountryID;
                                    }
                                    else
                                    {
                                        saveTaxParam.EconomicRegion_RefID = Guid.Empty;
                                        saveTaxParam.Country_RefID        = countryID;
                                    }
                                    var saveTaxResult = cls_Save_Tax.Invoke(Connection, Transaction, saveTaxParam, securityTicket).Result;

                                    #endregion

                                    #region Update Available taxes

                                    param = new P_L3TX_GTfCICaT_1359();
                                    param.CountryISOCode = "DE";

                                    taxes = cls_Get_Taxes_for_CountryISOCode_and_TenantID.Invoke(Connection, Transaction, param, securityTicket).Result;

                                    tax = taxes.Where(i => i.TaxRate == productVAT).SingleOrDefault();

                                    #endregion
                                }

                                var salesTax = new ORM_CMN_PRO_Product_SalesTaxAssignmnet();
                                salesTax.CMN_PRO_Product_SalesTaxAssignmnetID = Guid.NewGuid();
                                salesTax.Product_RefID            = product.CMN_PRO_ProductID;
                                salesTax.ApplicableSalesTax_RefID = tax.ACC_TAX_TaxeID;
                                salesTax.Creation_Timestamp       = DateTime.Now;
                                salesTax.Tenant_RefID             = securityTicket.TenantID;
                                salesTax.Save(Connection, Transaction);

                                #endregion
                            }
                        }
                    }
                    #endregion
                }

                /*
                 * @See if Supplier already exists in database
                 * */
                ORM_CMN_BPT_Supplier supplier = new ORM_CMN_BPT_Supplier();

                var supplierQuery = new ORM_CMN_BPT_BusinessParticipant.Query();
                supplierQuery.BusinessParticipantITL = Parameter.SupplierData.SupplierITL;
                supplierQuery.Tenant_RefID           = securityTicket.TenantID;
                supplierQuery.IsDeleted = false;

                var supplier_bussinessParticipant = ORM_CMN_BPT_BusinessParticipant.Query.Search(Connection, Transaction, supplierQuery).FirstOrDefault();

                #region if supplier does not exist

                if (supplier_bussinessParticipant == null)
                {
                    /*
                     * @Make Supplier Data
                     * */

                    var tenantQuery = new ORM_CMN_Tenant.Query()
                    {
                        TenantITL    = Parameter.SupplierData.TenantITL,
                        Tenant_RefID = securityTicket.TenantID
                    };

                    var supplierTenant = ORM_CMN_Tenant.Query.Search(Connection, Transaction, tenantQuery).SingleOrDefault();

                    if (supplierTenant == default(ORM_CMN_Tenant))
                    {
                        supplierTenant = new ORM_CMN_Tenant();
                        supplierTenant.CMN_TenantID       = Guid.NewGuid();
                        supplierTenant.TenantITL          = Parameter.SupplierData.TenantITL;
                        supplierTenant.Tenant_RefID       = securityTicket.TenantID;
                        supplierTenant.Creation_Timestamp = DateTime.Now;
                        supplierTenant.Save(Connection, Transaction);
                    }

                    supplier.CMN_BPT_SupplierID            = Guid.NewGuid();
                    supplier.Ext_BusinessParticipant_RefID = Guid.NewGuid();//supplierBussinessParticipant.CMN_BPT_BusinessParticipantID
                    supplier.Creation_Timestamp            = DateTime.Now;
                    supplier.IsDeleted    = false;
                    supplier.Tenant_RefID = securityTicket.TenantID;
                    supplier.Save(Connection, Transaction);

                    ORM_CMN_BPT_BusinessParticipant supplierBussinessParticipant = new ORM_CMN_BPT_BusinessParticipant();
                    supplierBussinessParticipant.CMN_BPT_BusinessParticipantID = supplier.Ext_BusinessParticipant_RefID;
                    supplierBussinessParticipant.DisplayName            = Parameter.SupplierData.Supplier_Name;
                    supplierBussinessParticipant.BusinessParticipantITL = Parameter.SupplierData.SupplierITL;
                    supplierBussinessParticipant.Creation_Timestamp     = DateTime.Now;
                    supplierBussinessParticipant.Tenant_RefID           = securityTicket.TenantID;
                    supplierBussinessParticipant.IsCompany             = true;
                    supplierBussinessParticipant.IsTenant              = true;
                    supplierBussinessParticipant.IfTenant_Tenant_RefID = supplierTenant.CMN_TenantID;
                    supplierBussinessParticipant.IfCompany_CMN_COM_CompanyInfo_RefID = Guid.NewGuid();//companyInfo.CMN_COM_CompanyInfoID
                    supplierBussinessParticipant.Save(Connection, Transaction);

                    ORM_CMN_COM_CompanyInfo companyInfo = new ORM_CMN_COM_CompanyInfo();
                    companyInfo.CMN_COM_CompanyInfoID = supplierBussinessParticipant.IfCompany_CMN_COM_CompanyInfo_RefID;
                    companyInfo.Creation_Timestamp    = DateTime.Now;
                    companyInfo.Tenant_RefID          = securityTicket.TenantID;
                    companyInfo.Contact_UCD_RefID     = Guid.NewGuid();//universalContactDetail.CMN_UniversalContactDetailID
                    companyInfo.Save(Connection, Transaction);

                    ORM_CMN_UniversalContactDetail universalContactDetail = new ORM_CMN_UniversalContactDetail();
                    universalContactDetail.CMN_UniversalContactDetailID = companyInfo.Contact_UCD_RefID;
                    universalContactDetail.IsCompany             = true;
                    universalContactDetail.Country_639_1_ISOCode = Parameter.SupplierData.CountryISO;
                    universalContactDetail.Street_Name           = Parameter.SupplierData.Supplier_Name;
                    universalContactDetail.Street_Number         = Parameter.SupplierData.Street_Number;
                    universalContactDetail.ZIP                = Parameter.SupplierData.ZIP;
                    universalContactDetail.Town               = Parameter.SupplierData.Town;
                    universalContactDetail.Region_Code        = Parameter.SupplierData.Region_Code;
                    universalContactDetail.Tenant_RefID       = securityTicket.TenantID;
                    universalContactDetail.Creation_Timestamp = DateTime.Now;
                    universalContactDetail.Save(Connection, Transaction);
                }
                #endregion
                #region if supplier exists , check if its data is changed
                else
                {
                    var tenantQuery = new ORM_CMN_Tenant.Query()
                    {
                        TenantITL    = Parameter.SupplierData.TenantITL,
                        Tenant_RefID = securityTicket.TenantID
                    };

                    var supplierTenant = ORM_CMN_Tenant.Query.Search(Connection, Transaction, tenantQuery).SingleOrDefault();

                    if (supplierTenant == default(ORM_CMN_Tenant))
                    {
                        supplierTenant = new ORM_CMN_Tenant();
                        supplierTenant.CMN_TenantID       = Guid.NewGuid();
                        supplierTenant.TenantITL          = Parameter.SupplierData.TenantITL;
                        supplierTenant.Tenant_RefID       = securityTicket.TenantID;
                        supplierTenant.Creation_Timestamp = DateTime.Now;
                        supplierTenant.Save(Connection, Transaction);

                        supplier_bussinessParticipant.IsTenant = true;
                        supplier_bussinessParticipant.IfTenant_Tenant_RefID = supplierTenant.CMN_TenantID;
                    }

                    supplier_bussinessParticipant.DisplayName = Parameter.SupplierData.Supplier_Name;
                    supplier_bussinessParticipant.Save(Connection, Transaction);

                    var query = new ORM_CMN_BPT_Supplier.Query();
                    query.Ext_BusinessParticipant_RefID = supplier_bussinessParticipant.CMN_BPT_BusinessParticipantID;
                    query.Tenant_RefID = securityTicket.TenantID;
                    query.IsDeleted    = false;

                    supplier = ORM_CMN_BPT_Supplier.Query.Search(Connection, Transaction, query).First();

                    //edit universal contact details

                    var companyInfoQuery = new ORM_CMN_COM_CompanyInfo.Query();
                    companyInfoQuery.CMN_COM_CompanyInfoID = supplier_bussinessParticipant.IfCompany_CMN_COM_CompanyInfo_RefID;
                    companyInfoQuery.Tenant_RefID          = securityTicket.TenantID;
                    companyInfoQuery.IsDeleted             = false;

                    var companyInfo = ORM_CMN_COM_CompanyInfo.Query.Search(Connection, Transaction, companyInfoQuery).First();

                    var universalContactDetailQuery = new ORM_CMN_UniversalContactDetail.Query();
                    universalContactDetailQuery.CMN_UniversalContactDetailID = companyInfo.Contact_UCD_RefID;
                    universalContactDetailQuery.Tenant_RefID = securityTicket.TenantID;
                    universalContactDetailQuery.IsDeleted    = false;

                    var universalContactDetail = ORM_CMN_UniversalContactDetail.Query.Search(Connection, Transaction, universalContactDetailQuery).First();

                    universalContactDetail.Country_639_1_ISOCode = Parameter.SupplierData.CountryISO;
                    universalContactDetail.Street_Name           = Parameter.SupplierData.Supplier_Name;
                    universalContactDetail.Street_Number         = Parameter.SupplierData.Street_Number;
                    universalContactDetail.ZIP         = Parameter.SupplierData.ZIP;
                    universalContactDetail.Town        = Parameter.SupplierData.Town;
                    universalContactDetail.Region_Code = Parameter.SupplierData.Region_Code;
                    universalContactDetail.Save(Connection, Transaction);
                }
                #endregion

                subscribedCatalog.SubscribedCatalog_PricelistRelease_RefID = pricelist_Release.CMN_SLS_Pricelist_ReleaseID;
                subscribedCatalog.PublishingSupplier_RefID = supplier.CMN_BPT_SupplierID;
                subscribedCatalog.Save(Connection, Transaction);

                /*
                 * @send Kika information which catalog has been subscribed to who
                 * */
                var result = _service.SubscribeToCatalog(subscriptionRequest);

                if (result.ResponseStatus != ResponseStatus.OK)
                {
                    throw new Exception("Catalog subscription failed!");
                }
            }
            #endregion

            returnValue.Result = ProductList.ToArray();
            return(returnValue);

            #endregion UserCode
        }
Beispiel #8
0
        protected static FR_Guid Execute(DbConnection Connection, DbTransaction Transaction, P_L5OU_SOUGD_1221 Parameter, CSV2Core.SessionSecurity.SessionSecurityTicket securityTicket = null)
        {
            #region UserCode
            var returnValue = new FR_Guid();

            #region Save
            if (Parameter.OrgUnitID == null || Parameter.OrgUnitID == Guid.Empty)
            {
                //*******************MedicalPracticeType************************

                var medicalPractice = new ORM_HEC_MedicalPractis();
                medicalPractice.HEC_MedicalPractiseID = Guid.NewGuid();
                medicalPractice.Tenant_RefID          = securityTicket.TenantID;
                medicalPractice.IsDeleted             = false;
                medicalPractice.Save(Connection, Transaction);

                foreach (var item in Parameter.MedicalPracticeType)
                {
                    var medicalPractice2PracticeType = new ORM_HEC_MedicalPractice_2_PracticeType();
                    medicalPractice2PracticeType.AssignmentID = Guid.NewGuid();
                    medicalPractice2PracticeType.HEC_MedicalPractice_Type_RefID = item.HEC_MedicalPractice_TypeID;
                    medicalPractice2PracticeType.HEC_MedicalPractice_RefID      = medicalPractice.HEC_MedicalPractiseID;
                    medicalPractice2PracticeType.Tenant_RefID = securityTicket.TenantID;
                    medicalPractice2PracticeType.IsDeleted    = false;
                    medicalPractice2PracticeType.Save(Connection, Transaction);
                }

                //******************* Office************************
                var Office = new ORM_CMN_STR_Office();
                Office.CMN_STR_OfficeID = Guid.NewGuid();
                Office.Office_Name      = Parameter.OrgUnitName_DictID;
                Office.Tenant_RefID     = securityTicket.TenantID;
                if (Parameter.ParentID != null && Parameter.ParentID != Guid.Empty)
                {
                    Office.Parent_RefID = Parameter.ParentID;
                }
                Office.Creation_Timestamp = DateTime.Now;

                var officeQuery = new ORM_CMN_STR_Office.Query();
                officeQuery.Tenant_RefID = securityTicket.TenantID;
                int officeCount = ORM_CMN_STR_Office.Query.Search(Connection, Transaction, officeQuery).Count;

                Office.Office_InternalNumber       = String.Format("{0:00000}", officeCount + 1);
                Office.Default_PhoneNumber         = Parameter.Telephone;
                Office.DisplayImage_Document_RefID = Parameter.DisplayImage_Document_RefID;
                Office.Default_Email      = Parameter.Email;
                Office.Default_Website    = Parameter.Website;
                Office.Office_Description = new Dict("cmn_str_offices");
                Office.Comment            = Parameter.Notes;
                Office.IsMedicalPractice  = true;
                Office.IfMedicalPractise_HEC_MedicalPractice_RefID = medicalPractice.HEC_MedicalPractiseID;
                Office.Save(Connection, Transaction);

                //*******************Save Address************************

                foreach (var address in Parameter.Adresses)
                {
                    var Office_2_Address = new ORM_CMN_STR_Office_Address();
                    Office_2_Address.CMN_STR_Office_AddressID = Guid.NewGuid();
                    Office_2_Address.IsBillingAddress         = address.IsBillingAddress;
                    Office_2_Address.IsShippingAddress        = address.IsShippingAddress;
                    Office_2_Address.IsSpecialAddress         = address.IsSpecialAddress;
                    Office_2_Address.CMN_Address_RefID        = address.AddressID;
                    Office_2_Address.Office_RefID             = Office.CMN_STR_OfficeID;
                    Office_2_Address.Tenant_RefID             = securityTicket.TenantID;
                    Office_2_Address.Creation_Timestamp       = DateTime.Now;
                    Office_2_Address.IsDefault = address.IsDefault;
                    Office_2_Address.Save(Connection, Transaction);

                    var Address = new ORM_CMN_Address();
                    Address.CMN_AddressID      = Office_2_Address.CMN_Address_RefID;
                    Address.Tenant_RefID       = securityTicket.TenantID;
                    Address.Creation_Timestamp = DateTime.Now;
                    Address.City_Name          = address.City;
                    Address.Street_Name        = address.Street_Name;
                    Address.Street_Number      = address.Street_Number;
                    Address.Country_ISOCode    = address.CountryISO;
                    Address.Country_Name       = address.CountryName;
                    Address.City_PostalCode    = address.ZIP;
                    if (address.IsDefault)
                    {
                        Address.Lattitude = address.Lattitude;
                        Address.Longitude = address.Longitude;
                    }
                    Address.Save(Connection, Transaction);
                }

                //*******************Save Languages************************

                foreach (var item in Parameter.SpokenLanguage)
                {
                    var officeSpokenLanguages = new ORM_CMN_STR_Office_SpokenLanguage();
                    officeSpokenLanguages.CMN_STR_Office_SpokenLanguageID = Guid.NewGuid();
                    officeSpokenLanguages.Office_RefID   = Office.CMN_STR_OfficeID;
                    officeSpokenLanguages.Language_RefID = item.CMN_LanguageID;
                    officeSpokenLanguages.IsDeleted      = item.IsDeleted;
                    officeSpokenLanguages.Tenant_RefID   = securityTicket.TenantID;
                    officeSpokenLanguages.Save(Connection, Transaction);
                }

                //*******************Save Contact Person************************

                var responsiblePerson = new ORM_CMN_STR_Office_ResponsiblePerson();
                responsiblePerson.CMN_STR_Office_ResponsiblePersonID = Guid.NewGuid();
                responsiblePerson.Office_RefID = Office.CMN_STR_OfficeID;
                responsiblePerson.CMN_BPT_EMP_Employee_RefID = Guid.NewGuid();
                responsiblePerson.Tenant_RefID       = securityTicket.TenantID;
                responsiblePerson.Creation_Timestamp = DateTime.Now;
                responsiblePerson.Save(Connection, Transaction);

                var employee = new ORM_CMN_BPT_EMP_Employee();
                employee.CMN_BPT_EMP_EmployeeID    = responsiblePerson.CMN_BPT_EMP_Employee_RefID;
                employee.BusinessParticipant_RefID = Guid.NewGuid();
                employee.Creation_Timestamp        = DateTime.Now;
                employee.Tenant_RefID = securityTicket.TenantID;
                employee.Save(Connection, Transaction);

                var businessParticpant = new ORM_CMN_BPT_BusinessParticipant();
                businessParticpant.CMN_BPT_BusinessParticipantID = employee.BusinessParticipant_RefID;
                businessParticpant.IsNaturalPerson    = true;
                businessParticpant.DisplayName        = Parameter.ContactPerson.Title + " " + Parameter.ContactPerson.FirstName + " " + Parameter.ContactPerson.LastName;
                businessParticpant.Tenant_RefID       = securityTicket.TenantID;
                businessParticpant.Creation_Timestamp = DateTime.Now;
                businessParticpant.IfNaturalPerson_CMN_PER_PersonInfo_RefID = Guid.NewGuid();
                businessParticpant.Save(Connection, Transaction);

                var personInfo = new ORM_CMN_PER_PersonInfo();
                personInfo.CMN_PER_PersonInfoID = businessParticpant.IfNaturalPerson_CMN_PER_PersonInfo_RefID;
                personInfo.Title              = Parameter.ContactPerson.Title;
                personInfo.FirstName          = Parameter.ContactPerson.FirstName;
                personInfo.LastName           = Parameter.ContactPerson.LastName;
                personInfo.Tenant_RefID       = securityTicket.TenantID;
                personInfo.Creation_Timestamp = DateTime.Now;
                personInfo.Save(Connection, Transaction);

                //*******************AppointmentType************************

                foreach (var item in Parameter.AppoitmentType)
                {
                    ORM_PPS_TSK_Task_Template_OrganizationalUnitAvailability orgUnitToAppointmentType = new ORM_PPS_TSK_Task_Template_OrganizationalUnitAvailability();
                    orgUnitToAppointmentType.PPS_TSK_Task_Template_OrganizationalUnitAvailabilityID = Guid.NewGuid();
                    orgUnitToAppointmentType.CMN_STR_Office_RefID        = Office.CMN_STR_OfficeID;
                    orgUnitToAppointmentType.PPS_TSK_Task_Template_RefID = item.PPS_TSK_Task_Template_RefID;
                    orgUnitToAppointmentType.Creation_Timestamp          = DateTime.Now;
                    orgUnitToAppointmentType.Tenant_RefID = securityTicket.TenantID;
                    orgUnitToAppointmentType.Save(Connection, Transaction);
                }

                returnValue.Result = Office.CMN_STR_OfficeID;
            }
            #endregion
            #region Delete
            else if (Parameter.IsDeleted)
            {
                List <Guid> guidList = new List <Guid>();
                guidList.Add(Parameter.OrgUnitID);
                cls_Delete_OrgsUnitsGeneralData.Invoke(Connection, Transaction, new P_L5OU_DOUGD_1221 {
                    OrgUnitID = guidList.ToArray()
                }, securityTicket);
            }
            #endregion
            #region Edit
            else
            {
                var officeQuery = new ORM_CMN_STR_Office.Query()
                {
                    Tenant_RefID     = securityTicket.TenantID,
                    IsDeleted        = false,
                    CMN_STR_OfficeID = Parameter.OrgUnitID
                };

                var office = ORM_CMN_STR_Office.Query.Search(Connection, Transaction, officeQuery).Single();
                office.Office_Name                 = Parameter.OrgUnitName_DictID;
                office.Default_PhoneNumber         = Parameter.Telephone;
                office.DisplayImage_Document_RefID = Parameter.DisplayImage_Document_RefID;
                office.Default_Email               = Parameter.Email;
                office.Comment         = Parameter.Notes;
                office.Default_Website = Parameter.Website;
                if (Parameter.ParentID != null && Parameter.ParentID != Guid.Empty)
                {
                    office.Parent_RefID = Parameter.ParentID;
                }
                office.IsMedicalPractice = true;
                office.Save(Connection, Transaction);

                //*******************Medical practice type************************

                var medicalPractice2TypeQuery = new ORM_HEC_MedicalPractice_2_PracticeType.Query()
                {
                    Tenant_RefID = securityTicket.TenantID,
                    IsDeleted    = false,
                    HEC_MedicalPractice_RefID = office.IfMedicalPractise_HEC_MedicalPractice_RefID
                };
                var medicalPractice2Type = ORM_HEC_MedicalPractice_2_PracticeType.Query.Search(Connection, Transaction, medicalPractice2TypeQuery).ToList();

                foreach (var item in Parameter.MedicalPracticeType)
                {
                    if (item.IsDeleted)
                    {
                        foreach (var medicalPractice2TypeItem in medicalPractice2Type)
                        {
                            if (medicalPractice2TypeItem.HEC_MedicalPractice_Type_RefID == item.HEC_MedicalPractice_TypeID)
                            {
                                medicalPractice2TypeItem.Tenant_RefID = securityTicket.TenantID;
                                if (office.IfMedicalPractise_HEC_MedicalPractice_RefID != Guid.Empty)
                                {
                                    medicalPractice2TypeItem.HEC_MedicalPractice_RefID = office.IfMedicalPractise_HEC_MedicalPractice_RefID;
                                }
                                else
                                {
                                    var medicalPractice = new ORM_HEC_MedicalPractis();
                                    medicalPractice.HEC_MedicalPractiseID = Guid.NewGuid();
                                    medicalPractice.Tenant_RefID          = securityTicket.TenantID;
                                    medicalPractice.IsDeleted             = false;
                                    medicalPractice.Save(Connection, Transaction);
                                    office.IfMedicalPractise_HEC_MedicalPractice_RefID = medicalPractice.HEC_MedicalPractiseID;
                                    office.Save(Connection, Transaction);
                                    medicalPractice2TypeItem.HEC_MedicalPractice_RefID = medicalPractice.HEC_MedicalPractiseID;
                                }
                                medicalPractice2TypeItem.IsDeleted = true;
                                medicalPractice2TypeItem.Save(Connection, Transaction);
                                break;
                            }
                        }
                    }
                    else
                    {
                        ORM_HEC_MedicalPractice_2_PracticeType medPracticeType = null;
                        foreach (var medicalPractice2TypeItem in medicalPractice2Type)
                        {
                            if (medicalPractice2TypeItem.HEC_MedicalPractice_Type_RefID == item.HEC_MedicalPractice_TypeID)
                            {
                                medPracticeType = medicalPractice2TypeItem;
                                if (medPracticeType.HEC_MedicalPractice_RefID == Guid.Empty)
                                {
                                    var medicalPractice = new ORM_HEC_MedicalPractis();
                                    medicalPractice.HEC_MedicalPractiseID = Guid.NewGuid();
                                    medicalPractice.Tenant_RefID          = securityTicket.TenantID;
                                    medicalPractice.IsDeleted             = false;
                                    medicalPractice.Save(Connection, Transaction);
                                    office.IfMedicalPractise_HEC_MedicalPractice_RefID = medicalPractice.HEC_MedicalPractiseID;
                                    office.Save(Connection, Transaction);
                                    medPracticeType.HEC_MedicalPractice_RefID = medicalPractice.HEC_MedicalPractiseID;
                                    medPracticeType.Save(Connection, Transaction);
                                }
                                break;
                            }
                        }

                        if (medPracticeType == null)
                        {
                            medPracticeType = new ORM_HEC_MedicalPractice_2_PracticeType();
                            medPracticeType.Tenant_RefID = securityTicket.TenantID;
                            medPracticeType.IsDeleted    = false;
                            medPracticeType.HEC_MedicalPractice_Type_RefID = item.HEC_MedicalPractice_TypeID;
                            if (office.IfMedicalPractise_HEC_MedicalPractice_RefID != Guid.Empty)
                            {
                                medPracticeType.HEC_MedicalPractice_RefID = office.IfMedicalPractise_HEC_MedicalPractice_RefID;
                            }
                            else
                            {
                                var medicalPractice = new ORM_HEC_MedicalPractis();
                                medicalPractice.HEC_MedicalPractiseID = Guid.NewGuid();
                                medicalPractice.Tenant_RefID          = securityTicket.TenantID;
                                medicalPractice.IsDeleted             = false;
                                medicalPractice.Save(Connection, Transaction);
                                office.IfMedicalPractise_HEC_MedicalPractice_RefID = medicalPractice.HEC_MedicalPractiseID;
                                office.Save(Connection, Transaction);
                                medPracticeType.HEC_MedicalPractice_RefID = medicalPractice.HEC_MedicalPractiseID;
                            }
                            medPracticeType.Save(Connection, Transaction);
                        }
                        else
                        {
                            if (medPracticeType.IsDeleted)
                            {
                                medPracticeType.Tenant_RefID = securityTicket.TenantID;
                                medPracticeType.IsDeleted    = true;
                                if (office.IfMedicalPractise_HEC_MedicalPractice_RefID != Guid.Empty)
                                {
                                    medPracticeType.HEC_MedicalPractice_RefID = office.IfMedicalPractise_HEC_MedicalPractice_RefID;
                                }
                                else
                                {
                                    var medicalPractice = new ORM_HEC_MedicalPractis();
                                    medicalPractice.HEC_MedicalPractiseID = Guid.NewGuid();
                                    medicalPractice.Tenant_RefID          = securityTicket.TenantID;
                                    medicalPractice.IsDeleted             = false;
                                    medicalPractice.Save(Connection, Transaction);
                                    office.IfMedicalPractise_HEC_MedicalPractice_RefID = medicalPractice.HEC_MedicalPractiseID;
                                    office.Save(Connection, Transaction);
                                    medPracticeType.HEC_MedicalPractice_RefID = medicalPractice.HEC_MedicalPractiseID;
                                }
                                medPracticeType.Save(Connection, Transaction);
                            }
                        }
                    }
                }

                //*******************Save Spoken Languages************************

                var office_spoken_languages = new ORM_CMN_STR_Office_SpokenLanguage.Query()
                {
                    Tenant_RefID = securityTicket.TenantID,
                    Office_RefID = office.CMN_STR_OfficeID,
                    IsDeleted    = false
                };

                var officeSpokenLanguageQuery = ORM_CMN_STR_Office_SpokenLanguage.Query.Search(Connection, Transaction, office_spoken_languages);

                foreach (var item in Parameter.SpokenLanguage)
                {
                    ORM_CMN_STR_Office_SpokenLanguage officeSpokenLang = null;
                    foreach (var officeSpokenLanguageItem in officeSpokenLanguageQuery)
                    {
                        if (officeSpokenLanguageItem.Language_RefID == item.CMN_LanguageID && officeSpokenLanguageItem.Office_RefID == office.CMN_STR_OfficeID)
                        {
                            officeSpokenLang = officeSpokenLanguageItem;
                            break;
                        }
                    }
                    if (officeSpokenLang == null)
                    {
                        var officeSpokenLanguage = new ORM_CMN_STR_Office_SpokenLanguage();
                        officeSpokenLanguage.CMN_STR_Office_SpokenLanguageID = Guid.NewGuid();
                        officeSpokenLanguage.Language_RefID = item.CMN_LanguageID;
                        officeSpokenLanguage.IsDeleted      = item.IsDeleted;
                        officeSpokenLanguage.Office_RefID   = office.CMN_STR_OfficeID;
                        officeSpokenLanguage.Tenant_RefID   = securityTicket.TenantID;
                        officeSpokenLanguage.Save(Connection, Transaction);
                    }
                    else
                    {
                        officeSpokenLang.Language_RefID = item.CMN_LanguageID;
                        officeSpokenLang.IsDeleted      = item.IsDeleted;
                        officeSpokenLang.Save(Connection, Transaction);
                    }
                }


                //*******************Save Address************************

                foreach (var address in Parameter.Adresses)
                {
                    var Office_2_Address = ORM_CMN_STR_Office_Address.Query.Search(Connection, Transaction, new ORM_CMN_STR_Office_Address.Query()
                    {
                        IsBillingAddress  = address.IsBillingAddress,
                        IsShippingAddress = address.IsShippingAddress,
                        IsSpecialAddress  = address.IsSpecialAddress,
                        Office_RefID      = office.CMN_STR_OfficeID,
                        Tenant_RefID      = securityTicket.TenantID,
                        CMN_Address_RefID = address.AddressID,
                        IsDeleted         = false
                    }).SingleOrDefault();

                    if (Office_2_Address == null)
                    {
                        Office_2_Address = new ORM_CMN_STR_Office_Address();
                        Office_2_Address.CMN_STR_Office_AddressID = Guid.NewGuid();
                        Office_2_Address.IsBillingAddress         = address.IsBillingAddress;
                        Office_2_Address.IsShippingAddress        = address.IsShippingAddress;
                        Office_2_Address.IsSpecialAddress         = address.IsSpecialAddress;
                        Office_2_Address.CMN_Address_RefID        = address.AddressID;
                        Office_2_Address.Office_RefID             = office.CMN_STR_OfficeID;
                        Office_2_Address.Tenant_RefID             = securityTicket.TenantID;
                        Office_2_Address.Creation_Timestamp       = DateTime.Now;
                    }

                    Office_2_Address.IsDefault = address.IsDefault;

                    var Address = ORM_CMN_Address.Query.Search(Connection, Transaction, new ORM_CMN_Address.Query()
                    {
                        Tenant_RefID  = securityTicket.TenantID,
                        IsDeleted     = false,
                        CMN_AddressID = Office_2_Address.CMN_Address_RefID
                    }).SingleOrDefault();

                    if (Address == null)
                    {
                        Address = new ORM_CMN_Address();
                        Address.CMN_AddressID      = Office_2_Address.CMN_Address_RefID;
                        Address.Tenant_RefID       = securityTicket.TenantID;
                        Address.Creation_Timestamp = DateTime.Now;
                    }

                    if (address.IsDeleted)
                    {
                        Address.IsDeleted          = true;
                        Office_2_Address.IsDeleted = true;
                    }
                    else
                    {
                        Address.City_Name       = address.City;
                        Address.Street_Name     = address.Street_Name;
                        Address.Street_Number   = address.Street_Number;
                        Address.Country_ISOCode = address.CountryISO;
                        Address.Country_Name    = address.CountryName;
                        Address.City_PostalCode = address.ZIP;
                        if (address.IsDefault)
                        {
                            Address.Lattitude = address.Lattitude;
                            Address.Longitude = address.Longitude;
                        }
                    }
                    Office_2_Address.Save(Connection, Transaction);
                    Address.Save(Connection, Transaction);
                }


                //*******************AppointmentType************************

                foreach (var item in Parameter.AppoitmentType)
                {
                    var orgUnitToAppointmentTypeQuery = new ORM_PPS_TSK_Task_Template_OrganizationalUnitAvailability.Query();
                    orgUnitToAppointmentTypeQuery.CMN_STR_Office_RefID        = Parameter.OrgUnitID;
                    orgUnitToAppointmentTypeQuery.PPS_TSK_Task_Template_RefID = item.PPS_TSK_Task_Template_RefID;
                    orgUnitToAppointmentTypeQuery.Tenant_RefID = securityTicket.TenantID;
                    orgUnitToAppointmentTypeQuery.IsDeleted    = false;

                    var orgUnitToAppointmentType = ORM_PPS_TSK_Task_Template_OrganizationalUnitAvailability.Query.Search(Connection, Transaction, orgUnitToAppointmentTypeQuery).SingleOrDefault();

                    if (orgUnitToAppointmentType == null)
                    {
                        if (!item.IsDeleted)
                        {
                            orgUnitToAppointmentType = new ORM_PPS_TSK_Task_Template_OrganizationalUnitAvailability();
                            orgUnitToAppointmentType.PPS_TSK_Task_Template_OrganizationalUnitAvailabilityID = Guid.NewGuid();
                            orgUnitToAppointmentType.CMN_STR_Office_RefID        = Parameter.OrgUnitID;
                            orgUnitToAppointmentType.PPS_TSK_Task_Template_RefID = item.PPS_TSK_Task_Template_RefID;
                            orgUnitToAppointmentType.Creation_Timestamp          = DateTime.Now;
                            orgUnitToAppointmentType.Tenant_RefID = securityTicket.TenantID;
                            orgUnitToAppointmentType.Save(Connection, Transaction);
                        }
                    }
                    else
                    {
                        if (item.IsDeleted)
                        {
                            orgUnitToAppointmentType.IsDeleted = true;
                            orgUnitToAppointmentType.Save(Connection, Transaction);
                        }
                    }
                }


                //*******************Save Contact Person************************

                var responsiblePerson = ORM_CMN_STR_Office_ResponsiblePerson.Query.Search(Connection, Transaction, new ORM_CMN_STR_Office_ResponsiblePerson.Query()
                {
                    IsDeleted    = false,
                    Tenant_RefID = securityTicket.TenantID,
                    Office_RefID = office.CMN_STR_OfficeID
                }).Single();

                var employee = ORM_CMN_BPT_EMP_Employee.Query.Search(Connection, Transaction, new ORM_CMN_BPT_EMP_Employee.Query()
                {
                    Tenant_RefID           = securityTicket.TenantID,
                    IsDeleted              = false,
                    CMN_BPT_EMP_EmployeeID = responsiblePerson.CMN_BPT_EMP_Employee_RefID
                }).Single();

                var businessParticpant = ORM_CMN_BPT_BusinessParticipant.Query.Search(Connection, Transaction, new ORM_CMN_BPT_BusinessParticipant.Query()
                {
                    Tenant_RefID = securityTicket.TenantID,
                    IsDeleted    = false,
                    CMN_BPT_BusinessParticipantID = employee.BusinessParticipant_RefID
                }).Single();
                businessParticpant.DisplayName = Parameter.ContactPerson.Title + " " + Parameter.ContactPerson.FirstName + " " + Parameter.ContactPerson.LastName;
                businessParticpant.Save(Connection, Transaction);

                var personInfo = ORM_CMN_PER_PersonInfo.Query.Search(Connection, Transaction, new ORM_CMN_PER_PersonInfo.Query()
                {
                    Tenant_RefID         = securityTicket.TenantID,
                    IsDeleted            = false,
                    CMN_PER_PersonInfoID = businessParticpant.IfNaturalPerson_CMN_PER_PersonInfo_RefID
                }).Single();
                personInfo.Title     = Parameter.ContactPerson.Title;
                personInfo.FirstName = Parameter.ContactPerson.FirstName;
                personInfo.LastName  = Parameter.ContactPerson.LastName;
                personInfo.Save(Connection, Transaction);

                returnValue.Result = office.CMN_STR_OfficeID;
            }
            #endregion

            return(returnValue);

            #endregion UserCode
        }
Beispiel #9
0
        protected static FR_Guid Execute(DbConnection Connection, DbTransaction Transaction, P_L5ACACU_SPC_1047 Parameter, CSV2Core.SessionSecurity.SessionSecurityTicket securityTicket = null)
        {
            #region UserCode
            var returnValue = new FR_Guid();

            if (Parameter.IsDelete && (Parameter.CMN_BPT_CTM_CustomerID == Guid.Empty))
            {
                return(returnValue);
            }

            ORM_CMN_BPT_CTM_Customer customer;
            if (Parameter.CMN_BPT_CTM_CustomerID != Guid.Empty)
            {
                var customerQ = new ORM_CMN_BPT_CTM_Customer.Query();
                customerQ.Tenant_RefID           = securityTicket.TenantID;
                customerQ.IsDeleted              = false;
                customerQ.CMN_BPT_CTM_CustomerID = Parameter.CMN_BPT_CTM_CustomerID;
                customer = ORM_CMN_BPT_CTM_Customer.Query.Search(Connection, Transaction, customerQ).First();
                customer.IsCustomerOrderAutomaticallyApprovedOnReceipt =
                    Parameter.IsCustomerOrderAutomaticallyApprovedOnReceipt;
            }
            else
            {
                customer = new ORM_CMN_BPT_CTM_Customer();
                customer.Tenant_RefID           = securityTicket.TenantID;
                customer.CMN_BPT_CTM_CustomerID = Guid.NewGuid();
                customer.InternalCustomerNumber = Parameter.Number;
                customer.IsCustomerOrderAutomaticallyApprovedOnReceipt =
                    Parameter.IsCustomerOrderAutomaticallyApprovedOnReceipt;
            }

            ORM_CMN_BPT_CTM_AvailablePaymentType customer2PaymentType;

            var customer2PaymentTypeQ = new ORM_CMN_BPT_CTM_AvailablePaymentType.Query();
            customer2PaymentTypeQ.Tenant_RefID   = securityTicket.TenantID;
            customer2PaymentTypeQ.IsDeleted      = false;
            customer2PaymentTypeQ.Customer_RefID = customer.CMN_BPT_CTM_CustomerID;

            customer2PaymentType = ORM_CMN_BPT_CTM_AvailablePaymentType.Query.Search(Connection, Transaction, customer2PaymentTypeQ).FirstOrDefault();
            if (customer2PaymentType == null)
            {
                customer2PaymentType = new ORM_CMN_BPT_CTM_AvailablePaymentType();
                customer2PaymentType.ACC_PAY_Type_RefID = Guid.NewGuid();
                customer2PaymentType.Tenant_RefID       = securityTicket.TenantID;
                customer2PaymentType.Customer_RefID     = customer.CMN_BPT_CTM_CustomerID;
            }
            customer2PaymentType.ACC_PAY_Type_RefID = Parameter.PaymentTypeID;
            customer2PaymentType.Save(Connection, Transaction);

            #region payment condition

            ORM_CMN_BPT_CTM_AvailablePaymentCondition customer2PaymentCondition;

            var customer2PaymentConditionQ = new ORM_CMN_BPT_CTM_AvailablePaymentCondition.Query();
            customer2PaymentConditionQ.Tenant_RefID   = securityTicket.TenantID;
            customer2PaymentConditionQ.IsDeleted      = false;
            customer2PaymentConditionQ.Customer_RefID = customer.CMN_BPT_CTM_CustomerID;

            customer2PaymentCondition = ORM_CMN_BPT_CTM_AvailablePaymentCondition.Query.Search(Connection, Transaction, customer2PaymentConditionQ).FirstOrDefault();
            if (customer2PaymentCondition == null)
            {
                customer2PaymentCondition = new ORM_CMN_BPT_CTM_AvailablePaymentCondition();
                customer2PaymentCondition.ACC_PAY_Condition_RefID = Guid.NewGuid();
                customer2PaymentCondition.Tenant_RefID            = securityTicket.TenantID;
                customer2PaymentCondition.Customer_RefID          = customer.CMN_BPT_CTM_CustomerID;
            }
            customer2PaymentCondition.ACC_PAY_Condition_RefID = Parameter.PaymentConditionID;
            customer2PaymentCondition.Save(Connection, Transaction);

            #endregion

            ORM_CMN_BPT_BusinessParticipant bParticipant;
            if (customer.Ext_BusinessParticipant_RefID != Guid.Empty)
            {
                var bParticipantQ = new ORM_CMN_BPT_BusinessParticipant.Query();
                bParticipantQ.Tenant_RefID = securityTicket.TenantID;
                bParticipantQ.IsDeleted    = false;
                bParticipantQ.CMN_BPT_BusinessParticipantID = customer.Ext_BusinessParticipant_RefID;
                bParticipant = ORM_CMN_BPT_BusinessParticipant.Query.Search(Connection, Transaction, bParticipantQ).First();
            }
            else
            {
                bParticipant = new ORM_CMN_BPT_BusinessParticipant();
                bParticipant.Tenant_RefID = securityTicket.TenantID;
                bParticipant.CMN_BPT_BusinessParticipantID = Guid.NewGuid();
                bParticipant.IsNaturalPerson           = true;
                customer.Ext_BusinessParticipant_RefID = bParticipant.CMN_BPT_BusinessParticipantID;
            }

            bParticipant.DisplayName = Parameter.FirstName + " " + Parameter.LastName;

            ORM_CMN_PER_PersonInfo personInfo;
            if (bParticipant.IfNaturalPerson_CMN_PER_PersonInfo_RefID != Guid.Empty)
            {
                var personInfoQ = new ORM_CMN_PER_PersonInfo.Query();
                personInfoQ.Tenant_RefID         = securityTicket.TenantID;
                personInfoQ.IsDeleted            = false;
                personInfoQ.CMN_PER_PersonInfoID = bParticipant.IfNaturalPerson_CMN_PER_PersonInfo_RefID;
                personInfo = ORM_CMN_PER_PersonInfo.Query.Search(Connection, Transaction, personInfoQ).First();
            }
            else
            {
                personInfo = new ORM_CMN_PER_PersonInfo();
                personInfo.Tenant_RefID         = securityTicket.TenantID;
                personInfo.CMN_PER_PersonInfoID = Guid.NewGuid();
                bParticipant.IfNaturalPerson_CMN_PER_PersonInfo_RefID = personInfo.CMN_PER_PersonInfoID;
            }

            #region connection with legal guardian
            //checking is there allready legal guardian associated with this business participant

            ORM_CMN_BPT_BusinessParticipant_AssociatedBusinessParticipant.Query LGCheckQuery = new ORM_CMN_BPT_BusinessParticipant_AssociatedBusinessParticipant.Query();
            LGCheckQuery.BusinessParticipant_RefID = bParticipant.CMN_BPT_BusinessParticipantID;
            LGCheckQuery.IsDeleted = false;

            Boolean oldLegalGuardianConnectionExist = ORM_CMN_BPT_BusinessParticipant_AssociatedBusinessParticipant.Query.Exists(Connection, Transaction, LGCheckQuery);

            if (Parameter.IsRepresentedByLegalGuardian)
            {
                if (oldLegalGuardianConnectionExist)
                {
                    ORM_CMN_BPT_BusinessParticipant_AssociatedBusinessParticipant oldLegalGuardianConnection = ORM_CMN_BPT_BusinessParticipant_AssociatedBusinessParticipant.Query.Search(Connection, Transaction, LGCheckQuery).First();
                    ORM_CMN_BPT_BusinessParticipant.Query oldLegalGuardianQuery = new ORM_CMN_BPT_BusinessParticipant.Query();
                    oldLegalGuardianQuery.CMN_BPT_BusinessParticipantID = oldLegalGuardianConnection.AssociatedBusinessParticipant_RefID;
                    oldLegalGuardianQuery.IsDeleted = false;

                    ORM_CMN_BPT_BusinessParticipant oldLegalGuardian = ORM_CMN_BPT_BusinessParticipant.Query.Search(Connection, Transaction, oldLegalGuardianQuery).First();
                    oldLegalGuardian.DisplayName = Parameter.LegalGuardianName;
                    oldLegalGuardian.Save(Connection, Transaction);
                }
                else
                {
                    // creating a new legal guardian
                    ORM_CMN_BPT_BusinessParticipant newLegalGuardian = new ORM_CMN_BPT_BusinessParticipant();
                    ORM_CMN_BPT_BusinessParticipant_AssociatedBusinessParticipant legalGuardianLink = new ORM_CMN_BPT_BusinessParticipant_AssociatedBusinessParticipant();

                    newLegalGuardian.DisplayName = Parameter.LegalGuardianName;
                    legalGuardianLink.AssociatedBusinessParticipant_RefID = newLegalGuardian.CMN_BPT_BusinessParticipantID;
                    legalGuardianLink.BusinessParticipant_RefID           = bParticipant.CMN_BPT_BusinessParticipantID;
                    newLegalGuardian.Save(Connection, Transaction);
                    legalGuardianLink.Save(Connection, Transaction);
                }
            }
            else
            {
                //delete old legal guardian if there is an old legal guardian
                if (oldLegalGuardianConnectionExist)
                {
                    ORM_CMN_BPT_BusinessParticipant_AssociatedBusinessParticipant oldLegalGuardianConnection = ORM_CMN_BPT_BusinessParticipant_AssociatedBusinessParticipant.Query.Search(Connection, Transaction, LGCheckQuery).First();
                    ORM_CMN_BPT_BusinessParticipant.Query oldLegalGuardianQuery = new ORM_CMN_BPT_BusinessParticipant.Query();
                    oldLegalGuardianQuery.CMN_BPT_BusinessParticipantID = oldLegalGuardianConnection.AssociatedBusinessParticipant_RefID;
                    oldLegalGuardianQuery.IsDeleted = false;

                    //deleting old legal guardian from business participant table
                    if (ORM_CMN_BPT_BusinessParticipant.Query.Exists(Connection, Transaction, oldLegalGuardianQuery))
                    {
                        ORM_CMN_BPT_BusinessParticipant oldLegalGuardian = ORM_CMN_BPT_BusinessParticipant.Query.Search(Connection, Transaction, oldLegalGuardianQuery).First();
                        oldLegalGuardian.IsDeleted = true;
                        oldLegalGuardian.Save(Connection, Transaction);
                    }
                    // deleting connenction beetwen customer and legal guardian
                    oldLegalGuardianConnection.IsDeleted = true;
                    oldLegalGuardianConnection.Save(Connection, Transaction);
                }
            }

            #endregion

            personInfo.FirstName = Parameter.FirstName;
            personInfo.LastName  = Parameter.LastName;
            personInfo.BirthDate = Parameter.BirthDate;
            personInfo.IsRepresentedByLegalGuardian = Parameter.IsRepresentedByLegalGuardian;

            personInfo.IsDeleted   = Parameter.IsDelete;
            bParticipant.IsDeleted = Parameter.IsDelete;
            customer.IsDeleted     = Parameter.IsDelete;

            personInfo.Save(Connection, Transaction);
            bParticipant.Save(Connection, Transaction);
            customer.Save(Connection, Transaction);

            returnValue.Result = customer.CMN_BPT_CTM_CustomerID;

            return(returnValue);

            #endregion UserCode
        }
        protected static FR_Guid Execute(DbConnection Connection, DbTransaction Transaction, P_L5PR_SMP__1122 Parameter, CSV2Core.SessionSecurity.SessionSecurityTicket securityTicket = null)
        {
            #region UserCode
            var returnValue = new FR_Guid();

            if (Parameter.isDeleted == true)
            {
                P_L3MP_DPBID_1026 param = new P_L3MP_DPBID_1026();
                param.HEC_MedicalPractiseID = Parameter.PracticeID;

                cls_Delete_Practice_By_ID.Invoke(Connection, Transaction, param, securityTicket);
            }
            else
            {
                #region Save

                if (Parameter.PracticeID == Guid.Empty)
                {
                    /*********************************
                     *  Save ContactPerson
                     ********************************/
                    //business Participants
                    ORM_CMN_BPT_BusinessParticipant contactPerson = new ORM_CMN_BPT_BusinessParticipant();
                    Guid businessParticipantsID = Guid.NewGuid();

                    contactPerson.CMN_BPT_BusinessParticipantID = businessParticipantsID;
                    contactPerson.IsCompany          = false;
                    contactPerson.IsNaturalPerson    = true;
                    contactPerson.IsTenant           = false;
                    contactPerson.Creation_Timestamp = DateTime.Now;
                    contactPerson.Tenant_RefID       = securityTicket.TenantID;

                    //person info
                    ORM_CMN_PER_PersonInfo personInfo = new ORM_CMN_PER_PersonInfo();
                    Guid personInfoID = Guid.NewGuid();

                    contactPerson.IfNaturalPerson_CMN_PER_PersonInfo_RefID = personInfoID;
                    contactPerson.Save(Connection, Transaction);

                    personInfo.CMN_PER_PersonInfoID = personInfoID;
                    personInfo.FirstName            = Parameter.ContactPersonFirstName;
                    personInfo.LastName             = Parameter.ContactPersonLastName;
                    personInfo.PrimaryEmail         = Parameter.ContactPersonEmail;
                    personInfo.Creation_Timestamp   = DateTime.Now;
                    personInfo.Tenant_RefID         = securityTicket.TenantID;

                    personInfo.Save(Connection, Transaction);

                    //Communication Contact
                    ORM_CMN_PER_CommunicationContact communicationContacts = new ORM_CMN_PER_CommunicationContact();

                    communicationContacts.CMN_PER_CommunicationContactID = Guid.NewGuid();
                    communicationContacts.PersonInfo_RefID   = personInfoID;
                    communicationContacts.Contact_Type       = Parameter.ContactTypePhone;
                    communicationContacts.Content            = Parameter.ContactPersonPhoneNumber;
                    communicationContacts.Creation_Timestamp = DateTime.Now;
                    communicationContacts.Tenant_RefID       = securityTicket.TenantID;

                    communicationContacts.Save(Connection, Transaction);

                    /*********************************
                     * Save Practice
                     ********************************/
                    P_L3MP_SPBI_1602 param = new P_L3MP_SPBI_1602();
                    param.Street_Number     = Parameter.PracticeNumber;
                    param.Street_Name       = Parameter.PracticeStreet;
                    param.Street_Name_Line2 = Parameter.PracticeStreet2;
                    param.PracticeName      = Parameter.PracticeName;
                    param.isLucentis        = true;
                    param.ifLucentis_BSNR   = Parameter.BSNR;
                    param.PracticeEmail     = Parameter.PracitceEmail;
                    param.Town = Parameter.Town;
                    param.ZIP  = Parameter.ZIP;
                    param.HEC_MedicalPractiseID = Parameter.PracticeID;

                    Guid HEC_MedicalPractiseID = cls_Save_Practice_BaseInfo.Invoke(Connection, Transaction, param, securityTicket).Result;


                    /*********************************
                     * Save Cooperating Practices
                     ********************************/
                    var queryMedicalPractice = new ORM_HEC_MedicalPractis.Query();
                    queryMedicalPractice.HEC_MedicalPractiseID = HEC_MedicalPractiseID;
                    queryMedicalPractice.IsDeleted             = false;

                    var medicalPractice = ORM_HEC_MedicalPractis.Query.Search(Connection, Transaction, queryMedicalPractice).FirstOrDefault();

                    if (medicalPractice != null)
                    {
                        medicalPractice.ContactPerson_RefID = businessParticipantsID;
                        medicalPractice.Save(Connection, Transaction);

                        var queryCompanyInfo = new ORM_CMN_COM_CompanyInfo.Query();
                        queryCompanyInfo.CMN_COM_CompanyInfoID = medicalPractice.Ext_CompanyInfo_RefID;
                        queryCompanyInfo.IsDeleted             = false;

                        var CompanyInfo = ORM_CMN_COM_CompanyInfo.Query.Search(Connection, Transaction, queryCompanyInfo).FirstOrDefault();

                        if (CompanyInfo != null)
                        {
                            var queryBussinessParticipients = new ORM_CMN_BPT_BusinessParticipant.Query();
                            queryBussinessParticipients.IfCompany_CMN_COM_CompanyInfo_RefID = CompanyInfo.CMN_COM_CompanyInfoID;
                            queryBussinessParticipients.IsDeleted = false;

                            var bussinessParticipants = ORM_CMN_BPT_BusinessParticipant.Query.Search(Connection, Transaction, queryBussinessParticipients).FirstOrDefault();


                            if (bussinessParticipants != null)
                            {
                                foreach (var cooperatingPractice in Parameter.CooperatingPractices)
                                {
                                    ORM_CMN_BPT_BusinessParticipant_AssociatedBusinessParticipant associatedBussinessParticipants = new ORM_CMN_BPT_BusinessParticipant_AssociatedBusinessParticipant();

                                    associatedBussinessParticipants.CMN_BPT_BusinessParticipant_AssociatedBusinessParticipantID = Guid.NewGuid();
                                    associatedBussinessParticipants.IsDeleted = cooperatingPractice.isDeleted;
                                    associatedBussinessParticipants.BusinessParticipant_RefID           = bussinessParticipants.CMN_BPT_BusinessParticipantID;
                                    associatedBussinessParticipants.AssociatedBusinessParticipant_RefID = cooperatingPractice.PracticeID;
                                    associatedBussinessParticipants.Creation_Timestamp = DateTime.Now;
                                    associatedBussinessParticipants.Tenant_RefID       = bussinessParticipants.Tenant_RefID;

                                    associatedBussinessParticipants.Save(Connection, Transaction);
                                }
                            }
                        }

                        returnValue.Result = medicalPractice.HEC_MedicalPractiseID;
                    }
                }
                #endregion
                else
                {
                    /*********************************
                     * Edit Practice
                     ********************************/
                    P_L3MP_SPBI_1602 param = new P_L3MP_SPBI_1602();
                    param.Street_Number     = Parameter.PracticeNumber;
                    param.Street_Name       = Parameter.PracticeStreet;
                    param.Street_Name_Line2 = Parameter.PracticeStreet2;
                    param.PracticeName      = Parameter.PracticeName;
                    param.isLucentis        = true;
                    param.ifLucentis_BSNR   = Parameter.BSNR;
                    param.PracticeEmail     = Parameter.PracitceEmail;
                    param.Town = Parameter.Town;
                    param.ZIP  = Parameter.ZIP;
                    param.HEC_MedicalPractiseID = Parameter.PracticeID;

                    Guid HEC_MedicalPractiseID = cls_Save_Practice_BaseInfo.Invoke(Connection, Transaction, param, securityTicket).Result;

                    var medicalPracticeQuery = new ORM_HEC_MedicalPractis.Query();
                    medicalPracticeQuery.IsDeleted             = false;
                    medicalPracticeQuery.HEC_MedicalPractiseID = HEC_MedicalPractiseID;

                    var medicalPractice = ORM_HEC_MedicalPractis.Query.Search(Connection, Transaction, medicalPracticeQuery).FirstOrDefault();

                    if (medicalPractice != null)
                    {
                        /*********************************
                         *  Edit Contact Person
                         ********************************/

                        //contact person
                        var contactPerson = new ORM_CMN_BPT_BusinessParticipant();

                        var contactPersonQuery = new ORM_CMN_BPT_BusinessParticipant.Query();
                        contactPersonQuery.IsDeleted = false;

                        if (medicalPractice.ContactPerson_RefID != Guid.Empty)
                        {
                            contactPersonQuery.CMN_BPT_BusinessParticipantID = medicalPractice.ContactPerson_RefID;
                            contactPerson = ORM_CMN_BPT_BusinessParticipant.Query.Search(Connection, Transaction, contactPersonQuery).FirstOrDefault();
                        }
                        else
                        {
                            contactPerson = null;
                        }

                        Guid personInfoID = Guid.NewGuid();

                        if (contactPerson == null)
                        {
                            contactPerson = new ORM_CMN_BPT_BusinessParticipant();
                            contactPerson.CMN_BPT_BusinessParticipantID = Guid.NewGuid();
                            contactPerson.IsCompany          = false;
                            contactPerson.IsNaturalPerson    = true;
                            contactPerson.IsTenant           = false;
                            contactPerson.Creation_Timestamp = DateTime.Now;
                            contactPerson.Tenant_RefID       = securityTicket.TenantID;

                            contactPerson.IfNaturalPerson_CMN_PER_PersonInfo_RefID = personInfoID;
                            contactPerson.Save(Connection, Transaction);

                            medicalPractice.ContactPerson_RefID = contactPerson.CMN_BPT_BusinessParticipantID;
                            medicalPractice.Save(Connection, Transaction);
                        }

                        var personInfo = new ORM_CMN_PER_PersonInfo();

                        //person info
                        var personInfoQuery = new ORM_CMN_PER_PersonInfo.Query();
                        personInfoQuery.IsDeleted            = false;
                        personInfoQuery.CMN_PER_PersonInfoID = contactPerson.IfNaturalPerson_CMN_PER_PersonInfo_RefID;

                        personInfo = ORM_CMN_PER_PersonInfo.Query.Search(Connection, Transaction, personInfoQuery).FirstOrDefault();

                        if (personInfo == null)
                        {
                            personInfo = new ORM_CMN_PER_PersonInfo();
                            personInfo.CMN_PER_PersonInfoID = Guid.NewGuid();
                            personInfo.Creation_Timestamp   = DateTime.Now;
                            personInfo.Tenant_RefID         = securityTicket.TenantID;
                            personInfo.CMN_PER_PersonInfoID = personInfoID;

                            contactPerson.IfNaturalPerson_CMN_PER_PersonInfo_RefID = personInfo.CMN_PER_PersonInfoID;
                            contactPerson.Save(Connection, Transaction);
                        }

                        personInfo.FirstName    = Parameter.ContactPersonFirstName;
                        personInfo.LastName     = Parameter.ContactPersonLastName;
                        personInfo.PrimaryEmail = Parameter.ContactPersonEmail;

                        personInfo.Save(Connection, Transaction);

                        //Communication Contact

                        var communicationContacts = new ORM_CMN_PER_CommunicationContact();

                        var communicationContactsQuery = new ORM_CMN_PER_CommunicationContact.Query();
                        communicationContactsQuery.IsDeleted        = false;
                        communicationContactsQuery.PersonInfo_RefID = personInfo.CMN_PER_PersonInfoID;

                        communicationContacts = ORM_CMN_PER_CommunicationContact.Query.Search(Connection, Transaction, communicationContactsQuery).FirstOrDefault();

                        if (communicationContacts == null)
                        {
                            communicationContacts = new ORM_CMN_PER_CommunicationContact();
                            communicationContacts.CMN_PER_CommunicationContactID = Guid.NewGuid();
                            communicationContacts.PersonInfo_RefID   = personInfo.CMN_PER_PersonInfoID;
                            communicationContacts.Creation_Timestamp = DateTime.Now;
                            communicationContacts.Tenant_RefID       = securityTicket.TenantID;
                        }
                        communicationContacts.Contact_Type = Parameter.ContactTypePhone;
                        communicationContacts.Content      = Parameter.ContactPersonPhoneNumber;

                        communicationContacts.Save(Connection, Transaction);


                        /*********************************
                         *  Edit Cooperating Practices
                         ********************************/

                        var queryCompanyInfo = new ORM_CMN_COM_CompanyInfo.Query();
                        queryCompanyInfo.CMN_COM_CompanyInfoID = medicalPractice.Ext_CompanyInfo_RefID;
                        queryCompanyInfo.IsDeleted             = false;

                        var CompanyInfo = ORM_CMN_COM_CompanyInfo.Query.Search(Connection, Transaction, queryCompanyInfo).FirstOrDefault();

                        if (CompanyInfo != null)
                        {
                            var queryBussinessParticipients = new ORM_CMN_BPT_BusinessParticipant.Query();
                            queryBussinessParticipients.IfCompany_CMN_COM_CompanyInfo_RefID = CompanyInfo.CMN_COM_CompanyInfoID;
                            queryBussinessParticipients.IsDeleted = false;

                            var bussinessParticipants = ORM_CMN_BPT_BusinessParticipant.Query.Search(Connection, Transaction, queryBussinessParticipients).FirstOrDefault();


                            if (bussinessParticipants != null)
                            {
                                foreach (var cooperatingPractice in Parameter.CooperatingPractices)
                                {
                                    var associatedBussinessParticipantsQuery = new ORM_CMN_BPT_BusinessParticipant_AssociatedBusinessParticipant.Query();
                                    associatedBussinessParticipantsQuery.AssociatedBusinessParticipant_RefID = cooperatingPractice.PracticeID;
                                    associatedBussinessParticipantsQuery.Tenant_RefID = bussinessParticipants.Tenant_RefID;
                                    associatedBussinessParticipantsQuery.BusinessParticipant_RefID = bussinessParticipants.CMN_BPT_BusinessParticipantID;

                                    var associtePractice = ORM_CMN_BPT_BusinessParticipant_AssociatedBusinessParticipant.Query.Search(Connection, Transaction, associatedBussinessParticipantsQuery).FirstOrDefault();

                                    if (associtePractice != null)
                                    {
                                        associtePractice.IsDeleted = cooperatingPractice.isDeleted;
                                        associtePractice.AssociatedBusinessParticipant_RefID = cooperatingPractice.PracticeID;
                                        associtePractice.Save(Connection, Transaction);
                                    }
                                    else
                                    {
                                        ORM_CMN_BPT_BusinessParticipant_AssociatedBusinessParticipant associatedBussinessParticipants = new ORM_CMN_BPT_BusinessParticipant_AssociatedBusinessParticipant();

                                        associatedBussinessParticipants.CMN_BPT_BusinessParticipant_AssociatedBusinessParticipantID = Guid.NewGuid();
                                        associatedBussinessParticipants.IsDeleted = cooperatingPractice.isDeleted;
                                        associatedBussinessParticipants.BusinessParticipant_RefID           = bussinessParticipants.CMN_BPT_BusinessParticipantID;
                                        associatedBussinessParticipants.AssociatedBusinessParticipant_RefID = cooperatingPractice.PracticeID;
                                        associatedBussinessParticipants.Creation_Timestamp = DateTime.Now;
                                        associatedBussinessParticipants.Tenant_RefID       = bussinessParticipants.Tenant_RefID;

                                        associatedBussinessParticipants.Save(Connection, Transaction);
                                    }
                                }
                            }
                        }

                        returnValue.Result = medicalPractice.HEC_MedicalPractiseID;
                    }
                }
            }

            return(returnValue);

            #endregion UserCode
        }
Beispiel #11
0
        protected static FR_Guid Execute(DbConnection Connection, DbTransaction Transaction, P_DO_SD_1517 Parameter, CSV2Core.SessionSecurity.SessionSecurityTicket securityTicket = null)
        {
            //Leave UserCode region to enable user code saving
            #region UserCode
            var returnValue = new FR_Guid();
            //Put your code here
            Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("de-DE");
            Guid   BusinessParticipantID         = Guid.NewGuid();
            Guid   personInfoID                  = Guid.NewGuid();
            Guid   PracticeCustomerID            = Guid.NewGuid();
            Guid   PracticeBusinessParticipantID = Guid.NewGuid();
            Guid   PracticeCompanyInfoID         = Guid.NewGuid();
            String PracticeName                  = "";
            Guid   BankAccountID                 = Guid.Empty;
            Guid   doctor_id    = Parameter.DoctorID;
            var    isOpPractice = false;

            //if (!String.IsNullOrEmpty(Parameter.Login_Email))
            //uncomment this if you've created account
            if (false)
            {
                string[] stringUser  = Parameter.Login_Email.Split('@');
                string   usernameStr = stringUser[0];

                try
                {
                    var doctorAccountInfo = ORM_USR_Account.Query.Search(Connection, Transaction, new ORM_USR_Account.Query()
                    {
                        IsDeleted    = false,
                        Tenant_RefID = securityTicket.TenantID,
                        AccountSignInEmailAddress = Parameter.Login_Email,
                    }).Single();

                    var accountGroupQuery = new ORM_USR_Account_FunctionLevelRights_Group.Query();
                    accountGroupQuery.Tenant_RefID             = securityTicket.TenantID;
                    accountGroupQuery.IsDeleted                = false;
                    accountGroupQuery.GlobalPropertyMatchingID = "mm.docconect.doc.app.group";

                    var accountGroup = ORM_USR_Account_FunctionLevelRights_Group.Query.Search(Connection, Transaction, accountGroupQuery).SingleOrDefault();

                    if (accountGroup == null)
                    {
                        accountGroup = new ORM_USR_Account_FunctionLevelRights_Group();
                        accountGroup.Tenant_RefID             = securityTicket.TenantID;
                        accountGroup.Label                    = "mm.docconect.doc.app.group";
                        accountGroup.GlobalPropertyMatchingID = "mm.docconect.doc.app.group";
                        accountGroup.Creation_Timestamp       = DateTime.Now;
                        accountGroup.USR_Account_FunctionLevelRights_GroupID = Guid.NewGuid();
                        accountGroup.Save(Connection, Transaction);
                    }

                    var PracticeAccount2UniversalProperty = ORM_HEC_MedicalPractice_2_UniversalProperty.Query.Search(Connection, Transaction, new ORM_HEC_MedicalPractice_2_UniversalProperty.Query()
                    {
                        IsDeleted    = false,
                        Tenant_RefID = securityTicket.TenantID,
                        HEC_MedicalPractice_RefID = Parameter.PracticeID
                    }).ToList();

                    List <ORM_HEC_MedicalPractice_UniversalProperty> PracticeUniversalPropertyList = new List <ORM_HEC_MedicalPractice_UniversalProperty>();
                    foreach (var item in PracticeAccount2UniversalProperty)
                    {
                        var PracticeUniversalProperty = ORM_HEC_MedicalPractice_UniversalProperty.Query.Search(Connection, Transaction, new ORM_HEC_MedicalPractice_UniversalProperty.Query()
                        {
                            IsDeleted    = false,
                            Tenant_RefID = securityTicket.TenantID,
                            HEC_MedicalPractice_UniversalPropertyID = item.HEC_MedicalPractice_UniversalProperty_RefID
                        }).Single();
                        PracticeUniversalPropertyList.Add(PracticeUniversalProperty);
                    }
                    ;

                    P_DO_GPAIDfPID_1522 practiceAccountIDParameter = new P_DO_GPAIDfPID_1522();
                    practiceAccountIDParameter.PracticeID = Parameter.PracticeID;

                    var practiceAccountToFunctionLevelRightQ = new ORM_USR_Account_2_FunctionLevelRight.Query();
                    practiceAccountToFunctionLevelRightQ.Account_RefID = cls_Get_Practice_AccountID_for_PracticeID.Invoke(Connection, Transaction, practiceAccountIDParameter, securityTicket).Result.accountID;
                    practiceAccountToFunctionLevelRightQ.Tenant_RefID  = securityTicket.TenantID;
                    practiceAccountToFunctionLevelRightQ.IsDeleted     = false;

                    var practiceAccountToFunctionLevelRight = ORM_USR_Account_2_FunctionLevelRight.Query.Search(Connection, Transaction, practiceAccountToFunctionLevelRightQ).SingleOrDefault();

                    if (practiceAccountToFunctionLevelRight != null)
                    {
                        var practiceAccountFunctionLevelRightQ = new ORM_USR_Account_FunctionLevelRight.Query();
                        practiceAccountFunctionLevelRightQ.Tenant_RefID = securityTicket.TenantID;
                        practiceAccountFunctionLevelRightQ.IsDeleted    = false;
                        practiceAccountFunctionLevelRightQ.USR_Account_FunctionLevelRightID = practiceAccountToFunctionLevelRight.FunctionLevelRight_RefID;

                        var practiceAccountFunctionLevelRight = ORM_USR_Account_FunctionLevelRight.Query.Search(Connection, Transaction, practiceAccountFunctionLevelRightQ).SingleOrDefault();

                        if (practiceAccountFunctionLevelRight != null)
                        {
                            isOpPractice = practiceAccountFunctionLevelRight.GlobalPropertyMatchingID.Equals("mm.docconect.doc.app.op.practice");
                        }
                    }

                    var functionLevelRightQ = new ORM_USR_Account_FunctionLevelRight.Query();
                    functionLevelRightQ.Tenant_RefID             = securityTicket.TenantID;
                    functionLevelRightQ.IsDeleted                = false;
                    functionLevelRightQ.GlobalPropertyMatchingID = isOpPractice ? "mm.docconect.doc.app.op.doctor" : "mm.docconect.doc.app.ac.doctor";

                    var existingFunctionLevelRight = ORM_USR_Account_FunctionLevelRight.Query.Search(Connection, Transaction, functionLevelRightQ).SingleOrDefault();

                    var tempFunctionLevelRightID = Guid.Empty;

                    if (existingFunctionLevelRight == null)
                    {
                        ORM_USR_Account_FunctionLevelRight functionLevelRight = new ORM_USR_Account_FunctionLevelRight();
                        functionLevelRight.USR_Account_FunctionLevelRightID = Guid.NewGuid();
                        functionLevelRight.FunctionLevelRights_Group_RefID  = accountGroup.USR_Account_FunctionLevelRights_GroupID;
                        functionLevelRight.Tenant_RefID       = securityTicket.TenantID;
                        functionLevelRight.Creation_Timestamp = DateTime.Now;

                        functionLevelRight.RightName = isOpPractice ? "mm.docconect.doc.app.op.doctor" : "mm.docconect.doc.app.ac.doctor";
                        functionLevelRight.GlobalPropertyMatchingID = isOpPractice ? "mm.docconect.doc.app.op.doctor" : "mm.docconect.doc.app.ac.doctor";

                        functionLevelRight.Save(Connection, Transaction);

                        tempFunctionLevelRightID = functionLevelRight.USR_Account_FunctionLevelRightID;
                    }
                    else
                    {
                        tempFunctionLevelRightID = existingFunctionLevelRight.USR_Account_FunctionLevelRightID;
                    }

                    var accountToFunctionLevelRight = new ORM_USR_Account_2_FunctionLevelRight();
                    accountToFunctionLevelRight.Tenant_RefID             = securityTicket.TenantID;
                    accountToFunctionLevelRight.Creation_Timestamp       = DateTime.Now;
                    accountToFunctionLevelRight.AssignmentID             = Guid.NewGuid();
                    accountToFunctionLevelRight.Account_RefID            = doctorAccountInfo.USR_AccountID;
                    accountToFunctionLevelRight.FunctionLevelRight_RefID = tempFunctionLevelRightID;

                    accountToFunctionLevelRight.Save(Connection, Transaction);

                    var businessParticipantQ = new ORM_CMN_BPT_BusinessParticipant.Query();

                    businessParticipantQ.IsDeleted    = false;
                    businessParticipantQ.Tenant_RefID = securityTicket.TenantID;
                    businessParticipantQ.CMN_BPT_BusinessParticipantID = doctorAccountInfo.BusinessParticipant_RefID;
                    BusinessParticipantID = doctorAccountInfo.BusinessParticipant_RefID;

                    var DoctorBusinessParticipant = ORM_CMN_BPT_BusinessParticipant.Query.Search(Connection, Transaction, businessParticipantQ).Single();
                    DoctorBusinessParticipant.IfNaturalPerson_CMN_PER_PersonInfo_RefID = Guid.NewGuid();
                    DoctorBusinessParticipant.DisplayName            = Parameter.First_Name + " " + Parameter.Last_Name;
                    DoctorBusinessParticipant.IsNaturalPerson        = true;
                    DoctorBusinessParticipant.Modification_Timestamp = DateTime.Now;
                    DoctorBusinessParticipant.Save(Connection, Transaction);
                    personInfoID = DoctorBusinessParticipant.IfNaturalPerson_CMN_PER_PersonInfo_RefID;


                    var companyInfoPractice = new ORM_CMN_PER_PersonInfo();
                    companyInfoPractice.IsDeleted            = false;
                    companyInfoPractice.Tenant_RefID         = securityTicket.TenantID;
                    companyInfoPractice.CMN_PER_PersonInfoID = personInfoID;
                    companyInfoPractice.FirstName            = Parameter.First_Name;
                    companyInfoPractice.LastName             = Parameter.Last_Name;
                    companyInfoPractice.Salutation_General   = Parameter.Salutation;
                    companyInfoPractice.Title = Parameter.Title;
                    companyInfoPractice.Save(Connection, Transaction);

                    var communicationContact = new ORM_CMN_PER_CommunicationContact();
                    communicationContact.IsDeleted              = false;
                    communicationContact.Contact_Type           = Guid.NewGuid();
                    communicationContact.Tenant_RefID           = securityTicket.TenantID;
                    communicationContact.Modification_Timestamp = DateTime.Now;
                    communicationContact.PersonInfo_RefID       = personInfoID;
                    communicationContact.Content = Parameter.Email;
                    communicationContact.Save(Connection, Transaction);
                    Guid CommunicationContactTypeID = communicationContact.Contact_Type;


                    var communicationContactType = new ORM_CMN_PER_CommunicationContact_Type();
                    communicationContactType.IsDeleted    = false;
                    communicationContactType.Tenant_RefID = securityTicket.TenantID;
                    communicationContactType.CMN_PER_CommunicationContact_TypeID = CommunicationContactTypeID;
                    communicationContactType.Type = "Email";
                    communicationContactType.Save(Connection, Transaction);

                    var communicationContact2 = new ORM_CMN_PER_CommunicationContact();
                    communicationContact2.IsDeleted              = false;
                    communicationContact2.Contact_Type           = Guid.NewGuid();
                    communicationContact2.Tenant_RefID           = securityTicket.TenantID;
                    communicationContact2.Modification_Timestamp = DateTime.Now;
                    communicationContact2.PersonInfo_RefID       = personInfoID;
                    communicationContact2.Content = Parameter.Phone;
                    communicationContact2.Save(Connection, Transaction);
                    Guid CommunicationContactTypeID2 = communicationContact2.Contact_Type;


                    var communicationContactType2 = new ORM_CMN_PER_CommunicationContact_Type();
                    communicationContactType2.IsDeleted    = false;
                    communicationContactType2.Tenant_RefID = securityTicket.TenantID;
                    communicationContactType2.CMN_PER_CommunicationContact_TypeID = CommunicationContactTypeID2;
                    communicationContactType2.Type = "Phone";
                    communicationContactType2.Save(Connection, Transaction);

                    var doctor = new ORM_HEC_Doctor();
                    doctor.HEC_DoctorID = Guid.NewGuid();
                    doctor.IsDeleted    = false;
                    doctor.Tenant_RefID = securityTicket.TenantID;
                    doctor.BusinessParticipant_RefID = BusinessParticipantID;
                    doctor.DoctorIDNumber            = Parameter.LANR.ToString();
                    doctor.Save(Connection, Transaction);

                    doctor_id = doctor.HEC_DoctorID;

                    var ogranizationUnitPractice = ORM_CMN_BPT_CTM_OrganizationalUnit.Query.Search(Connection, Transaction, new ORM_CMN_BPT_CTM_OrganizationalUnit.Query()
                    {
                        IsDeleted    = false,
                        Tenant_RefID = securityTicket.TenantID,
                        IfMedicalPractise_HEC_MedicalPractice_RefID = Parameter.PracticeID
                    }).Single();


                    var organizationalunit_Staff = new ORM_CMN_BPT_CTM_OrganizationalUnit_Staff();
                    organizationalunit_Staff.IsDeleted    = false;
                    organizationalunit_Staff.Tenant_RefID = securityTicket.TenantID;
                    organizationalunit_Staff.BusinessParticipant_RefID = BusinessParticipantID;
                    organizationalunit_Staff.OrganizationalUnit_RefID  = ogranizationUnitPractice.CMN_BPT_CTM_OrganizationalUnitID;
                    organizationalunit_Staff.Save(Connection, Transaction);

                    var CustomerPRactice = ORM_CMN_BPT_CTM_Customer.Query.Search(Connection, Transaction, new ORM_CMN_BPT_CTM_Customer.Query()
                    {
                        IsDeleted              = false,
                        Tenant_RefID           = securityTicket.TenantID,
                        CMN_BPT_CTM_CustomerID = ogranizationUnitPractice.Customer_RefID
                    }).Single();
                    var PracticeBusinessParticipant = ORM_CMN_BPT_BusinessParticipant.Query.Search(Connection, Transaction, new ORM_CMN_BPT_BusinessParticipant.Query()
                    {
                        IsDeleted    = false,
                        Tenant_RefID = securityTicket.TenantID,
                        CMN_BPT_BusinessParticipantID = CustomerPRactice.Ext_BusinessParticipant_RefID
                    }).Single();

                    PracticeName = PracticeBusinessParticipant.DisplayName;
                    PracticeBusinessParticipantID = PracticeBusinessParticipant.CMN_BPT_BusinessParticipantID;
                    PracticeCompanyInfoID         = PracticeBusinessParticipant.IfCompany_CMN_COM_CompanyInfo_RefID;

                    if (Parameter.From_Practice_Bank)
                    {
                        var PracticeBusinessParticipant2bankaccount = ORM_CMN_BPT_BusinessParticipant_2_BankAccount.Query.Search(Connection, Transaction, new ORM_CMN_BPT_BusinessParticipant_2_BankAccount.Query()
                        {
                            IsDeleted    = false,
                            Tenant_RefID = securityTicket.TenantID,
                            CMN_BPT_BusinessParticipant_RefID = PracticeBusinessParticipant.CMN_BPT_BusinessParticipantID,
                        }).Single();


                        var business2bankAccount = new ORM_CMN_BPT_BusinessParticipant_2_BankAccount();
                        business2bankAccount.IsDeleted    = false;
                        business2bankAccount.Tenant_RefID = securityTicket.TenantID;
                        business2bankAccount.CMN_BPT_BusinessParticipant_RefID = BusinessParticipantID;
                        business2bankAccount.ACC_BNK_BankAccount_RefID         = PracticeBusinessParticipant2bankaccount.ACC_BNK_BankAccount_RefID;
                        business2bankAccount.Creation_Timestamp = DateTime.Now;
                        business2bankAccount.Save(Connection, Transaction);

                        BankAccountID = PracticeBusinessParticipant2bankaccount.ACC_BNK_BankAccount_RefID;
                        //end of save bank data if inherited from practice
                    }
                    else
                    {
                        if (!String.IsNullOrEmpty(Parameter.IBAN) || !String.IsNullOrEmpty(Parameter.Bank))
                        {
                            var business2bankAccount = new ORM_CMN_BPT_BusinessParticipant_2_BankAccount();
                            business2bankAccount.IsDeleted    = false;
                            business2bankAccount.Tenant_RefID = securityTicket.TenantID;
                            business2bankAccount.CMN_BPT_BusinessParticipant_RefID = BusinessParticipantID;
                            business2bankAccount.ACC_BNK_BankAccount_RefID         = Guid.NewGuid();
                            business2bankAccount.Creation_Timestamp = DateTime.Now;
                            business2bankAccount.Save(Connection, Transaction);

                            var bankAccountDoctor = new ORM_ACC_BNK_BankAccount();
                            bankAccountDoctor.IsDeleted             = false;
                            bankAccountDoctor.Tenant_RefID          = securityTicket.TenantID;
                            bankAccountDoctor.ACC_BNK_BankAccountID = business2bankAccount.ACC_BNK_BankAccount_RefID;
                            bankAccountDoctor.OwnerText             = Parameter.Account_Holder;
                            bankAccountDoctor.IBAN               = Parameter.IBAN;
                            bankAccountDoctor.Bank_RefID         = Guid.NewGuid();
                            bankAccountDoctor.Creation_Timestamp = DateTime.Now;
                            bankAccountDoctor.Save(Connection, Transaction);

                            if (!String.IsNullOrEmpty(Parameter.Bank))
                            {
                                var bank = new ORM_ACC_BNK_Bank();
                                bank.IsDeleted          = false;
                                bank.Tenant_RefID       = securityTicket.TenantID;
                                bank.ACC_BNK_BankID     = bankAccountDoctor.Bank_RefID;
                                bank.BICCode            = Parameter.BIC;
                                bank.BankName           = Parameter.Bank;
                                bank.Creation_Timestamp = DateTime.Now;
                                bank.Save(Connection, Transaction);
                            }

                            BankAccountID = business2bankAccount.ACC_BNK_BankAccount_RefID;
                            // end save bank data
                        }
                    }
                }
                catch
                {
                    throw new Exception();
                }
            }
            else
            {
                var DoctorBusinessParticipant = new ORM_CMN_BPT_BusinessParticipant();

                DoctorBusinessParticipant.IsDeleted    = false;
                DoctorBusinessParticipant.Tenant_RefID = securityTicket.TenantID;
                DoctorBusinessParticipant.CMN_BPT_BusinessParticipantID            = Guid.NewGuid();
                DoctorBusinessParticipant.IfNaturalPerson_CMN_PER_PersonInfo_RefID = Guid.NewGuid();
                DoctorBusinessParticipant.DisplayName            = Parameter.First_Name + " " + Parameter.Last_Name;
                DoctorBusinessParticipant.IsNaturalPerson        = true;
                DoctorBusinessParticipant.Modification_Timestamp = DateTime.Now;
                DoctorBusinessParticipant.Save(Connection, Transaction);
                personInfoID          = DoctorBusinessParticipant.IfNaturalPerson_CMN_PER_PersonInfo_RefID;
                BusinessParticipantID = DoctorBusinessParticipant.CMN_BPT_BusinessParticipantID;

                var companyInfoPractice = new ORM_CMN_PER_PersonInfo();
                companyInfoPractice.IsDeleted            = false;
                companyInfoPractice.Tenant_RefID         = securityTicket.TenantID;
                companyInfoPractice.CMN_PER_PersonInfoID = personInfoID;
                companyInfoPractice.FirstName            = Parameter.First_Name;
                companyInfoPractice.LastName             = Parameter.Last_Name;
                companyInfoPractice.Salutation_General   = Parameter.Salutation;
                companyInfoPractice.Title = Parameter.Title;
                companyInfoPractice.Save(Connection, Transaction);

                var communicationContact = new ORM_CMN_PER_CommunicationContact();
                communicationContact.IsDeleted              = false;
                communicationContact.Contact_Type           = Guid.NewGuid();
                communicationContact.Tenant_RefID           = securityTicket.TenantID;
                communicationContact.Modification_Timestamp = DateTime.Now;
                communicationContact.PersonInfo_RefID       = personInfoID;
                communicationContact.Content = Parameter.Email;
                communicationContact.Save(Connection, Transaction);
                Guid CommunicationContactTypeID = communicationContact.Contact_Type;

                var communicationContactType = new ORM_CMN_PER_CommunicationContact_Type();
                communicationContactType.IsDeleted    = false;
                communicationContactType.Tenant_RefID = securityTicket.TenantID;
                communicationContactType.CMN_PER_CommunicationContact_TypeID = CommunicationContactTypeID;
                communicationContactType.Type = "Email";
                communicationContactType.Save(Connection, Transaction);

                var communicationContact2 = new ORM_CMN_PER_CommunicationContact();
                communicationContact2.IsDeleted              = false;
                communicationContact2.Contact_Type           = Guid.NewGuid();
                communicationContact2.Tenant_RefID           = securityTicket.TenantID;
                communicationContact2.Modification_Timestamp = DateTime.Now;
                communicationContact2.PersonInfo_RefID       = personInfoID;
                communicationContact2.Content = Parameter.Phone;
                communicationContact2.Save(Connection, Transaction);
                Guid CommunicationContactTypeID2 = communicationContact2.Contact_Type;


                var communicationContactType2 = new ORM_CMN_PER_CommunicationContact_Type();
                communicationContactType2.IsDeleted    = false;
                communicationContactType2.Tenant_RefID = securityTicket.TenantID;
                communicationContactType2.CMN_PER_CommunicationContact_TypeID = CommunicationContactTypeID2;
                communicationContactType2.Type = "Phone";
                communicationContactType2.Save(Connection, Transaction);

                var doctor = new ORM_HEC_Doctor();
                doctor.HEC_DoctorID = Guid.NewGuid();
                doctor.IsDeleted    = false;
                doctor.Tenant_RefID = securityTicket.TenantID;
                doctor.BusinessParticipant_RefID = BusinessParticipantID;
                doctor.DoctorIDNumber            = Parameter.LANR.ToString();
                doctor.Save(Connection, Transaction);

                doctor_id = doctor.HEC_DoctorID;

                var ogranizationUnitPractice = ORM_CMN_BPT_CTM_OrganizationalUnit.Query.Search(Connection, Transaction, new ORM_CMN_BPT_CTM_OrganizationalUnit.Query()
                {
                    IsDeleted    = false,
                    Tenant_RefID = securityTicket.TenantID,
                    IfMedicalPractise_HEC_MedicalPractice_RefID = Parameter.PracticeID
                }).Single();


                var organizationalunit_Staff = new ORM_CMN_BPT_CTM_OrganizationalUnit_Staff();
                organizationalunit_Staff.IsDeleted    = false;
                organizationalunit_Staff.Tenant_RefID = securityTicket.TenantID;
                organizationalunit_Staff.BusinessParticipant_RefID = BusinessParticipantID;
                organizationalunit_Staff.OrganizationalUnit_RefID  = ogranizationUnitPractice.CMN_BPT_CTM_OrganizationalUnitID;
                organizationalunit_Staff.Save(Connection, Transaction);


                var CustomerPRactice = ORM_CMN_BPT_CTM_Customer.Query.Search(Connection, Transaction, new ORM_CMN_BPT_CTM_Customer.Query()
                {
                    IsDeleted              = false,
                    Tenant_RefID           = securityTicket.TenantID,
                    CMN_BPT_CTM_CustomerID = ogranizationUnitPractice.Customer_RefID
                }).Single();
                var PracticeBusinessParticipant = ORM_CMN_BPT_BusinessParticipant.Query.Search(Connection, Transaction, new ORM_CMN_BPT_BusinessParticipant.Query()
                {
                    IsDeleted    = false,
                    Tenant_RefID = securityTicket.TenantID,
                    CMN_BPT_BusinessParticipantID = CustomerPRactice.Ext_BusinessParticipant_RefID
                }).Single();
                PracticeName = PracticeBusinessParticipant.DisplayName;
                PracticeBusinessParticipantID = PracticeBusinessParticipant.CMN_BPT_BusinessParticipantID;
                PracticeCompanyInfoID         = PracticeBusinessParticipant.IfCompany_CMN_COM_CompanyInfo_RefID;
                if (Parameter.From_Practice_Bank == true)
                {
                    var PracticeBusinessParticipant2bankaccount = ORM_CMN_BPT_BusinessParticipant_2_BankAccount.Query.Search(Connection, Transaction, new ORM_CMN_BPT_BusinessParticipant_2_BankAccount.Query()
                    {
                        IsDeleted    = false,
                        Tenant_RefID = securityTicket.TenantID,
                        CMN_BPT_BusinessParticipant_RefID = PracticeBusinessParticipant.CMN_BPT_BusinessParticipantID,
                    }).Single();


                    var business2bankAccount = new ORM_CMN_BPT_BusinessParticipant_2_BankAccount();
                    business2bankAccount.IsDeleted    = false;
                    business2bankAccount.Tenant_RefID = securityTicket.TenantID;
                    business2bankAccount.CMN_BPT_BusinessParticipant_RefID = BusinessParticipantID;
                    business2bankAccount.ACC_BNK_BankAccount_RefID         = PracticeBusinessParticipant2bankaccount.ACC_BNK_BankAccount_RefID;
                    business2bankAccount.Creation_Timestamp = DateTime.Now;
                    business2bankAccount.Save(Connection, Transaction);

                    BankAccountID = PracticeBusinessParticipant2bankaccount.ACC_BNK_BankAccount_RefID;
                    //end of save bank data if inherited from practice
                }
                else
                {
                    if (!String.IsNullOrEmpty(Parameter.IBAN) || !String.IsNullOrEmpty(Parameter.Bank))
                    {
                        var business2bankAccount = new ORM_CMN_BPT_BusinessParticipant_2_BankAccount();
                        business2bankAccount.IsDeleted    = false;
                        business2bankAccount.Tenant_RefID = securityTicket.TenantID;
                        business2bankAccount.CMN_BPT_BusinessParticipant_RefID = BusinessParticipantID;
                        business2bankAccount.ACC_BNK_BankAccount_RefID         = Guid.NewGuid();
                        business2bankAccount.Creation_Timestamp = DateTime.Now;
                        business2bankAccount.Save(Connection, Transaction);

                        var bankAccountDoctor = new ORM_ACC_BNK_BankAccount();
                        bankAccountDoctor.IsDeleted             = false;
                        bankAccountDoctor.Tenant_RefID          = securityTicket.TenantID;
                        bankAccountDoctor.ACC_BNK_BankAccountID = business2bankAccount.ACC_BNK_BankAccount_RefID;
                        bankAccountDoctor.OwnerText             = Parameter.Account_Holder;
                        bankAccountDoctor.IBAN               = Parameter.IBAN;
                        bankAccountDoctor.Bank_RefID         = Guid.NewGuid();
                        bankAccountDoctor.Creation_Timestamp = DateTime.Now;
                        bankAccountDoctor.Save(Connection, Transaction);

                        if (!String.IsNullOrEmpty(Parameter.Bank))
                        {
                            var bank = new ORM_ACC_BNK_Bank();
                            bank.IsDeleted          = false;
                            bank.Tenant_RefID       = securityTicket.TenantID;
                            bank.ACC_BNK_BankID     = bankAccountDoctor.Bank_RefID;
                            bank.BICCode            = Parameter.BIC;
                            bank.BankName           = Parameter.Bank;
                            bank.Creation_Timestamp = DateTime.Now;
                            bank.Save(Connection, Transaction);
                        }

                        BankAccountID = business2bankAccount.ACC_BNK_BankAccount_RefID;
                        // end save bank data
                    }
                }
            }
            var PracticeCompanyInfoAddress = ORM_CMN_COM_CompanyInfo_Address.Query.Search(Connection, Transaction, new ORM_CMN_COM_CompanyInfo_Address.Query()
            {
                IsDeleted           = false,
                Tenant_RefID        = securityTicket.TenantID,
                CompanyInfo_RefID   = PracticeCompanyInfoID,
                Address_Description = "Standard address for billing, shipping",
            }).SingleOrDefault();

            Practice_Doctors_Model DPModel = new Practice_Doctors_Model();

            if (PracticeCompanyInfoAddress != null)
            {
                var PracticeUCD = ORM_CMN_UniversalContactDetail.Query.Search(Connection, Transaction, new ORM_CMN_UniversalContactDetail.Query()
                {
                    IsDeleted    = false,
                    Tenant_RefID = securityTicket.TenantID,
                    CMN_UniversalContactDetailID = PracticeCompanyInfoAddress.Address_UCD_RefID,
                }).SingleOrDefault();
                DPModel.address = PracticeUCD.Street_Name + " " + PracticeUCD.Street_Number;
                DPModel.zip     = PracticeUCD.ZIP;
                DPModel.city    = PracticeUCD.Town;
            }

            DPModel.account_status = "aktiv";
            DPModel.id             = doctor_id.ToString();

            var title = string.IsNullOrEmpty(Parameter.Title) ? "" : Parameter.Title.Trim();

            DPModel.name           = title + " " + Parameter.Last_Name + " " + Parameter.First_Name;
            DPModel.name_untouched = Parameter.Last_Name + " " + Parameter.First_Name;
            DPModel.bsnr_lanr      = Parameter.LANR.ToString();

            DPModel.salutation = title;

            DPModel.type = "Doctor";

            DPModel.bank = string.IsNullOrEmpty(Parameter.Bank) ? "" : Parameter.Bank;

            DPModel.bank_untouched = string.IsNullOrEmpty(Parameter.Bank) ? "" : Parameter.Bank;


            DPModel.phone = Parameter.Phone;

            DPModel.email = string.IsNullOrEmpty(Parameter.Email) ? "" : Parameter.Email;

            DPModel.iban = string.IsNullOrEmpty(Parameter.IBAN) ? "" : Parameter.IBAN;

            DPModel.bic = string.IsNullOrEmpty(Parameter.BIC) ? "" : Parameter.BIC;

            DPModel.bank_id             = BankAccountID.ToString();
            DPModel.bank_info_inherited = Parameter.From_Practice_Bank;
            DPModel.aditional_info      = "";
            DPModel.contract            = 0;


            DPModel.tenantid = securityTicket.TenantID.ToString();
            DPModel.practice_name_for_doctor = PracticeName;
            DPModel.practice_for_doctor_id   = Parameter.PracticeID.ToString();

            DPModel.role = isOpPractice ? "op" : "ac";

            List <Practice_Doctors_Model> DPModelL = new List <Practice_Doctors_Model>();
            DPModelL.Add(DPModel);

            Add_New_Practice.Import_Practice_Data_to_ElasticDB(DPModelL, securityTicket.TenantID.ToString());
            return(returnValue);

            #endregion UserCode
        }
Beispiel #12
0
        public static void ImportTestPatients(DbConnection Connection, DbTransaction Transaction, SessionSecurityTicket securityTicket, Guid medical_practice_id)
        {
            List <Patient_Model_xls> patientList        = new List <Patient_Model_xls>();
            List <Patient_Model>     elasticPatientList = new List <Patient_Model>();
            IFormatProvider          culture            = new System.Globalization.CultureInfo("de", true);

            string folder    = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName;
            string filePath  = Path.Combine(folder, "Excel\\german_names_sheet.xlsx");
            bool   hasHeader = true;

            System.Data.DataTable excelData = ExcelUtils.getDataFromExcelFile(filePath, hasHeader);

            foreach (System.Data.DataRow item in excelData.Rows)
            {
                if (item.ItemArray[0].ToString() == "")
                {
                    break;
                }
                Patient_Model_xls patientModel = new Patient_Model_xls();
                patientModel.name     = item.ItemArray[0].ToString();
                patientModel.LastName = item.ItemArray[1].ToString();
                patientModel.sex      = item.ItemArray[2].ToString();
                patientModel.birthday = DateTime.Parse(item.ItemArray[3].ToString(), culture, System.Globalization.DateTimeStyles.AssumeLocal);
                patientList.Add(patientModel);
            }

            List <string> StateCode_first_Caracter = new List <string>();

            StateCode_first_Caracter.Add("1");
            StateCode_first_Caracter.Add("3");
            StateCode_first_Caracter.Add("5");


            List <string> StateCode_fift_Caracter = new List <string>();

            StateCode_fift_Caracter.Add("1");
            StateCode_fift_Caracter.Add("4");
            StateCode_fift_Caracter.Add("6");
            StateCode_fift_Caracter.Add("7");
            StateCode_fift_Caracter.Add("8");
            StateCode_fift_Caracter.Add("9");
            StateCode_fift_Caracter.Add("D");
            StateCode_fift_Caracter.Add("F");
            StateCode_fift_Caracter.Add("A");
            StateCode_fift_Caracter.Add("C");
            StateCode_fift_Caracter.Add("S");
            StateCode_fift_Caracter.Add("P");
            StateCode_fift_Caracter.Add("E");
            StateCode_fift_Caracter.Add("N");
            StateCode_fift_Caracter.Add("M");
            StateCode_fift_Caracter.Add("X");
            StateCode_fift_Caracter.Add("L");
            StateCode_fift_Caracter.Add("K");

            int status_code_counter = 0;
            int status_fift_counter = 0;
            int counter             = 0;

            var medicalPracticeQuery = new ORM_HEC_HIS_HealthInsurance_Company.Query();

            medicalPracticeQuery.IsDeleted    = false;
            medicalPracticeQuery.Tenant_RefID = securityTicket.TenantID;

            var HIPList = ORM_HEC_HIS_HealthInsurance_Company.Query.Search(Connection, Transaction, medicalPracticeQuery).ToList();


            int i = 0;

            foreach (var item in patientList)
            {
                ORM_HEC_Patient patients = new ORM_HEC_Patient();
                patients.HEC_PatientID                     = Guid.NewGuid();
                patients.Tenant_RefID                      = securityTicket.TenantID;
                patients.Creation_Timestamp                = DateTime.Now;
                patients.Modification_Timestamp            = DateTime.Now;
                patients.CMN_BPT_BusinessParticipant_RefID = Guid.NewGuid();
                patients.Save(Connection, Transaction);

                ORM_CMN_BPT_BusinessParticipant businesParticipantPatient = new ORM_CMN_BPT_BusinessParticipant();
                businesParticipantPatient.CMN_BPT_BusinessParticipantID = patients.CMN_BPT_BusinessParticipant_RefID;
                businesParticipantPatient.Tenant_RefID           = securityTicket.TenantID;
                businesParticipantPatient.Creation_Timestamp     = DateTime.Now;
                businesParticipantPatient.Modification_Timestamp = DateTime.Now;
                businesParticipantPatient.IsNaturalPerson        = true;
                businesParticipantPatient.IfNaturalPerson_CMN_PER_PersonInfo_RefID = Guid.NewGuid();
                businesParticipantPatient.Save(Connection, Transaction);

                ORM_CMN_PER_PersonInfo personInfo = new ORM_CMN_PER_PersonInfo();
                personInfo.CMN_PER_PersonInfoID   = businesParticipantPatient.IfNaturalPerson_CMN_PER_PersonInfo_RefID;
                personInfo.Tenant_RefID           = securityTicket.TenantID;
                personInfo.Creation_Timestamp     = DateTime.Now;
                personInfo.Modification_Timestamp = DateTime.Now;
                personInfo.FirstName = item.name;           //
                personInfo.LastName  = item.LastName;       //
                personInfo.BirthDate = item.birthday;       //
                personInfo.Gender    = int.Parse(item.sex); //
                personInfo.Save(Connection, Transaction);

                ORM_HEC_Patient_MedicalPractice medical_practice_to_patient = new ORM_HEC_Patient_MedicalPractice();
                medical_practice_to_patient.HEC_Patient_MedicalPracticeID = Guid.NewGuid();
                medical_practice_to_patient.HEC_Patient_RefID             = patients.HEC_PatientID;
                medical_practice_to_patient.HEC_MedicalPractices_RefID    = medical_practice_id;//
                medical_practice_to_patient.Tenant_RefID       = securityTicket.TenantID;
                medical_practice_to_patient.Creation_Timestamp = DateTime.Now;
                medical_practice_to_patient.Save(Connection, Transaction);


                ORM_HEC_Patient_HealthInsurance patientHealthInsurance = new ORM_HEC_Patient_HealthInsurance();
                patientHealthInsurance.HEC_Patient_HealthInsurancesID = Guid.NewGuid();
                patientHealthInsurance.Patient_RefID = patients.HEC_PatientID;

                Random rnd = new Random();
                int    random_insurance_number = rnd.Next(10000000, 99999999);

                int genre = 0;
                switch (int.Parse(item.sex))
                {
                case 0:
                    genre = 2;
                    break;

                case 1:
                    genre = 1;
                    break;

                case 2:
                    genre = 0;
                    break;
                }

                var birth = item.birthday.Year.ToString().Substring(2);
                patientHealthInsurance.HealthInsurance_Number            = random_insurance_number.ToString();                                                                                      //
                patientHealthInsurance.Tenant_RefID                      = securityTicket.TenantID;
                patientHealthInsurance.InsuranceStateCode                = StateCode_first_Caracter[status_code_counter] + genre.ToString() + birth + StateCode_fift_Caracter[status_fift_counter]; //
                patientHealthInsurance.HIS_HealthInsurance_Company_RefID = HIPList[i].HEC_HealthInsurance_CompanyID;
                patientHealthInsurance.Save(Connection, Transaction);


                if (status_code_counter == 2)
                {
                    status_code_counter = 0;
                }
                else
                {
                    status_code_counter++;
                }

                if (status_fift_counter == 17)
                {
                    status_fift_counter = 0;
                }
                else
                {
                    status_fift_counter++;
                }

                if (i == HIPList.Count - 1)
                {
                    i = 0;
                }
                else
                {
                    i++;
                }


                var businesParticipantHIPQuery = new ORM_CMN_BPT_BusinessParticipant.Query();
                businesParticipantHIPQuery.IsDeleted    = false;
                businesParticipantHIPQuery.Tenant_RefID = securityTicket.TenantID;
                businesParticipantHIPQuery.CMN_BPT_BusinessParticipantID = HIPList[i].CMN_BPT_BusinessParticipant_RefID;

                var businesParticipantHIP = ORM_CMN_BPT_BusinessParticipant.Query.Search(Connection, Transaction, businesParticipantHIPQuery).Single();;

                Patient_Model patientModel = new Patient_Model();


                patientModel.birthday                  = DateTime.Parse(item.birthday.ToString("dd.MM.yyyy"), culture, System.Globalization.DateTimeStyles.AssumeLocal);
                patientModel.birthday_string           = item.birthday.ToString("dd.MM.yyyy");
                patientModel.name                      = item.LastName + ", " + item.name;
                patientModel.health_insurance_provider = businesParticipantHIP.DisplayName;
                patientModel.name_with_birthdate       = item.name + " " + item.LastName + " (" + item.birthday.ToString("dd.MM.yyyy") + ")";
                patientModel.id               = patients.HEC_PatientID.ToString();
                patientModel.insurance_id     = patientHealthInsurance.HealthInsurance_Number;
                patientModel.insurance_status = patientHealthInsurance.InsuranceStateCode;
                patientModel.practice_id      = medical_practice_id.ToString();

                if (int.Parse(item.sex) == 0)
                {
                    patientModel.sex = "M";
                }
                else if (int.Parse(item.sex) == 1)
                {
                    patientModel.sex = "W";
                }
                else if (int.Parse(item.sex) == 2)
                {
                    patientModel.sex = "o.A.";
                }


                elasticPatientList.Add(patientModel);



                counter++;
                Console.WriteLine(counter + "________________________" + patientList.Count);
            }



            string indexElastic = securityTicket.TenantID.ToString();
            var    serializer   = new JsonNetSerializer();
            var    connection   = Elastic_Utils.ElsaticConnection();

            bool checkIndex = Elastic_Utils.IfIndexOrTypeExists(indexElastic, connection);


            if (!checkIndex)
            {
                string settings = Elastic_Utils.BuildIndexSettings();
                connection.Put(indexElastic, settings);

                string jsonProductMapping   = Add_New_Patient.BuildPatientMapping();
                string resultProductMapping = connection.Put(new PutMappingCommand(indexElastic, "patient"), jsonProductMapping);
            }

            bool checkTupe = Elastic_Utils.IfIndexOrTypeExists(indexElastic + "/patient", connection);

            if (!checkTupe)
            {
                string jsonProductMapping   = Add_New_Patient.BuildPatientMapping();
                string resultProductMapping = connection.Put(new PutMappingCommand(indexElastic, "patient"), jsonProductMapping);
            }
            Elastic_Utils.BulkType_Generic <Patient_Model>(elasticPatientList, connection, serializer, indexElastic, "patient");
        }
Beispiel #13
0
        protected static FR_Bool Execute(DbConnection Connection, DbTransaction Transaction, P_L5PA_SPEM_1413 Parameter, CSV2Core.SessionSecurity.SessionSecurityTicket securityTicket = null)
        {
            #region UserCode
            var returnValue = new FR_Bool();

            var medPro_Credentials = cls_Get_TenantMemershipData.Invoke(Connection, Transaction, securityTicket).Result;

            P_L2LN_GALFTID_1530 langParam = new P_L2LN_GALFTID_1530();
            langParam.Tenant_RefID = securityTicket.TenantID;
            var DBLanguages = cls_Get_All_Languages_ForTenantID.Invoke(Connection, Transaction, langParam, securityTicket).Result;

            var examination = ORM_HEC_ACT_PerformedAction.Query.Search(Connection, Transaction, new ORM_HEC_ACT_PerformedAction.Query()
            {
                IsDeleted    = false,
                Tenant_RefID = securityTicket.TenantID,
                HEC_ACT_PerformedActionID = Parameter.ExaminationID
            }).Single();
            #region Save

            foreach (var item in Parameter.new_medication)
            {
                //check if dosage exists

                var dosageQuery = new ORM_HEC_Dosage.Query();
                dosageQuery.IsDeleted    = false;
                dosageQuery.Tenant_RefID = securityTicket.TenantID;
                dosageQuery.DosageText   = item.dosage_text;

                var dosage_table = ORM_HEC_Dosage.Query.Search(Connection, Transaction, dosageQuery).SingleOrDefault();

                if (dosage_table == null)
                {
                    dosage_table = new ORM_HEC_Dosage();
                    dosage_table.HEC_DosageID           = Guid.NewGuid();
                    dosage_table.Tenant_RefID           = securityTicket.TenantID;
                    dosage_table.Creation_Timestamp     = DateTime.Now;
                    dosage_table.Modification_Timestamp = DateTime.Now;
                    dosage_table.DosageText             = item.dosage_text;
                    dosage_table.Save(Connection, Transaction);
                }

                ORM_HEC_ACT_PerformedAction_MedicationUpdate medicationUpdate = new ORM_HEC_ACT_PerformedAction_MedicationUpdate();
                medicationUpdate.HEC_ACT_PerformedAction_MedicationUpdateID = Guid.NewGuid();
                medicationUpdate.Tenant_RefID           = securityTicket.TenantID;
                medicationUpdate.Creation_Timestamp     = DateTime.Now;
                medicationUpdate.Modification_Timestamp = DateTime.Now;
                medicationUpdate.IsSubstance            = !item.is_product;
                medicationUpdate.IsHealthcareProduct    = item.is_product;
                medicationUpdate.IntendedApplicationDuration_in_days = item.days_valid;
                medicationUpdate.HEC_ACT_PerformedAction_RefID       = Parameter.ExaminationID;
                medicationUpdate.HEC_Patient_Medication_RefID        = Guid.NewGuid();

                ORM_HEC_Patient_Medication patient_medications = new ORM_HEC_Patient_Medication();
                patient_medications.HEC_Patient_MedicationID = medicationUpdate.HEC_Patient_Medication_RefID;
                patient_medications.Patient_RefID            = Parameter.PatientID;
                patient_medications.Creation_Timestamp       = DateTime.Now;
                patient_medications.Tenant_RefID             = securityTicket.TenantID;
                patient_medications.Modification_Timestamp   = DateTime.Now;
                patient_medications.R_IsActive            = true;
                patient_medications.R_DateOfAdding        = examination.IfPerfomed_DateOfAction;
                patient_medications.R_IsHealthcareProduct = item.is_product;
                patient_medications.R_IsSubstance         = !item.is_product;
                patient_medications.R_ActiveUntill        = patient_medications.R_DateOfAdding.AddDays(item.days_valid);


                if (item.is_product)//medication is a product
                {
                    Guid Hec_ProductID = Guid.Empty;

                    //check if product exists
                    var productQuery = new ORM_CMN_PRO_Product.Query();
                    productQuery.Tenant_RefID = securityTicket.TenantID;
                    productQuery.IsDeleted    = false;
                    productQuery.ProductITL   = item.product_itl;

                    var product = ORM_CMN_PRO_Product.Query.Search(Connection, Transaction, productQuery).SingleOrDefault();

                    //if product does not exist create it
                    if (product == null)
                    {
                        ORM_CMN_PRO_Product cmn_pro_product = new ORM_CMN_PRO_Product();
                        cmn_pro_product.CMN_PRO_ProductID      = Guid.NewGuid();
                        cmn_pro_product.Tenant_RefID           = securityTicket.TenantID;
                        cmn_pro_product.Creation_Timestamp     = DateTime.Now;
                        cmn_pro_product.Modification_Timestamp = DateTime.Now;

                        Dict product_name = new Dict("cmn_pro_products");
                        for (int i = 0; i < DBLanguages.Length; i++)
                        {
                            product_name.AddEntry(DBLanguages[i].CMN_LanguageID, item.product_name);
                        }

                        cmn_pro_product.Product_Name = product_name;
                        cmn_pro_product.ProductITL   = item.product_itl;
                        cmn_pro_product.ProducingBusinessParticipant_RefID = Guid.NewGuid(); //manufacturer
                        cmn_pro_product.PackageInfo_RefID = Guid.NewGuid();                  // package info
                        cmn_pro_product.Save(Connection, Transaction);

                        ORM_CMN_BPT_BusinessParticipant manufacturer = new ORM_CMN_BPT_BusinessParticipant();
                        manufacturer.CMN_BPT_BusinessParticipantID = cmn_pro_product.ProducingBusinessParticipant_RefID;
                        manufacturer.DisplayName            = item.product_manufacturer;
                        manufacturer.IsCompany              = true;
                        manufacturer.IsNaturalPerson        = false;
                        manufacturer.Tenant_RefID           = securityTicket.TenantID;
                        manufacturer.Creation_Timestamp     = DateTime.Now;
                        manufacturer.Modification_Timestamp = DateTime.Now;
                        manufacturer.Save(Connection, Transaction);

                        ORM_CMN_PRO_PAC_PackageInfo package_info = new ORM_CMN_PRO_PAC_PackageInfo();
                        package_info.CMN_PRO_PAC_PackageInfoID = cmn_pro_product.PackageInfo_RefID;
                        package_info.Tenant_RefID           = securityTicket.TenantID;
                        package_info.Creation_Timestamp     = DateTime.Now;
                        package_info.Modification_Timestamp = DateTime.Now;

                        string amount = String.Empty;
                        string unit   = String.Empty;
                        foreach (char c in item.product_strength)
                        {
                            // Do not use IsDigit as it will include more than the characters 0 through to 9
                            if (c >= '0' && c <= '9')
                            {
                                amount += c;
                            }
                            else
                            {
                                unit += c;
                            }
                        }
                        package_info.PackageContent_Amount       = Int32.Parse(amount);
                        package_info.PackageContent_DisplayLabel = amount;


                        var unitQuery = new ORM_CMN_Unit.Query();
                        unitQuery.IsDeleted    = false;
                        unitQuery.Tenant_RefID = securityTicket.TenantID;
                        unitQuery.ISOCode      = unit;

                        var cmn_unit = ORM_CMN_Unit.Query.Search(Connection, Transaction, unitQuery).FirstOrDefault();

                        if (cmn_unit == null)
                        {
                            cmn_unit                        = new ORM_CMN_Unit();
                            cmn_unit.CMN_UnitID             = Guid.NewGuid();
                            cmn_unit.Tenant_RefID           = securityTicket.TenantID;
                            cmn_unit.Creation_Timestamp     = DateTime.Now;
                            cmn_unit.Modification_Timestamp = DateTime.Now;
                            cmn_unit.ISOCode                = unit;
                            cmn_unit.Save(Connection, Transaction);
                        }

                        package_info.PackageContent_MeasuredInUnit_RefID = cmn_unit.CMN_UnitID;
                        package_info.Save(Connection, Transaction);


                        //hec_products
                        ORM_HEC_Product hec_product = new ORM_HEC_Product();
                        hec_product.HEC_ProductID          = Guid.NewGuid();
                        hec_product.Ext_PRO_Product_RefID  = cmn_pro_product.CMN_PRO_ProductID;
                        hec_product.Tenant_RefID           = securityTicket.TenantID;
                        hec_product.Creation_Timestamp     = DateTime.Now;
                        hec_product.Modification_Timestamp = DateTime.Now;

                        Hec_ProductID = hec_product.HEC_ProductID;

                        var dosage_formQuery = new ORM_HEC_Product_DosageForm.Query();
                        dosage_formQuery.Tenant_RefID             = securityTicket.TenantID;
                        dosage_formQuery.IsDeleted                = false;
                        dosage_formQuery.GlobalPropertyMatchingID = item.product_form;

                        var dosage_form = ORM_HEC_Product_DosageForm.Query.Search(Connection, Transaction, dosage_formQuery).SingleOrDefault();

                        if (dosage_form == null)
                        {
                            dosage_form = new ORM_HEC_Product_DosageForm();
                            dosage_form.HEC_Product_DosageFormID = Guid.NewGuid();
                            dosage_form.GlobalPropertyMatchingID = item.product_form;
                            dosage_form.Tenant_RefID             = securityTicket.TenantID;
                            dosage_form.Creation_Timestamp       = DateTime.Now;
                            dosage_form.Modification_Timestamp   = DateTime.Now;

                            Dict form_name = new Dict("hec_product_dosageforms");
                            for (int i = 0; i < DBLanguages.Length; i++)
                            {
                                form_name.AddEntry(DBLanguages[i].CMN_LanguageID, item.product_form);
                            }
                            dosage_form.DosageForm_Name = form_name;
                            dosage_form.Save(Connection, Transaction);
                        }

                        hec_product.ProductDosageForm_RefID = dosage_form.HEC_Product_DosageFormID;  //dosage form
                        hec_product.Save(Connection, Transaction);


                        //product component

                        ORM_HEC_PRO_Product_Component product_component = new ORM_HEC_PRO_Product_Component();
                        product_component.HEC_PRO_Product_ComponentID = Guid.NewGuid();
                        product_component.HEC_PRO_Component_RefID     = Guid.NewGuid();//pro_component
                        product_component.HEC_PRO_Product_RefID       = hec_product.HEC_ProductID;
                        product_component.Tenant_RefID           = securityTicket.TenantID;
                        product_component.Creation_Timestamp     = DateTime.Now;
                        product_component.Modification_Timestamp = DateTime.Now;
                        product_component.Save(Connection, Transaction);

                        ORM_HEC_PRO_Component pro_component = new ORM_HEC_PRO_Component();
                        pro_component.HEC_PRO_ComponentID    = product_component.HEC_PRO_Component_RefID;
                        pro_component.Tenant_RefID           = securityTicket.TenantID;
                        pro_component.Creation_Timestamp     = DateTime.Now;
                        pro_component.Modification_Timestamp = DateTime.Now;
                        pro_component.Save(Connection, Transaction);

                        ORM_HEC_PRO_Component_SubstanceIngredient component_SubstanceIngredient = new ORM_HEC_PRO_Component_SubstanceIngredient();
                        component_SubstanceIngredient.HEC_PRO_Component_SubstanceIngredientID = Guid.NewGuid();
                        component_SubstanceIngredient.Component_RefID        = pro_component.HEC_PRO_ComponentID;
                        component_SubstanceIngredient.Tenant_RefID           = securityTicket.TenantID;
                        component_SubstanceIngredient.Creation_Timestamp     = DateTime.Now;
                        component_SubstanceIngredient.Modification_Timestamp = DateTime.Now;


                        var substanceQuery = new ORM_HEC_SUB_Substance.Query();
                        substanceQuery.IsDeleted              = false;
                        substanceQuery.Tenant_RefID           = securityTicket.TenantID;
                        substanceQuery.HealthcareSubstanceITL = item.substance_itl;

                        var substance = ORM_HEC_SUB_Substance.Query.Search(Connection, Transaction, substanceQuery).SingleOrDefault();

                        if (substance == null)
                        {
                            substance = new ORM_HEC_SUB_Substance();
                            substance.HealthcareSubstanceITL   = item.substance_itl;
                            substance.HEC_SUB_SubstanceID      = Guid.NewGuid();
                            substance.GlobalPropertyMatchingID = item.substance_name;
                            substance.Tenant_RefID             = securityTicket.TenantID;
                            substance.Creation_Timestamp       = DateTime.Now;
                            substance.Modification_Timestamp   = DateTime.Now;
                            substance.Save(Connection, Transaction);

                            ORM_HEC_SUB_Substance_Name substance_name = new ORM_HEC_SUB_Substance_Name();
                            substance_name.HEC_SUB_Substance_NameID = Guid.NewGuid();
                            substance_name.HEC_SUB_Substance_RefID  = substance.HEC_SUB_SubstanceID;

                            Dict substance_name_ = new Dict("hec_sub_substance_names");
                            for (int i = 0; i < DBLanguages.Length; i++)
                            {
                                substance_name_.AddEntry(DBLanguages[i].CMN_LanguageID, item.substance_name);
                            }
                            substance_name.SubstanceName_Label    = substance_name_;
                            substance_name.Tenant_RefID           = securityTicket.TenantID;
                            substance_name.Creation_Timestamp     = DateTime.Now;
                            substance_name.Modification_Timestamp = DateTime.Now;
                            substance_name.Save(Connection, Transaction);
                        }

                        component_SubstanceIngredient.Substance_RefID = substance.HEC_SUB_SubstanceID;
                        component_SubstanceIngredient.Save(Connection, Transaction);
                    }
                    else
                    {
                        var hec_productQuery = new ORM_HEC_Product.Query();
                        hec_productQuery.IsDeleted             = false;
                        hec_productQuery.Tenant_RefID          = securityTicket.TenantID;
                        hec_productQuery.Ext_PRO_Product_RefID = product.CMN_PRO_ProductID;

                        var hec_product = ORM_HEC_Product.Query.Search(Connection, Transaction, hec_productQuery).Single();

                        Hec_ProductID = hec_product.HEC_ProductID;
                    }


                    medicationUpdate.HEC_Product_RefID      = Hec_ProductID;
                    patient_medications.R_HEC_Product_RefID = Hec_ProductID;
                    patient_medications.R_DosageText        = item.dosage_text;
                    medicationUpdate.DosageText             = item.dosage_text;
                }
                else// medication is a substance
                {
                    medicationUpdate.IfSubstance_Strength        = item.substance_strength;
                    patient_medications.R_IfSubstance_Strength   = item.substance_strength;
                    medicationUpdate.IfSubstance_Unit_RefID      = item.substance_unit;
                    patient_medications.R_IfSubstance_Unit_RefID = item.substance_unit;
                    patient_medications.R_DosageText             = item.dosage_text;
                    medicationUpdate.DosageText = item.dosage_text;

                    var substanceQuery = new ORM_HEC_SUB_Substance.Query();
                    substanceQuery.IsDeleted              = false;
                    substanceQuery.Tenant_RefID           = securityTicket.TenantID;
                    substanceQuery.HealthcareSubstanceITL = item.substance_itl;

                    var substance = ORM_HEC_SUB_Substance.Query.Search(Connection, Transaction, substanceQuery).SingleOrDefault();

                    if (substance == null)
                    {
                        substance = new ORM_HEC_SUB_Substance();
                        substance.HealthcareSubstanceITL   = item.substance_itl;
                        substance.HEC_SUB_SubstanceID      = Guid.NewGuid();
                        substance.GlobalPropertyMatchingID = item.substance_name;
                        substance.Tenant_RefID             = securityTicket.TenantID;
                        substance.Creation_Timestamp       = DateTime.Now;
                        substance.Modification_Timestamp   = DateTime.Now;
                        substance.Save(Connection, Transaction);

                        ORM_HEC_SUB_Substance_Name substance_name = new ORM_HEC_SUB_Substance_Name();
                        substance_name.HEC_SUB_Substance_NameID = Guid.NewGuid();
                        substance_name.HEC_SUB_Substance_RefID  = substance.HEC_SUB_SubstanceID;

                        Dict substance_name_ = new Dict("hec_sub_substance_names");
                        for (int i = 0; i < DBLanguages.Length; i++)
                        {
                            substance_name_.AddEntry(DBLanguages[i].CMN_LanguageID, item.substance_name);
                        }
                        substance_name.SubstanceName_Label    = substance_name_;
                        substance_name.Tenant_RefID           = securityTicket.TenantID;
                        substance_name.Creation_Timestamp     = DateTime.Now;
                        substance_name.Modification_Timestamp = DateTime.Now;
                        substance_name.Save(Connection, Transaction);
                    }

                    medicationUpdate.IfSubstance_Substance_RefiD      = substance.HEC_SUB_SubstanceID;
                    patient_medications.R_IfSubstance_Substance_RefiD = substance.HEC_SUB_SubstanceID;
                }

                patient_medications.Save(Connection, Transaction);
                medicationUpdate.Save(Connection, Transaction);
                returnValue.Result = true;
            }

            #endregion

            #region Delete
            foreach (var item in Parameter.deleted_medications)
            {
                var medicationUpdateQuery = new ORM_HEC_ACT_PerformedAction_MedicationUpdate.Query();
                medicationUpdateQuery.IsDeleted = false;
                medicationUpdateQuery.IsMedicationDeactivated = false;
                medicationUpdateQuery.Tenant_RefID            = securityTicket.TenantID;
                medicationUpdateQuery.HEC_ACT_PerformedAction_MedicationUpdateID = item.performedAction_medicationUpdate_id;

                var medicationUpdate = ORM_HEC_ACT_PerformedAction_MedicationUpdate.Query.Search(Connection, Transaction, medicationUpdateQuery).Single();
                medicationUpdate.IsMedicationDeactivated = true;
                medicationUpdate.Save(Connection, Transaction);
            }

            #endregion
            return(returnValue);

            #endregion UserCode
        }
        protected static FR_Guid Execute(DbConnection Connection, DbTransaction Transaction, P_L6MB_CUMBE_2302 Parameter, CSV2Core.SessionSecurity.SessionSecurityTicket securityTicket = null)
        {
            #region UserCode
            var returnValue = new FR_Guid();

            var statusUploaded = ORM_MRS_RUN_MeasurementRun_Status.Query.Search(Connection, Transaction, new ORM_MRS_RUN_MeasurementRun_Status.Query()
            {
                GlobalPropertyMatchingID = EnumUtils.GetEnumDescription(MeasurementRunStatus.Uploaded),
                Tenant_RefID             = securityTicket.TenantID,
                IsDeleted = false
            }).Single();

            var run = new ORM_MRS_RUN_MeasurementRun()
            {
                Tenant_RefID             = securityTicket.TenantID,
                MRS_RUN_MeasurementRunID = Guid.NewGuid(),
                DateFrom            = DateTime.Now,
                DateThrough         = DateTime.MaxValue,
                CurrentStatus_RefID = statusUploaded.MRS_RUN_MeasurementRun_StatusID
            };

            returnValue.Result = run.MRS_RUN_MeasurementRunID;

            var account = ORM_USR_Account.Query.Search(Connection, Transaction, new ORM_USR_Account.Query()
            {
                Tenant_RefID  = securityTicket.TenantID,
                USR_AccountID = securityTicket.AccountID
            }).Single();


            var runHistory = new ORM_MRS_RUN_MeasurementRun_StatusHistory()
            {
                Tenant_RefID = securityTicket.TenantID,
                MRS_RUN_MeasurementRun_StatusHistoryID = Guid.NewGuid(),
                MeasurementRun_Status_RefID            = statusUploaded.MRS_RUN_MeasurementRun_StatusID,
                TriggeredBy_BusinessParticipant_RefID  = account.BusinessParticipant_RefID,
                MeasurementRun_RefID = run.MRS_RUN_MeasurementRunID,
                Comment = string.Empty
            };

            run.Save(Connection, Transaction);
            runHistory.Save(Connection, Transaction);

            foreach (var row in Parameter.Positions)
            {
                #region reader
                var readerPersonInfo = ORM_CMN_PER_PersonInfo.Query.Search(Connection, Transaction, new ORM_CMN_PER_PersonInfo.Query()
                {
                    Tenant_RefID = securityTicket.TenantID,
                    IsDeleted    = false,
                    PrimaryEmail = row.ReaderEmail
                }).SingleOrDefault();

                if (readerPersonInfo == null)
                {
                    readerPersonInfo = new ORM_CMN_PER_PersonInfo()
                    {
                        Tenant_RefID         = securityTicket.TenantID,
                        PrimaryEmail         = row.ReaderEmail,
                        CMN_PER_PersonInfoID = Guid.NewGuid()
                    };
                }

                readerPersonInfo.FirstName = row.ReaderFirstName;
                readerPersonInfo.LastName  = row.ReaderLastName;

                readerPersonInfo.Save(Connection, Transaction);

                var readerBP = ORM_CMN_BPT_BusinessParticipant.Query.Search(Connection, Transaction, new ORM_CMN_BPT_BusinessParticipant.Query()
                {
                    Tenant_RefID    = securityTicket.TenantID,
                    IsDeleted       = false,
                    IsNaturalPerson = true,
                    IfNaturalPerson_CMN_PER_PersonInfo_RefID = readerPersonInfo.CMN_PER_PersonInfoID
                }).SingleOrDefault();

                if (readerBP == null)
                {
                    readerBP = new ORM_CMN_BPT_BusinessParticipant()
                    {
                        CMN_BPT_BusinessParticipantID = Guid.NewGuid(),
                        Tenant_RefID    = securityTicket.TenantID,
                        IsNaturalPerson = true,
                        IfNaturalPerson_CMN_PER_PersonInfo_RefID = readerPersonInfo.CMN_PER_PersonInfoID,
                    };

                    readerBP.Save(Connection, Transaction);
                }

                var bpCode = ORM_CMN_BPT_BusinessParticipant_AccessCode.Query.Search(Connection, Transaction, new ORM_CMN_BPT_BusinessParticipant_AccessCode.Query()
                {
                    Tenant_RefID = securityTicket.TenantID,
                    IsDeleted    = false,
                    BusinessParticipant_RefID = readerBP.CMN_BPT_BusinessParticipantID,
                    IsValid            = true,
                    IsDeviceAccessCode = true
                }).SingleOrDefault();

                if (bpCode == null)
                {
                    bpCode = new ORM_CMN_BPT_BusinessParticipant_AccessCode()
                    {
                        CMN_BPT_BusinessParticipant_AccessCodeID = Guid.NewGuid(),
                        Tenant_RefID = securityTicket.TenantID,
                        BusinessParticipant_RefID = readerBP.CMN_BPT_BusinessParticipantID,
                        IsValid            = true,
                        IsDeviceAccessCode = true,
                        ValidFrom          = DateTime.Now,
                        ValidThrough       = DateTime.MaxValue,
                        Code = StringUtils.CodeGen(8).ToLower()
                    };
                    bpCode.Save(Connection, Transaction);
                }

                #endregion

                #region meter
                var meter = ORM_MRS_MPT_Meter.Query.Search(Connection, Transaction, new ORM_MRS_MPT_Meter.Query()
                {
                    Tenant_RefID = securityTicket.TenantID,
                    IsDeleted    = false,
                    SerialNumber = row.MeterSerialNumber
                }).SingleOrDefault();

                if (meter == null)
                {
                    meter = new ORM_MRS_MPT_Meter()
                    {
                        MRS_MPT_MeterID = Guid.NewGuid(),
                        SerialNumber    = row.MeterSerialNumber,
                        Tenant_RefID    = securityTicket.TenantID,
                    };
                    meter.Save(Connection, Transaction);
                }

                var meterBinding = ORM_MRS_MPT_MeasuringPoint_MeterBinding.Query.Search(Connection, Transaction, new ORM_MRS_MPT_MeasuringPoint_MeterBinding.Query()
                {
                    Tenant_RefID = securityTicket.TenantID,
                    IsDeleted    = false,
                    Meter_RefID  = meter.MRS_MPT_MeterID
                }).SingleOrDefault();

                if (meterBinding == null)
                {
                    meterBinding = new ORM_MRS_MPT_MeasuringPoint_MeterBinding()
                    {
                        Tenant_RefID = securityTicket.TenantID,
                        ActiveFrom   = DateTime.Now,
                        Meter_RefID  = meter.MRS_MPT_MeterID,
                        MRS_MPT_MeasuringPoint_MeterBindingID = Guid.NewGuid()
                    };
                    meterBinding.Save(Connection, Transaction);
                }

                var measurentPoint = ORM_MRS_MPT_MeasuringPoint.Query.Search(Connection, Transaction, new ORM_MRS_MPT_MeasuringPoint.Query()
                {
                    Tenant_RefID             = securityTicket.TenantID,
                    IsDeleted                = false,
                    MRS_MPT_MeasuringPointID = meterBinding.MeasuringPoint_RefID
                }).SingleOrDefault();

                if (measurentPoint == null)
                {
                    measurentPoint = new ORM_MRS_MPT_MeasuringPoint()
                    {
                        Tenant_RefID             = securityTicket.TenantID,
                        MRS_MPT_MeasuringPointID = Guid.NewGuid()
                    };

                    meterBinding.MeasuringPoint_RefID = measurentPoint.MRS_MPT_MeasuringPointID;
                    meterBinding.Save(Connection, Transaction);

                    measurentPoint.Save(Connection, Transaction);
                }

                #endregion

                #region customer
                var customerOwnership = ORM_MRS_MPT_CustomerOwnership.Query.Search(Connection, Transaction, new ORM_MRS_MPT_CustomerOwnership.Query()
                {
                    Tenant_RefID   = securityTicket.TenantID,
                    IsDeleted      = false,
                    ContractNumber = row.ContractNumber
                }).SingleOrDefault();

                if (customerOwnership == null)
                {
                    var customerPersonInfo = new ORM_CMN_PER_PersonInfo()
                    {
                        Tenant_RefID         = securityTicket.TenantID,
                        FirstName            = row.ContractOwnerFirstName,
                        LastName             = row.ContractOwnerLastName,
                        CMN_PER_PersonInfoID = Guid.NewGuid()
                    };
                    customerPersonInfo.Save(Connection, Transaction);

                    var customerBP = new ORM_CMN_BPT_BusinessParticipant()
                    {
                        CMN_BPT_BusinessParticipantID = Guid.NewGuid(),
                        Tenant_RefID    = securityTicket.TenantID,
                        IsNaturalPerson = true,
                        IfNaturalPerson_CMN_PER_PersonInfo_RefID = customerPersonInfo.CMN_PER_PersonInfoID,
                    };
                    customerBP.Save(Connection, Transaction);

                    var customer = new ORM_CMN_BPT_CTM_Customer()
                    {
                        Tenant_RefID                  = securityTicket.TenantID,
                        CMN_BPT_CTM_CustomerID        = Guid.NewGuid(),
                        Ext_BusinessParticipant_RefID = customerBP.CMN_BPT_BusinessParticipantID
                    };
                    customer.Save(Connection, Transaction);

                    customerOwnership = new ORM_MRS_MPT_CustomerOwnership()
                    {
                        Tenant_RefID = securityTicket.TenantID,
                        MRS_MPT_CustomerOwnershipID = Guid.NewGuid(),
                        ContractNumber       = row.ContractNumber,
                        ValidFrom            = DateTime.Now,
                        Customer_RefID       = customer.CMN_BPT_CTM_CustomerID,
                        MeasuringPoint_RefID = measurentPoint.MRS_MPT_MeasuringPointID
                    };
                    customerOwnership.Save(Connection, Transaction);
                }
                else
                {
                    var customer = ORM_CMN_BPT_CTM_Customer.Query.Search(Connection, Transaction, new ORM_CMN_BPT_CTM_Customer.Query()
                    {
                        Tenant_RefID           = securityTicket.TenantID,
                        IsDeleted              = false,
                        CMN_BPT_CTM_CustomerID = customerOwnership.Customer_RefID
                    }).Single();

                    var customerBP = ORM_CMN_BPT_BusinessParticipant.Query.Search(Connection, Transaction, new ORM_CMN_BPT_BusinessParticipant.Query()
                    {
                        Tenant_RefID = securityTicket.TenantID,
                        IsDeleted    = false,
                        CMN_BPT_BusinessParticipantID = customer.Ext_BusinessParticipant_RefID
                    }).Single();

                    var customerPI = ORM_CMN_PER_PersonInfo.Query.Search(Connection, Transaction, new ORM_CMN_PER_PersonInfo.Query()
                    {
                        Tenant_RefID         = securityTicket.TenantID,
                        IsDeleted            = false,
                        CMN_PER_PersonInfoID = customerBP.IfNaturalPerson_CMN_PER_PersonInfo_RefID
                    }).Single();

                    customerPI.FirstName = row.ContractOwnerFirstName;
                    customerPI.LastName  = row.ContractOwnerLastName;
                    customerPI.Save(Connection, Transaction);
                }

                customerOwnership.MeasuringPoint_RefID = measurentPoint.MRS_MPT_MeasuringPointID;
                customerOwnership.Save(Connection, Transaction);

                #region address
                var address = ORM_CMN_Address.Query.Search(Connection, Transaction, new ORM_CMN_Address.Query()
                {
                    Tenant_RefID    = securityTicket.TenantID,
                    IsDeleted       = false,
                    City_Name       = row.City,
                    Street_Name     = row.AddressName,
                    Street_Number   = row.AddressNumber,
                    City_PostalCode = row.ZipCode
                }).SingleOrDefault();

                if (address == null)
                {
                    address = new ORM_CMN_Address()
                    {
                        Tenant_RefID    = securityTicket.TenantID,
                        City_Name       = row.City,
                        Street_Name     = row.AddressName,
                        Street_Number   = row.AddressNumber,
                        City_PostalCode = row.ZipCode,
                        CMN_AddressID   = Guid.NewGuid()
                    };
                    address.Save(Connection, Transaction);
                }

                measurentPoint.CurrentAddress_RefID = address.CMN_AddressID;
                measurentPoint.Save(Connection, Transaction);

                #endregion

                #endregion

                #region route

                var route = ORM_MRS_RUT_Route.Query.Search(Connection, Transaction, new ORM_MRS_RUT_Route.Query()
                {
                    Tenant_RefID = securityTicket.TenantID,
                    IsDeleted    = false,
                    DisplayName  = row.RouteName
                }).SingleOrDefault();

                if (route == null)
                {
                    route = new ORM_MRS_RUT_Route()
                    {
                        Tenant_RefID    = securityTicket.TenantID,
                        MRS_RUT_RouteID = Guid.NewGuid(),
                        DisplayName     = row.RouteName,
                        //Default_RouteReaderAccount_RefID = readerBP.CMN_BPT_BusinessParticipantID
                    };
                    route.Save(Connection, Transaction);
                }

                var routeMeasuringPoint = ORM_MRS_RUT_Route_MeasuringPoint.Query.Search(Connection, Transaction, new ORM_MRS_RUT_Route_MeasuringPoint.Query()
                {
                    Tenant_RefID         = securityTicket.TenantID,
                    IsDeleted            = false,
                    Route_RefID          = route.MRS_RUT_RouteID,
                    MeasuringPoint_RefID = measurentPoint.MRS_MPT_MeasuringPointID
                }).SingleOrDefault();

                if (routeMeasuringPoint == null)
                {
                    routeMeasuringPoint = new ORM_MRS_RUT_Route_MeasuringPoint()
                    {
                        Tenant_RefID = securityTicket.TenantID,
                        MRS_RUT_Route_MeasuringPointID = Guid.NewGuid(),
                        Route_RefID          = route.MRS_RUT_RouteID,
                        MeasuringPoint_RefID = measurentPoint.MRS_MPT_MeasuringPointID
                    };
                }

                routeMeasuringPoint.OrderSequence = row.SequenceInRoute;
                routeMeasuringPoint.Save(Connection, Transaction);


                #endregion

                #region measurement

                var measurement = new ORM_MRS_RUN_Measurement()
                {
                    Tenant_RefID          = securityTicket.TenantID,
                    MRS_RUN_MeasurementID = Guid.NewGuid(),
                    MeasurementRun_RefID  = run.MRS_RUN_MeasurementRunID,
                    MeasuringPoint_RefID  = routeMeasuringPoint.MRS_RUT_Route_MeasuringPointID
                };
                measurement.Save(Connection, Transaction);


                var run2route = ORM_MRS_RUN_MeasurementRun_Route.Query.Search(Connection, Transaction, new ORM_MRS_RUN_MeasurementRun_Route.Query()
                {
                    Tenant_RefID         = securityTicket.TenantID,
                    IsDeleted            = false,
                    Route_RefID          = route.MRS_RUT_RouteID,
                    MeasurementRun_RefID = run.MRS_RUN_MeasurementRunID
                }).SingleOrDefault();

                if (run2route == null)
                {
                    run2route = new ORM_MRS_RUN_MeasurementRun_Route()
                    {
                        MRS_RUN_MeasurementRun_RouteID = Guid.NewGuid(),
                        Tenant_RefID         = securityTicket.TenantID,
                        Route_RefID          = route.MRS_RUT_RouteID,
                        MeasurementRun_RefID = run.MRS_RUN_MeasurementRunID
                    }
                }
                ;

                run2route.BoundTo_Account_RefID = readerBP.CMN_BPT_BusinessParticipantID;
                run2route.Save(Connection, Transaction);


                #endregion
            }
            return(returnValue);

            #endregion UserCode
        }
Beispiel #15
0
        protected static FR_Bool Execute(DbConnection Connection, DbTransaction Transaction, P_L5ZW_SDfNC_1707 Parameter, CSV2Core.SessionSecurity.SessionSecurityTicket securityTicket = null)
        {
            #region UserCode
            var returnValue = new FR_Bool();
            returnValue.Result = false;

            //Put your code here
            #region get securityTicket and businessParticipantID by Paramter.AccountID and set defaultLanguageID
            Guid tenantID;
            Guid businessParticipantID;

            if (Parameter.AccountID == Guid.Empty)
            {
                return(returnValue);
            }

            ORM_USR_Account orm_account = new ORM_USR_Account();
            var             result      = orm_account.Load(Connection, Transaction, Parameter.AccountID);
            if (result.Status != FR_Status.Success || orm_account.USR_AccountID == Guid.Empty)
            {
                return(returnValue);
            }

            tenantID       = orm_account.Tenant_RefID;
            securityTicket = new CSV2Core.SessionSecurity.SessionSecurityTicket()
            {
                TenantID = tenantID
            };

            ORM_CMN_BPT_BusinessParticipant.Query businessParticipantQuery = new ORM_CMN_BPT_BusinessParticipant.Query();
            businessParticipantQuery.IfTenant_Tenant_RefID = tenantID;
            businessParticipantQuery.IsDeleted             = false;
            ORM_CMN_BPT_BusinessParticipant businessParticipant = ORM_CMN_BPT_BusinessParticipant.Query.Search(Connection, Transaction, businessParticipantQuery).FirstOrDefault();

            if (businessParticipant == null)
            {
                return(returnValue);
            }

            businessParticipantID = businessParticipant.CMN_BPT_BusinessParticipantID;
            #endregion

            #region get languages for tenant and set parameter dict values
            P_L2LN_GALFTID_1530 languageParam = new P_L2LN_GALFTID_1530()
            {
                Tenant_RefID = tenantID
            };
            L2LN_GALFTID_1530[] languages = cls_Get_All_Languages_ForTenantID.Invoke(Connection, Transaction, languageParam, securityTicket).Result;
            SetParameterDictValues(Parameter, languages);

            List <ISOLanguage> languagesISOs = new List <ISOLanguage>();
            languagesISOs.AddRange(languages.Select(l => new ISOLanguage()
            {
                ISO        = l.ISO_639_1,
                LanguageID = l.CMN_LanguageID
            }).ToList());
            #endregion

            #region save defaultLanguage

            // We are setting language for bp and acc
            var defaultLanguage = languages.FirstOrDefault(i => i.ISO_639_1.ToLower().Contains(Parameter.DefaultLanguageCode.ToLower()));
            if (defaultLanguage != null)
            {
                businessParticipant.DefaultLanguage_RefID = defaultLanguage.CMN_LanguageID;
                businessParticipant.Save(Connection, Transaction);

                orm_account.DefaultLanguage_RefID = defaultLanguage.CMN_LanguageID;
                orm_account.Save(Connection, Transaction);
            }

            #endregion

            #region save default country

            if (Parameter.DefaultCountry != null)
            {
                ORM_CMN_Country country = new ORM_CMN_Country();
                country.CMN_CountryID          = Guid.NewGuid();
                country.Country_ISOCode_Alpha3 = Parameter.DefaultCountry.Code;
                country.Country_Name           = new Dict()
                {
                    DictionaryID = Guid.NewGuid()
                };
                country.Creation_Timestamp     = DateTime.Now;
                country.Default_Currency_RefID = Guid.Empty;
                country.Default_Language_RefID = Guid.Empty;
                country.Tenant_RefID           = tenantID;
                country.IsDeleted = false;
                country.IsDefault = true;

                foreach (var languageItem in languages)
                {
                    country.Country_Name.UpdateEntry(languageItem.CMN_LanguageID, Parameter.DefaultCountry.Name);
                }

                country.Save(Connection, Transaction);
            }

            #endregion

            #region save default currency

            //asign currency
            if (Parameter.DefaultCurrency != null)
            {
                ORM_CMN_Currency currency = new ORM_CMN_Currency();
                currency.CMN_CurrencyID     = Guid.NewGuid();
                currency.Creation_Timestamp = DateTime.Now;
                currency.IsDeleted          = false;
                currency.ISO4127            = Parameter.DefaultCurrency.Code;
                currency.Name = new Dict()
                {
                    DictionaryID = Guid.NewGuid()
                };
                currency.Tenant_RefID = tenantID;

                foreach (var language in languages)
                {
                    currency.Name.UpdateEntry(language.CMN_LanguageID, Parameter.DefaultCurrency.Name);
                }

                currency.Save(Connection, Transaction);

                //set default currency
                ORM_CMN_BPT_BusinessParticipant businessPart = new ORM_CMN_BPT_BusinessParticipant();
                businessPart.Load(Connection, Transaction, businessParticipantID);

                businessPart.DefaultCurrency_RefID = currency.CMN_CurrencyID;
                businessPart.Save(Connection, Transaction);
            }

            #endregion

            #region save organisational units
            if (Parameter.OrganisationalUnitParameters.Length > 0)
            {
                foreach (var item in Parameter.OrganisationalUnitParameters)
                {
                    cls_Save_Office.Invoke(Connection, Transaction, item, securityTicket);
                }
            }
            #endregion

            #region save cost centers
            if (Parameter.CostCenterParameters.Length > 0)
            {
                foreach (var item in Parameter.CostCenterParameters)
                {
                    cls_Save_CostCenter.Invoke(Connection, Transaction, item, securityTicket);
                }
            }
            #endregion

            #region save warehouses
            if (Parameter.WarehousesParameters.Length > 0)
            {
                #region save warehouse group
                P_L2WH_SWHG_1327 warehouseGroupParam = new P_L2WH_SWHG_1327();
                warehouseGroupParam.Parent_RefID               = Guid.Empty;
                warehouseGroupParam.WarehouseGroup_Name        = "Waregouse group";
                warehouseGroupParam.WarehouseGroup_Description = new Dict()
                {
                    DictionaryID = Guid.NewGuid()
                };
                foreach (var language in languages)
                {
                    warehouseGroupParam.WarehouseGroup_Description.UpdateEntry(language.CMN_LanguageID, String.Empty);
                }

                var warehouseGroupID = cls_Save_Warehouse_Group.Invoke(Connection, Transaction, warehouseGroupParam, securityTicket).Result;
                #endregion

                foreach (var item in Parameter.WarehousesParameters)
                {
                    item.LOG_WRH_WarehouseGroupID = warehouseGroupID;
                    cls_Save_Warehouse.Invoke(Connection, Transaction, item, securityTicket);
                }
            }
            #endregion

            #region create dimension templates
            string           jsonTemplates      = ReadFromFile.LoadContentFromFile(@"Dimensions.json");
            List <Dimension> dimensionTemplates = JsonConvert.DeserializeObject <List <Dimension> >(jsonTemplates);

            int orderSequence = 1;
            ORM_CMN_PRO_Dimension       orm_dimension;
            ORM_CMN_PRO_Dimension_Value orm_dimensionValue;
            foreach (var template in dimensionTemplates)
            {
                orderSequence = 1;

                #region save dimension
                orm_dimension = new ORM_CMN_PRO_Dimension();
                orm_dimension.Product_RefID = Guid.Empty;
                orm_dimension.DimensionName = new Dict()
                {
                    DictionaryID = Guid.NewGuid()
                };
                orm_dimension.IsDimensionTemplate = true;
                orm_dimension.Tenant_RefID        = tenantID;

                foreach (var language in languages)
                {
                    orm_dimension.DimensionName.UpdateEntry(language.CMN_LanguageID, template.Name);
                }

                orm_dimension.Save(Connection, Transaction);
                #endregion

                #region save dimension values
                foreach (var templateValue in template.DimansionValues)
                {
                    orm_dimensionValue = new ORM_CMN_PRO_Dimension_Value();
                    orm_dimensionValue.Dimensions_RefID    = orm_dimension.CMN_PRO_DimensionID;
                    orm_dimensionValue.DimensionValue_Text = new Dict()
                    {
                        DictionaryID = Guid.NewGuid()
                    };
                    orm_dimensionValue.Tenant_RefID  = tenantID;
                    orm_dimensionValue.OrderSequence = orderSequence;

                    foreach (var language in languages)
                    {
                        orm_dimensionValue.DimensionValue_Text.UpdateEntry(language.CMN_LanguageID, templateValue);
                    }

                    orm_dimensionValue.Save(Connection, Transaction);

                    orderSequence++;
                }
                #endregion
            }
            #endregion

            #region create shipment types
            string shipmentTypesJson           = ReadFromFile.LoadContentFromFile(@"ShipmentTypes.json");
            List <ShipmentTypes> shipmentTypes = JsonConvert.DeserializeObject <List <ShipmentTypes> >(shipmentTypesJson);

            ORM_LOG_SHP_Shipment_Type orm_shipmentType;
            foreach (var type in shipmentTypes)
            {
                #region save LOG_SHP_Shipment_Type
                orm_shipmentType = new ORM_LOG_SHP_Shipment_Type();
                orm_shipmentType.ShipmentType_Name = new Dict()
                {
                    DictionaryID = Guid.NewGuid()
                };
                orm_shipmentType.ShipmentType_Description = new Dict()
                {
                    DictionaryID = Guid.NewGuid()
                };
                orm_shipmentType.Tenant_RefID = tenantID;

                foreach (var language in languages)
                {
                    orm_shipmentType.ShipmentType_Name.UpdateEntry(language.CMN_LanguageID, type.Name);
                    orm_shipmentType.ShipmentType_Description.UpdateEntry(language.CMN_LanguageID, string.Empty);
                }

                orm_shipmentType.Save(Connection, Transaction);
                #endregion
            }
            #endregion

            #region create number ranges

            string      numberRangesJson = ReadFromFile.LoadContentFromFile(@"NumberRanges.json");
            NumberRange numberRanges     = JsonConvert.DeserializeObject <NumberRange>(numberRangesJson);


            ORM_CMN_NumberRange_UsageArea numberRangeUsageArea;
            ORM_CMN_NumberRange           orm_numberRanges;
            foreach (var item in numberRanges.NumberRanges)
            {
                if (Parameter.IsCustomerRegistration && item.Name == "Customer orders")
                {
                    continue;
                }

                if (!Parameter.IsCustomerRegistration && item.Name == "Distribution orders")
                {
                    continue;
                }

                if (!Parameter.IsCustomerRegistration && item.Name == "Procurement orders")
                {
                    continue;
                }

                numberRangeUsageArea = new ORM_CMN_NumberRange_UsageArea();
                numberRangeUsageArea.UsageArea_Name = new Dict()
                {
                    DictionaryID = Guid.NewGuid()
                };
                numberRangeUsageArea.UsageArea_Description = new Dict()
                {
                    DictionaryID = Guid.NewGuid()
                };
                foreach (var language in languages)
                {
                    numberRangeUsageArea.UsageArea_Name.UpdateEntry(language.CMN_LanguageID, item.Name);
                    numberRangeUsageArea.UsageArea_Description.UpdateEntry(language.CMN_LanguageID, string.Empty);
                }
                numberRangeUsageArea.Tenant_RefID           = tenantID;
                numberRangeUsageArea.GlobalStaticMatchingID = item.GlobalStaticMatchingID;
                numberRangeUsageArea.Save(Connection, Transaction);

                orm_numberRanges = new ORM_CMN_NumberRange();
                orm_numberRanges.NumberRange_Name            = item.Name;
                orm_numberRanges.Tenant_RefID                = tenantID;
                orm_numberRanges.NumberRange_UsageArea_RefID = numberRangeUsageArea.CMN_NumberRange_UsageAreaID;
                orm_numberRanges.FixedPrefix = item.FixedPrefix;
                orm_numberRanges.Formatting_LeadingFillCharacter = item.FillCharacter;
                orm_numberRanges.Formatting_NumberLength         = item.Length;
                orm_numberRanges.Value_Current = item.CurrentValue;
                orm_numberRanges.Value_Start   = item.StartValue;
                orm_numberRanges.Value_End     = item.EndValue;
                orm_numberRanges.Save(Connection, Transaction);
            }


            #endregion

            #region create inventory change reasons

            string inventoryChangeReasonsJson = ReadFromFile.LoadContentFromFile(@"InventoryChangeReasons.json");
            List <InventoryChangeReasons> inventoryChangeReasons = JsonConvert.DeserializeObject <List <InventoryChangeReasons> >(inventoryChangeReasonsJson);

            ORM_LOG_WRH_InventoryChangeReason orm_inventoryChangeReason;
            foreach (var reason in inventoryChangeReasons)
            {
                #region save inventory change reason

                orm_inventoryChangeReason = new ORM_LOG_WRH_InventoryChangeReason();
                orm_inventoryChangeReason.GlobalPropertyMatchingID = InventoryChangeReasons.InventoryChangeReasonGlobalPropertyMatchingID + "-" + reason.Name;
                orm_inventoryChangeReason.InventoryChange_Name     = new Dict()
                {
                    DictionaryID = Guid.NewGuid()
                };
                orm_inventoryChangeReason.InventoryChange_Description = new Dict()
                {
                    DictionaryID = Guid.NewGuid()
                };
                orm_inventoryChangeReason.Tenant_RefID = tenantID;

                foreach (var language in languages)
                {
                    orm_inventoryChangeReason.InventoryChange_Name.UpdateEntry(language.CMN_LanguageID, reason.Name);
                    orm_inventoryChangeReason.InventoryChange_Description.UpdateEntry(language.CMN_LanguageID, string.Empty);
                }

                orm_inventoryChangeReason.Save(Connection, Transaction);

                #endregion
            }

            #endregion

            #region create shipment statuses
            var shipmentStatuses = Enum.GetValues(typeof(EShipmentStatus));

            var shipmentStatusDicts = EnumUtils.GetDictObjectsForStaticListData <EShipmentStatus>(
                ResourceFilePath.ShipmentStatus, ORM_LOG_SHP_Shipment_Status.TableName, languagesISOs);

            var statusCodeCount = 1;
            ORM_LOG_SHP_Shipment_Status shipmentStatus;
            foreach (EShipmentStatus status in shipmentStatuses)
            {
                shipmentStatus = new ORM_LOG_SHP_Shipment_Status();
                shipmentStatus.GlobalPropertyMatchingID = EnumUtils.GetEnumDescription((EShipmentStatus)status);
                shipmentStatus.Status_Code  = statusCodeCount++;
                shipmentStatus.Status_Name  = shipmentStatusDicts[EnumUtils.GetEnumDescription((EShipmentStatus)status)];
                shipmentStatus.Tenant_RefID = tenantID;

                shipmentStatus.Save(Connection, Transaction);
            }
            #endregion

            if (Parameter.IsCustomerRegistration)
            {
                #region create procurement order statuses
                var procurementStatuses = Enum.GetValues(typeof(EProcurementStatus));
                ORM_ORD_PRC_ProcurementOrder_Status procurementOrderStatus;
                foreach (EProcurementStatus status in procurementStatuses)
                {
                    procurementOrderStatus = new ORM_ORD_PRC_ProcurementOrder_Status();
                    procurementOrderStatus.GlobalPropertyMatchingID = EnumUtils.GetEnumDescription(status);
                    procurementOrderStatus.Tenant_RefID             = tenantID;

                    procurementOrderStatus.Save(Connection, Transaction);
                }
                #endregion
            }
            else
            {
                #region create customer order statuses
                var customerOrderStatuses = Enum.GetValues(typeof(ECustomerOrderStatus));

                var customerOrderStatusesDicts = EnumUtils.GetDictObjectsForStaticListData <ECustomerOrderStatus>(
                    ResourceFilePath.CustomerOrderStatus, ORM_ORD_CUO_CustomerOrder_Status.TableName, languagesISOs);

                var count = 1;
                ORM_ORD_CUO_CustomerOrder_Status customerOrderStatus;
                foreach (var status in customerOrderStatuses)
                {
                    customerOrderStatus = new ORM_ORD_CUO_CustomerOrder_Status();
                    customerOrderStatus.GlobalPropertyMatchingID = EnumUtils.GetEnumDescription((ECustomerOrderStatus)status);
                    customerOrderStatus.Status_Code  = count++;
                    customerOrderStatus.Status_Name  = customerOrderStatusesDicts[EnumUtils.GetEnumDescription((ECustomerOrderStatus)status)];
                    customerOrderStatus.Tenant_RefID = tenantID;

                    customerOrderStatus.Save(Connection, Transaction);
                }
                #endregion
            }

            returnValue.Result = true;
            return(returnValue);

            #endregion UserCode
        }
Beispiel #16
0
        protected static FR_Guid Execute(DbConnection Connection, DbTransaction Transaction, P_L6PA_SMSP_1548 Parameter, CSV2Core.SessionSecurity.SessionSecurityTicket securityTicket = null)
        {
            //Leave UserCode region to enable user code saving
            #region UserCode
            var             returnValue = new FR_Guid();
            ORM_HEC_Patient patient     = new ORM_HEC_Patient();
            if (Parameter.HEC_PatientID != Guid.Empty)
            {
                var result = patient.Load(Connection, Transaction, Parameter.HEC_PatientID);
                if (result.Status != FR_Status.Success || patient.HEC_PatientID == Guid.Empty)
                {
                    var error = new FR_Guid();
                    error.ErrorMessage = "No Such ID";
                    error.Status       = FR_Status.Error_Internal;
                    return(error);
                }
            }
            patient.IsPatientParticipationPolicyValidated = Parameter.HasFulfilledParticipationPolicyRequirements;
            patient.PatientComment = Parameter.Comment;
            patient.Tenant_RefID   = securityTicket.TenantID;

            ORM_CMN_BPT_BusinessParticipant bParticipant = new ORM_CMN_BPT_BusinessParticipant();
            if (patient.CMN_BPT_BusinessParticipant_RefID != Guid.Empty)
            {
                var result = bParticipant.Load(Connection, Transaction, patient.CMN_BPT_BusinessParticipant_RefID);
                if (result.Status != FR_Status.Success || bParticipant.CMN_BPT_BusinessParticipantID == Guid.Empty)
                {
                    var error = new FR_Guid();
                    error.ErrorMessage = "No Such ID";
                    error.Status       = FR_Status.Error_Internal;
                    return(error);
                }
            }
            bParticipant.IsNaturalPerson = true;
            bParticipant.Tenant_RefID    = securityTicket.TenantID;


            ORM_CMN_PER_PersonInfo person = new ORM_CMN_PER_PersonInfo();
            if (bParticipant.IfNaturalPerson_CMN_PER_PersonInfo_RefID != Guid.Empty)
            {
                var result = person.Load(Connection, Transaction, bParticipant.IfNaturalPerson_CMN_PER_PersonInfo_RefID);
                if (result.Status != FR_Status.Success || person.CMN_PER_PersonInfoID == Guid.Empty)
                {
                    var error = new FR_Guid();
                    error.ErrorMessage = "No Such ID";
                    error.Status       = FR_Status.Error_Internal;
                    return(error);
                }
            }
            person.FirstName          = Parameter.FirstName;
            person.LastName           = Parameter.LastName;
            person.PrimaryEmail       = Parameter.Mail;
            person.Tenant_RefID       = securityTicket.TenantID;
            person.Salutation_General = Parameter.Salutation;
            person.Save(Connection, Transaction);

            bParticipant.IfNaturalPerson_CMN_PER_PersonInfo_RefID = person.CMN_PER_PersonInfoID;
            bParticipant.Save(Connection, Transaction);

            patient.CMN_BPT_BusinessParticipant_RefID = bParticipant.CMN_BPT_BusinessParticipantID;
            patient.Save(Connection, Transaction);

            ORM_CMN_PER_CommunicationContact.Query contactQuery = new ORM_CMN_PER_CommunicationContact.Query();
            contactQuery.IsDeleted        = false;
            contactQuery.Tenant_RefID     = securityTicket.TenantID;
            contactQuery.PersonInfo_RefID = person.CMN_PER_PersonInfoID;
            var contactQueryRes = ORM_CMN_PER_CommunicationContact.Query.Search(Connection, Transaction, contactQuery);
            ORM_CMN_PER_CommunicationContact contactPhone = contactQueryRes.FirstOrDefault(c => c.Contact_Type == STLD_ContactTypes.Phone);
            ORM_CMN_PER_CommunicationContact contactFax   = contactQueryRes.FirstOrDefault(c => c.Contact_Type == STLD_ContactTypes.Fax);

            if (contactPhone == null)
            {
                contactPhone = new ORM_CMN_PER_CommunicationContact();
                contactPhone.Contact_Type     = STLD_ContactTypes.Phone;
                contactPhone.Tenant_RefID     = securityTicket.TenantID;
                contactPhone.PersonInfo_RefID = person.CMN_PER_PersonInfoID;
            }
            contactPhone.Content = Parameter.Phone;
            contactPhone.Save(Connection, Transaction);

            if (contactFax == null)
            {
                contactFax                  = new ORM_CMN_PER_CommunicationContact();
                contactFax.Content          = Parameter.Fax;
                contactFax.Contact_Type     = STLD_ContactTypes.Fax;
                contactFax.Tenant_RefID     = securityTicket.TenantID;
                contactFax.PersonInfo_RefID = person.CMN_PER_PersonInfoID;
                contactFax.Save(Connection, Transaction);
            }
            contactFax.Content = Parameter.Fax;
            contactFax.Save(Connection, Transaction);

            ORM_HEC_Patient_HealthInsurance.Query Patient_HealthInsuranceQuery = new ORM_HEC_Patient_HealthInsurance.Query();
            Patient_HealthInsuranceQuery.Tenant_RefID  = securityTicket.TenantID;
            Patient_HealthInsuranceQuery.IsDeleted     = false;
            Patient_HealthInsuranceQuery.Patient_RefID = patient.HEC_PatientID;

            ORM_HEC_Patient_HealthInsurance Patient_HealthInsurance;
            var Patient_HealthInsuranceQueryRes = ORM_HEC_Patient_HealthInsurance.Query.Search(Connection, Transaction, Patient_HealthInsuranceQuery);
            if (Patient_HealthInsuranceQueryRes.Count == 1)
            {
                Patient_HealthInsurance = Patient_HealthInsuranceQueryRes[0];
            }
            else
            {
                Patient_HealthInsurance = new ORM_HEC_Patient_HealthInsurance();
                Patient_HealthInsurance.Patient_RefID = patient.HEC_PatientID;
                Patient_HealthInsurance.Tenant_RefID  = securityTicket.TenantID;
                Patient_HealthInsurance.IsPrimary     = true;
            }
            Patient_HealthInsurance.HealthInsurance_Number = Parameter.HealthcareNumber;
            Patient_HealthInsurance.Save(Connection, Transaction);

            ORM_HEC_STU_Study_ParticipatingPatient.Query Study_ParticipatingPatientsQuery = new ORM_HEC_STU_Study_ParticipatingPatient.Query();
            Study_ParticipatingPatientsQuery.Tenant_RefID  = securityTicket.TenantID;
            Study_ParticipatingPatientsQuery.IsDeleted     = false;
            Study_ParticipatingPatientsQuery.Patient_RefID = patient.HEC_PatientID;

            ORM_HEC_STU_Study_ParticipatingPatient Study_ParticipatingPatients;

            var Study_ParticipatingPatientsQueryRes = ORM_HEC_STU_Study_ParticipatingPatient.Query.Search(Connection, Transaction, Study_ParticipatingPatientsQuery);
            if (Study_ParticipatingPatientsQueryRes.Count == 1)
            {
                Study_ParticipatingPatients = Study_ParticipatingPatientsQueryRes[0];
            }
            else
            {
                Study_ParticipatingPatients = new ORM_HEC_STU_Study_ParticipatingPatient();
                Study_ParticipatingPatients.Patient_RefID = patient.HEC_PatientID;
                Study_ParticipatingPatients.Tenant_RefID  = securityTicket.TenantID;
            }
            Study_ParticipatingPatients.HasFulfilledParticipationPolicyRequirements = Parameter.HasFulfilledParticipationPolicyRequirements;
            Study_ParticipatingPatients.Save(Connection, Transaction);


            ORM_USR_Account       account;
            ORM_USR_Account.Query ORM_USR_AccountQuery = new ORM_USR_Account.Query();
            ORM_USR_AccountQuery.IsDeleted    = false;
            ORM_USR_AccountQuery.Tenant_RefID = securityTicket.TenantID;
            ORM_USR_AccountQuery.BusinessParticipant_RefID = bParticipant.CMN_BPT_BusinessParticipantID;
            var accountRes = ORM_USR_Account.Query.Search(Connection, Transaction, ORM_USR_AccountQuery);
            if (accountRes.Count == 1)
            {
                account = accountRes[0];
            }
            else
            {
                account = new ORM_USR_Account();
                account.Tenant_RefID = securityTicket.TenantID;
                account.BusinessParticipant_RefID = bParticipant.CMN_BPT_BusinessParticipantID;
                account.AccountType = 3;
                account.Save(Connection, Transaction);
            }

            ORM_USR_Device_AccountCode.Query ORM_USR_Device_AccountCodeQuery = new ORM_USR_Device_AccountCode.Query();
            ORM_USR_Device_AccountCodeQuery.IsDeleted     = false;
            ORM_USR_Device_AccountCodeQuery.Tenant_RefID  = securityTicket.TenantID;
            ORM_USR_Device_AccountCodeQuery.Account_RefID = account.USR_AccountID;
            var accountCodeRes = ORM_USR_Device_AccountCode.Query.Search(Connection, Transaction, ORM_USR_Device_AccountCodeQuery);
            if (accountCodeRes.Count == 0)
            {
                P_L2DC_GUDCfT_1505 codeParam = new P_L2DC_GUDCfT_1505();
                codeParam.codeLength = 8;
                var checkCodeValue = cls_GetUniqueDeviceCodeForTenant.Invoke(Connection, Transaction, codeParam, securityTicket).Result;

                ORM_USR_Device_AccountCode_StatusHistory AccountCode_StatusHistory = new ORM_USR_Device_AccountCode_StatusHistory();
                AccountCode_StatusHistory.Tenant_RefID         = securityTicket.TenantID;
                AccountCode_StatusHistory.IsAccountCode_Active = true;
                AccountCode_StatusHistory.Save(Connection, Transaction);

                ORM_USR_Device_AccountCode devoceAccpimtCpde = new ORM_USR_Device_AccountCode();
                devoceAccpimtCpde.Account_RefID                   = account.USR_AccountID;
                devoceAccpimtCpde.Tenant_RefID                    = securityTicket.TenantID;
                devoceAccpimtCpde.AccountCode_Value               = checkCodeValue.CodeValue;
                devoceAccpimtCpde.IsAccountCode_Expirable         = false;
                devoceAccpimtCpde.AccountCode_CurrentStatus_RefID = AccountCode_StatusHistory.USR_Device_AccountCode_StatusHistoryID;
                devoceAccpimtCpde.Save(Connection, Transaction);

                AccountCode_StatusHistory.Device_AccountCode_RefID = devoceAccpimtCpde.USR_Device_AccountCodeID;
                AccountCode_StatusHistory.Save(Connection, Transaction);
            }

            returnValue.Result = patient.HEC_PatientID;
            return(returnValue);

            #endregion UserCode
        }
        protected static FR_Guid Execute(DbConnection Connection, DbTransaction Transaction, P_L3CA_CoUSfIC_1602 Parameter, CSV2Core.SessionSecurity.SessionSecurityTicket securityTicket = null)
        {
            //Leave UserCode region to enable user code saving
            #region UserCode
            var returnValue = new FR_Guid();

            /*
             * @See if Supplier already exists in database
             * */
            ORM_CMN_BPT_Supplier supplier = new ORM_CMN_BPT_Supplier();

            var supplierQuery = new ORM_CMN_BPT_BusinessParticipant.Query();
            supplierQuery.BusinessParticipantITL = Parameter.SupplierITL;
            supplierQuery.Tenant_RefID           = securityTicket.TenantID;
            supplierQuery.IsDeleted = false;

            var supplier_bussinessParticipant = ORM_CMN_BPT_BusinessParticipant.Query.Search(Connection, Transaction, supplierQuery).FirstOrDefault();

            #region if supplier does not exist

            if (supplier_bussinessParticipant == null)
            {
                /*
                 * @Make Supplier Data
                 * */

                var tenantQuery = new ORM_CMN_Tenant.Query()
                {
                    TenantITL    = Parameter.TenantITL,
                    Tenant_RefID = securityTicket.TenantID
                };

                var supplierTenant = ORM_CMN_Tenant.Query.Search(Connection, Transaction, tenantQuery).SingleOrDefault();

                if (supplierTenant == default(ORM_CMN_Tenant))
                {
                    supplierTenant = new ORM_CMN_Tenant();
                    supplierTenant.CMN_TenantID       = Guid.NewGuid();
                    supplierTenant.TenantITL          = Parameter.TenantITL;
                    supplierTenant.Tenant_RefID       = securityTicket.TenantID;
                    supplierTenant.Creation_Timestamp = DateTime.Now;
                    supplierTenant.Save(Connection, Transaction);
                }

                supplier.CMN_BPT_SupplierID            = Guid.NewGuid();
                supplier.Ext_BusinessParticipant_RefID = Guid.NewGuid();
                supplier.Creation_Timestamp            = DateTime.Now;
                supplier.IsDeleted    = false;
                supplier.Tenant_RefID = securityTicket.TenantID;
                supplier.Save(Connection, Transaction);

                ORM_CMN_BPT_BusinessParticipant supplierBussinessParticipant = new ORM_CMN_BPT_BusinessParticipant();
                supplierBussinessParticipant.CMN_BPT_BusinessParticipantID = supplier.Ext_BusinessParticipant_RefID;
                supplierBussinessParticipant.DisplayName            = Parameter.Supplier_Name;
                supplierBussinessParticipant.BusinessParticipantITL = Parameter.SupplierITL;
                supplierBussinessParticipant.Creation_Timestamp     = DateTime.Now;
                supplierBussinessParticipant.Tenant_RefID           = securityTicket.TenantID;
                supplierBussinessParticipant.IsCompany             = true;
                supplierBussinessParticipant.IsTenant              = true;
                supplierBussinessParticipant.IfTenant_Tenant_RefID = Guid.Parse(Parameter.TenantITL);
                supplierBussinessParticipant.IfCompany_CMN_COM_CompanyInfo_RefID = Guid.NewGuid();//companyInfo.CMN_COM_CompanyInfoID
                supplierBussinessParticipant.Save(Connection, Transaction);

                ORM_CMN_COM_CompanyInfo companyInfo = new ORM_CMN_COM_CompanyInfo();
                companyInfo.CMN_COM_CompanyInfoID = supplierBussinessParticipant.IfCompany_CMN_COM_CompanyInfo_RefID;
                companyInfo.Creation_Timestamp    = DateTime.Now;
                companyInfo.Tenant_RefID          = securityTicket.TenantID;
                companyInfo.Contact_UCD_RefID     = Guid.NewGuid();//universalContactDetail.CMN_UniversalContactDetailID
                companyInfo.Save(Connection, Transaction);

                ORM_CMN_UniversalContactDetail universalContactDetail = new ORM_CMN_UniversalContactDetail();
                universalContactDetail.CMN_UniversalContactDetailID = companyInfo.Contact_UCD_RefID;
                universalContactDetail.IsCompany             = true;
                universalContactDetail.Country_639_1_ISOCode = Parameter.CountryISO;
                universalContactDetail.Street_Name           = Parameter.Supplier_Name;
                universalContactDetail.Street_Number         = Parameter.Street_Number;
                universalContactDetail.ZIP                = Parameter.ZIP;
                universalContactDetail.Town               = Parameter.Town;
                universalContactDetail.Region_Code        = Parameter.Region_Code;
                universalContactDetail.Tenant_RefID       = securityTicket.TenantID;
                universalContactDetail.Creation_Timestamp = DateTime.Now;
                universalContactDetail.Save(Connection, Transaction);
            }
            #endregion
            #region if supplier exists , check if its data is changed
            else
            {
                var tenantQuery = new ORM_CMN_Tenant.Query()
                {
                    TenantITL    = Parameter.TenantITL,
                    Tenant_RefID = securityTicket.TenantID,
                    IsDeleted    = false
                };

                ORM_CMN_Tenant supplierTenant;

                if (ORM_CMN_Tenant.Query.Search(Connection, Transaction, tenantQuery).Count > 1)
                {
                    supplierTenant = ORM_CMN_Tenant.Query.Search(Connection, Transaction, tenantQuery).First(); //QUICKFIX
                }
                else
                {
                    supplierTenant = ORM_CMN_Tenant.Query.Search(Connection, Transaction, tenantQuery).SingleOrDefault();
                }

                if (supplierTenant == default(ORM_CMN_Tenant))
                {
                    supplierTenant = new ORM_CMN_Tenant();
                    supplierTenant.CMN_TenantID       = Guid.NewGuid();
                    supplierTenant.TenantITL          = Parameter.TenantITL;
                    supplierTenant.Tenant_RefID       = securityTicket.TenantID;
                    supplierTenant.Creation_Timestamp = DateTime.Now;
                    supplierTenant.Save(Connection, Transaction);

                    supplier_bussinessParticipant.IsTenant = true;
                    supplier_bussinessParticipant.IfTenant_Tenant_RefID = Guid.Parse(Parameter.TenantITL);
                }

                supplier_bussinessParticipant.DisplayName = Parameter.Supplier_Name;
                supplier_bussinessParticipant.Save(Connection, Transaction);

                var query = new ORM_CMN_BPT_Supplier.Query();
                query.Ext_BusinessParticipant_RefID = supplier_bussinessParticipant.CMN_BPT_BusinessParticipantID;
                query.Tenant_RefID = securityTicket.TenantID;
                query.IsDeleted    = false;

                supplier = ORM_CMN_BPT_Supplier.Query.Search(Connection, Transaction, query).First();

                //edit universal contact details

                var companyInfoQuery = new ORM_CMN_COM_CompanyInfo.Query();
                companyInfoQuery.CMN_COM_CompanyInfoID = supplier_bussinessParticipant.IfCompany_CMN_COM_CompanyInfo_RefID;
                companyInfoQuery.Tenant_RefID          = securityTicket.TenantID;
                companyInfoQuery.IsDeleted             = false;

                var companyInfo = ORM_CMN_COM_CompanyInfo.Query.Search(Connection, Transaction, companyInfoQuery).First();

                var universalContactDetailQuery = new ORM_CMN_UniversalContactDetail.Query();
                universalContactDetailQuery.CMN_UniversalContactDetailID = companyInfo.Contact_UCD_RefID;
                universalContactDetailQuery.Tenant_RefID = securityTicket.TenantID;
                universalContactDetailQuery.IsDeleted    = false;

                var universalContactDetail = ORM_CMN_UniversalContactDetail.Query.Search(Connection, Transaction, universalContactDetailQuery).First();

                universalContactDetail.Country_639_1_ISOCode = Parameter.CountryISO;
                universalContactDetail.Street_Name           = Parameter.Supplier_Name;
                universalContactDetail.Street_Number         = Parameter.Street_Number;
                universalContactDetail.ZIP         = Parameter.ZIP;
                universalContactDetail.Town        = Parameter.Town;
                universalContactDetail.Region_Code = Parameter.Region_Code;
                universalContactDetail.Save(Connection, Transaction);
            }
            #endregion

            returnValue.Result = supplier.CMN_BPT_SupplierID;
            return(returnValue);

            #endregion UserCode
        }
Beispiel #18
0
        protected static FR_Guid Execute(DbConnection Connection, DbTransaction Transaction, P_L6PA_SBBVP_1223 Parameter, CSV2Core.SessionSecurity.SessionSecurityTicket securityTicket = null)
        {
            #region UserCode
            var returnValue = new FR_Guid();

            ORM_HEC_Patient patient = new ORM_HEC_Patient();
            if (Parameter.HEC_PatientID != Guid.Empty)
            {
                var result = patient.Load(Connection, Transaction, Parameter.HEC_PatientID);
                if (result.Status != FR_Status.Success || patient.HEC_PatientID == Guid.Empty)
                {
                    var error = new FR_Guid();
                    error.ErrorMessage = "No Such ID";
                    error.Status       = FR_Status.Error_Internal;
                    return(error);
                }
            }
            patient.IsPatientParticipationPolicyValidated = Parameter.HasFulfilledParticipationPolicyRequirements;
            patient.PatientComment = Parameter.Comment;
            patient.Tenant_RefID   = securityTicket.TenantID;

            ORM_CMN_BPT_BusinessParticipant bParticipant = new ORM_CMN_BPT_BusinessParticipant();
            if (patient.CMN_BPT_BusinessParticipant_RefID != Guid.Empty)
            {
                var result = bParticipant.Load(Connection, Transaction, patient.CMN_BPT_BusinessParticipant_RefID);
                if (result.Status != FR_Status.Success || bParticipant.CMN_BPT_BusinessParticipantID == Guid.Empty)
                {
                    var error = new FR_Guid();
                    error.ErrorMessage = "No Such ID";
                    error.Status       = FR_Status.Error_Internal;
                    return(error);
                }
            }
            bParticipant.IsNaturalPerson = true;
            bParticipant.Tenant_RefID    = securityTicket.TenantID;


            ORM_CMN_PER_PersonInfo person = new ORM_CMN_PER_PersonInfo();
            if (bParticipant.IfNaturalPerson_CMN_PER_PersonInfo_RefID != Guid.Empty)
            {
                var result = person.Load(Connection, Transaction, bParticipant.IfNaturalPerson_CMN_PER_PersonInfo_RefID);
                if (result.Status != FR_Status.Success || person.CMN_PER_PersonInfoID == Guid.Empty)
                {
                    var error = new FR_Guid();
                    error.ErrorMessage = "No Such ID";
                    error.Status       = FR_Status.Error_Internal;
                    return(error);
                }
            }
            person.FirstName          = Parameter.FirstName;
            person.LastName           = Parameter.LastName;
            person.PrimaryEmail       = Parameter.Mail;
            person.Tenant_RefID       = securityTicket.TenantID;
            person.Salutation_General = Parameter.Salutation;
            person.Save(Connection, Transaction);

            bParticipant.IfNaturalPerson_CMN_PER_PersonInfo_RefID = person.CMN_PER_PersonInfoID;
            bParticipant.Save(Connection, Transaction);

            patient.CMN_BPT_BusinessParticipant_RefID = bParticipant.CMN_BPT_BusinessParticipantID;
            patient.Save(Connection, Transaction);

            ORM_CMN_PER_CommunicationContact.Query contactQuery = new ORM_CMN_PER_CommunicationContact.Query();
            contactQuery.IsDeleted        = false;
            contactQuery.Tenant_RefID     = securityTicket.TenantID;
            contactQuery.PersonInfo_RefID = person.CMN_PER_PersonInfoID;
            var contactQueryRes = ORM_CMN_PER_CommunicationContact.Query.Search(Connection, Transaction, contactQuery);
            ORM_CMN_PER_CommunicationContact contactPhone = contactQueryRes.FirstOrDefault(c => c.Contact_Type == STLD_ContactTypes.Phone);
            ORM_CMN_PER_CommunicationContact contactFax   = contactQueryRes.FirstOrDefault(c => c.Contact_Type == STLD_ContactTypes.Fax);

            if (contactPhone == null)
            {
                contactPhone = new ORM_CMN_PER_CommunicationContact();
                contactPhone.Contact_Type     = STLD_ContactTypes.Phone;
                contactPhone.Tenant_RefID     = securityTicket.TenantID;
                contactPhone.PersonInfo_RefID = person.CMN_PER_PersonInfoID;
            }
            contactPhone.Content = Parameter.Phone;
            contactPhone.Save(Connection, Transaction);

            if (contactFax == null)
            {
                contactFax                  = new ORM_CMN_PER_CommunicationContact();
                contactFax.Content          = Parameter.Fax;
                contactFax.Contact_Type     = STLD_ContactTypes.Fax;
                contactFax.Tenant_RefID     = securityTicket.TenantID;
                contactFax.PersonInfo_RefID = person.CMN_PER_PersonInfoID;
                contactFax.Save(Connection, Transaction);
            }
            contactFax.Content = Parameter.Fax;
            contactFax.Save(Connection, Transaction);

            ORM_HEC_Patient_HealthInsurance.Query Patient_HealthInsuranceQuery = new ORM_HEC_Patient_HealthInsurance.Query();
            Patient_HealthInsuranceQuery.Tenant_RefID  = securityTicket.TenantID;
            Patient_HealthInsuranceQuery.IsDeleted     = false;
            Patient_HealthInsuranceQuery.Patient_RefID = patient.HEC_PatientID;

            ORM_HEC_Patient_HealthInsurance Patient_HealthInsurance;
            var Patient_HealthInsuranceQueryRes = ORM_HEC_Patient_HealthInsurance.Query.Search(Connection, Transaction, Patient_HealthInsuranceQuery);
            if (Patient_HealthInsuranceQueryRes.Count == 1)
            {
                Patient_HealthInsurance = Patient_HealthInsuranceQueryRes[0];
            }
            else
            {
                Patient_HealthInsurance = new ORM_HEC_Patient_HealthInsurance();
                Patient_HealthInsurance.Patient_RefID = patient.HEC_PatientID;
                Patient_HealthInsurance.Tenant_RefID  = securityTicket.TenantID;
                Patient_HealthInsurance.IsPrimary     = true;
            }
            Patient_HealthInsurance.HealthInsurance_Number = Parameter.HealthcareNumber;
            Patient_HealthInsurance.Save(Connection, Transaction);

            ORM_HEC_STU_Study_ParticipatingPatient.Query Study_ParticipatingPatientsQuery = new ORM_HEC_STU_Study_ParticipatingPatient.Query();
            Study_ParticipatingPatientsQuery.Tenant_RefID  = securityTicket.TenantID;
            Study_ParticipatingPatientsQuery.IsDeleted     = false;
            Study_ParticipatingPatientsQuery.Patient_RefID = patient.HEC_PatientID;

            ORM_HEC_STU_Study_ParticipatingPatient Study_ParticipatingPatients;

            var Study_ParticipatingPatientsQueryRes = ORM_HEC_STU_Study_ParticipatingPatient.Query.Search(Connection, Transaction, Study_ParticipatingPatientsQuery);
            if (Study_ParticipatingPatientsQueryRes.Count == 1)
            {
                Study_ParticipatingPatients = Study_ParticipatingPatientsQueryRes[0];
            }
            else
            {
                Study_ParticipatingPatients = new ORM_HEC_STU_Study_ParticipatingPatient();
                Study_ParticipatingPatients.Patient_RefID = patient.HEC_PatientID;
                Study_ParticipatingPatients.Tenant_RefID  = securityTicket.TenantID;
            }
            Study_ParticipatingPatients.HasFulfilledParticipationPolicyRequirements = Parameter.HasFulfilledParticipationPolicyRequirements;
            Study_ParticipatingPatients.Save(Connection, Transaction);

            returnValue.Result = patient.HEC_PatientID;
            return(returnValue);

            #endregion UserCode
        }
Beispiel #19
0
        protected static FR_Guid Execute(DbConnection Connection, DbTransaction Transaction, P_L5PR_SP__1122 Parameter, CSV2Core.SessionSecurity.SessionSecurityTicket securityTicket = null)
        {
            #region UserCode
            var returnValue = new FR_Guid();

            ORM_HEC_MedicalPractis item = new ORM_HEC_MedicalPractis();

            if (Parameter.PracticeID != Guid.Empty)
            {
                var result = item.Load(Connection, Transaction, Parameter.PracticeID);
                if (result.Status != FR_Status.Success || item.HEC_MedicalPractiseID == Guid.Empty)
                {
                    var error = new FR_Guid();
                    error.ErrorMessage = "No Such ID";
                    error.Status       = FR_Status.Error_Internal;
                    return(error);
                }

                #region Delete

                if (Parameter.isDeleted == true)
                {
                    var query_BP_ContactPerson_del = new ORM_CMN_BPT_BusinessParticipant.Query();
                    query_BP_ContactPerson_del.CMN_BPT_BusinessParticipantID = item.ContactPerson_RefID;
                    query_BP_ContactPerson_del.Tenant_RefID = securityTicket.TenantID;

                    var found_BP_ContactPerson_del = ORM_CMN_BPT_BusinessParticipant.Query.Search(Connection, Transaction, query_BP_ContactPerson_del).First();
                    found_BP_ContactPerson_del.IsDeleted = true;

                    var query_PersonInfo_del = new ORM_CMN_PER_PersonInfo.Query();
                    query_PersonInfo_del.CMN_PER_PersonInfoID = found_BP_ContactPerson_del.IfNaturalPerson_CMN_PER_PersonInfo_RefID;

                    var found_PersonInfo_del = ORM_CMN_PER_PersonInfo.Query.Search(Connection, Transaction, query_PersonInfo_del).First();
                    found_PersonInfo_del.IsDeleted = true;
                    found_PersonInfo_del.Save(Connection, Transaction);


                    var query_CommunicationContact_del = new ORM_CMN_PER_CommunicationContact.Query();
                    query_CommunicationContact_del.PersonInfo_RefID = found_PersonInfo_del.CMN_PER_PersonInfoID;


                    var found_CommunicationContact_del = ORM_CMN_PER_CommunicationContact.Query.Search(Connection, Transaction, query_CommunicationContact_del).First();
                    found_CommunicationContact_del.IsDeleted = true;

                    found_CommunicationContact_del.Save(Connection, Transaction);


                    var query_CompanyInfo_del = new ORM_CMN_COM_CompanyInfo.Query();
                    query_CompanyInfo_del.CMN_COM_CompanyInfoID = item.Ext_CompanyInfo_RefID;

                    var found_CompanyInfo_del = ORM_CMN_COM_CompanyInfo.Query.Search(Connection, Transaction, query_CompanyInfo_del).First();
                    found_CompanyInfo_del.IsDeleted = true;

                    found_CompanyInfo_del.Save(Connection, Transaction);

                    var query_BP_Company_del = new ORM_CMN_BPT_BusinessParticipant.Query();
                    query_BP_Company_del.IfCompany_CMN_COM_CompanyInfo_RefID = found_CompanyInfo_del.CMN_COM_CompanyInfoID;

                    var found_BP_Company_del = ORM_CMN_BPT_BusinessParticipant.Query.Search(Connection, Transaction, query_BP_Company_del).First();
                    found_BP_Company_del.IsDeleted = true;
                    found_BP_Company_del.Save(Connection, Transaction);

                    var query_UniversalContactDetails_del = new ORM_CMN_UniversalContactDetail.Query();
                    query_UniversalContactDetails_del.CMN_UniversalContactDetailID = found_CompanyInfo_del.Contact_UCD_RefID;

                    var found_UniversalCompanyDetails_del = ORM_CMN_UniversalContactDetail.Query.Search(Connection, Transaction, query_UniversalContactDetails_del).First();

                    found_UniversalCompanyDetails_del.IsDeleted = true;
                    found_UniversalCompanyDetails_del.Save(Connection, Transaction);

                    item.IsDeleted = true;
                    return(new FR_Guid(item.Save(Connection, Transaction), item.HEC_MedicalPractiseID));
                }

                #endregion
                #region Edit

                var query1 = new ORM_CMN_BPT_BusinessParticipant.Query();
                query1.CMN_BPT_BusinessParticipantID = item.ContactPerson_RefID;
                query1.Tenant_RefID    = securityTicket.TenantID;
                query1.IsCompany       = false;
                query1.IsNaturalPerson = true;
                query1.IsTenant        = false;

                var bussinessParticipant = ORM_CMN_BPT_BusinessParticipant.Query.Search(Connection, Transaction, query1).First();


                var query2 = new ORM_CMN_PER_PersonInfo.Query();
                query2.CMN_PER_PersonInfoID = bussinessParticipant.IfNaturalPerson_CMN_PER_PersonInfo_RefID;

                var personInfo = ORM_CMN_PER_PersonInfo.Query.Search(Connection, Transaction, query2).First();

                personInfo.FirstName    = Parameter.ContactPersonFirstName;
                personInfo.LastName     = Parameter.ContactPersonLastName;
                personInfo.PrimaryEmail = Parameter.ContactPersonEmail;
                personInfo.Save(Connection, Transaction);


                var query3 = new ORM_CMN_PER_CommunicationContact.Query();
                query3.PersonInfo_RefID = personInfo.CMN_PER_PersonInfoID;


                var communicationContacts = ORM_CMN_PER_CommunicationContact.Query.Search(Connection, Transaction, query3).First();
                communicationContacts.Contact_Type = Parameter.ContactTypePhone;
                communicationContacts.Content      = Parameter.ContactPersonPhoneNumber;

                communicationContacts.Save(Connection, Transaction);


                var query4 = new ORM_CMN_COM_CompanyInfo.Query();
                query4.CMN_COM_CompanyInfoID = item.Ext_CompanyInfo_RefID;

                var companyInfo = ORM_CMN_COM_CompanyInfo.Query.Search(Connection, Transaction, query4).First();
                companyInfo.CompanyInfo_EstablishmentNumber = Parameter.BSNR;

                companyInfo.Save(Connection, Transaction);

                var query5 = new ORM_CMN_BPT_BusinessParticipant.Query();
                query5.IfCompany_CMN_COM_CompanyInfo_RefID = companyInfo.CMN_COM_CompanyInfoID;

                var extCompany = ORM_CMN_BPT_BusinessParticipant.Query.Search(Connection, Transaction, query5).First();
                extCompany.DisplayName = Parameter.PracticeName;
                extCompany.Save(Connection, Transaction);

                var query6 = new ORM_CMN_UniversalContactDetail.Query();
                query6.CMN_UniversalContactDetailID = companyInfo.Contact_UCD_RefID;

                var companyDetails = ORM_CMN_UniversalContactDetail.Query.Search(Connection, Transaction, query6).First();

                companyDetails.ZIP               = Parameter.ZIP;
                companyDetails.Town              = Parameter.Town;
                companyDetails.Street_Name       = Parameter.PracticeStreet;
                companyDetails.Street_Number     = Parameter.PracticeNumber;
                companyDetails.Contact_Email     = Parameter.PracitceEmail;
                companyDetails.Street_Name_Line2 = Parameter.PracticeStreet2;

                companyDetails.Save(Connection, Transaction);
                #endregion
            }
            else
            {
                #region Save

                item.HEC_MedicalPractiseID = Guid.NewGuid();

                item.Creation_Timestamp = DateTime.Now;
                item.Tenant_RefID       = securityTicket.TenantID;


                //business Participants
                ORM_CMN_BPT_BusinessParticipant contactPerson = new ORM_CMN_BPT_BusinessParticipant();
                Guid businessParticipantsID = Guid.NewGuid();

                contactPerson.CMN_BPT_BusinessParticipantID = businessParticipantsID;
                contactPerson.IsCompany          = false;
                contactPerson.IsNaturalPerson    = true;
                contactPerson.IsTenant           = false;
                contactPerson.Creation_Timestamp = DateTime.Now;
                contactPerson.Tenant_RefID       = securityTicket.TenantID;

                item.ContactPerson_RefID = businessParticipantsID;

                //person info
                ORM_CMN_PER_PersonInfo personInfo = new ORM_CMN_PER_PersonInfo();
                Guid personInfoID = Guid.NewGuid();

                contactPerson.IfNaturalPerson_CMN_PER_PersonInfo_RefID = personInfoID;
                contactPerson.Save(Connection, Transaction);

                personInfo.CMN_PER_PersonInfoID = personInfoID;
                personInfo.FirstName            = Parameter.ContactPersonFirstName;
                personInfo.LastName             = Parameter.ContactPersonLastName;
                personInfo.PrimaryEmail         = Parameter.ContactPersonEmail;
                personInfo.Creation_Timestamp   = DateTime.Now;
                personInfo.Tenant_RefID         = securityTicket.TenantID;

                personInfo.Save(Connection, Transaction);

                //Communication Contact
                ORM_CMN_PER_CommunicationContact communicationContacts = new ORM_CMN_PER_CommunicationContact();

                communicationContacts.CMN_PER_CommunicationContactID = Guid.NewGuid();
                communicationContacts.PersonInfo_RefID   = personInfoID;
                communicationContacts.Contact_Type       = Parameter.ContactTypePhone;
                communicationContacts.Content            = Parameter.ContactPersonPhoneNumber;
                communicationContacts.Creation_Timestamp = DateTime.Now;
                communicationContacts.Tenant_RefID       = securityTicket.TenantID;

                communicationContacts.Save(Connection, Transaction);


                ORM_CMN_COM_CompanyInfo companyInfo = new ORM_CMN_COM_CompanyInfo();
                Guid companyInfoID = Guid.NewGuid();
                companyInfo.CMN_COM_CompanyInfoID           = companyInfoID;
                companyInfo.Creation_Timestamp              = DateTime.Now;
                companyInfo.Tenant_RefID                    = securityTicket.TenantID;
                companyInfo.CompanyInfo_EstablishmentNumber = Parameter.BSNR;

                item.Ext_CompanyInfo_RefID = companyInfoID;


                ORM_CMN_BPT_BusinessParticipant extCompany = new ORM_CMN_BPT_BusinessParticipant();
                extCompany.CMN_BPT_BusinessParticipantID = Guid.NewGuid();
                extCompany.Creation_Timestamp            = DateTime.Now;
                extCompany.Tenant_RefID    = securityTicket.TenantID;
                extCompany.DisplayName     = Parameter.PracticeName;
                extCompany.IsCompany       = true;
                extCompany.IsNaturalPerson = false;
                extCompany.IsTenant        = false;
                extCompany.IsDeleted       = false;
                extCompany.IfCompany_CMN_COM_CompanyInfo_RefID = companyInfoID;

                extCompany.Save(Connection, Transaction);

                ORM_CMN_UniversalContactDetail companyDetails = new ORM_CMN_UniversalContactDetail();
                Guid companyDetailsID = Guid.NewGuid();

                companyInfo.Contact_UCD_RefID = companyDetailsID;
                companyInfo.Save(Connection, Transaction);

                companyDetails.CMN_UniversalContactDetailID = companyDetailsID;
                companyDetails.Tenant_RefID       = securityTicket.TenantID;
                companyDetails.Creation_Timestamp = DateTime.Now;
                companyDetails.IsCompany          = true;
                companyDetails.ZIP               = Parameter.ZIP;
                companyDetails.Town              = Parameter.Town;
                companyDetails.Street_Name       = Parameter.PracticeStreet;
                companyDetails.Street_Number     = Parameter.PracticeNumber;
                companyDetails.Contact_Email     = Parameter.PracitceEmail;
                companyDetails.Street_Name_Line2 = Parameter.PracticeStreet2;
                companyDetails.IsDeleted         = false;
                companyDetails.Save(Connection, Transaction);

                item.Save(Connection, Transaction);


                #endregion
            }

            returnValue.Result = item.HEC_MedicalPractiseID;

            return(returnValue);

            #endregion UserCode
        }
Beispiel #20
0
        protected static FR_Guid Execute(DbConnection Connection, DbTransaction Transaction, P_L5PH_SP_1226 Parameter, CSV2Core.SessionSecurity.SessionSecurityTicket securityTicket = null)
        {
            #region UserCode
            var returnValue = new FR_Guid();

            ORM_HEC_Pharmacy item = new ORM_HEC_Pharmacy();


            if (Parameter.PharmacyID != Guid.Empty)
            {
                var result = item.Load(Connection, Transaction, Parameter.PharmacyID);
                if (result.Status != FR_Status.Success)
                {
                    var error = new FR_Guid();
                    error.ErrorMessage = "No Such ID";
                    error.Status       = FR_Status.Error_Internal;
                    return(error);
                }

                #region Delete

                if (Parameter.IsDeleted)
                {
                    //Contact person data finding and deleting
                    var query_BusinessParticipant_ContactPerson_del = new ORM_CMN_BPT_BusinessParticipant.Query();
                    query_BusinessParticipant_ContactPerson_del.CMN_BPT_BusinessParticipantID = item.ContactPerson_BusinessParticipant_RefID;
                    query_BusinessParticipant_ContactPerson_del.Tenant_RefID = item.Tenant_RefID;

                    ORM_CMN_BPT_BusinessParticipant found_BusinessParticipant_ContactPerson_del = ORM_CMN_BPT_BusinessParticipant.Query.Search(Connection, Transaction, query_BusinessParticipant_ContactPerson_del).First();
                    found_BusinessParticipant_ContactPerson_del.IsDeleted = true;

                    var query_PersonInfo_del = new ORM_CMN_PER_PersonInfo.Query();
                    query_PersonInfo_del.CMN_PER_PersonInfoID = found_BusinessParticipant_ContactPerson_del.IfNaturalPerson_CMN_PER_PersonInfo_RefID;

                    ORM_CMN_PER_PersonInfo found_PersonInfo_del = ORM_CMN_PER_PersonInfo.Query.Search(Connection, Transaction, query_PersonInfo_del).First();
                    found_PersonInfo_del.IsDeleted = true;

                    var query_CommunicationContact_del = new ORM_CMN_PER_CommunicationContact.Query();
                    query_CommunicationContact_del.PersonInfo_RefID = found_PersonInfo_del.CMN_PER_PersonInfoID;

                    ORM_CMN_PER_CommunicationContact found_CommunicationContact_del = ORM_CMN_PER_CommunicationContact.Query.Search(Connection, Transaction, query_CommunicationContact_del).First();
                    found_CommunicationContact_del.IsDeleted = true;

                    found_BusinessParticipant_ContactPerson_del.Save(Connection, Transaction);
                    found_CommunicationContact_del.Save(Connection, Transaction);
                    found_PersonInfo_del.Save(Connection, Transaction);


                    //Company (pharmacy) finding and deleting

                    var query_CompanyInfo_del = new ORM_CMN_COM_CompanyInfo.Query();
                    query_CompanyInfo_del.CMN_COM_CompanyInfoID = item.Ext_CompanyInfo_RefID;

                    ORM_CMN_COM_CompanyInfo found_CompanyInfo_del = ORM_CMN_COM_CompanyInfo.Query.Search(Connection, Transaction, query_CompanyInfo_del).First();
                    found_CompanyInfo_del.IsDeleted = true;

                    var query_CompanyContactDetails_del = new ORM_CMN_UniversalContactDetail.Query();
                    query_CompanyContactDetails_del.CMN_UniversalContactDetailID = found_CompanyInfo_del.Contact_UCD_RefID;

                    ORM_CMN_UniversalContactDetail found_CompanyContactDetails_del = ORM_CMN_UniversalContactDetail.Query.Search(Connection, Transaction, query_CompanyContactDetails_del).First();
                    found_CompanyContactDetails_del.IsDeleted = true;

                    var query_BusinessParticipant_Company_del = new ORM_CMN_BPT_BusinessParticipant.Query();
                    query_BusinessParticipant_Company_del.IfCompany_CMN_COM_CompanyInfo_RefID = found_CompanyInfo_del.CMN_COM_CompanyInfoID;

                    ORM_CMN_BPT_BusinessParticipant found_BusinessParticipant_Company_del = ORM_CMN_BPT_BusinessParticipant.Query.Search(Connection, Transaction, query_BusinessParticipant_Company_del).First();
                    found_BusinessParticipant_Company_del.IsDeleted = true;

                    found_CompanyInfo_del.Save(Connection, Transaction);
                    found_CompanyContactDetails_del.Save(Connection, Transaction);
                    found_BusinessParticipant_Company_del.Save(Connection, Transaction);

                    item.IsDeleted = true;
                    return(new FR_Guid(item.Save(Connection, Transaction), item.HEC_PharmacyID));
                }

                #endregion

                #region Edit

                //Contact person data finding and edit

                var query_BusinessParticipant_ContactPerson = new ORM_CMN_BPT_BusinessParticipant.Query();
                query_BusinessParticipant_ContactPerson.CMN_BPT_BusinessParticipantID = item.ContactPerson_BusinessParticipant_RefID;
                query_BusinessParticipant_ContactPerson.Tenant_RefID = item.Tenant_RefID;

                ORM_CMN_BPT_BusinessParticipant found_BusinessParticipant_ContactPerson = new ORM_CMN_BPT_BusinessParticipant();
                if (item.ContactPerson_BusinessParticipant_RefID != null && item.ContactPerson_BusinessParticipant_RefID != Guid.Empty)
                {
                    found_BusinessParticipant_ContactPerson = ORM_CMN_BPT_BusinessParticipant.Query.Search(Connection, Transaction, query_BusinessParticipant_ContactPerson).First();
                }
                else
                {
                    found_BusinessParticipant_ContactPerson = null;
                }
                if (found_BusinessParticipant_ContactPerson != null)
                {
                    var query_PersonInfo = new ORM_CMN_PER_PersonInfo.Query();
                    query_PersonInfo.CMN_PER_PersonInfoID = found_BusinessParticipant_ContactPerson.IfNaturalPerson_CMN_PER_PersonInfo_RefID;

                    ORM_CMN_PER_PersonInfo found_PersonInfo = ORM_CMN_PER_PersonInfo.Query.Search(Connection, Transaction, query_PersonInfo).First();
                    found_PersonInfo.FirstName    = Parameter.ContactFirstName;
                    found_PersonInfo.LastName     = Parameter.ContactLastName;
                    found_PersonInfo.PrimaryEmail = Parameter.ContactEmail;

                    var query_CommunicationContact = new ORM_CMN_PER_CommunicationContact.Query();
                    query_CommunicationContact.PersonInfo_RefID = found_PersonInfo.CMN_PER_PersonInfoID;

                    ORM_CMN_PER_CommunicationContact found_CommunicationContact = ORM_CMN_PER_CommunicationContact.Query.Search(Connection, Transaction, query_CommunicationContact).First();
                    found_CommunicationContact.Content = Parameter.ContactPhoneNumber;

                    found_CommunicationContact.Save(Connection, Transaction);
                    found_PersonInfo.Save(Connection, Transaction);
                }
                else
                {
                    ORM_CMN_BPT_BusinessParticipant contactPerson = new ORM_CMN_BPT_BusinessParticipant();
                    Guid businessParticipantID = Guid.NewGuid();

                    contactPerson.CMN_BPT_BusinessParticipantID = businessParticipantID;
                    contactPerson.IsCompany          = false;
                    contactPerson.IsNaturalPerson    = true;
                    contactPerson.IsTenant           = false;
                    contactPerson.Creation_Timestamp = DateTime.Now;
                    contactPerson.Tenant_RefID       = securityTicket.TenantID;

                    item.ContactPerson_BusinessParticipant_RefID = businessParticipantID;

                    //person info
                    ORM_CMN_PER_PersonInfo personInfo = new ORM_CMN_PER_PersonInfo();
                    Guid personInfoID = Guid.NewGuid();

                    contactPerson.IfNaturalPerson_CMN_PER_PersonInfo_RefID = personInfoID;
                    contactPerson.Save(Connection, Transaction);

                    personInfo.CMN_PER_PersonInfoID = personInfoID;
                    personInfo.FirstName            = Parameter.ContactFirstName;
                    personInfo.LastName             = Parameter.ContactLastName;
                    personInfo.PrimaryEmail         = Parameter.ContactEmail;
                    personInfo.Creation_Timestamp   = DateTime.Now;
                    personInfo.Tenant_RefID         = securityTicket.TenantID;

                    personInfo.Save(Connection, Transaction);

                    //Communication Contact
                    ORM_CMN_PER_CommunicationContact communicationContacts = new ORM_CMN_PER_CommunicationContact();

                    communicationContacts.CMN_PER_CommunicationContactID = Guid.NewGuid();
                    communicationContacts.PersonInfo_RefID   = personInfoID;
                    communicationContacts.Contact_Type       = Parameter.ContactTypePhone;
                    communicationContacts.Content            = Parameter.ContactPhoneNumber;
                    communicationContacts.Creation_Timestamp = DateTime.Now;
                    communicationContacts.Tenant_RefID       = securityTicket.TenantID;

                    communicationContacts.Save(Connection, Transaction);


                    item.ContactPerson_BusinessParticipant_RefID = businessParticipantID;
                    item.Save(Connection, Transaction);
                }

                //Company (pharmacy) finding and edit

                var query_CompanyInfo = new ORM_CMN_COM_CompanyInfo.Query();
                query_CompanyInfo.CMN_COM_CompanyInfoID = item.Ext_CompanyInfo_RefID;

                ORM_CMN_COM_CompanyInfo found_CompanyInfo = ORM_CMN_COM_CompanyInfo.Query.Search(Connection, Transaction, query_CompanyInfo).First();

                var query_CompanyContactDetails = new ORM_CMN_UniversalContactDetail.Query();
                query_CompanyContactDetails.CMN_UniversalContactDetailID = found_CompanyInfo.Contact_UCD_RefID;

                ORM_CMN_UniversalContactDetail found_CompanyContactDetails = ORM_CMN_UniversalContactDetail.Query.Search(Connection, Transaction, query_CompanyContactDetails).FirstOrDefault();
                if (found_CompanyContactDetails != null)
                {
                    found_CompanyContactDetails.CompanyName_Line1 = Parameter.PharmacyName;
                    found_CompanyContactDetails.Contact_Email     = Parameter.MainEmail;
                    found_CompanyContactDetails.Street_Name       = Parameter.Street;
                    found_CompanyContactDetails.Street_Number     = Parameter.Number;
                    found_CompanyContactDetails.Street_Name_Line2 = Parameter.Street2;
                    found_CompanyContactDetails.Town = Parameter.Town;
                    found_CompanyContactDetails.ZIP  = Parameter.ZIP;
                    found_CompanyContactDetails.Save(Connection, Transaction);
                }
                else
                {
                    ORM_CMN_UniversalContactDetail universalContactDetails = new ORM_CMN_UniversalContactDetail();
                    universalContactDetails.CMN_UniversalContactDetailID = Guid.NewGuid();
                    universalContactDetails.IsCompany         = true;
                    universalContactDetails.CompanyName_Line1 = Parameter.PharmacyName;
                    universalContactDetails.Street_Name       = Parameter.Street;
                    universalContactDetails.Street_Name_Line2 = Parameter.Street2;
                    universalContactDetails.Street_Number     = Parameter.Number;
                    universalContactDetails.Contact_Email     = Parameter.MainEmail;
                    universalContactDetails.ZIP          = Parameter.ZIP;
                    universalContactDetails.Town         = Parameter.Town;
                    universalContactDetails.Tenant_RefID = securityTicket.TenantID;


                    universalContactDetails.Save(Connection, Transaction);

                    found_CompanyInfo.Contact_UCD_RefID = universalContactDetails.CMN_UniversalContactDetailID;
                    found_CompanyInfo.Save(Connection, Transaction);
                }

                var query_BusinessParticipant_Company = new ORM_CMN_BPT_BusinessParticipant.Query();
                query_BusinessParticipant_Company.IfCompany_CMN_COM_CompanyInfo_RefID = found_CompanyInfo.CMN_COM_CompanyInfoID;

                ORM_CMN_BPT_BusinessParticipant found_BusinessParticipant_Company = ORM_CMN_BPT_BusinessParticipant.Query.Search(Connection, Transaction, query_BusinessParticipant_Company).First();
                found_BusinessParticipant_Company.DisplayName = Parameter.PharmacyName;


                found_BusinessParticipant_Company.Save(Connection, Transaction);

                #endregion
            }
            else
            {
                #region Save

                item.HEC_PharmacyID = Guid.NewGuid();

                item.Creation_Timestamp = DateTime.Now;
                item.Tenant_RefID       = securityTicket.TenantID;

                //business Participants
                ORM_CMN_BPT_BusinessParticipant contactPerson = new ORM_CMN_BPT_BusinessParticipant();
                Guid businessParticipantID = Guid.NewGuid();

                contactPerson.CMN_BPT_BusinessParticipantID = businessParticipantID;
                contactPerson.IsCompany          = false;
                contactPerson.IsNaturalPerson    = true;
                contactPerson.IsTenant           = false;
                contactPerson.Creation_Timestamp = DateTime.Now;
                contactPerson.Tenant_RefID       = securityTicket.TenantID;

                item.ContactPerson_BusinessParticipant_RefID = businessParticipantID;

                //person info
                ORM_CMN_PER_PersonInfo personInfo = new ORM_CMN_PER_PersonInfo();
                Guid personInfoID = Guid.NewGuid();

                contactPerson.IfNaturalPerson_CMN_PER_PersonInfo_RefID = personInfoID;
                contactPerson.Save(Connection, Transaction);

                personInfo.CMN_PER_PersonInfoID = personInfoID;
                personInfo.FirstName            = Parameter.ContactFirstName;
                personInfo.LastName             = Parameter.ContactLastName;
                personInfo.PrimaryEmail         = Parameter.ContactEmail;
                personInfo.Creation_Timestamp   = DateTime.Now;
                personInfo.Tenant_RefID         = securityTicket.TenantID;

                personInfo.Save(Connection, Transaction);

                //Communication Contact
                ORM_CMN_PER_CommunicationContact communicationContacts = new ORM_CMN_PER_CommunicationContact();

                communicationContacts.CMN_PER_CommunicationContactID = Guid.NewGuid();
                communicationContacts.PersonInfo_RefID   = personInfoID;
                communicationContacts.Contact_Type       = Parameter.ContactTypePhone;
                communicationContacts.Content            = Parameter.ContactPhoneNumber;
                communicationContacts.Creation_Timestamp = DateTime.Now;
                communicationContacts.Tenant_RefID       = securityTicket.TenantID;

                communicationContacts.Save(Connection, Transaction);

                //ORM_CMN_COM_CompanyInfo companyInfo = new ORM_CMN_COM_CompanyInfo();
                //Guid companyInfoID = Guid.NewGuid();

                ORM_CMN_COM_CompanyInfo extCompanyInfo = new ORM_CMN_COM_CompanyInfo();
                Guid extCompanyInfoID = Guid.NewGuid();
                extCompanyInfo.CMN_COM_CompanyInfoID = extCompanyInfoID;
                Guid contactUCDID = Guid.NewGuid();
                extCompanyInfo.Contact_UCD_RefID  = contactUCDID;
                extCompanyInfo.Creation_Timestamp = DateTime.Now;
                extCompanyInfo.Tenant_RefID       = securityTicket.TenantID;

                item.Ext_CompanyInfo_RefID = extCompanyInfoID;

                ORM_CMN_UniversalContactDetail universalContactDetails = new ORM_CMN_UniversalContactDetail();
                universalContactDetails.CMN_UniversalContactDetailID = contactUCDID;
                universalContactDetails.IsCompany         = true;
                universalContactDetails.CompanyName_Line1 = Parameter.PharmacyName;
                universalContactDetails.Street_Name       = Parameter.Street;
                universalContactDetails.Street_Name_Line2 = Parameter.Street2;
                universalContactDetails.Street_Number     = Parameter.Number;
                universalContactDetails.Contact_Email     = Parameter.MainEmail;
                universalContactDetails.ZIP          = Parameter.ZIP;
                universalContactDetails.Town         = Parameter.Town;
                universalContactDetails.Tenant_RefID = securityTicket.TenantID;

                ORM_CMN_BPT_BusinessParticipant extCompany = new ORM_CMN_BPT_BusinessParticipant();
                extCompany.CMN_BPT_BusinessParticipantID = Guid.NewGuid();
                extCompany.Creation_Timestamp            = DateTime.Now;
                extCompany.Tenant_RefID    = securityTicket.TenantID;
                extCompany.DisplayName     = Parameter.PharmacyName;
                extCompany.IsCompany       = true;
                extCompany.IsNaturalPerson = false;
                extCompany.IsTenant        = false;
                extCompany.IsDeleted       = false;
                extCompany.IfCompany_CMN_COM_CompanyInfo_RefID = extCompanyInfoID;

                extCompany.Save(Connection, Transaction);
                extCompanyInfo.Save(Connection, Transaction);
                universalContactDetails.Save(Connection, Transaction);
                item.Save(Connection, Transaction);

                returnValue.Result = item.HEC_PharmacyID;
                #endregion
            }

            return(returnValue);

            #endregion UserCode
        }
Beispiel #21
0
        protected static FR_Guid Execute(DbConnection Connection, DbTransaction Transaction, P_L5EM_SE_1657 Parameter, CSV2Core.SessionSecurity.SessionSecurityTicket securityTicket = null)
        {
            #region UserCode
            var returnValue = new FR_Guid();
            //Put your code here

            ORM_CMN_Address address = new ORM_CMN_Address();
            if (Parameter.CMN_AddressID != Guid.Empty)
            {
                var result = address.Load(Connection, Transaction, Parameter.CMN_AddressID);
                if (result.Status != FR_Status.Success || address.CMN_AddressID == Guid.Empty)
                {
                    var error = new FR_Guid();
                    error.ErrorMessage = "No Such ID";
                    error.Status       = FR_Status.Error_Internal;
                    return(error);
                }
            }
            address.City_Name       = Parameter.City_Name;
            address.Street_Name     = Parameter.Street_Name;
            address.Street_Number   = Parameter.Street_Number;
            address.Country_Name    = Parameter.Country_Name;
            address.Province_Name   = Parameter.Province_Name;
            address.Tenant_RefID    = securityTicket.TenantID;
            address.City_PostalCode = Parameter.City_PostalCode;
            address.Save(Connection, Transaction);
            CSV2Core.DlTrace.Trace("success address");
            ORM_CMN_PER_PersonInfo person = new ORM_CMN_PER_PersonInfo();
            if (Parameter.CMN_PER_PersonInfoID != Guid.Empty)
            {
                var result = person.Load(Connection, Transaction, Parameter.CMN_PER_PersonInfoID);
                if (result.Status != FR_Status.Success || person.CMN_PER_PersonInfoID == Guid.Empty)
                {
                    var error = new FR_Guid();
                    error.ErrorMessage = "No Such ID";
                    error.Status       = FR_Status.Error_Internal;
                    return(error);
                }
            }

            //person.AccountImage_URL = Parameter.ProfileImage_Document_RefID;
            person.FirstName     = Parameter.FirstName;
            person.LastName      = Parameter.LastName;
            person.PrimaryEmail  = Parameter.PrimaryEmail;
            person.Tenant_RefID  = securityTicket.TenantID;
            person.Title         = Parameter.Title;
            person.Address_RefID = address.CMN_AddressID;
            person.ProfileImage_Document_RefID = Parameter.ImageID;
            person.BirthDate        = Parameter.BirthDate;
            person.NumberOfChildren = Parameter.TaxInfoParameter != null ? Parameter.TaxInfoParameter.NumberOfChildren : 0;
            person.Save(Connection, Transaction);
            CSV2Core.DlTrace.Trace("success persopm");

            var contactQuery = new ORM_CMN_PER_CommunicationContact.Query();
            contactQuery.Tenant_RefID     = securityTicket.TenantID;
            contactQuery.PersonInfo_RefID = person.CMN_PER_PersonInfoID;
            contactQuery.IsDeleted        = false;
            var deleteContacts = ORM_CMN_PER_CommunicationContact.Query.SoftDelete(Connection, Transaction, contactQuery);
            foreach (var parContact in Parameter.Contacts)
            {
                ORM_CMN_PER_CommunicationContact contact = new ORM_CMN_PER_CommunicationContact();
                if (parContact.CMN_PER_CommunicationContactID != Guid.Empty)
                {
                    var result = contact.Load(Connection, Transaction, parContact.CMN_PER_CommunicationContactID);
                    if (result.Status != FR_Status.Success || contact.CMN_PER_CommunicationContactID == Guid.Empty)
                    {
                        var error = new FR_Guid();
                        error.ErrorMessage = "No Such ID";
                        error.Status       = FR_Status.Error_Internal;
                        return(error);
                    }
                }
                contact.Content          = parContact.Content;
                contact.Contact_Type     = parContact.CMN_PER_CommunicationContact_TypeID;
                contact.Tenant_RefID     = securityTicket.TenantID;
                contact.PersonInfo_RefID = person.CMN_PER_PersonInfoID;
                contact.Save(Connection, Transaction);
                CSV2Core.DlTrace.Trace("success contact");
            }

            ORM_CMN_BPT_BusinessParticipant bParticipant = new ORM_CMN_BPT_BusinessParticipant();
            if (Parameter.CMN_BPT_BusinessParticipantID != Guid.Empty)
            {
                var result = bParticipant.Load(Connection, Transaction, Parameter.CMN_BPT_BusinessParticipantID);
                if (result.Status != FR_Status.Success || bParticipant.CMN_BPT_BusinessParticipantID == Guid.Empty)
                {
                    var error = new FR_Guid();
                    error.ErrorMessage = "No Such ID";
                    error.Status       = FR_Status.Error_Internal;
                    return(error);
                }
            }
            bParticipant.DisplayName = Parameter.DisplayName;
            bParticipant.IfNaturalPerson_CMN_PER_PersonInfo_RefID = person.CMN_PER_PersonInfoID;
            bParticipant.IsNaturalPerson = true;
            bParticipant.Tenant_RefID    = securityTicket.TenantID;
            bParticipant.Save(Connection, Transaction);
            ORM_CMN_BPT_EMP_Employee employee = new ORM_CMN_BPT_EMP_Employee();
            CSV2Core.DlTrace.Trace("success bpart");


            if (Parameter.CMN_BPT_EMP_EmployeeID != Guid.Empty)
            {
                var result = employee.Load(Connection, Transaction, Parameter.CMN_BPT_EMP_EmployeeID);
                if (result.Status != FR_Status.Success || employee.CMN_BPT_EMP_EmployeeID == Guid.Empty)
                {
                    var error = new FR_Guid();
                    error.ErrorMessage = "No Such ID";
                    error.Status       = FR_Status.Error_Internal;
                    return(error);
                }
            }
            employee.BusinessParticipant_RefID = bParticipant.CMN_BPT_BusinessParticipantID;
            employee.Staff_Number     = Parameter.Staff_Number;
            employee.StandardFunction = Parameter.StandardFunction;
            employee.Tenant_RefID     = securityTicket.TenantID;
            employee.Save(Connection, Transaction);
            CSV2Core.DlTrace.Trace("success employee");


            ORM_CMN_BPT_EMP_EmploymentRelationship employmentRelationship = new ORM_CMN_BPT_EMP_EmploymentRelationship();
            if (Parameter.CMN_BPT_EMP_Employee_EmploymentRelationshipID != Guid.Empty)
            {
                var result = employmentRelationship.Load(Connection, Transaction, Parameter.CMN_BPT_EMP_Employee_EmploymentRelationshipID);
                if (result.Status != FR_Status.Success || employmentRelationship.CMN_BPT_EMP_EmploymentRelationshipID == Guid.Empty)
                {
                    var error = new FR_Guid();
                    error.ErrorMessage = "No Such ID";
                    error.Status       = FR_Status.Error_Internal;
                    return(error);
                }
            }
            employmentRelationship.Work_StartDate = Parameter.Work_StartDate;

            bool resignationDateChanged = false;
            if (employmentRelationship.Work_EndDate != Parameter.Work_EndDate)
            {
                resignationDateChanged = true;
            }

            employmentRelationship.Work_EndDate   = Parameter.Work_EndDate;
            employmentRelationship.Tenant_RefID   = securityTicket.TenantID;
            employmentRelationship.Employee_RefID = employee.CMN_BPT_EMP_EmployeeID;
            employmentRelationship.Save(Connection, Transaction);
            CSV2Core.DlTrace.Trace("success employmentRelationship");

            if (Parameter.Work_EndDate.Ticks != 0)
            {
                ORM_CMN_BPT_EMP_EmploymentRelationship_2_WorkingContract.Query empRelationShipToWorkingContractQuery = new ORM_CMN_BPT_EMP_EmploymentRelationship_2_WorkingContract.Query();
                empRelationShipToWorkingContractQuery.EmploymentRelationship_RefID = employmentRelationship.CMN_BPT_EMP_EmploymentRelationshipID;
                empRelationShipToWorkingContractQuery.Tenant_RefID = securityTicket.TenantID;
                empRelationShipToWorkingContractQuery.IsDeleted    = false;
                List <ORM_CMN_BPT_EMP_EmploymentRelationship_2_WorkingContract> workingContractAssignments = ORM_CMN_BPT_EMP_EmploymentRelationship_2_WorkingContract.Query.Search(Connection, Transaction, empRelationShipToWorkingContractQuery);
                foreach (var workingContractAssignment in workingContractAssignments)
                {
                    ORM_CMN_BPT_EMP_WorkingContract workingContract = new ORM_CMN_BPT_EMP_WorkingContract();
                    if (workingContractAssignment.WorkingContract_RefID != Guid.Empty)
                    {
                        var result = workingContract.Load(Connection, Transaction, workingContractAssignment.WorkingContract_RefID);
                        if (result.Status != FR_Status.Success || workingContract.CMN_BPT_EMP_WorkingContractID == Guid.Empty)
                        {
                            var error = new FR_Guid();
                            error.ErrorMessage = "No Such ID";
                            error.Status       = FR_Status.Error_Internal;
                            return(error);
                        }
                    }
                    if (workingContract.Contract_EndDate.Ticks == 0 || workingContract.Contract_EndDate.Ticks > Parameter.Work_EndDate.Ticks)
                    {
                        workingContract.Contract_EndDate         = Parameter.Work_EndDate;
                        workingContract.IsContractEndDateDefined = true;
                        workingContract.Save(Connection, Transaction);
                    }
                }
            }

            var activeTimeFrame = cls_Get_Active_CalculationTimeFrame.Invoke(Connection, Transaction, securityTicket).Result;

            var timeframes   = cls_Get_CalculationTimeFramesForTenant.Invoke(Connection, Transaction, securityTicket).Result.ToList();
            var resultFrames = timeframes.Where(i => i.CalculationTimeframe_StartDate.Year == employmentRelationship.Work_StartDate.Year).ToList();
            if (resultFrames.Count == 0)
            {
                var newFrame    = new ORM_CMN_CAL_CalculationTimeframe();
                int currentYear = Parameter.Work_StartDate.Year;
                while (currentYear < activeTimeFrame.CalculationTimeframe_StartDate.Year)
                {
                    if (!timeframes.Any(i => i.CalculationTimeframe_StartDate.Year == currentYear))
                    {
                        newFrame.CalculationTimeframe_StartDate        = new DateTime(currentYear, 1, 1);
                        newFrame.CalculationTimeframe_EstimatedEndDate = new DateTime(currentYear, 12, 31);
                        newFrame.Tenant_RefID = securityTicket.TenantID;
                        newFrame.Save(Connection, Transaction);
                        newFrame = new ORM_CMN_CAL_CalculationTimeframe();
                    }
                    currentYear++;

                    ORM_CMN_BPT_EMP_EmploymentRelationship_Timeframe relationshipFrame = new ORM_CMN_BPT_EMP_EmploymentRelationship_Timeframe();
                    relationshipFrame.CalculationTimeframe_RefID   = newFrame.CMN_CAL_CalculationTimeframeID;
                    relationshipFrame.EmploymentRelationship_RefID = employmentRelationship.CMN_BPT_EMP_EmploymentRelationshipID;
                    relationshipFrame.Tenant_RefID = securityTicket.TenantID;
                    relationshipFrame.Save(Connection, Transaction);
                }
            }
            else
            {
                timeframes = timeframes.Where(i => i.CalculationTimeframe_StartDate.Year < activeTimeFrame.CalculationTimeframe_StartDate.Year && i.CalculationTimeframe_StartDate.Year >= employmentRelationship.Work_StartDate.Year).ToList();
                foreach (var timeframe in timeframes)
                {
                    ORM_CMN_BPT_EMP_EmploymentRelationship_Timeframe.Query relationshipFrameQuery = new ORM_CMN_BPT_EMP_EmploymentRelationship_Timeframe.Query();
                    relationshipFrameQuery.CalculationTimeframe_RefID   = timeframe.CMN_CAL_CalculationTimeframeID;
                    relationshipFrameQuery.EmploymentRelationship_RefID = employmentRelationship.CMN_BPT_EMP_EmploymentRelationshipID;
                    relationshipFrameQuery.Tenant_RefID = securityTicket.TenantID;
                    List <ORM_CMN_BPT_EMP_EmploymentRelationship_Timeframe> oldContractFrames = ORM_CMN_BPT_EMP_EmploymentRelationship_Timeframe.Query.Search(Connection, Transaction, relationshipFrameQuery);
                    if (oldContractFrames.Count == 0)
                    {
                        ORM_CMN_BPT_EMP_EmploymentRelationship_Timeframe relationshipFrame = new ORM_CMN_BPT_EMP_EmploymentRelationship_Timeframe();
                        relationshipFrame.CalculationTimeframe_RefID   = timeframe.CMN_CAL_CalculationTimeframeID;
                        relationshipFrame.EmploymentRelationship_RefID = employmentRelationship.CMN_BPT_EMP_EmploymentRelationshipID;
                        relationshipFrame.Tenant_RefID = securityTicket.TenantID;
                        relationshipFrame.Save(Connection, Transaction);
                    }
                }
            }



            P_L5EM_GAERCTFFE_1405 timeFrameParam = new P_L5EM_GAERCTFFE_1405();
            timeFrameParam.EmployeeID = employee.CMN_BPT_EMP_EmployeeID;
            L5EM_GAERCTFFE_1405 employeeTimeFrame = cls_Get_Active_EmployeeRelationshipTimeFrame_For_EmployeeID.Invoke(Connection, Transaction, timeFrameParam, securityTicket).Result;
            if (employeeTimeFrame == null)
            {
                ORM_CMN_BPT_EMP_EmploymentRelationship_Timeframe timeFrame = new ORM_CMN_BPT_EMP_EmploymentRelationship_Timeframe();
                timeFrame.CalculationTimeframe_RefID   = activeTimeFrame.CMN_CAL_CalculationTimeframeID;
                timeFrame.EmploymentRelationship_RefID = employmentRelationship.CMN_BPT_EMP_EmploymentRelationshipID;
                timeFrame.Tenant_RefID = securityTicket.TenantID;
                timeFrame.Save(Connection, Transaction);
                CSV2Core.DlTrace.Trace("success timeFrame");
            }

            //save employee professions
            P_L5EM_SEP_1447 saveProfessionsPar = new P_L5EM_SEP_1447();
            saveProfessionsPar.Employee_RefID    = employee.CMN_BPT_EMP_EmployeeID;
            saveProfessionsPar.FunctionHistories = Parameter.FunctionHistories;
            cls_Save_EmployeeFunctionHistory.Invoke(Connection, Transaction, saveProfessionsPar, securityTicket);
            CSV2Core.DlTrace.Trace("success employee function history");

            //save workplace histories
            P_L5EM_SWPH_1625 saveWorkplaceHistoryPar = new P_L5EM_SWPH_1625();
            saveWorkplaceHistoryPar.Employee_RefID     = employee.CMN_BPT_EMP_EmployeeID;
            saveWorkplaceHistoryPar.WorkplaceHistories = Parameter.WorkplaceHistories;
            cls_Save_WorkplaceHistories.Invoke(Connection, Transaction, saveWorkplaceHistoryPar, securityTicket);
            CSV2Core.DlTrace.Trace("success workplaceHistories");

            P_L5EM_SUED_1648 saveDocuments = new P_L5EM_SUED_1648();
            saveDocuments.Employee_RefID = employee.CMN_BPT_EMP_EmployeeID;
            saveDocuments.Documents      = Parameter.Documents;
            cls_Save_Uploaded_Employee_Document.Invoke(Connection, Transaction, saveDocuments, securityTicket);
            CSV2Core.DlTrace.Trace("success documents");

            P_L5EM_SEQS_0959 saveSkillsPar = new P_L5EM_SEQS_0959();
            saveSkillsPar.Employee_RefID = employee.CMN_BPT_EMP_EmployeeID;
            saveSkillsPar.Skills         = Parameter.Skills;
            cls_Save_Employee_QualificationSkills.Invoke(Connection, Transaction, saveSkillsPar, securityTicket);
            CSV2Core.DlTrace.Trace("success skills");

            CSV2Core.DlTrace.Trace("AccountID :" + Parameter.USR_AccountID);

            if (Parameter.USR_AccountID != null && Parameter.USR_AccountID != Guid.Empty)
            {
                CSV2Core.DlTrace.Trace("success param");

                ORM_USR_Account account = new ORM_USR_Account();
                if (Parameter.USR_AccountID != Guid.Empty)
                {
                    var result = account.Load(Connection, Transaction, Parameter.USR_AccountID);
                    if (account.USR_AccountID == Guid.Empty)
                    {
                        account.USR_AccountID = Guid.NewGuid();
                        account.AccountType   = 2;
                    }
                    account.Username = Parameter.username;
                    account.DefaultLanguage_RefID     = Parameter.LanguageID;
                    account.BusinessParticipant_RefID = bParticipant.CMN_BPT_BusinessParticipantID;
                    account.Tenant_RefID = securityTicket.TenantID;
                    account.Save(Connection, Transaction);


                    var personToAccountQuery = new ORM_CMN_PER_PersonInfo_2_Account.Query();
                    personToAccountQuery.Tenant_RefID      = securityTicket.TenantID;
                    personToAccountQuery.USR_Account_RefID = account.USR_AccountID;
                    personToAccountQuery.IsDeleted         = false;
                    var personToAccounts = ORM_CMN_PER_PersonInfo_2_Account.Query.Search(Connection, Transaction, personToAccountQuery);
                    if (personToAccounts.Count != 0)
                    {
                        ORM_CMN_PER_PersonInfo_2_Account personToAccount = personToAccounts[0];
                        personToAccount.CMN_PER_PersonInfo_RefID = person.CMN_PER_PersonInfoID;
                        personToAccount.USR_Account_RefID        = account.USR_AccountID;
                        personToAccount.Tenant_RefID             = securityTicket.TenantID;
                        personToAccount.Save(Connection, Transaction);
                    }
                    else
                    {
                        ORM_CMN_PER_PersonInfo_2_Account personToAccount = new ORM_CMN_PER_PersonInfo_2_Account();
                        personToAccount.CMN_PER_PersonInfo_RefID = person.CMN_PER_PersonInfoID;
                        personToAccount.USR_Account_RefID        = account.USR_AccountID;
                        personToAccount.Tenant_RefID             = securityTicket.TenantID;
                        personToAccount.Save(Connection, Transaction);
                    }
                }



                if (Parameter.Rights != null)
                {
                    foreach (var rightsParam in Parameter.Rights)
                    {
                        if (rightsParam.RightAssinmentID == Guid.Empty && rightsParam.RightID != Guid.Empty)
                        {
                            var right2account = new ORM_USR_Account_2_FunctionLevelRight();
                            right2account.Account_RefID            = Parameter.USR_AccountID;
                            right2account.FunctionLevelRight_RefID = rightsParam.RightID;
                            right2account.Tenant_RefID             = securityTicket.TenantID;
                            right2account.Save(Connection, Transaction);
                            CSV2Core.DlTrace.Trace("success save right: " + right2account.FunctionLevelRight_RefID);
                        }

                        if (rightsParam.RightAssinmentID != Guid.Empty && rightsParam.RightID == Guid.Empty)
                        {
                            var right2account = new ORM_USR_Account_2_FunctionLevelRight();
                            if (rightsParam.RightAssinmentID != Guid.Empty)
                            {
                                var result = right2account.Load(Connection, Transaction, rightsParam.RightAssinmentID);
                                if (result.Status != FR_Status.Success || right2account.AssignmentID == Guid.Empty)
                                {
                                    var error = new FR_Guid();
                                    error.ErrorMessage = "No Such ID";
                                    error.Status       = FR_Status.Error_Internal;
                                    return(error);
                                }
                            }
                            right2account.IsDeleted = true;
                            right2account.Save(Connection, Transaction);
                            CSV2Core.DlTrace.Trace("success save right2Acc: " + right2account.FunctionLevelRight_RefID);
                        }
                    }
                }
            }

            CSV2Core.DlTrace.Trace("emp id wtf " + Parameter.CMN_BPT_EMP_EmployeeID);

            if (Parameter.CMN_BPT_EMP_EmployeeID == Guid.Empty || resignationDateChanged)
            {
                var enterpriseService          = InfrastructureFactory.CreateEnterpriseService();
                KeyPerformanceIndicator action = new KeyPerformanceIndicator();
                action.PerformedByAccountID     = securityTicket.AccountID;
                action.PerformedByApplicationID = Parameter.ApplicationID;
                action.PerformedOn               = DateTime.Now;
                action.PerformedByTenantID       = securityTicket.TenantID;
                action.KeyPerformanceIndicatorID = Guid.Parse("4dda967a-5399-4929-afae-7af64699895b");
                action.Value = cls_Get_Employees_For_Tenant.Invoke(Connection, Transaction, securityTicket).Result.Where(i => i.Work_EndDate.Ticks == 0 || i.Work_EndDate.Ticks > DateTime.Now.Ticks).ToArray().Length;

                var result = enterpriseService.SendMessage(action.ToPayload(), KeyPerformanceIndicator.MESSAGE_TYPE, Parameter.ApplicationID, EMessageRecipient.CUSTOMER_MANAGEMENT_PLATFORM);
                // ServerLog.Instance.Info("Enterprise message sending " + (result.Code == 200 ? "successful" : "failed"));
                CSV2Core.DlTrace.Trace("success send kpi");
            }

            Parameter.TaxInfoParameter.EmployeeID = employee.CMN_BPT_EMP_EmployeeID;
            Parameter.TaxInfoParameter.CMN_BPT_BusinessParticipantID = bParticipant.CMN_BPT_BusinessParticipantID;
            cls_Save_Employee_TaxInformation.Invoke(Connection, Transaction, Parameter.TaxInfoParameter, securityTicket);
            cls_Save_Employee_BankAccount.Invoke(Connection, Transaction, Parameter.BankAccountParameter, securityTicket);
            Parameter.SocialSecurity.CMN_PER_PersonInfoID          = person.CMN_PER_PersonInfoID;
            Parameter.SocialSecurity.CMN_BPT_EMP_EmployeeID        = employee.CMN_BPT_EMP_EmployeeID;
            Parameter.SocialSecurity.CMN_BPT_BusinessParticipantID = bParticipant.CMN_BPT_BusinessParticipantID;
            cls_Save_Employee_SocialSecurity.Invoke(Connection, Transaction, Parameter.SocialSecurity, securityTicket);

            returnValue.Result = employee.CMN_BPT_EMP_EmployeeID;
            return(returnValue);

            #endregion UserCode
        }
Beispiel #22
0
        protected static FR_Guid Execute(DbConnection Connection, DbTransaction Transaction, P_L3TX_STXO_0929 Parameter, CSV2Core.SessionSecurity.SessionSecurityTicket securityTicket = null)
        {
            #region UserCode
            var returnValue = new FR_Guid();
            var item        = new ORM_ACC_TAX_TaxOffice();
            if (Parameter.ACC_TAX_TaxOfficeID != Guid.Empty)
            {
                var result = item.Load(Connection, Transaction, Parameter.ACC_TAX_TaxOfficeID);
                if (result.Status != FR_Status.Success || item.ACC_TAX_TaxOfficeID == Guid.Empty)
                {
                    var error = new FR_Guid();
                    error.ErrorMessage = "No Such ID";
                    error.Status       = FR_Status.Error_Internal;
                    return(error);
                }

                ORM_CMN_BPT_BusinessParticipant.Query bptQuery = new ORM_CMN_BPT_BusinessParticipant.Query();
                bptQuery.CMN_BPT_BusinessParticipantID = item.CMN_BPT_BusinessParticipant_RefID;
                bptQuery.Tenant_RefID = securityTicket.TenantID;
                bptQuery.IsDeleted    = false;

                ORM_CMN_BPT_BusinessParticipant bparticipant = ORM_CMN_BPT_BusinessParticipant.Query.Search(Connection, Transaction, bptQuery).FirstOrDefault();

                bparticipant.DisplayName = Parameter.DisplayName;
                bparticipant.Save(Connection, Transaction);

                ORM_CMN_COM_CompanyInfo.Query cmpInfoQuery = new ORM_CMN_COM_CompanyInfo.Query();
                cmpInfoQuery.CMN_COM_CompanyInfoID = bparticipant.IfCompany_CMN_COM_CompanyInfo_RefID;
                cmpInfoQuery.IsDeleted             = false;
                cmpInfoQuery.Tenant_RefID          = securityTicket.TenantID;

                ORM_CMN_COM_CompanyInfo companyInfo = ORM_CMN_COM_CompanyInfo.Query.Search(Connection, Transaction, cmpInfoQuery).FirstOrDefault();
                companyInfo.VATIdentificationNumber = Parameter.VATIdentificationNumber;
                companyInfo.Save(Connection, Transaction);
                returnValue.Result = item.ACC_TAX_TaxOfficeID;

                if (companyInfo.Contact_UCD_RefID != Guid.Empty)
                {
                    var countries = cls_Get_AllCountries.Invoke(Connection, Transaction, securityTicket).Result;

                    ORM_CMN_UniversalContactDetail.Query ucdQuery = new ORM_CMN_UniversalContactDetail.Query();
                    ucdQuery.CMN_UniversalContactDetailID = companyInfo.Contact_UCD_RefID;
                    ucdQuery.Tenant_RefID = securityTicket.TenantID;
                    ucdQuery.IsDeleted    = false;

                    ORM_CMN_UniversalContactDetail ucd = ORM_CMN_UniversalContactDetail.Query.Search(Connection, Transaction, ucdQuery).FirstOrDefault();
                    ucd.Country_639_1_ISOCode = Parameter.Country_ISO;
                    ucd.Save(Connection, Transaction);
                }
            }
            else
            {
                ORM_CMN_COM_CompanyInfo companyInfo = new ORM_CMN_COM_CompanyInfo();
                companyInfo.VATIdentificationNumber = Parameter.VATIdentificationNumber;
                companyInfo.Tenant_RefID            = securityTicket.TenantID;


                ORM_CMN_BPT_BusinessParticipant bparticipant = new ORM_CMN_BPT_BusinessParticipant();
                bparticipant.DisplayName = Parameter.DisplayName;
                bparticipant.IsCompany   = true;
                bparticipant.IfCompany_CMN_COM_CompanyInfo_RefID = companyInfo.CMN_COM_CompanyInfoID;
                bparticipant.Tenant_RefID = securityTicket.TenantID;
                bparticipant.Save(Connection, Transaction);

                ORM_ACC_TAX_TaxOffice taxOffice = new ORM_ACC_TAX_TaxOffice();
                taxOffice.CMN_BPT_BusinessParticipant_RefID = bparticipant.CMN_BPT_BusinessParticipantID;
                taxOffice.Tenant_RefID = securityTicket.TenantID;
                taxOffice.Save(Connection, Transaction);
                returnValue.Result = taxOffice.ACC_TAX_TaxOfficeID;

                if (Parameter.Country_ISO != "")
                {
                    var countries = cls_Get_AllCountries.Invoke(Connection, Transaction, securityTicket).Result;
                    ORM_CMN_UniversalContactDetail ucd = new ORM_CMN_UniversalContactDetail();
                    ucd.Country_639_1_ISOCode = Parameter.Country_ISO;
                    ucd.Tenant_RefID          = securityTicket.TenantID;
                    ucd.Save(Connection, Transaction);
                    companyInfo.Contact_UCD_RefID = ucd.CMN_UniversalContactDetailID;
                }

                companyInfo.Save(Connection, Transaction);
            }



            //Put your code here
            return(returnValue);

            #endregion UserCode
        }
        protected static FR_L3PR_IoUPBD_1614_Array Execute(DbConnection Connection, DbTransaction Transaction, P_L3PR_IoUPBD_1614 Parameter, CSV2Core.SessionSecurity.SessionSecurityTicket securityTicket = null)
        {
            //Leave UserCode region to enable user code saving
            #region UserCode
            var returnValue = new FR_L3PR_IoUPBD_1614_Array();
            var result      = new List <L3PR_IoUPBD_1614>();

            //Put your code here

            #region Get All Producers for Tenant

            var allProducers = ORM_CMN_BPT_BusinessParticipant.Query.Search(Connection, Transaction, new ORM_CMN_BPT_BusinessParticipant.Query()
            {
                Tenant_RefID = securityTicket.TenantID,
                IsDeleted    = false
            });

            #endregion

            #region Get Taxes For Default Country

            var taxesToImport = Parameter.Products.Select(i => i.VAT).Distinct();

            var param = new P_L3TX_STfDCaRR_1119();
            param.TaxRates = taxesToImport.ToArray();
            var allTaxes = cls_Save_Taxes_for_DefaultCountry_and_ReturnResult.Invoke(Connection, Transaction, param, securityTicket).Result;

            #endregion

            foreach (var item in Parameter.Products)
            {
                bool alreadyExistingInDB = true;

                #region ORM_CMN_PRO_Product
                var productQuery = new ORM_CMN_PRO_Product.Query();
                productQuery.ProductITL   = item.ProductITL;
                productQuery.Tenant_RefID = securityTicket.TenantID;
                productQuery.IsDeleted    = false;
                productQuery.IsProductAvailableForOrdering = true;

                var product = ORM_CMN_PRO_Product.Query.Search(Connection, Transaction, productQuery).FirstOrDefault();

                if (product == null)
                {
                    product = new ORM_CMN_PRO_Product();
                    product.CMN_PRO_ProductID  = Guid.NewGuid();
                    product.ProductITL         = item.ProductITL;
                    product.PackageInfo_RefID  = Guid.NewGuid();
                    product.Creation_Timestamp = DateTime.Now;
                    product.Tenant_RefID       = securityTicket.TenantID;

                    alreadyExistingInDB = false;
                }

                product.Product_Name                  = item.Product_Name;
                product.Product_Description           = item.Product_Description;
                product.Product_Number                = item.Product_Number;
                product.IsProduct_Article             = true;
                product.IsProductAvailableForOrdering = true;

                #region Save Producer
                var producerBPT = allProducers.Where(i => i.DisplayName == item.Producer).FirstOrDefault();

                if (producerBPT == default(ORM_CMN_BPT_BusinessParticipant))
                {
                    producerBPT = new ORM_CMN_BPT_BusinessParticipant();
                    producerBPT.CMN_BPT_BusinessParticipantID = Guid.NewGuid();
                    producerBPT.DisplayName        = item.Producer;
                    producerBPT.IsCompany          = true;
                    producerBPT.Tenant_RefID       = securityTicket.TenantID;
                    producerBPT.Creation_Timestamp = DateTime.Now;
                    producerBPT.Save(Connection, Transaction);
                }

                #endregion

                product.ProducingBusinessParticipant_RefID = producerBPT.CMN_BPT_BusinessParticipantID;
                product.Save(Connection, Transaction);
                #endregion

                #region Unit
                //Unit could be used for multiple products, there is no sense to edit unit
                //If there is need to change unit, we should find unit with that iso code and change reference

                var unitsQuery = new ORM_CMN_Unit.Query();
                unitsQuery.Tenant_RefID = securityTicket.TenantID;
                unitsQuery.ISOCode      = item.MeasuredInUnit_ISO_um_ums;
                unitsQuery.IsDeleted    = false;

                var measuredInUnit = ORM_CMN_Unit.Query.Search(Connection, Transaction, unitsQuery).FirstOrDefault();
                if (measuredInUnit == null)
                {
                    measuredInUnit = new ORM_CMN_Unit();
                    measuredInUnit.Tenant_RefID       = securityTicket.TenantID;
                    measuredInUnit.Creation_Timestamp = DateTime.Now;
                    measuredInUnit.ISOCode            = item.MeasuredInUnit_ISO_um_ums;
                    measuredInUnit.CMN_UnitID         = Guid.NewGuid();
                    measuredInUnit.Save(Connection, Transaction);
                }
                #endregion

                #region PackageInfo
                var packageInfo = new ORM_CMN_PRO_PAC_PackageInfo();
                packageInfo.Load(Connection, Transaction, product.PackageInfo_RefID);
                if (packageInfo.CMN_PRO_PAC_PackageInfoID == Guid.Empty)
                {
                    packageInfo.CMN_PRO_PAC_PackageInfoID = product.PackageInfo_RefID;
                    packageInfo.Creation_Timestamp        = DateTime.Now;
                    packageInfo.Tenant_RefID = securityTicket.TenantID;
                }
                packageInfo.PackageContent_DisplayLabel         = item.Amount;
                packageInfo.PackageContent_Amount               = PackageAmountUtils.GetPackageAmount(item.Amount);
                packageInfo.PackageContent_MeasuredInUnit_RefID = measuredInUnit.CMN_UnitID;

                packageInfo.Save(Connection, Transaction);
                #endregion

                #region VAT
                var salesTax = ORM_CMN_PRO_Product_SalesTaxAssignmnet.Query.Search(Connection, Transaction, new ORM_CMN_PRO_Product_SalesTaxAssignmnet.Query()
                {
                    Product_RefID = product.CMN_PRO_ProductID,
                    Tenant_RefID  = securityTicket.TenantID,
                    IsDeleted     = false
                }).FirstOrDefault();

                if (salesTax == null)
                {
                    salesTax = new ORM_CMN_PRO_Product_SalesTaxAssignmnet();
                    salesTax.CMN_PRO_Product_SalesTaxAssignmnetID = Guid.NewGuid();
                    salesTax.Product_RefID      = product.CMN_PRO_ProductID;
                    salesTax.Creation_Timestamp = DateTime.Now;
                    salesTax.Tenant_RefID       = securityTicket.TenantID;
                }

                salesTax.ApplicableSalesTax_RefID = allTaxes.Where(i => i.TaxRate == item.VAT).Select(j => j.TaxID).FirstOrDefault();
                salesTax.Save(Connection, Transaction);
                #endregion

                result.Add(new L3PR_IoUPBD_1614()
                {
                    ProductITL       = product.ProductITL,
                    ProductID        = product.CMN_PRO_ProductID,
                    IsAlreadyExisted = alreadyExistingInDB
                });
            }

            returnValue.Result = result.ToArray();
            return(returnValue);
        }
        protected static FR_Base Execute(DbConnection Connection, DbTransaction Transaction, P_L3_ACTT_1558 Parameter, CSV2Core.SessionSecurity.SessionSecurityTicket securityTicket = null)
        {
            //Leave UserCode region to enable user code saving
            #region UserCode
            var returnValue = new FR_Base();

            if (Parameter == null)
            {
                returnValue.Status       = FR_Status.Error_Internal;
                returnValue.ErrorMessage = "Assign_Countries_To_Tenant method returned error message: Parameter is null.";
                return(returnValue);
            }

            ORM_CMN_Currency[] currencies = null;

            #region Retrieve all currencies for tenant

            currencies = ORM_CMN_Currency.Query.Search(Connection, Transaction, new ORM_CMN_Currency.Query()
            {
                Tenant_RefID = securityTicket.TenantID
            }).ToArray();

            #endregion

            #region Assign/deassign currencies

            foreach (var currencyToAssign in Parameter.AssignedCurrencies)
            {
                var currency = currencies.FirstOrDefault(c => c.ISO4127 == currencyToAssign.CurrencyISoCode);
                if (currency == null)
                {
                    currency = new ORM_CMN_Currency();
                    currency.CMN_CurrencyID     = Guid.NewGuid();
                    currency.Creation_Timestamp = DateTime.Now;
                    currency.IsDeleted          = false;
                    currency.ISO4127            = currencyToAssign.CurrencyISoCode;
                    currency.Name         = currencyToAssign.CurrencyName;
                    currency.Symbol       = currencyToAssign.CurrencySymbol;
                    currency.Tenant_RefID = securityTicket.TenantID;
                    currency.Save(Connection, Transaction);
                }

                if (currency.IsDeleted == true)
                {
                    currency.IsDeleted = false;
                    currency.Save(Connection, Transaction);
                }
            }

            foreach (var currency in currencies.Where(c => c.IsDeleted == false))
            {
                var currencyToAssign = Parameter.AssignedCurrencies.FirstOrDefault(cta => cta.CurrencyISoCode == currency.ISO4127);
                if (currencyToAssign == null)
                {
                    currency.IsDeleted = true;
                    currency.Save(Connection, Transaction);
                }
            }


            #endregion

            #region Set default currency for tenant

            if (Parameter.DefaultCurrency != null)
            {
                ORM_CMN_BPT_BusinessParticipant businesParticipant = ORM_CMN_BPT_BusinessParticipant.Query.Search(Connection, Transaction, new ORM_CMN_BPT_BusinessParticipant.Query()
                {
                    IsDeleted             = false,
                    Tenant_RefID          = securityTicket.TenantID,
                    IfTenant_Tenant_RefID = securityTicket.TenantID
                }).FirstOrDefault();

                if (businesParticipant != null)
                {
                    var defaultCurrency = currencies.FirstOrDefault(c => c.ISO4127 == Parameter.DefaultCurrency.CurrencyISoCode);
                    if (defaultCurrency != null)
                    {
                        businesParticipant.DefaultCurrency_RefID = defaultCurrency.CMN_CurrencyID;
                        businesParticipant.Save(Connection, Transaction);
                    }
                }
            }

            #endregion

            returnValue.Status = FR_Status.Success;
            return(returnValue);

            #endregion UserCode
        }
        protected static FR_Guid Execute(DbConnection Connection, DbTransaction Transaction, P_L6DR_DDBID_1653 Parameter, CSV2Core.SessionSecurity.SessionSecurityTicket securityTicket = null)
        {
            //Leave UserCode region to enable user code saving
            #region UserCode
            var returnValue = new FR_Guid();
            //Put your code here


            P_L6DR_DDBID_1653 param = new P_L6DR_DDBID_1653();
            param.CMN_BPT_BusinessParticipantID = Parameter.CMN_BPT_BusinessParticipantID;

            var drivers = cls_Retrieve_Driver_Info_and_VerCode.Invoke(Connection, Transaction, securityTicket).Result;

            var driver = drivers.FirstOrDefault(x => x.CMN_BPT_BusinessParticipantID == param.CMN_BPT_BusinessParticipantID);

            if (driver != null)
            {
                ORM_CMN_PER_PersonInfo person = new ORM_CMN_PER_PersonInfo();
                if (driver.CMN_PER_PersonInfoID != Guid.Empty)
                {
                    var result = person.Load(Connection, Transaction, driver.CMN_PER_PersonInfoID);
                    if (result.Status != FR_Status.Success || person.CMN_PER_PersonInfoID == Guid.Empty)
                    {
                        var error = new FR_Guid();
                        error.ErrorMessage = "No Such ID";
                        error.Status       = FR_Status.Error_Internal;
                        return(error);
                    }
                    person.IsDeleted = true;
                    person.Save(Connection, Transaction);
                }

                ORM_CMN_BPT_BusinessParticipant bParticipant = new ORM_CMN_BPT_BusinessParticipant();
                if (driver.CMN_BPT_BusinessParticipantID != Guid.Empty)
                {
                    var result = bParticipant.Load(Connection, Transaction, driver.CMN_BPT_BusinessParticipantID);
                    if (result.Status != FR_Status.Success || bParticipant.CMN_BPT_BusinessParticipantID == Guid.Empty)
                    {
                        var error = new FR_Guid();
                        error.ErrorMessage = "No Such ID";
                        error.Status       = FR_Status.Error_Internal;
                        return(error);
                    }
                    bParticipant.IsDeleted = true;
                    bParticipant.Save(Connection, Transaction);
                }

                if (driver.Contacts != null)
                {
                    foreach (var parContact in driver.Contacts)
                    {
                        ORM_CMN_PER_CommunicationContact contact = new ORM_CMN_PER_CommunicationContact();
                        if (parContact.CMN_PER_CommunicationContact_TypeID != Guid.Empty)
                        {
                            var result = contact.Load(Connection, Transaction, parContact.CMN_PER_CommunicationContact_TypeID);
                            if (result.Status != FR_Status.Success || contact.CMN_PER_CommunicationContactID == Guid.Empty)
                            {
                                var error = new FR_Guid();
                                error.ErrorMessage = "No Such ID";
                                error.Status       = FR_Status.Error_Internal;
                                return(error);
                            }
                            contact.IsDeleted = true;
                            contact.Save(Connection, Transaction);
                        }
                    }
                }

                ORM_CMN_Address adress = new ORM_CMN_Address();
                if (driver.CMN_AddressID != Guid.Empty)
                {
                    var result = adress.Load(Connection, Transaction, driver.CMN_AddressID);
                    if (result.Status != FR_Status.Success || adress.CMN_AddressID == Guid.Empty)
                    {
                        var error = new FR_Guid();
                        error.ErrorMessage = "No Such ID";
                        error.Status       = FR_Status.Error_Internal;
                        return(error);
                    }
                    adress.IsDeleted = true;
                    adress.Save(Connection, Transaction);
                }

                ORM_CMN_BPT_Supplier supplier = new ORM_CMN_BPT_Supplier();
                if (driver.CMN_BPT_SupplierID != Guid.Empty)
                {
                    var result = supplier.Load(Connection, Transaction, driver.CMN_BPT_SupplierID);
                    if (result.Status != FR_Status.Success || supplier.CMN_BPT_SupplierID == Guid.Empty)
                    {
                        var error = new FR_Guid();
                        error.ErrorMessage = "No Such ID";
                        error.Status       = FR_Status.Error_Internal;
                        return(error);
                    }
                    supplier.IsDeleted = true;
                    supplier.Save(Connection, Transaction);
                }

                ORM_CMN_BPT_BusinessParticipant asossBParticipant = new ORM_CMN_BPT_BusinessParticipant();
                if (driver.AssociatedBusinessParticipant_RefID != Guid.Empty)
                {
                    var result = asossBParticipant.Load(Connection, Transaction, driver.AssociatedBusinessParticipant_RefID);
                    if (result.Status != FR_Status.Success || asossBParticipant.CMN_BPT_BusinessParticipantID == Guid.Empty)
                    {
                        var error = new FR_Guid();
                        error.ErrorMessage = "No Such ID";
                        error.Status       = FR_Status.Error_Internal;
                        return(error);
                    }
                    asossBParticipant.IsDeleted = true;
                    asossBParticipant.Save(Connection, Transaction);
                }


                ORM_CMN_BPT_BusinessParticipant_AssociatedBusinessParticipant BusinessParticipant_AssociatedBusinessParticipant = new ORM_CMN_BPT_BusinessParticipant_AssociatedBusinessParticipant();
                if (driver.AssociatedBusinessParticipant_RefID != Guid.Empty)
                {
                    var result = BusinessParticipant_AssociatedBusinessParticipant.Load(Connection, Transaction, driver.CMN_BPT_BusinessParticipant_AssociatedBusinessParticipantID);
                    if (result.Status != FR_Status.Success || BusinessParticipant_AssociatedBusinessParticipant.CMN_BPT_BusinessParticipant_AssociatedBusinessParticipantID == Guid.Empty)
                    {
                        var error = new FR_Guid();
                        error.ErrorMessage = "No Such ID";
                        error.Status       = FR_Status.Error_Internal;
                        return(error);
                    }
                    BusinessParticipant_AssociatedBusinessParticipant.IsDeleted = true;
                    BusinessParticipant_AssociatedBusinessParticipant.Save(Connection, Transaction);
                }

                ORM_USR_Account account = new ORM_USR_Account();
                if (driver.USR_AccountID != Guid.Empty)
                {
                    var result = account.Load(Connection, Transaction, driver.USR_AccountID);
                    if (result.Status != FR_Status.Success || account.USR_AccountID == Guid.Empty)
                    {
                        var error = new FR_Guid();
                        error.ErrorMessage = "No Such ID";
                        error.Status       = FR_Status.Error_Internal;
                        return(error);
                    }
                    account.IsDeleted = true;
                    account.Save(Connection, Transaction);
                }

                ORM_USR_Device_AccountCode_StatusHistory Device_AccountCode_StatusHistory = new ORM_USR_Device_AccountCode_StatusHistory();
                if (driver.USR_Device_AccountCode_UsageHistoryID != Guid.Empty)
                {
                    var result = Device_AccountCode_StatusHistory.Load(Connection, Transaction, driver.USR_Device_AccountCode_UsageHistoryID);
                    if (result.Status != FR_Status.Success || Device_AccountCode_StatusHistory.USR_Device_AccountCode_StatusHistoryID == Guid.Empty)
                    {
                        var error = new FR_Guid();
                        error.ErrorMessage = "No Such ID";
                        error.Status       = FR_Status.Error_Internal;
                        return(error);
                    }
                    Device_AccountCode_StatusHistory.IsDeleted = true;
                    Device_AccountCode_StatusHistory.Save(Connection, Transaction);
                }

                ORM_USR_Device_AccountCode accountCode = new ORM_USR_Device_AccountCode();
                if (driver.USR_Device_AccountCodeID != Guid.Empty)
                {
                    var result = accountCode.Load(Connection, Transaction, driver.USR_Device_AccountCodeID);
                    if (result.Status != FR_Status.Success || accountCode.USR_Device_AccountCodeID == Guid.Empty)
                    {
                        var error = new FR_Guid();
                        error.ErrorMessage = "No Such ID";
                        error.Status       = FR_Status.Error_Internal;
                        return(error);
                    }
                    accountCode.IsDeleted = true;
                    accountCode.Save(Connection, Transaction);
                }

                var Device_AccountCode_UsageHistoryQuery = new ORM_USR_Device_AccountCode_UsageHistory.Query();
                Device_AccountCode_UsageHistoryQuery.Device_AccountCode_RefID = accountCode.USR_Device_AccountCodeID;
                Device_AccountCode_UsageHistoryQuery.IsDeleted    = false;
                Device_AccountCode_UsageHistoryQuery.Tenant_RefID = securityTicket.TenantID;

                var historyArray = ORM_USR_Device_AccountCode_UsageHistory.Query.Search(Connection, Transaction, Device_AccountCode_UsageHistoryQuery);
                if (historyArray != null && historyArray.Count > 0)
                {
                    foreach (var historyItem in historyArray)
                    {
                        historyItem.IsDeleted = true;
                        historyItem.Save(Connection, Transaction);
                    }
                }
            }



            return(returnValue);

            #endregion UserCode
        }
Beispiel #26
0
        protected static FR_L3AR_IoUPBD_1631_Array Execute(DbConnection Connection, DbTransaction Transaction, P_L3AR_IoUPBD_1631 Parameter, CSV2Core.SessionSecurity.SessionSecurityTicket securityTicket = null)
        {
            #region UserCode
            var returnValue = new FR_L3AR_IoUPBD_1631_Array();
            var result      = new List <L3AR_IoUPBD_1631>();

            #region Get All Producers for Tenant

            var allProducers = ORM_CMN_BPT_BusinessParticipant.Query.Search(Connection, Transaction, new ORM_CMN_BPT_BusinessParticipant.Query()
            {
                Tenant_RefID = securityTicket.TenantID,
                IsDeleted    = false
            });

            #endregion

            #region Get Taxes For Default Country

            var taxesToImport = Parameter.Products.Select(i => i.VAT).Distinct();

            var param = new P_L3TX_STfDCaRR_1119();
            param.TaxRates = taxesToImport.ToArray();
            var allTaxes = cls_Save_Taxes_for_DefaultCountry_and_ReturnResult.Invoke(Connection, Transaction, param, securityTicket).Result;

            #endregion

            #region DosageForms

            var dosageQuery = new ORM_HEC_Product_DosageForm.Query();
            dosageQuery.Tenant_RefID = securityTicket.TenantID;
            dosageQuery.IsDeleted    = false;

            var allDosages = ORM_HEC_Product_DosageForm.Query.Search(Connection, Transaction, dosageQuery);

            #endregion

            foreach (var item in Parameter.Products)
            {
                bool alreadyExistingInDB = true;

                #region ORM_CMN_PRO_Product

                var productQuery = new ORM_CMN_PRO_Product.Query();
                productQuery.ProductITL   = item.ProductITL;
                productQuery.Tenant_RefID = securityTicket.TenantID;
                productQuery.IsDeleted    = false;
                productQuery.IsProductAvailableForOrdering = true;

                var product = ORM_CMN_PRO_Product.Query.Search(Connection, Transaction, productQuery).FirstOrDefault();

                if (product == null)
                {
                    product = new ORM_CMN_PRO_Product();
                    product.CMN_PRO_ProductID  = Guid.NewGuid();
                    product.ProductITL         = item.ProductITL;
                    product.PackageInfo_RefID  = Guid.NewGuid();
                    product.Creation_Timestamp = DateTime.Now;
                    product.Tenant_RefID       = securityTicket.TenantID;

                    alreadyExistingInDB = false;
                }

                product.Product_Name                   = item.Product_Name;
                product.Product_Description            = item.Product_Description;
                product.Product_Number                 = item.Product_Number;
                product.IsProduct_Article              = true;
                product.IsProductAvailableForOrdering  = true;
                product.DefaultExpirationPeriod_in_sec = item.DefaultExpirationPeriod_in_sec;

                if (item.DefaultStorageTemperature_min_in_kelvin != 0)
                {
                    product.DefaultStorageTemperature_min_in_kelvin = (float)Math.Round(item.DefaultStorageTemperature_min_in_kelvin, 2);
                }

                if (item.DefaultStorageTemperature_max_in_kelvin != 0)
                {
                    product.DefaultStorageTemperature_max_in_kelvin = (float)Math.Round(item.DefaultStorageTemperature_max_in_kelvin, 2);
                }

                product.IsStorage_CoolingRequired = item.IsStorage_CoolingRequired;

                var xmlModel = new ProductAdditionalInfoXML()
                {
                    IsPharmacyOnlyDistribution = item.IsPharmacyOnlyDistribution
                };

                product.ProductAdditionalInfoXML      = xmlModel.ToPayload();
                product.IsStorage_ExpiryDateMandatory = (item.DefaultExpirationPeriod_in_sec != 0);

                product.Save(Connection, Transaction);

                #endregion

                #region Save Producer

                var producerBPT = allProducers.Where(i => i.DisplayName == item.Producer).FirstOrDefault();

                if (producerBPT == default(ORM_CMN_BPT_BusinessParticipant))
                {
                    producerBPT = new ORM_CMN_BPT_BusinessParticipant();
                    producerBPT.CMN_BPT_BusinessParticipantID = Guid.NewGuid();
                    producerBPT.DisplayName        = item.Producer;
                    producerBPT.IsCompany          = true;
                    producerBPT.Tenant_RefID       = securityTicket.TenantID;
                    producerBPT.Creation_Timestamp = DateTime.Now;
                    producerBPT.Save(Connection, Transaction);
                }

                product.ProducingBusinessParticipant_RefID = producerBPT.CMN_BPT_BusinessParticipantID;
                product.Save(Connection, Transaction);

                #endregion

                #region Product Code (EAN)

                var product2Code = ORM_CMN_PRO_Product_2_ProductCode.Query.Search(Connection, Transaction, new ORM_CMN_PRO_Product_2_ProductCode.Query()
                {
                    CMN_PRO_Product_RefID = product.CMN_PRO_ProductID,
                    Tenant_RefID          = securityTicket.TenantID,
                    IsDeleted             = false
                }).SingleOrDefault();

                if (product2Code == null)
                {
                    var eanID = DMProductCodeTypes.Get_ProductCodeType_ByGlobalMatchingID(Connection, Transaction, EProductCodeType.EAN, securityTicket);

                    var productCode = new ORM_CMN_PRO_ProductCode();
                    productCode.CMN_PRO_ProductCodeID  = Guid.NewGuid();
                    productCode.ProductCode_Type_RefID = eanID;
                    productCode.ProductCode_Value      = String.Empty;
                    productCode.Creation_Timestamp     = DateTime.Now;
                    productCode.Tenant_RefID           = securityTicket.TenantID;
                    productCode.Save(Connection, Transaction);

                    product2Code = new ORM_CMN_PRO_Product_2_ProductCode();
                    product2Code.AssignmentID              = Guid.NewGuid();
                    product2Code.CMN_PRO_Product_RefID     = product.CMN_PRO_ProductID;
                    product2Code.CMN_PRO_ProductCode_RefID = productCode.CMN_PRO_ProductCodeID;
                    product2Code.Creation_Timestamp        = DateTime.Now;
                    product2Code.Tenant_RefID              = securityTicket.TenantID;
                    product2Code.Save(Connection, Transaction);
                }
                else
                {
                    var productCode = new ORM_CMN_PRO_ProductCode();
                    productCode.Load(Connection, Transaction, product2Code.CMN_PRO_ProductCode_RefID);
                    productCode.ProductCode_Value = String.Empty;
                    productCode.Save(Connection, Transaction);
                }

                #endregion

                #region Unit

                //Unit could be used for multiple products, there is no sense to edit unit
                //If there is need to change unit, we should find unit with that iso code and change reference

                var unitsQuery = new ORM_CMN_Unit.Query();
                unitsQuery.Tenant_RefID = securityTicket.TenantID;
                unitsQuery.ISOCode      = item.MeasuredInUnit_ISO_um_ums;
                unitsQuery.IsDeleted    = false;

                var measuredInUnit = ORM_CMN_Unit.Query.Search(Connection, Transaction, unitsQuery).FirstOrDefault();
                if (measuredInUnit == null)
                {
                    measuredInUnit = new ORM_CMN_Unit();
                    measuredInUnit.Tenant_RefID       = securityTicket.TenantID;
                    measuredInUnit.Creation_Timestamp = DateTime.Now;
                    measuredInUnit.ISOCode            = item.MeasuredInUnit_ISO_um_ums;
                    measuredInUnit.CMN_UnitID         = Guid.NewGuid();
                    measuredInUnit.Save(Connection, Transaction);
                }

                #endregion

                #region PackageInfo

                var packageInfo = new ORM_CMN_PRO_PAC_PackageInfo();
                packageInfo.Load(Connection, Transaction, product.PackageInfo_RefID);
                if (packageInfo.CMN_PRO_PAC_PackageInfoID == Guid.Empty)
                {
                    packageInfo.CMN_PRO_PAC_PackageInfoID = product.PackageInfo_RefID;
                    packageInfo.Creation_Timestamp        = DateTime.Now;
                    packageInfo.Tenant_RefID = securityTicket.TenantID;
                }
                packageInfo.PackageContent_DisplayLabel         = item.Amount;
                packageInfo.PackageContent_Amount               = PackageAmountUtils.GetPackageAmount(item.Amount);
                packageInfo.PackageContent_MeasuredInUnit_RefID = measuredInUnit.CMN_UnitID;

                packageInfo.Save(Connection, Transaction);

                #endregion

                #region VAT

                var salesTax = ORM_CMN_PRO_Product_SalesTaxAssignmnet.Query.Search(Connection, Transaction, new ORM_CMN_PRO_Product_SalesTaxAssignmnet.Query()
                {
                    Product_RefID = product.CMN_PRO_ProductID,
                    Tenant_RefID  = securityTicket.TenantID,
                    IsDeleted     = false
                }).SingleOrDefault();

                if (salesTax == null)
                {
                    salesTax = new ORM_CMN_PRO_Product_SalesTaxAssignmnet();
                    salesTax.CMN_PRO_Product_SalesTaxAssignmnetID = Guid.NewGuid();
                    salesTax.Product_RefID      = product.CMN_PRO_ProductID;
                    salesTax.Creation_Timestamp = DateTime.Now;
                    salesTax.Tenant_RefID       = securityTicket.TenantID;
                }

                salesTax.ApplicableSalesTax_RefID = allTaxes.Where(i => i.TaxRate == item.VAT).Select(j => j.TaxID).FirstOrDefault();
                salesTax.Save(Connection, Transaction);

                #endregion

                #region DosageForms

                //DosageForms could be used for multiple products, there is no sense to edit unit
                //If there is need to change unit, we should find unit with that GlobalPropertyMatchingID and change reference

                var dosage = allDosages.Where(i => i.GlobalPropertyMatchingID == item.Dosage).FirstOrDefault();

                //if not create new
                if (dosage == null)
                {
                    dosage = new ORM_HEC_Product_DosageForm();
                    dosage.HEC_Product_DosageFormID = Guid.NewGuid();
                    dosage.Tenant_RefID             = securityTicket.TenantID;
                    dosage.Creation_Timestamp       = DateTime.Now;

                    dosage.GlobalPropertyMatchingID = item.Dosage;
                    dosage.Save(Connection, Transaction);
                }

                #endregion

                #region HecProduct

                var hec_product = ORM_HEC_Product.Query.Search(Connection, Transaction, new ORM_HEC_Product.Query()
                {
                    Ext_PRO_Product_RefID = product.CMN_PRO_ProductID,
                    Tenant_RefID          = securityTicket.TenantID,
                    IsDeleted             = false
                }).SingleOrDefault();

                if (hec_product == null)
                {
                    hec_product = new ORM_HEC_Product();
                    hec_product.HEC_ProductID      = Guid.NewGuid();
                    hec_product.Creation_Timestamp = DateTime.Now;
                    hec_product.Tenant_RefID       = securityTicket.TenantID;
                }
                hec_product.Ext_PRO_Product_RefID     = product.CMN_PRO_ProductID;
                hec_product.ProductDosageForm_RefID   = dosage.HEC_Product_DosageFormID;
                hec_product.ProductDistributionStatus = item.DistributionStatus;
                hec_product.IsProduct_AddictiveDrug   = item.IsProduct_AddictiveDrug;
                hec_product.Save(Connection, Transaction);

                #endregion

                var date = DateTime.Now;

                #region Save Active Components

                var componentsParam = new P_L3CO_SCfIPFC_1324();
                componentsParam.HEC_ProductID    = hec_product.HEC_ProductID;
                componentsParam.ActiveComponents = item.ActiveComponents;
                cls_Save_Componets_for_ImportedProductFromCatalog.Invoke(Connection, Transaction, componentsParam, securityTicket);

                #endregion

                result.Add(new L3AR_IoUPBD_1631()
                {
                    ProductITL       = product.ProductITL,
                    ProductID        = product.CMN_PRO_ProductID,
                    IsAlreadyExisted = alreadyExistingInDB
                });

                date = DateTime.Now;
            }

            returnValue.Result = result.ToArray();
            return(returnValue);

            #endregion UserCode
        }
Beispiel #27
0
        public static void Save_Doctors_to_DB(Doctor_model_from_xlsx Parameter, string connectionString, SessionSecurityTicket securityTicket)
        {
            DbConnection  Connection         = null;
            DbTransaction Transaction        = null;
            bool          cleanupConnection  = Connection == null;
            bool          cleanupTransaction = Transaction == null;

            if (cleanupConnection == true)
            {
                Connection = CSV2Core_MySQL.Support.DBSQLSupport.CreateConnection(connectionString);
                Connection.Open();
            }
            if (cleanupTransaction == true)
            {
                Transaction = Connection.BeginTransaction();
            }
            try
            {
                Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("de-DE");
                Guid   BusinessParticipantID         = Guid.NewGuid();
                Guid   personInfoID                  = Guid.NewGuid();
                Guid   PracticeCustomerID            = Guid.NewGuid();
                Guid   PracticeBusinessParticipantID = Guid.NewGuid();
                Guid   PracticeCompanyInfoID         = Guid.NewGuid();
                String PracticeName                  = "";
                Guid   BankAccountID                 = Guid.Empty;
                Guid   doctor_id    = Parameter.DoctorID;
                var    isOpPractice = false;

                if (!String.IsNullOrEmpty(Parameter.LoginEmail))
                //uncomment this if you've created account
                //  if (false)
                {
                    string[] stringUser  = Parameter.LoginEmail.Split('@');
                    string   usernameStr = stringUser[0];

                    try
                    {
                        var doctorAccountInfo = ORM_USR_Account.Query.Search(Connection, Transaction, new ORM_USR_Account.Query()
                        {
                            IsDeleted    = false,
                            Tenant_RefID = securityTicket.TenantID,
                            AccountSignInEmailAddress = Parameter.LoginEmail,
                        }).Single();

                        var accountGroupQuery = new ORM_USR_Account_FunctionLevelRights_Group.Query();
                        accountGroupQuery.Tenant_RefID             = securityTicket.TenantID;
                        accountGroupQuery.IsDeleted                = false;
                        accountGroupQuery.GlobalPropertyMatchingID = "mm.docconect.doc.app.group";

                        var accountGroup = ORM_USR_Account_FunctionLevelRights_Group.Query.Search(Connection, Transaction, accountGroupQuery).SingleOrDefault();

                        if (accountGroup == null)
                        {
                            accountGroup = new ORM_USR_Account_FunctionLevelRights_Group();
                            accountGroup.Tenant_RefID             = securityTicket.TenantID;
                            accountGroup.Label                    = "mm.docconect.doc.app.group";
                            accountGroup.GlobalPropertyMatchingID = "mm.docconect.doc.app.group";
                            accountGroup.Creation_Timestamp       = DateTime.Now;
                            accountGroup.USR_Account_FunctionLevelRights_GroupID = Guid.NewGuid();
                            accountGroup.Save(Connection, Transaction);
                        }

                        var PracticeAccount2UniversalProperty = ORM_HEC_MedicalPractice_2_UniversalProperty.Query.Search(Connection, Transaction, new ORM_HEC_MedicalPractice_2_UniversalProperty.Query()
                        {
                            IsDeleted    = false,
                            Tenant_RefID = securityTicket.TenantID,
                            HEC_MedicalPractice_RefID = Parameter.PracticeID
                        }).ToList();

                        List <ORM_HEC_MedicalPractice_UniversalProperty> PracticeUniversalPropertyList = new List <ORM_HEC_MedicalPractice_UniversalProperty>();
                        foreach (var item in PracticeAccount2UniversalProperty)
                        {
                            var PracticeUniversalProperty = ORM_HEC_MedicalPractice_UniversalProperty.Query.Search(Connection, Transaction, new ORM_HEC_MedicalPractice_UniversalProperty.Query()
                            {
                                IsDeleted    = false,
                                Tenant_RefID = securityTicket.TenantID,
                                HEC_MedicalPractice_UniversalPropertyID = item.HEC_MedicalPractice_UniversalProperty_RefID
                            }).Single();
                            PracticeUniversalPropertyList.Add(PracticeUniversalProperty);
                        }
                        ;

                        P_DO_GPAIDfPID_1522 practiceAccountIDParameter = new P_DO_GPAIDfPID_1522();
                        practiceAccountIDParameter.PracticeID = Parameter.PracticeID;

                        var practiceAccountToFunctionLevelRightQ = new ORM_USR_Account_2_FunctionLevelRight.Query();
                        practiceAccountToFunctionLevelRightQ.Account_RefID = cls_Get_Practice_AccountID_for_PracticeID.Invoke(Connection, Transaction, practiceAccountIDParameter, securityTicket).Result.accountID;
                        practiceAccountToFunctionLevelRightQ.Tenant_RefID  = securityTicket.TenantID;
                        practiceAccountToFunctionLevelRightQ.IsDeleted     = false;

                        var practiceAccountToFunctionLevelRight = ORM_USR_Account_2_FunctionLevelRight.Query.Search(Connection, Transaction, practiceAccountToFunctionLevelRightQ).SingleOrDefault();

                        if (practiceAccountToFunctionLevelRight != null)
                        {
                            var practiceAccountFunctionLevelRightQ = new ORM_USR_Account_FunctionLevelRight.Query();
                            practiceAccountFunctionLevelRightQ.Tenant_RefID = securityTicket.TenantID;
                            practiceAccountFunctionLevelRightQ.IsDeleted    = false;
                            practiceAccountFunctionLevelRightQ.USR_Account_FunctionLevelRightID = practiceAccountToFunctionLevelRight.FunctionLevelRight_RefID;

                            var practiceAccountFunctionLevelRight = ORM_USR_Account_FunctionLevelRight.Query.Search(Connection, Transaction, practiceAccountFunctionLevelRightQ).SingleOrDefault();

                            if (practiceAccountFunctionLevelRight != null)
                            {
                                isOpPractice = practiceAccountFunctionLevelRight.GlobalPropertyMatchingID.Equals("mm.docconect.doc.app.op.practice");
                            }
                        }

                        var functionLevelRightQ = new ORM_USR_Account_FunctionLevelRight.Query();
                        functionLevelRightQ.Tenant_RefID             = securityTicket.TenantID;
                        functionLevelRightQ.IsDeleted                = false;
                        functionLevelRightQ.GlobalPropertyMatchingID = isOpPractice ? "mm.docconect.doc.app.op.doctor" : "mm.docconect.doc.app.ac.doctor";

                        var existingFunctionLevelRight = ORM_USR_Account_FunctionLevelRight.Query.Search(Connection, Transaction, functionLevelRightQ).SingleOrDefault();

                        var tempFunctionLevelRightID = Guid.Empty;

                        if (existingFunctionLevelRight == null)
                        {
                            ORM_USR_Account_FunctionLevelRight functionLevelRight = new ORM_USR_Account_FunctionLevelRight();
                            functionLevelRight.USR_Account_FunctionLevelRightID = Guid.NewGuid();
                            functionLevelRight.FunctionLevelRights_Group_RefID  = accountGroup.USR_Account_FunctionLevelRights_GroupID;
                            functionLevelRight.Tenant_RefID       = securityTicket.TenantID;
                            functionLevelRight.Creation_Timestamp = DateTime.Now;

                            functionLevelRight.RightName = isOpPractice ? "mm.docconect.doc.app.op.doctor" : "mm.docconect.doc.app.ac.doctor";
                            functionLevelRight.GlobalPropertyMatchingID = isOpPractice ? "mm.docconect.doc.app.op.doctor" : "mm.docconect.doc.app.ac.doctor";

                            functionLevelRight.Save(Connection, Transaction);

                            tempFunctionLevelRightID = functionLevelRight.USR_Account_FunctionLevelRightID;
                        }
                        else
                        {
                            tempFunctionLevelRightID = existingFunctionLevelRight.USR_Account_FunctionLevelRightID;
                        }

                        var accountToFunctionLevelRight = new ORM_USR_Account_2_FunctionLevelRight();
                        accountToFunctionLevelRight.Tenant_RefID             = securityTicket.TenantID;
                        accountToFunctionLevelRight.Creation_Timestamp       = DateTime.Now;
                        accountToFunctionLevelRight.AssignmentID             = Guid.NewGuid();
                        accountToFunctionLevelRight.Account_RefID            = doctorAccountInfo.USR_AccountID;
                        accountToFunctionLevelRight.FunctionLevelRight_RefID = tempFunctionLevelRightID;

                        accountToFunctionLevelRight.Save(Connection, Transaction);

                        var businessParticipantQ = new ORM_CMN_BPT_BusinessParticipant.Query();

                        businessParticipantQ.IsDeleted    = false;
                        businessParticipantQ.Tenant_RefID = securityTicket.TenantID;
                        businessParticipantQ.CMN_BPT_BusinessParticipantID = doctorAccountInfo.BusinessParticipant_RefID;
                        BusinessParticipantID = doctorAccountInfo.BusinessParticipant_RefID;

                        var DoctorBusinessParticipant = ORM_CMN_BPT_BusinessParticipant.Query.Search(Connection, Transaction, businessParticipantQ).Single();
                        DoctorBusinessParticipant.IfNaturalPerson_CMN_PER_PersonInfo_RefID = Guid.NewGuid();
                        DoctorBusinessParticipant.DisplayName            = Parameter.FirstName + " " + Parameter.LastNAme;
                        DoctorBusinessParticipant.IsNaturalPerson        = true;
                        DoctorBusinessParticipant.Modification_Timestamp = DateTime.Now;
                        DoctorBusinessParticipant.Save(Connection, Transaction);
                        personInfoID = DoctorBusinessParticipant.IfNaturalPerson_CMN_PER_PersonInfo_RefID;


                        var companyInfoPractice = new ORM_CMN_PER_PersonInfo();
                        companyInfoPractice.IsDeleted            = false;
                        companyInfoPractice.Tenant_RefID         = securityTicket.TenantID;
                        companyInfoPractice.CMN_PER_PersonInfoID = personInfoID;
                        companyInfoPractice.FirstName            = Parameter.FirstName;
                        companyInfoPractice.LastName             = Parameter.LastNAme;
                        companyInfoPractice.Salutation_General   = Parameter.Salutation;
                        companyInfoPractice.Title = Parameter.Title;
                        companyInfoPractice.Save(Connection, Transaction);

                        var communicationContact = new ORM_CMN_PER_CommunicationContact();
                        communicationContact.IsDeleted              = false;
                        communicationContact.Contact_Type           = Guid.NewGuid();
                        communicationContact.Tenant_RefID           = securityTicket.TenantID;
                        communicationContact.Modification_Timestamp = DateTime.Now;
                        communicationContact.PersonInfo_RefID       = personInfoID;
                        communicationContact.Content = Parameter.Email;
                        communicationContact.Save(Connection, Transaction);
                        Guid CommunicationContactTypeID = communicationContact.Contact_Type;


                        var communicationContactType = new ORM_CMN_PER_CommunicationContact_Type();
                        communicationContactType.IsDeleted    = false;
                        communicationContactType.Tenant_RefID = securityTicket.TenantID;
                        communicationContactType.CMN_PER_CommunicationContact_TypeID = CommunicationContactTypeID;
                        communicationContactType.Type = "Email";
                        communicationContactType.Save(Connection, Transaction);

                        var communicationContact2 = new ORM_CMN_PER_CommunicationContact();
                        communicationContact2.IsDeleted              = false;
                        communicationContact2.Contact_Type           = Guid.NewGuid();
                        communicationContact2.Tenant_RefID           = securityTicket.TenantID;
                        communicationContact2.Modification_Timestamp = DateTime.Now;
                        communicationContact2.PersonInfo_RefID       = personInfoID;
                        communicationContact2.Content = Parameter.Phone;
                        communicationContact2.Save(Connection, Transaction);
                        Guid CommunicationContactTypeID2 = communicationContact2.Contact_Type;


                        var communicationContactType2 = new ORM_CMN_PER_CommunicationContact_Type();
                        communicationContactType2.IsDeleted    = false;
                        communicationContactType2.Tenant_RefID = securityTicket.TenantID;
                        communicationContactType2.CMN_PER_CommunicationContact_TypeID = CommunicationContactTypeID2;
                        communicationContactType2.Type = "Phone";
                        communicationContactType2.Save(Connection, Transaction);

                        var doctor = new ORM_HEC_Doctor();
                        doctor.HEC_DoctorID = Guid.NewGuid();
                        doctor.IsDeleted    = false;
                        doctor.Tenant_RefID = securityTicket.TenantID;
                        doctor.BusinessParticipant_RefID = BusinessParticipantID;
                        doctor.DoctorIDNumber            = Parameter.LANR.ToString();
                        doctor.Account_RefID             = Parameter.account_id;

                        doctor.Save(Connection, Transaction);

                        doctor_id = doctor.HEC_DoctorID;

                        var ogranizationUnitPractice = ORM_CMN_BPT_CTM_OrganizationalUnit.Query.Search(Connection, Transaction, new ORM_CMN_BPT_CTM_OrganizationalUnit.Query()
                        {
                            IsDeleted    = false,
                            Tenant_RefID = securityTicket.TenantID,
                            IfMedicalPractise_HEC_MedicalPractice_RefID = Parameter.PracticeID
                        }).Single();


                        var organizationalunit_Staff = new ORM_CMN_BPT_CTM_OrganizationalUnit_Staff();
                        organizationalunit_Staff.IsDeleted    = false;
                        organizationalunit_Staff.Tenant_RefID = securityTicket.TenantID;
                        organizationalunit_Staff.BusinessParticipant_RefID = BusinessParticipantID;
                        organizationalunit_Staff.OrganizationalUnit_RefID  = ogranizationUnitPractice.CMN_BPT_CTM_OrganizationalUnitID;
                        organizationalunit_Staff.Save(Connection, Transaction);

                        var CustomerPRactice = ORM_CMN_BPT_CTM_Customer.Query.Search(Connection, Transaction, new ORM_CMN_BPT_CTM_Customer.Query()
                        {
                            IsDeleted              = false,
                            Tenant_RefID           = securityTicket.TenantID,
                            CMN_BPT_CTM_CustomerID = ogranizationUnitPractice.Customer_RefID
                        }).Single();
                        var PracticeBusinessParticipant = ORM_CMN_BPT_BusinessParticipant.Query.Search(Connection, Transaction, new ORM_CMN_BPT_BusinessParticipant.Query()
                        {
                            IsDeleted    = false,
                            Tenant_RefID = securityTicket.TenantID,
                            CMN_BPT_BusinessParticipantID = CustomerPRactice.Ext_BusinessParticipant_RefID
                        }).Single();

                        PracticeName = PracticeBusinessParticipant.DisplayName;
                        PracticeBusinessParticipantID = PracticeBusinessParticipant.CMN_BPT_BusinessParticipantID;
                        PracticeCompanyInfoID         = PracticeBusinessParticipant.IfCompany_CMN_COM_CompanyInfo_RefID;

                        if (Parameter.IsUsePracticeBank)
                        {
                            var PracticeBusinessParticipant2bankaccount = ORM_CMN_BPT_BusinessParticipant_2_BankAccount.Query.Search(Connection, Transaction, new ORM_CMN_BPT_BusinessParticipant_2_BankAccount.Query()
                            {
                                IsDeleted    = false,
                                Tenant_RefID = securityTicket.TenantID,
                                CMN_BPT_BusinessParticipant_RefID = PracticeBusinessParticipant.CMN_BPT_BusinessParticipantID,
                            }).Single();


                            var business2bankAccount = new ORM_CMN_BPT_BusinessParticipant_2_BankAccount();
                            business2bankAccount.IsDeleted    = false;
                            business2bankAccount.Tenant_RefID = securityTicket.TenantID;
                            business2bankAccount.CMN_BPT_BusinessParticipant_RefID = BusinessParticipantID;
                            business2bankAccount.ACC_BNK_BankAccount_RefID         = PracticeBusinessParticipant2bankaccount.ACC_BNK_BankAccount_RefID;
                            business2bankAccount.Creation_Timestamp = DateTime.Now;
                            business2bankAccount.Save(Connection, Transaction);

                            BankAccountID = PracticeBusinessParticipant2bankaccount.ACC_BNK_BankAccount_RefID;
                            //end of save bank data if inherited from practice
                        }
                        else
                        {
                            if (!String.IsNullOrEmpty(Parameter.IBAN) || !String.IsNullOrEmpty(Parameter.Bank))
                            {
                                var business2bankAccount = new ORM_CMN_BPT_BusinessParticipant_2_BankAccount();
                                business2bankAccount.IsDeleted    = false;
                                business2bankAccount.Tenant_RefID = securityTicket.TenantID;
                                business2bankAccount.CMN_BPT_BusinessParticipant_RefID = BusinessParticipantID;
                                business2bankAccount.ACC_BNK_BankAccount_RefID         = Guid.NewGuid();
                                business2bankAccount.Creation_Timestamp = DateTime.Now;
                                business2bankAccount.Save(Connection, Transaction);

                                var bankAccountDoctor = new ORM_ACC_BNK_BankAccount();
                                bankAccountDoctor.IsDeleted             = false;
                                bankAccountDoctor.Tenant_RefID          = securityTicket.TenantID;
                                bankAccountDoctor.ACC_BNK_BankAccountID = business2bankAccount.ACC_BNK_BankAccount_RefID;
                                bankAccountDoctor.OwnerText             = Parameter.AccountHolder;
                                bankAccountDoctor.IBAN               = Parameter.IBAN;
                                bankAccountDoctor.Bank_RefID         = Guid.NewGuid();
                                bankAccountDoctor.Creation_Timestamp = DateTime.Now;
                                bankAccountDoctor.Save(Connection, Transaction);

                                if (!String.IsNullOrEmpty(Parameter.Bank))
                                {
                                    var bank = new ORM_ACC_BNK_Bank();
                                    bank.IsDeleted          = false;
                                    bank.Tenant_RefID       = securityTicket.TenantID;
                                    bank.ACC_BNK_BankID     = bankAccountDoctor.Bank_RefID;
                                    bank.BICCode            = Parameter.Bic;
                                    bank.BankName           = Parameter.Bank;
                                    bank.Creation_Timestamp = DateTime.Now;
                                    bank.Save(Connection, Transaction);
                                }

                                BankAccountID = business2bankAccount.ACC_BNK_BankAccount_RefID;
                                // end save bank data
                            }
                        }
                    }
                    catch
                    {
                        throw new Exception();
                    }
                }
                else
                {
                    var DoctorBusinessParticipant = new ORM_CMN_BPT_BusinessParticipant();

                    DoctorBusinessParticipant.IsDeleted    = false;
                    DoctorBusinessParticipant.Tenant_RefID = securityTicket.TenantID;
                    DoctorBusinessParticipant.CMN_BPT_BusinessParticipantID            = Guid.NewGuid();
                    DoctorBusinessParticipant.IfNaturalPerson_CMN_PER_PersonInfo_RefID = Guid.NewGuid();
                    DoctorBusinessParticipant.DisplayName            = Parameter.FirstName + " " + Parameter.LastNAme;
                    DoctorBusinessParticipant.IsNaturalPerson        = true;
                    DoctorBusinessParticipant.Modification_Timestamp = DateTime.Now;
                    DoctorBusinessParticipant.Save(Connection, Transaction);
                    personInfoID          = DoctorBusinessParticipant.IfNaturalPerson_CMN_PER_PersonInfo_RefID;
                    BusinessParticipantID = DoctorBusinessParticipant.CMN_BPT_BusinessParticipantID;

                    var companyInfoPractice = new ORM_CMN_PER_PersonInfo();
                    companyInfoPractice.IsDeleted            = false;
                    companyInfoPractice.Tenant_RefID         = securityTicket.TenantID;
                    companyInfoPractice.CMN_PER_PersonInfoID = personInfoID;
                    companyInfoPractice.FirstName            = Parameter.FirstName;
                    companyInfoPractice.LastName             = Parameter.LastNAme;
                    companyInfoPractice.Salutation_General   = Parameter.Salutation;
                    companyInfoPractice.Title = Parameter.Title;
                    companyInfoPractice.Save(Connection, Transaction);

                    var communicationContact = new ORM_CMN_PER_CommunicationContact();
                    communicationContact.IsDeleted              = false;
                    communicationContact.Contact_Type           = Guid.NewGuid();
                    communicationContact.Tenant_RefID           = securityTicket.TenantID;
                    communicationContact.Modification_Timestamp = DateTime.Now;
                    communicationContact.PersonInfo_RefID       = personInfoID;
                    communicationContact.Content = Parameter.Email;
                    communicationContact.Save(Connection, Transaction);
                    Guid CommunicationContactTypeID = communicationContact.Contact_Type;

                    var communicationContactType = new ORM_CMN_PER_CommunicationContact_Type();
                    communicationContactType.IsDeleted    = false;
                    communicationContactType.Tenant_RefID = securityTicket.TenantID;
                    communicationContactType.CMN_PER_CommunicationContact_TypeID = CommunicationContactTypeID;
                    communicationContactType.Type = "Email";
                    communicationContactType.Save(Connection, Transaction);

                    var communicationContact2 = new ORM_CMN_PER_CommunicationContact();
                    communicationContact2.IsDeleted              = false;
                    communicationContact2.Contact_Type           = Guid.NewGuid();
                    communicationContact2.Tenant_RefID           = securityTicket.TenantID;
                    communicationContact2.Modification_Timestamp = DateTime.Now;
                    communicationContact2.PersonInfo_RefID       = personInfoID;
                    communicationContact2.Content = Parameter.Phone;
                    communicationContact2.Save(Connection, Transaction);
                    Guid CommunicationContactTypeID2 = communicationContact2.Contact_Type;


                    var communicationContactType2 = new ORM_CMN_PER_CommunicationContact_Type();
                    communicationContactType2.IsDeleted    = false;
                    communicationContactType2.Tenant_RefID = securityTicket.TenantID;
                    communicationContactType2.CMN_PER_CommunicationContact_TypeID = CommunicationContactTypeID2;
                    communicationContactType2.Type = "Phone";
                    communicationContactType2.Save(Connection, Transaction);

                    var doctor = new ORM_HEC_Doctor();
                    doctor.HEC_DoctorID = Guid.NewGuid();
                    doctor.IsDeleted    = false;
                    doctor.Tenant_RefID = securityTicket.TenantID;
                    doctor.BusinessParticipant_RefID = BusinessParticipantID;
                    doctor.DoctorIDNumber            = Parameter.LANR.ToString();
                    doctor.Account_RefID             = Parameter.account_id;

                    doctor.Save(Connection, Transaction);

                    doctor_id = doctor.HEC_DoctorID;

                    var ogranizationUnitPractice = ORM_CMN_BPT_CTM_OrganizationalUnit.Query.Search(Connection, Transaction, new ORM_CMN_BPT_CTM_OrganizationalUnit.Query()
                    {
                        IsDeleted    = false,
                        Tenant_RefID = securityTicket.TenantID,
                        IfMedicalPractise_HEC_MedicalPractice_RefID = Parameter.PracticeID
                    }).Single();


                    var organizationalunit_Staff = new ORM_CMN_BPT_CTM_OrganizationalUnit_Staff();
                    organizationalunit_Staff.IsDeleted    = false;
                    organizationalunit_Staff.Tenant_RefID = securityTicket.TenantID;
                    organizationalunit_Staff.BusinessParticipant_RefID = BusinessParticipantID;
                    organizationalunit_Staff.OrganizationalUnit_RefID  = ogranizationUnitPractice.CMN_BPT_CTM_OrganizationalUnitID;
                    organizationalunit_Staff.Save(Connection, Transaction);


                    var CustomerPRactice = ORM_CMN_BPT_CTM_Customer.Query.Search(Connection, Transaction, new ORM_CMN_BPT_CTM_Customer.Query()
                    {
                        IsDeleted              = false,
                        Tenant_RefID           = securityTicket.TenantID,
                        CMN_BPT_CTM_CustomerID = ogranizationUnitPractice.Customer_RefID
                    }).Single();
                    var PracticeBusinessParticipant = ORM_CMN_BPT_BusinessParticipant.Query.Search(Connection, Transaction, new ORM_CMN_BPT_BusinessParticipant.Query()
                    {
                        IsDeleted    = false,
                        Tenant_RefID = securityTicket.TenantID,
                        CMN_BPT_BusinessParticipantID = CustomerPRactice.Ext_BusinessParticipant_RefID
                    }).Single();
                    PracticeName = PracticeBusinessParticipant.DisplayName;
                    PracticeBusinessParticipantID = PracticeBusinessParticipant.CMN_BPT_BusinessParticipantID;
                    PracticeCompanyInfoID         = PracticeBusinessParticipant.IfCompany_CMN_COM_CompanyInfo_RefID;
                    if (Parameter.IsUsePracticeBank == true)
                    {
                        var PracticeBusinessParticipant2bankaccount = ORM_CMN_BPT_BusinessParticipant_2_BankAccount.Query.Search(Connection, Transaction, new ORM_CMN_BPT_BusinessParticipant_2_BankAccount.Query()
                        {
                            IsDeleted    = false,
                            Tenant_RefID = securityTicket.TenantID,
                            CMN_BPT_BusinessParticipant_RefID = PracticeBusinessParticipant.CMN_BPT_BusinessParticipantID,
                        }).Single();


                        var business2bankAccount = new ORM_CMN_BPT_BusinessParticipant_2_BankAccount();
                        business2bankAccount.IsDeleted    = false;
                        business2bankAccount.Tenant_RefID = securityTicket.TenantID;
                        business2bankAccount.CMN_BPT_BusinessParticipant_RefID = BusinessParticipantID;
                        business2bankAccount.ACC_BNK_BankAccount_RefID         = PracticeBusinessParticipant2bankaccount.ACC_BNK_BankAccount_RefID;
                        business2bankAccount.Creation_Timestamp = DateTime.Now;
                        business2bankAccount.Save(Connection, Transaction);

                        BankAccountID = PracticeBusinessParticipant2bankaccount.ACC_BNK_BankAccount_RefID;
                        //end of save bank data if inherited from practice
                    }
                    else
                    {
                        if (!String.IsNullOrEmpty(Parameter.IBAN) || !String.IsNullOrEmpty(Parameter.Bank))
                        {
                            var business2bankAccount = new ORM_CMN_BPT_BusinessParticipant_2_BankAccount();
                            business2bankAccount.IsDeleted    = false;
                            business2bankAccount.Tenant_RefID = securityTicket.TenantID;
                            business2bankAccount.CMN_BPT_BusinessParticipant_RefID = BusinessParticipantID;
                            business2bankAccount.ACC_BNK_BankAccount_RefID         = Guid.NewGuid();
                            business2bankAccount.Creation_Timestamp = DateTime.Now;
                            business2bankAccount.Save(Connection, Transaction);

                            var bankAccountDoctor = new ORM_ACC_BNK_BankAccount();
                            bankAccountDoctor.IsDeleted             = false;
                            bankAccountDoctor.Tenant_RefID          = securityTicket.TenantID;
                            bankAccountDoctor.ACC_BNK_BankAccountID = business2bankAccount.ACC_BNK_BankAccount_RefID;
                            bankAccountDoctor.OwnerText             = Parameter.AccountHolder;
                            bankAccountDoctor.IBAN               = Parameter.IBAN;
                            bankAccountDoctor.Bank_RefID         = Guid.NewGuid();
                            bankAccountDoctor.Creation_Timestamp = DateTime.Now;
                            bankAccountDoctor.Save(Connection, Transaction);

                            if (!String.IsNullOrEmpty(Parameter.Bank))
                            {
                                var bank = new ORM_ACC_BNK_Bank();
                                bank.IsDeleted          = false;
                                bank.Tenant_RefID       = securityTicket.TenantID;
                                bank.ACC_BNK_BankID     = bankAccountDoctor.Bank_RefID;
                                bank.BICCode            = Parameter.Bic;
                                bank.BankName           = Parameter.Bank;
                                bank.Creation_Timestamp = DateTime.Now;
                                bank.Save(Connection, Transaction);
                            }

                            BankAccountID = business2bankAccount.ACC_BNK_BankAccount_RefID;
                            // end save bank data
                        }
                    }
                }
                var PracticeCompanyInfoAddress = ORM_CMN_COM_CompanyInfo_Address.Query.Search(Connection, Transaction, new ORM_CMN_COM_CompanyInfo_Address.Query()
                {
                    IsDeleted           = false,
                    Tenant_RefID        = securityTicket.TenantID,
                    CompanyInfo_RefID   = PracticeCompanyInfoID,
                    Address_Description = "Standard address for billing, shipping",
                }).SingleOrDefault();



                Practice_Doctors_Model DPModel = new Practice_Doctors_Model();

                if (PracticeCompanyInfoAddress != null)
                {
                    var PracticeUCD = ORM_CMN_UniversalContactDetail.Query.Search(Connection, Transaction, new ORM_CMN_UniversalContactDetail.Query()
                    {
                        IsDeleted    = false,
                        Tenant_RefID = securityTicket.TenantID,
                        CMN_UniversalContactDetailID = PracticeCompanyInfoAddress.Address_UCD_RefID,
                    }).SingleOrDefault();
                    DPModel.address = PracticeUCD.Street_Name + " " + PracticeUCD.Street_Number;
                    DPModel.zip     = PracticeUCD.ZIP;
                    DPModel.city    = PracticeUCD.Town;
                }

                DPModel.account_status = "aktiv";
                DPModel.id             = doctor_id.ToString();

                var title = string.IsNullOrEmpty(Parameter.Title) ? "" : Parameter.Title.Trim();

                DPModel.name              = title + " " + Parameter.FirstName + " " + Parameter.LastNAme;
                DPModel.name_untouched    = Parameter.FirstName + " " + Parameter.LastNAme;
                DPModel.bsnr_lanr         = Parameter.LANR.ToString();
                DPModel.autocomplete_name = title + " " + Parameter.FirstName + " " + Parameter.LastNAme;
                DPModel.salutation        = title;

                DPModel.type = "Doctor";

                DPModel.bank = string.IsNullOrEmpty(Parameter.Bank) ? "" : Parameter.Bank;

                DPModel.bank_untouched = string.IsNullOrEmpty(Parameter.Bank) ? "" : Parameter.Bank;


                DPModel.phone = Parameter.Phone;

                DPModel.email = string.IsNullOrEmpty(Parameter.Email) ? "" : Parameter.Email;

                DPModel.iban = string.IsNullOrEmpty(Parameter.IBAN) ? "" : Parameter.IBAN;

                DPModel.bic = string.IsNullOrEmpty(Parameter.Bic) ? "" : Parameter.Bic;

                DPModel.bank_id             = BankAccountID.ToString();
                DPModel.bank_info_inherited = Parameter.IsUsePracticeBank;
                DPModel.aditional_info      = "";
                DPModel.contract            = 0;


                DPModel.tenantid = securityTicket.TenantID.ToString();
                DPModel.practice_name_for_doctor = PracticeName;
                DPModel.practice_for_doctor_id   = Parameter.PracticeID.ToString();

                DPModel.role = isOpPractice ? "op" : "ac";

                List <Practice_Doctors_Model> DPModelL = new List <Practice_Doctors_Model>();
                DPModelL.Add(DPModel);

                Add_Practice_Doctors_to_Elastic.Import_Practice_Data_to_ElasticDB(DPModelL, securityTicket.TenantID.ToString());

                #region Assignment to Contract

                var contractIvi = ORM_CMN_CTR_Contract.Query.Search(Connection, Transaction, new ORM_CMN_CTR_Contract.Query()
                {
                    IsDeleted    = false,
                    Tenant_RefID = securityTicket.TenantID,
                    ContractName = "IVI-Vertrag"
                }).SingleOrDefault();
                if (contractIvi != null)
                {
                    Guid AssignmentID = Guid.NewGuid();
                    var  insuranceTobrokerContract = ORM_HEC_CRT_InsuranceToBrokerContract.Query.Search(Connection, Transaction, new ORM_HEC_CRT_InsuranceToBrokerContract.Query()
                    {
                        Ext_CMN_CTR_Contract_RefID = contractIvi.CMN_CTR_ContractID,
                        Tenant_RefID = securityTicket.TenantID,
                        IsDeleted    = false,
                    }).SingleOrDefault();
                    if (insuranceTobrokerContract != null)
                    {
                        AssignmentID = insuranceTobrokerContract.HEC_CRT_InsuranceToBrokerContractID;
                    }
                    else
                    {
                        var insuranceTobrokerContractNew = new ORM_HEC_CRT_InsuranceToBrokerContract();
                        insuranceTobrokerContractNew.HEC_CRT_InsuranceToBrokerContractID = Guid.NewGuid();
                        insuranceTobrokerContractNew.Creation_Timestamp         = DateTime.Now;
                        insuranceTobrokerContractNew.IsDeleted                  = false;
                        insuranceTobrokerContractNew.Tenant_RefID               = securityTicket.TenantID;
                        insuranceTobrokerContractNew.Ext_CMN_CTR_Contract_RefID = contractIvi.CMN_CTR_ContractID;
                        insuranceTobrokerContractNew.Save(Connection, Transaction);
                        AssignmentID = insuranceTobrokerContractNew.HEC_CRT_InsuranceToBrokerContractID;
                    }
                    var insuranceTobrokerContract2doctor = new ORM_HEC_CRT_InsuranceToBrokerContract_ParticipatingDoctor();
                    insuranceTobrokerContract2doctor.Creation_Timestamp = DateTime.Now;
                    insuranceTobrokerContract2doctor.HEC_CRT_InsuranceToBrokerContract_ParticipatingDoctorID = Guid.NewGuid();
                    insuranceTobrokerContract2doctor.InsuranceToBrokerContract_RefID = AssignmentID;
                    insuranceTobrokerContract2doctor.Tenant_RefID = securityTicket.TenantID;
                    insuranceTobrokerContract2doctor.IsDeleted    = false;
                    insuranceTobrokerContract2doctor.Doctor_RefID = doctor_id;
                    insuranceTobrokerContract2doctor.ValidFrom    = new DateTime(2013, 6, 15);
                    insuranceTobrokerContract2doctor.ValidThrough = DateTime.MinValue;
                    insuranceTobrokerContract2doctor.Save(Connection, Transaction);

                    P_DO_CDCD_1505 ParameterDoctorID = new P_DO_CDCD_1505();
                    ParameterDoctorID.DoctorID = doctor_id;
                    var data = cls_Get_Doctor_Contract_Numbers.Invoke(Connection, Transaction, ParameterDoctorID, securityTicket).Result;

                    int DoctorContracts = data.Count();
                    Doctor_Contracts ParameterDoctor = new Doctor_Contracts();
                    ParameterDoctor.DocID = doctor_id;

                    Practice_Doctors_Model DoctorFound = Get_Doctors_for_PracticeID.Set_Contract_Number_for_DoctorID(ParameterDoctor, securityTicket);

                    if (DoctorFound != null)
                    {
                        List <Practice_Doctors_Model> DoctorFoundL = new List <Practice_Doctors_Model>();
                        DoctorFound.contract = DoctorContracts;
                        DoctorFoundL.Add(DoctorFound);
                        Add_Practice_Doctors_to_Elastic.Import_Practice_Data_to_ElasticDB(DoctorFoundL, securityTicket.TenantID.ToString());
                    }


                    P_DO_GPIDfDID_1353 ParametarDocID = new P_DO_GPIDfDID_1353();
                    ParametarDocID.DoctorID = doctor_id;
                    DO_GPIDfDID_1353[] data2 = cls_Get_PracticeID_for_DoctorID.Invoke(Connection, Transaction, ParametarDocID, securityTicket).Result;

                    P_DO_GCfPID_1507 ParametarPractice = new P_DO_GCfPID_1507();

                    ParametarPractice.PracticeID = data2.First().HEC_MedicalPractiseID;
                    DO_GCfPID_1507[] Contracts       = cls_Get_all_Doctors_Contract_Assignment_for_PracticeID.Invoke(Connection, Transaction, ParametarPractice, securityTicket).Result;
                    int NumberOfContractsForPractice = Contracts.Count();
                    Practice_Doctors_Model practice  = new Practice_Doctors_Model();
                    practice.id = ParametarPractice.PracticeID.ToString();

                    Practice_Doctors_Model        PracticeFound = Get_Doctors_for_PracticeID.Get_Practice_for_PracticeID(practice, securityTicket);
                    List <Practice_Doctors_Model> practiceL     = new List <Practice_Doctors_Model>();
                    PracticeFound.contract = NumberOfContractsForPractice;
                    practiceL.Add(PracticeFound);
                    Add_Practice_Doctors_to_Elastic.Import_Practice_Data_to_ElasticDB(practiceL, securityTicket.TenantID.ToString());
                }
                #endregion



                if (cleanupTransaction == true)
                {
                    Transaction.Commit();
                }
                //Close the connection
                if (cleanupConnection == true)
                {
                    Connection.Close();
                }
            }



            catch (Exception ex)
            {
                try
                {
                    if (cleanupTransaction == true && Transaction != null)
                    {
                        Transaction.Rollback();
                    }
                }
                catch { }

                try
                {
                    if (cleanupConnection == true && Connection != null)
                    {
                        Connection.Close();
                    }
                }
                catch { }

                throw ex;
            }
        }
Beispiel #28
0
        public static void Save_Patients_to_DB(Patient_Model_xls Parameter, bool create_consents, string connectionString, SessionSecurityTicket securityTicket)
        {
            DbConnection  Connection         = null;
            DbTransaction Transaction        = null;
            bool          cleanupConnection  = Connection == null;
            bool          cleanupTransaction = Transaction == null;
            Guid          patient_id         = Guid.NewGuid();

            if (cleanupConnection == true)
            {
                Connection = CSV2Core_MySQL.Support.DBSQLSupport.CreateConnection(connectionString);
                Connection.Open();
            }
            if (cleanupTransaction == true)
            {
                Transaction = Connection.BeginTransaction();
            }

            try
            {
                Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("de-DE");

                ORM_HEC_Patient patients = new ORM_HEC_Patient();
                patients.HEC_PatientID                     = Guid.NewGuid();
                patients.Tenant_RefID                      = securityTicket.TenantID;
                patients.Creation_Timestamp                = DateTime.Now;
                patients.Modification_Timestamp            = DateTime.Now;
                patients.CMN_BPT_BusinessParticipant_RefID = Guid.NewGuid();
                patients.Save(Connection, Transaction);
                patient_id = patients.HEC_PatientID;

                ORM_CMN_BPT_BusinessParticipant businesParticipantPatient = new ORM_CMN_BPT_BusinessParticipant();
                businesParticipantPatient.CMN_BPT_BusinessParticipantID = patients.CMN_BPT_BusinessParticipant_RefID;
                businesParticipantPatient.Tenant_RefID           = securityTicket.TenantID;
                businesParticipantPatient.Creation_Timestamp     = DateTime.Now;
                businesParticipantPatient.Modification_Timestamp = DateTime.Now;
                businesParticipantPatient.IsNaturalPerson        = true;
                businesParticipantPatient.IfNaturalPerson_CMN_PER_PersonInfo_RefID = Guid.NewGuid();
                businesParticipantPatient.Save(Connection, Transaction);
                int PatientSex = 0;
                switch (Parameter.sex)
                {
                case "M":
                    PatientSex = 0;
                    break;

                case "W":
                    PatientSex = 1;
                    break;

                case "o.A.":
                    PatientSex = 2;
                    break;
                }

                ORM_CMN_PER_PersonInfo personInfo = new ORM_CMN_PER_PersonInfo();
                personInfo.CMN_PER_PersonInfoID   = businesParticipantPatient.IfNaturalPerson_CMN_PER_PersonInfo_RefID;
                personInfo.Tenant_RefID           = securityTicket.TenantID;
                personInfo.Creation_Timestamp     = DateTime.Now;
                personInfo.Modification_Timestamp = DateTime.Now;
                personInfo.FirstName = Parameter.name;
                personInfo.LastName  = Parameter.LastName;
                personInfo.BirthDate = Parameter.birthday;
                personInfo.Gender    = PatientSex;
                personInfo.Save(Connection, Transaction);

                ORM_HEC_Patient_MedicalPractice medical_practice_to_patient = new ORM_HEC_Patient_MedicalPractice();
                medical_practice_to_patient.HEC_Patient_MedicalPracticeID = Guid.NewGuid();
                medical_practice_to_patient.HEC_Patient_RefID             = patients.HEC_PatientID;
                medical_practice_to_patient.HEC_MedicalPractices_RefID    = Guid.Parse(Parameter.practice_id);//
                medical_practice_to_patient.Tenant_RefID       = securityTicket.TenantID;
                medical_practice_to_patient.Creation_Timestamp = DateTime.Now;
                medical_practice_to_patient.Save(Connection, Transaction);


                var medicalPracticeQuery = new ORM_HEC_HIS_HealthInsurance_Company.Query();
                medicalPracticeQuery.IsDeleted    = false;
                medicalPracticeQuery.Tenant_RefID = securityTicket.TenantID;

                var HIPList = ORM_HEC_HIS_HealthInsurance_Company.Query.Search(Connection, Transaction, medicalPracticeQuery).ToList();

                if (Parameter.isPrivatelyInsured)
                {
                    Parameter.health_insurance_providerNumber = "000000000";
                }

                var GetHip = HIPList.Where(hp => hp.HealthInsurance_IKNumber == Parameter.health_insurance_providerNumber).SingleOrDefault();
                if (GetHip == null)
                {
                    var businessParticipantHIP = new ORM_CMN_BPT_BusinessParticipant();
                    businessParticipantHIP.IsCompany              = true;
                    businessParticipantHIP.Tenant_RefID           = securityTicket.TenantID;
                    businessParticipantHIP.Modification_Timestamp = DateTime.Now;
                    businessParticipantHIP.DisplayName            = Parameter.health_insurance_provider;

                    businessParticipantHIP.Save(Connection, Transaction);

                    GetHip = new ORM_HEC_HIS_HealthInsurance_Company();
                    GetHip.Tenant_RefID = securityTicket.TenantID;
                    GetHip.CMN_BPT_BusinessParticipant_RefID = businessParticipantHIP.CMN_BPT_BusinessParticipantID;
                    GetHip.HealthInsurance_IKNumber          = String.IsNullOrEmpty(Parameter.health_insurance_provider) ? "privat versichert" : Parameter.health_insurance_provider;

                    GetHip.Save(Connection, Transaction);
                }

                ORM_HEC_Patient_HealthInsurance patientHealthInsurance = new ORM_HEC_Patient_HealthInsurance();
                patientHealthInsurance.HEC_Patient_HealthInsurancesID = Guid.NewGuid();
                patientHealthInsurance.Patient_RefID                     = patients.HEC_PatientID;
                patientHealthInsurance.HealthInsurance_Number            = Parameter.insurance_id;     //
                patientHealthInsurance.Tenant_RefID                      = securityTicket.TenantID;
                patientHealthInsurance.InsuranceStateCode                = Parameter.insurance_status; //
                patientHealthInsurance.HIS_HealthInsurance_Company_RefID = GetHip.HEC_HealthInsurance_CompanyID;
                patientHealthInsurance.Save(Connection, Transaction);

                #region import Patient to Elastic
                Patient_Model patientModel = new Patient_Model();


                patientModel.birthday                  = Parameter.birthday;
                patientModel.birthday_string           = Parameter.birthday.ToString("dd.MM.yyyy");
                patientModel.name                      = Parameter.LastName + ", " + Parameter.name;
                patientModel.health_insurance_provider = String.IsNullOrEmpty(Parameter.health_insurance_provider) ? "privat versichert" : Parameter.health_insurance_provider;
                patientModel.name_with_birthdate       = Parameter.name + " " + Parameter.LastName + " (" + Parameter.birthday.ToString("dd.MM.yyyy") + ")";
                patientModel.id               = patients.HEC_PatientID.ToString();
                patientModel.insurance_id     = String.IsNullOrEmpty(Parameter.insurance_id) ? "-" : Parameter.insurance_id;
                patientModel.insurance_status = String.IsNullOrEmpty(Parameter.insurance_status) ? "-" : Parameter.insurance_status;
                patientModel.practice_id      = Parameter.practice_id.ToString();

                if (PatientSex == 0)
                {
                    patientModel.sex = "M";
                }
                else if (PatientSex == 1)
                {
                    patientModel.sex = "W";
                }
                else if (PatientSex == 2)
                {
                    patientModel.sex = "o.A.";
                }

                Add_New_Patient.Import_Patients_to_ElasticDB(patientModel, securityTicket.TenantID.ToString());
                if (create_consents)
                {
                    #region Participation Consent
                    var contractIvi = ORM_CMN_CTR_Contract.Query.Search(Connection, Transaction, new ORM_CMN_CTR_Contract.Query()
                    {
                        IsDeleted    = false,
                        Tenant_RefID = securityTicket.TenantID,
                        ContractName = "IVI-Vertrag"
                    }).SingleOrDefault();

                    if (contractIvi != null)
                    {
                        var InsuranceToBrokerContractQuery = new ORM_HEC_CRT_InsuranceToBrokerContract.Query();
                        InsuranceToBrokerContractQuery.Tenant_RefID = securityTicket.TenantID;
                        InsuranceToBrokerContractQuery.IsDeleted    = false;
                        InsuranceToBrokerContractQuery.Ext_CMN_CTR_Contract_RefID = contractIvi.CMN_CTR_ContractID;

                        ORM_HEC_CRT_InsuranceToBrokerContract InsuranceToBrokerContract = ORM_HEC_CRT_InsuranceToBrokerContract.Query.Search(Connection, Transaction, InsuranceToBrokerContractQuery).Single();

                        List <DateTime> TimeFrom = new List <DateTime>();
                        DateTime        time1    = new DateTime(2013, 6, 15);
                        DateTime        time2    = new DateTime(2014, 6, 15);
                        DateTime        time3    = new DateTime(2015, 6, 15);

                        TimeFrom.Add(time1);
                        TimeFrom.Add(time2);
                        TimeFrom.Add(time3);
                        foreach (var date in TimeFrom)
                        {
                            ORM_HEC_CRT_InsuranceToBrokerContract_ParticipatingPatient InsuranceToBrokerContract_ParticipatingPatient = new ORM_HEC_CRT_InsuranceToBrokerContract_ParticipatingPatient();
                            InsuranceToBrokerContract_ParticipatingPatient.HEC_CRT_InsuranceToBrokerContract_ParticipatingPatientID = Guid.NewGuid();
                            InsuranceToBrokerContract_ParticipatingPatient.InsuranceToBrokerContract_RefID = InsuranceToBrokerContract.HEC_CRT_InsuranceToBrokerContractID;
                            InsuranceToBrokerContract_ParticipatingPatient.Creation_Timestamp     = DateTime.Now;
                            InsuranceToBrokerContract_ParticipatingPatient.Modification_Timestamp = DateTime.Now;
                            InsuranceToBrokerContract_ParticipatingPatient.Tenant_RefID           = securityTicket.TenantID;
                            InsuranceToBrokerContract_ParticipatingPatient.ValidFrom     = date;
                            InsuranceToBrokerContract_ParticipatingPatient.ValidThrough  = DateTime.MinValue;
                            InsuranceToBrokerContract_ParticipatingPatient.Patient_RefID = patient_id;
                            InsuranceToBrokerContract_ParticipatingPatient.Save(Connection, Transaction);

                            Patient_Model patientModel2 = new Patient_Model();
                            patientModel2 = Retrieve_Patients.Get_Patient_for_PatientID(patient_id.ToString(), securityTicket);

                            var InsuranceToBrokerContract_ParticipatingPatientQuery = new ORM_HEC_CRT_InsuranceToBrokerContract_ParticipatingPatient.Query();
                            InsuranceToBrokerContract_ParticipatingPatientQuery.IsDeleted     = false;
                            InsuranceToBrokerContract_ParticipatingPatientQuery.Tenant_RefID  = securityTicket.TenantID;
                            InsuranceToBrokerContract_ParticipatingPatientQuery.Patient_RefID = patient_id;

                            var allInsuranceToBrokerContract_ParticipatingPatient = ORM_HEC_CRT_InsuranceToBrokerContract_ParticipatingPatient.Query.Search(Connection, Transaction, InsuranceToBrokerContract_ParticipatingPatientQuery).ToList();
                            var latest_participation_date = allInsuranceToBrokerContract_ParticipatingPatient.OrderByDescending(m => m.ValidFrom).FirstOrDefault();

                            patientModel2.participation_consent_from = latest_participation_date.ValidFrom;
                            patientModel2.participation_consent_to   = latest_participation_date.ValidThrough;
                            patientModel2.has_participation_consent  = true;

                            Add_New_Patient.Import_Patients_to_ElasticDB(patientModel2, securityTicket.TenantID.ToString());
                        }
                    }
                }

                #endregion
                //Commit the transaction
                if (cleanupTransaction == true)
                {
                    Transaction.Commit();
                }
                //Close the connection
                if (cleanupConnection == true)
                {
                    Connection.Close();
                }
            }
            catch (Exception ex)
            {
                try
                {
                    if (cleanupTransaction == true && Transaction != null)
                    {
                        Transaction.Rollback();
                    }
                }
                catch { }

                try
                {
                    if (cleanupConnection == true && Connection != null)
                    {
                        Connection.Close();
                    }
                }
                catch { }

                throw ex;
            }

            #endregion
        }
        protected static FR_L3CU_CCaMR_1308 Execute(DbConnection Connection, DbTransaction Transaction, P_L3CU_CCaMR_1308 Parameter, CSV2Core.SessionSecurity.SessionSecurityTicket securityTicket = null)
        {
            #region UserCode
            var returnValue = new FR_L3CU_CCaMR_1308();
            returnValue.Status = FR_Status.Error_Internal;
            returnValue.Result = new L3CU_CCaMR_1308();

            #region Load or Create Customer Tenant Initial Table Structure
            var customerTenantStructure = cls_Create_Tenant_Initial_Table_Structure.Invoke(
                Connection,
                Transaction,
                new P_L3TE_CTITS_1108()
            {
                TenantITL = Parameter.Customer_TenantITL,
                BusinessParticipantITL               = Parameter.Customer_BusinessParticipantITL,
                TenantUniversalContactDetailITL      = Parameter.Customer_TenantUniversalContactDetailITL,
                CompanyInfoUniversalContactDetailITL = Parameter.Customer_CompanyInfoUniversalContactDetailITL,
                CompanyName  = Parameter.Customer_CompanyName,
                ContactEmail = Parameter.Customer_ContactEmail
            },
                securityTicket);
            #endregion
            if (customerTenantStructure.Status != FR_Status.Success)
            {
                return(returnValue);
            }

            #region Load or Create Customer
            var cust = ORM_CMN_BPT_CTM_Customer.Query.Search(Connection, Transaction, new ORM_CMN_BPT_CTM_Customer.Query()
            {
                Ext_BusinessParticipant_RefID = customerTenantStructure.Result.BusinessParticipantID,
                Tenant_RefID = securityTicket.TenantID,
                IsDeleted    = false
            }).SingleOrDefault();

            if (cust == default(ORM_CMN_BPT_CTM_Customer))
            {
                cust = new ORM_CMN_BPT_CTM_Customer();
                cust.CMN_BPT_CTM_CustomerID        = Guid.NewGuid();
                cust.Ext_BusinessParticipant_RefID = customerTenantStructure.Result.BusinessParticipantID;
                cust.Tenant_RefID       = securityTicket.TenantID;
                cust.Creation_Timestamp = DateTime.Now;
                cust.Save(Connection, Transaction);
            }
            #endregion

            #region Create booking account
            var fiscalYear = cls_Get_Current_FiscalYear.Invoke(Connection, Transaction, securityTicket).Result;

            var bookingAccountParam = new P_L3BA_CCAfBP_1655()
            {
                BusinessParticipantIDs = new Guid[1] {
                    customerTenantStructure.Result.BusinessParticipantID
                },
                FiscalYearID = fiscalYear.ACC_FiscalYearID
            };

            var result = cls_Create_Customer_Account_for_BusinessParticipants.Invoke(Connection, Transaction, bookingAccountParam, securityTicket).Result;
            #endregion

            #region create defaultPerson for customer

            var businessParticipantQuery = new ORM_CMN_BPT_BusinessParticipant.Query();
            businessParticipantQuery.CMN_BPT_BusinessParticipantID = cust.Ext_BusinessParticipant_RefID;
            businessParticipantQuery.IsDeleted = false;
            var businessParticipant = ORM_CMN_BPT_BusinessParticipant.Query.Search(Connection, Transaction, businessParticipantQuery).Single();

            if (businessParticipant.IsNaturalPerson)
            {
                if (businessParticipant.IfNaturalPerson_CMN_PER_PersonInfo_RefID == null || businessParticipant.IfNaturalPerson_CMN_PER_PersonInfo_RefID == Guid.Empty)
                {
                    var personInfo = new ORM_CMN_PER_PersonInfo();
                    personInfo.CMN_PER_PersonInfoID = Guid.NewGuid();
                    personInfo.Tenant_RefID         = securityTicket.TenantID;
                    personInfo.IsDeleted            = false;
                    personInfo.FirstName            = businessParticipant.DisplayName;
                    personInfo.LastName             = businessParticipant.DisplayName;
                    personInfo.Creation_Timestamp   = DateTime.Now;
                    personInfo.Save(Connection, Transaction);

                    businessParticipant.IfNaturalPerson_CMN_PER_PersonInfo_RefID = personInfo.CMN_PER_PersonInfoID;
                }
            }
            else if (businessParticipant.IsCompany)
            {
                Boolean needDefaultPerson = true;
                var     associatedBPQuery = new ORM_CMN_BPT_BusinessParticipant_AssociatedBusinessParticipant.Query();
                associatedBPQuery.AssociatedBusinessParticipant_RefID = businessParticipant.CMN_BPT_BusinessParticipantID;
                associatedBPQuery.Tenant_RefID = securityTicket.TenantID;
                associatedBPQuery.IsDeleted    = false;
                List <ORM_CMN_BPT_BusinessParticipant_AssociatedBusinessParticipant> associations =
                    ORM_CMN_BPT_BusinessParticipant_AssociatedBusinessParticipant.Query.Search(Connection, Transaction, associatedBPQuery);
                if (associations.Count > 0)
                {
                    foreach (var assotiation in associations)
                    {
                        if (assotiation.BusinessParticipant_RefID != Guid.Empty)
                        {
                            ORM_CMN_BPT_BusinessParticipant.Query businessParticipantPersonQuery = new ORM_CMN_BPT_BusinessParticipant.Query();
                            businessParticipantPersonQuery.CMN_BPT_BusinessParticipantID = assotiation.BusinessParticipant_RefID;
                            businessParticipantPersonQuery.IsDeleted       = false;
                            businessParticipantPersonQuery.IsNaturalPerson = true;
                            List <ORM_CMN_BPT_BusinessParticipant> businessParticipantsPerson =
                                ORM_CMN_BPT_BusinessParticipant.Query.Search(Connection, Transaction, businessParticipantPersonQuery);
                            foreach (var person in businessParticipantsPerson)
                            {
                                if (person.IfNaturalPerson_CMN_PER_PersonInfo_RefID == Guid.Empty)
                                {
                                    ORM_CMN_PER_PersonInfo personInfoNew = new ORM_CMN_PER_PersonInfo();
                                    personInfoNew.CMN_PER_PersonInfoID = Guid.NewGuid();
                                    personInfoNew.Tenant_RefID         = securityTicket.TenantID;
                                    personInfoNew.IsDeleted            = false;
                                    personInfoNew.FirstName            = person.DisplayName;
                                    personInfoNew.LastName             = person.DisplayName;
                                    personInfoNew.Creation_Timestamp   = DateTime.Now;
                                    personInfoNew.Save(Connection, Transaction);

                                    person.IfNaturalPerson_CMN_PER_PersonInfo_RefID = personInfoNew.CMN_PER_PersonInfoID;
                                }

                                needDefaultPerson = false;
                                break;
                            }
                        }
                    }
                }

                if (needDefaultPerson)
                {
                    #region create personalInfo
                    ORM_CMN_PER_PersonInfo personInfo = new ORM_CMN_PER_PersonInfo();
                    personInfo.CMN_PER_PersonInfoID = Guid.NewGuid();
                    personInfo.Tenant_RefID         = securityTicket.TenantID;
                    personInfo.IsDeleted            = false;
                    personInfo.FirstName            = businessParticipant.DisplayName;
                    personInfo.LastName             = businessParticipant.DisplayName;
                    personInfo.Creation_Timestamp   = DateTime.Now;
                    personInfo.Save(Connection, Transaction);
                    #endregion

                    #region create new businessParticipiant
                    ORM_CMN_BPT_BusinessParticipant bParticipant = new ORM_CMN_BPT_BusinessParticipant();
                    bParticipant.CMN_BPT_BusinessParticipantID = Guid.NewGuid();
                    bParticipant.Tenant_RefID    = securityTicket.TenantID;
                    bParticipant.IsNaturalPerson = true;
                    bParticipant.IfNaturalPerson_CMN_PER_PersonInfo_RefID = personInfo.CMN_PER_PersonInfoID;
                    bParticipant.DisplayName        = businessParticipant.DisplayName;
                    bParticipant.Creation_Timestamp = DateTime.Now;
                    bParticipant.Save(Connection, Transaction);
                    #endregion

                    #region create associated businessParticipant table
                    ORM_CMN_BPT_BusinessParticipant_AssociatedBusinessParticipant associatedBP = new ORM_CMN_BPT_BusinessParticipant_AssociatedBusinessParticipant();
                    associatedBP.CMN_BPT_BusinessParticipant_AssociatedBusinessParticipantID = Guid.NewGuid();
                    associatedBP.IsDeleted = false;
                    associatedBP.BusinessParticipant_RefID           = bParticipant.CMN_BPT_BusinessParticipantID;
                    associatedBP.AssociatedBusinessParticipant_RefID = businessParticipant.CMN_BPT_BusinessParticipantID;
                    associatedBP.Creation_Timestamp = DateTime.Now;
                    associatedBP.Tenant_RefID       = securityTicket.TenantID;
                    associatedBP.Save(Connection, Transaction);
                    #endregion
                }
            }
            #endregion


            returnValue.Result.Customer_TenantID = customerTenantStructure.Result.TenantID;
            returnValue.Result.Customer_BusinessParticipantID = customerTenantStructure.Result.BusinessParticipantID;
            returnValue.Result.Customer_CompanyInfo_UniversalContactDetailID = customerTenantStructure.Result.CompanyInfoUniversalContactDetailID;
            returnValue.Result.Customer_Tenant_UniversalContactDetailID      = customerTenantStructure.Result.TenantUniversalContactDetailID;
            returnValue.Result.Customer_CustomerID    = cust.CMN_BPT_CTM_CustomerID;
            returnValue.Result.Customer_CompanyInfoID = customerTenantStructure.Result.CompanyInfoID;
            returnValue.Result.IsCustomerOrderAutomaticallyApprovedOnReceipt = cust.IsCustomerOrderAutomaticallyApprovedOnReceipt;
            returnValue.Status = FR_Status.Success;

            return(returnValue);


            #endregion UserCode
        }
Beispiel #30
0
        protected static FR_Guid Execute(DbConnection Connection, DbTransaction Transaction, P_L5DI_SRMP_1425 Parameter, CSV2Core.SessionSecurity.SessionSecurityTicket securityTicket = null)
        {
            #region UserCode
            var returnValue = new FR_Guid();

            P_L2LN_GALFTID_1530 langParam = new P_L2LN_GALFTID_1530();
            langParam.Tenant_RefID = securityTicket.TenantID;
            var DBLanguages = cls_Get_All_Languages_ForTenantID.Invoke(Connection, Transaction, langParam, securityTicket).Result;

            #region Save
            if (Parameter.HEC_MedicalPractiseID == Guid.Empty)
            {
                ORM_HEC_MedicalPractis medicalPractice = new ORM_HEC_MedicalPractis();
                medicalPractice.HEC_MedicalPractiseID = Guid.NewGuid();
                medicalPractice.IsHospital            = Parameter.IsHospital;
                medicalPractice.Tenant_RefID          = securityTicket.TenantID;
                medicalPractice.IsDeleted             = false;
                medicalPractice.Save(Connection, Transaction);

                //*******************Save Medical Practice Type*******************
                if (Parameter.MedicalPracticeType != null && Parameter.MedicalPracticeType.Count() > 0)
                {
                    foreach (var medicalPracticeTypeParam in Parameter.MedicalPracticeType)
                    {
                        if (!medicalPracticeTypeParam.IsDeleted)
                        {
                            ORM_HEC_MedicalPractice_2_PracticeType medicalPracticeType = new ORM_HEC_MedicalPractice_2_PracticeType();
                            medicalPracticeType.AssignmentID = Guid.NewGuid();
                            medicalPracticeType.HEC_MedicalPractice_Type_RefID = medicalPracticeTypeParam.HEC_MedicalPractice_TypeID;
                            medicalPracticeType.HEC_MedicalPractice_RefID      = medicalPractice.HEC_MedicalPractiseID;
                            medicalPracticeType.Tenant_RefID = securityTicket.TenantID;
                            medicalPracticeType.IsDeleted    = false;
                            medicalPracticeType.Save(Connection, Transaction);
                        }
                    }
                }
                //*******************Save Medical Practice Service*******************
                //on front we must find if medical practice already exist for given service name
                if (Parameter.MedicalService != null && Parameter.MedicalService.Count() > 0)
                {
                    //ORM_HEC_MedicalService medicalService = ORM_HEC_MedicalService.Query.Search(Connection, Transaction, new ORM_HEC_MedicalService.Query
                    //{
                    //    HEC_MedicalServiceID = Parameter.MedicalService.HEC_MedicalServiceID,
                    //    IsDeleted = false,
                    //    Tenant_RefID = securityTicket.TenantID
                    //}).SingleOrDefault();
                    foreach (var medicalServiceParam in Parameter.MedicalService)
                    {
                        ORM_HEC_MedicalService medicalService = new ORM_HEC_MedicalService();
                        if (medicalServiceParam.NewMedicalService)
                        {
                            medicalService.HEC_MedicalServiceID = Guid.NewGuid();
                            medicalService.ServiceName          = medicalServiceParam.ServiceName;
                            medicalService.Tenant_RefID         = securityTicket.TenantID;
                            medicalService.IsDeleted            = false;
                            medicalService.Save(Connection, Transaction);
                        }

                        ORM_HEC_MedicalPractice_OfferedService medicalPracticeOfferedService = new ORM_HEC_MedicalPractice_OfferedService();
                        if (!medicalServiceParam.NewMedicalService)
                        {
                            medicalPracticeOfferedService.MedicalService_RefID = medicalServiceParam.HEC_MedicalServiceID;
                        }
                        else
                        {
                            medicalPracticeOfferedService.MedicalService_RefID = medicalService.HEC_MedicalServiceID;
                        }
                        medicalPracticeOfferedService.MedicalPractice_RefID = medicalPractice.HEC_MedicalPractiseID;
                        medicalPracticeOfferedService.IsDeleted             = false;
                        medicalPracticeOfferedService.Tenant_RefID          = securityTicket.TenantID;
                        medicalPracticeOfferedService.Save(Connection, Transaction);
                    }
                }
                //*******************Save Contact Person************************

                ORM_CMN_PER_PersonInfo personInfo = new ORM_CMN_PER_PersonInfo();
                personInfo.CMN_PER_PersonInfoID = Guid.NewGuid();
                personInfo.Title        = Parameter.ContactPersonTitle;
                personInfo.FirstName    = Parameter.ContactPersonFirstName;
                personInfo.LastName     = Parameter.ContactPersonLastName;
                personInfo.Tenant_RefID = securityTicket.TenantID;
                personInfo.IsDeleted    = false;
                personInfo.Save(Connection, Transaction);

                ORM_CMN_BPT_BusinessParticipant businessParticpant = new ORM_CMN_BPT_BusinessParticipant();
                businessParticpant.CMN_BPT_BusinessParticipantID = Guid.NewGuid();
                businessParticpant.IsNaturalPerson = true;
                businessParticpant.DisplayName     = Parameter.ContactPersonTitle + " " + Parameter.ContactPersonFirstName + " " + Parameter.ContactPersonLastName;
                businessParticpant.Tenant_RefID    = securityTicket.TenantID;
                businessParticpant.IsDeleted       = false;
                businessParticpant.IfNaturalPerson_CMN_PER_PersonInfo_RefID = personInfo.CMN_PER_PersonInfoID;
                businessParticpant.Save(Connection, Transaction);

                medicalPractice.ContactPerson_RefID = businessParticpant.CMN_BPT_BusinessParticipantID;

                //*******************Customer OrganizationalUnit************************
                ORM_CMN_BPT_CTM_OrganizationalUnit organizationalUnit = new ORM_CMN_BPT_CTM_OrganizationalUnit();
                organizationalUnit.CMN_BPT_CTM_OrganizationalUnitID = Guid.NewGuid();

                Dict medicationPracticeName = new Dict("hec_dia_potentialdiagnoses");
                for (int i = 0; i < DBLanguages.Length; i++)
                {
                    medicationPracticeName.AddEntry(DBLanguages[i].CMN_LanguageID, Parameter.MedicalPractiseName);
                }

                organizationalUnit.OrganizationalUnit_Name = medicationPracticeName;
                organizationalUnit.IsDeleted           = false;
                organizationalUnit.Tenant_RefID        = securityTicket.TenantID;
                organizationalUnit.Default_PhoneNumber = Parameter.Contact_Telephone;
                organizationalUnit.IsMedicalPractice   = true;
                organizationalUnit.IfMedicalPractise_HEC_MedicalPractice_RefID = medicalPractice.HEC_MedicalPractiseID;
                organizationalUnit.Save(Connection, Transaction);

                //*******************AppointmentType************************
                //if (Parameter.AppoitmentType != null && Parameter.AppoitmentType.Count() > 0)
                //{
                //    foreach (var item in Parameter.AppoitmentType)
                //    {
                //        ORM_PPS_TSK_Task_Template_CustomerOrgUnitAvailability customerOrgUnitAvailability = new ORM_PPS_TSK_Task_Template_CustomerOrgUnitAvailability();
                //        customerOrgUnitAvailability.PPS_TSK_Task_Template_CustomerOrgUnitAvailabilityID = Guid.NewGuid();
                //        customerOrgUnitAvailability.CMN_BPT_CTM_OrganizationalUnit_RefID = organizationalUnit.CMN_BPT_CTM_OrganizationalUnitID;
                //        customerOrgUnitAvailability.PPS_TSK_Task_Template_RefID = item.PPS_TSK_Task_Template_RefID;
                //        customerOrgUnitAvailability.Tenant_RefID = securityTicket.TenantID;
                //        customerOrgUnitAvailability.Save(Connection, Transaction);
                //    }
                //}
                //*******************Save Address************************
                ORM_CMN_UniversalContactDetail contactDetail = new ORM_CMN_UniversalContactDetail();
                contactDetail.CMN_UniversalContactDetailID = Guid.NewGuid();
                contactDetail.IsCompany           = true;
                contactDetail.Street_Name         = Parameter.Street_Name;
                contactDetail.Street_Number       = Parameter.Street_Number;
                contactDetail.Town                = Parameter.Town;
                contactDetail.Contact_Website_URL = Parameter.Contact_Website_URL;
                contactDetail.Contact_Telephone   = Parameter.Contact_Telephone;
                contactDetail.IsDeleted           = false;
                contactDetail.Tenant_RefID        = securityTicket.TenantID;
                contactDetail.Save(Connection, Transaction);

                ORM_CMN_COM_CompanyInfo companyInfo = new ORM_CMN_COM_CompanyInfo();
                companyInfo.CMN_COM_CompanyInfoID = Guid.NewGuid();
                companyInfo.Contact_UCD_RefID     = contactDetail.CMN_UniversalContactDetailID;
                companyInfo.IsDeleted             = false;
                companyInfo.Tenant_RefID          = securityTicket.TenantID;
                companyInfo.Save(Connection, Transaction);

                medicalPractice.Ext_CompanyInfo_RefID = companyInfo.CMN_COM_CompanyInfoID;
                medicalPractice.Save(Connection, Transaction);

                //*******************Save Address************************
                //ORM_CMN_UniversalContactDetail contactDetail = new ORM_CMN_UniversalContactDetail();
                //contactDetail.CMN_UniversalContactDetailID = Guid.NewGuid();
                //contactDetail.IsCompany = true;
                //contactDetail.Street_Name = Parameter.Street_Name;
                //contactDetail.Street_Number = Parameter.Street_Number;
                //contactDetail.Town = Parameter.Town;
                //contactDetail.Contact_Website_URL = Parameter.Contact_Website_URL;
                //contactDetail.Contact_Telephone = Parameter.Contact_Telephone;
                //contactDetail.IsDeleted = false;
                //contactDetail.Tenant_RefID = securityTicket.TenantID;
                //contactDetail.Save(Connection, Transaction);

                //ORM_CMN_BPT_CTM_OrganizationalUnit_Address organizationalUnitAddress = new ORM_CMN_BPT_CTM_OrganizationalUnit_Address();
                //organizationalUnitAddress.UniversalContactDetail_Address_RefID = contactDetail.CMN_UniversalContactDetailID;
                //organizationalUnitAddress.OrganizationalUnit_RefID = organizationalUnit.CMN_BPT_CTM_OrganizationalUnitID;
                //organizationalUnitAddress.IsDeleted = false;
                //organizationalUnitAddress.Tenant_RefID = securityTicket.TenantID;
                //organizationalUnitAddress.Save(Connection, Transaction);

                returnValue.Result = medicalPractice.HEC_MedicalPractiseID;
            }
            #endregion
            //=====================Edit or Delete=====================
            else
            {
                ORM_HEC_MedicalPractis medicalPractice = ORM_HEC_MedicalPractis.Query.Search(Connection, Transaction, new ORM_HEC_MedicalPractis.Query
                {
                    HEC_MedicalPractiseID = Parameter.HEC_MedicalPractiseID,
                    IsDeleted             = false,
                    Tenant_RefID          = securityTicket.TenantID
                }).Single();
                ORM_CMN_BPT_CTM_OrganizationalUnit organizationalUnit = ORM_CMN_BPT_CTM_OrganizationalUnit.Query.Search(Connection, Transaction, new ORM_CMN_BPT_CTM_OrganizationalUnit.Query
                {
                    IfMedicalPractise_HEC_MedicalPractice_RefID = medicalPractice.HEC_MedicalPractiseID,
                    IsDeleted    = false,
                    Tenant_RefID = securityTicket.TenantID
                }).Single();

                #region Edit
                if (Parameter.IsDeleted == false)
                {
                    //*******************Edit Medical Practice Service*******************
                    if (Parameter.MedicalService != null && Parameter.MedicalService.Count() > 0)
                    {
                        foreach (var medicalServiceParam in Parameter.MedicalService)
                        {
                            ORM_HEC_MedicalPractice_OfferedService medicalPracticeOfferedService = ORM_HEC_MedicalPractice_OfferedService.Query.Search(Connection, Transaction, new ORM_HEC_MedicalPractice_OfferedService.Query
                            {
                                HEC_MedicalPractice_OfferedServiceID = medicalServiceParam.HEC_MedicalPractice_OfferedServiceID,
                                IsDeleted    = false,
                                Tenant_RefID = securityTicket.TenantID
                            }).SingleOrDefault();
                            ORM_HEC_MedicalService medicalService = ORM_HEC_MedicalService.Query.Search(Connection, Transaction, new ORM_HEC_MedicalService.Query
                            {
                                HEC_MedicalServiceID = medicalServiceParam.HEC_MedicalServiceID,
                                IsDeleted            = false,
                                Tenant_RefID         = securityTicket.TenantID
                            }).SingleOrDefault();

                            if (medicalServiceParam.NewMedicalService && !medicalServiceParam.IsDeleted)
                            {
                                medicalService = new ORM_HEC_MedicalService();
                                medicalService.HEC_MedicalServiceID = Guid.NewGuid();
                                medicalService.ServiceName          = medicalServiceParam.ServiceName;
                                medicalService.Tenant_RefID         = securityTicket.TenantID;
                                medicalService.IsDeleted            = false;
                                medicalService.Save(Connection, Transaction);
                            }

                            if (medicalPracticeOfferedService == null && !medicalServiceParam.IsDeleted)
                            {
                                medicalPracticeOfferedService = new ORM_HEC_MedicalPractice_OfferedService();
                                if (!medicalServiceParam.NewMedicalService)
                                {
                                    medicalPracticeOfferedService.MedicalService_RefID = medicalServiceParam.HEC_MedicalServiceID;
                                }
                                else
                                {
                                    medicalPracticeOfferedService.MedicalService_RefID = medicalService.HEC_MedicalServiceID;
                                }
                                medicalPracticeOfferedService.MedicalPractice_RefID = medicalPractice.HEC_MedicalPractiseID;
                                medicalPracticeOfferedService.IsDeleted             = false;
                                medicalPracticeOfferedService.Tenant_RefID          = securityTicket.TenantID;
                                medicalPracticeOfferedService.Save(Connection, Transaction);
                            }
                            else if (medicalPracticeOfferedService != null && !medicalServiceParam.IsDeleted)
                            {
                                medicalPracticeOfferedService.MedicalService_RefID = medicalService.HEC_MedicalServiceID;
                                medicalPracticeOfferedService.Save(Connection, Transaction);
                            }
                            else if (medicalPracticeOfferedService != null && medicalServiceParam.IsDeleted)
                            {
                                medicalPracticeOfferedService.IsDeleted = true;
                                medicalPracticeOfferedService.Save(Connection, Transaction);
                            }
                        }
                    }


                    //*******************Edit Customer OrganizationalUnit************************
                    Dict medicationPracticeName = new Dict("hec_dia_potentialdiagnoses");
                    for (int i = 0; i < DBLanguages.Length; i++)
                    {
                        medicationPracticeName.AddEntry(DBLanguages[i].CMN_LanguageID, Parameter.MedicalPractiseName);
                    }

                    organizationalUnit.OrganizationalUnit_Name = medicationPracticeName;
                    organizationalUnit.Default_PhoneNumber     = Parameter.Contact_Telephone;
                    organizationalUnit.Save(Connection, Transaction);

                    //*******************Edit Contact Person************************
                    ORM_CMN_BPT_BusinessParticipant businessParticipant = ORM_CMN_BPT_BusinessParticipant.Query.Search(Connection, Transaction, new ORM_CMN_BPT_BusinessParticipant.Query
                    {
                        CMN_BPT_BusinessParticipantID = medicalPractice.ContactPerson_RefID,
                        IsDeleted    = false,
                        Tenant_RefID = securityTicket.TenantID
                    }).Single();
                    businessParticipant.DisplayName = Parameter.ContactPersonTitle + " " + Parameter.ContactPersonFirstName + " " + Parameter.ContactPersonLastName;
                    businessParticipant.Save(Connection, Transaction);

                    ORM_CMN_PER_PersonInfo personInfo = ORM_CMN_PER_PersonInfo.Query.Search(Connection, Transaction, new ORM_CMN_PER_PersonInfo.Query
                    {
                        CMN_PER_PersonInfoID = businessParticipant.IfNaturalPerson_CMN_PER_PersonInfo_RefID,
                        IsDeleted            = false,
                        Tenant_RefID         = securityTicket.TenantID
                    }).Single();
                    personInfo.Title     = Parameter.ContactPersonTitle;
                    personInfo.FirstName = Parameter.ContactPersonFirstName;
                    personInfo.LastName  = Parameter.ContactPersonLastName;
                    personInfo.Save(Connection, Transaction);

                    //*******************Edit Medical Practice Type*******************
                    foreach (var medicalPracticeTypeParam in Parameter.MedicalPracticeType)
                    {
                        ORM_HEC_MedicalPractice_2_PracticeType existingPracticeType = ORM_HEC_MedicalPractice_2_PracticeType.Query.Search(Connection, Transaction, new ORM_HEC_MedicalPractice_2_PracticeType.Query
                        {
                            HEC_MedicalPractice_RefID      = medicalPractice.HEC_MedicalPractiseID,
                            HEC_MedicalPractice_Type_RefID = medicalPracticeTypeParam.HEC_MedicalPractice_TypeID,
                            IsDeleted    = false,
                            Tenant_RefID = securityTicket.TenantID
                        }).SingleOrDefault();
                        if (existingPracticeType == null && !medicalPracticeTypeParam.IsDeleted)
                        {
                            ORM_HEC_MedicalPractice_2_PracticeType medicalPracticeType = new ORM_HEC_MedicalPractice_2_PracticeType();
                            medicalPracticeType.AssignmentID = Guid.NewGuid();
                            medicalPracticeType.HEC_MedicalPractice_Type_RefID = medicalPracticeTypeParam.HEC_MedicalPractice_TypeID;
                            medicalPracticeType.HEC_MedicalPractice_RefID      = medicalPractice.HEC_MedicalPractiseID;
                            medicalPracticeType.Tenant_RefID = securityTicket.TenantID;
                            medicalPracticeType.IsDeleted    = false;
                            medicalPracticeType.Save(Connection, Transaction);
                        }
                        else if (existingPracticeType != null && !medicalPracticeTypeParam.IsDeleted)
                        {
                            existingPracticeType.HEC_MedicalPractice_Type_RefID = medicalPracticeTypeParam.HEC_MedicalPractice_TypeID;
                            existingPracticeType.Save(Connection, Transaction);
                        }
                        else if (existingPracticeType != null && medicalPracticeTypeParam.IsDeleted)
                        {
                            existingPracticeType.IsDeleted = true;
                            existingPracticeType.Save(Connection, Transaction);
                        }
                    }

                    //*******************Edit AppointmentType*******************
                    //if (Parameter.AppoitmentType != null && Parameter.AppoitmentType.Count() > 0)
                    //{
                    //    foreach (var appointmentTypeParam in Parameter.AppoitmentType)
                    //    {
                    //        ORM_PPS_TSK_Task_Template_CustomerOrgUnitAvailability existingAppointmentType = ORM_PPS_TSK_Task_Template_CustomerOrgUnitAvailability.Query.Search(Connection, Transaction, new ORM_PPS_TSK_Task_Template_CustomerOrgUnitAvailability.Query
                    //        {
                    //            CMN_BPT_CTM_OrganizationalUnit_RefID = organizationalUnit.CMN_BPT_CTM_OrganizationalUnitID,
                    //            PPS_TSK_Task_Template_RefID = appointmentTypeParam.PPS_TSK_Task_Template_RefID,
                    //            IsDeleted = false,
                    //            Tenant_RefID = securityTicket.TenantID
                    //        }).SingleOrDefault();
                    //        if (existingAppointmentType == null & !appointmentTypeParam.IsDeleted)
                    //        {
                    //            ORM_PPS_TSK_Task_Template_CustomerOrgUnitAvailability customerOrgUnitAvailability = new ORM_PPS_TSK_Task_Template_CustomerOrgUnitAvailability();
                    //            customerOrgUnitAvailability.PPS_TSK_Task_Template_CustomerOrgUnitAvailabilityID = Guid.NewGuid();
                    //            customerOrgUnitAvailability.CMN_BPT_CTM_OrganizationalUnit_RefID = organizationalUnit.CMN_BPT_CTM_OrganizationalUnitID;
                    //            customerOrgUnitAvailability.PPS_TSK_Task_Template_RefID = appointmentTypeParam.PPS_TSK_Task_Template_RefID;
                    //            customerOrgUnitAvailability.Tenant_RefID = securityTicket.TenantID;
                    //            customerOrgUnitAvailability.Save(Connection, Transaction);
                    //        }
                    //        else if (existingAppointmentType != null & !appointmentTypeParam.IsDeleted)
                    //        {
                    //            existingAppointmentType.PPS_TSK_Task_Template_RefID = appointmentTypeParam.PPS_TSK_Task_Template_RefID;
                    //            existingAppointmentType.Save(Connection, Transaction);
                    //        }
                    //        else if (existingAppointmentType != null & !appointmentTypeParam.IsDeleted)
                    //        {
                    //            existingAppointmentType.IsDeleted = true;
                    //            existingAppointmentType.Save(Connection, Transaction);
                    //        }
                    //    }
                    //}
                    //*******************Edit Address and name************************
                    ORM_CMN_COM_CompanyInfo companyInfo = ORM_CMN_COM_CompanyInfo.Query.Search(Connection, Transaction, new ORM_CMN_COM_CompanyInfo.Query
                    {
                        CMN_COM_CompanyInfoID = medicalPractice.Ext_CompanyInfo_RefID,
                        IsDeleted             = false,
                        Tenant_RefID          = securityTicket.TenantID
                    }).Single();

                    ORM_CMN_UniversalContactDetail contactDetail = ORM_CMN_UniversalContactDetail.Query.Search(Connection, Transaction, new ORM_CMN_UniversalContactDetail.Query
                    {
                        CMN_UniversalContactDetailID = companyInfo.Contact_UCD_RefID,
                        IsDeleted    = false,
                        Tenant_RefID = securityTicket.TenantID
                    }).Single();
                    contactDetail.Street_Name         = Parameter.Street_Name;
                    contactDetail.Street_Number       = Parameter.Street_Number;
                    contactDetail.Town                = Parameter.Town;
                    contactDetail.Contact_Website_URL = Parameter.Contact_Website_URL;
                    contactDetail.Contact_Telephone   = Parameter.Contact_Telephone;
                    contactDetail.Save(Connection, Transaction);

                    returnValue.Result = medicalPractice.HEC_MedicalPractiseID;
                }
                #endregion
                #region Delete
                else
                {
                    ORM_HEC_MedicalPractice_2_PracticeType.Query.SoftDelete(Connection, Transaction, new ORM_HEC_MedicalPractice_2_PracticeType.Query
                    {
                        HEC_MedicalPractice_RefID = medicalPractice.HEC_MedicalPractiseID,
                        IsDeleted    = false,
                        Tenant_RefID = securityTicket.TenantID
                    });

                    ORM_PPS_TSK_Task_Template_CustomerOrgUnitAvailability.Query.SoftDelete(Connection, Transaction, new ORM_PPS_TSK_Task_Template_CustomerOrgUnitAvailability.Query
                    {
                        CMN_BPT_CTM_OrganizationalUnit_RefID = organizationalUnit.CMN_BPT_CTM_OrganizationalUnitID,
                        IsDeleted    = false,
                        Tenant_RefID = securityTicket.TenantID
                    });

                    ORM_HEC_MedicalPractice_OfferedService.Query.SoftDelete(Connection, Transaction, new ORM_HEC_MedicalPractice_OfferedService.Query
                    {
                        MedicalPractice_RefID = medicalPractice.HEC_MedicalPractiseID,
                        IsDeleted             = false,
                        Tenant_RefID          = securityTicket.TenantID
                    });

                    ORM_CMN_BPT_BusinessParticipant businessParticipant = ORM_CMN_BPT_BusinessParticipant.Query.Search(Connection, Transaction, new ORM_CMN_BPT_BusinessParticipant.Query
                    {
                        CMN_BPT_BusinessParticipantID = medicalPractice.ContactPerson_RefID,
                        IsDeleted    = false,
                        Tenant_RefID = securityTicket.TenantID
                    }).Single();
                    businessParticipant.IsDeleted = true;
                    ORM_CMN_PER_PersonInfo personInfo = ORM_CMN_PER_PersonInfo.Query.Search(Connection, Transaction, new ORM_CMN_PER_PersonInfo.Query
                    {
                        CMN_PER_PersonInfoID = businessParticipant.IfNaturalPerson_CMN_PER_PersonInfo_RefID,
                        IsDeleted            = false,
                        Tenant_RefID         = securityTicket.TenantID
                    }).Single();
                    personInfo.IsDeleted = true;
                    ORM_CMN_COM_CompanyInfo companyInfo = ORM_CMN_COM_CompanyInfo.Query.Search(Connection, Transaction, new ORM_CMN_COM_CompanyInfo.Query
                    {
                        CMN_COM_CompanyInfoID = medicalPractice.Ext_CompanyInfo_RefID,
                        IsDeleted             = false,
                        Tenant_RefID          = securityTicket.TenantID
                    }).Single();
                    companyInfo.IsDeleted = true;
                    ORM_CMN_UniversalContactDetail contactDetail = ORM_CMN_UniversalContactDetail.Query.Search(Connection, Transaction, new ORM_CMN_UniversalContactDetail.Query
                    {
                        CMN_UniversalContactDetailID = companyInfo.Contact_UCD_RefID,
                        IsDeleted    = false,
                        Tenant_RefID = securityTicket.TenantID
                    }).Single();
                    contactDetail.IsDeleted = true;

                    ORM_HEC_MedicalPractis.Query.SoftDelete(Connection, Transaction, new ORM_HEC_MedicalPractis.Query
                    {
                        HEC_MedicalPractiseID = Parameter.HEC_MedicalPractiseID,
                        IsDeleted             = false,
                        Tenant_RefID          = securityTicket.TenantID
                    });
                    contactDetail.Save(Connection, Transaction);
                    companyInfo.Save(Connection, Transaction);
                    personInfo.Save(Connection, Transaction);
                    businessParticipant.Save(Connection, Transaction);
                }
                #endregion
                returnValue.Result = medicalPractice.HEC_MedicalPractiseID;
            }
            return(returnValue);

            #endregion UserCode
        }