예제 #1
0
 def update_record(self, record_id=None, object_name=None, data=None):
     session_id = self.security_token
     try:
         sf_obj = SFType( object_name, session_id, ConnectionString.SF_URL )
         result = sf_obj.update(record_id, data)
     except Exception as ex:
         result = ex
         print(repr(ex))
     return result
예제 #2
0
    def update_salesforce_object(self, object_type: str, object_id: str,
                                 object_data: Any) -> bool:
        """Update Salesfoce object by type, id and data.

        :param object_type: Salesforce object type
        :param object_id: Salesforce object id
        :param object_data: Salesforce object data
        :raises SalesforceDataNotAnDictionary: when `object_data` is not dictionary
        :return: True if successful
        """
        self._require_authentication()
        if not isinstance(object_data, dict):
            raise SalesforceDataNotAnDictionary(object_data)
        salesforce_object = SFType(object_type, self.session_id, self.instance)
        result_code = salesforce_object.update(object_id, object_data)
        return result_code == 204
예제 #3
0
"""

# Import Dependencies
from simple_salesforce import Salesforce, SFType, SalesforceLogin
from pandas import DataFrame, read_csv
import json
from pprint import pprint as pp

login = json.load(open('login.json'))
username = login['username']
password = login['password']
token = login['token']

session_id, instance = SalesforceLogin(username=username,
                                       password=password,
                                       security_token=token)

sOpportunity = SFType(object_name='opportunity',
                      session_id=session_id,
                      sf_instance=instance)

data = dict(Name='Test Opportunity MG',
            StageName='Prospecting',
            CloseDate='2020-07-15',
            Amount='10000.00',
            Type='New Customer')
rec = sOpportunity.update(record_id='0063h000007nGmIAAU', data=data)

rec = sOpportunity.delete(record_id='0063h000007nGmIAAU')
print(rec)
    response_oppurtunity = oppurtunity__c.create(data_oppurtunity)
    contactID = response_oppurtunity.get('id')

    print('Records created')
    print('-'.center(20, '-'))
    print('Conatct ID: {0}'.format(accountID))
    print('Project ID: {0}'.format(contactID))
"""
Update the existing records
"""

update_data = {}
update_data['AccountNumber'] = 1293012931
update_data['CustomerPriority__c'] = 'Medium'

accounts__c.update(response.get('id'), update_data)
"""
Delete Records
"""
account.delete('0xxxxxxxxxxxxx')  # xxxxx is id
"""
Upsert records inserting new fields in the exiting records without using account id and using existing field names
"""
update_data['Name'] = 'Account_Fightclub'
externalid = 'AnnualRevenue/{0}'.format(10000)
update_data['AccountNumber'] = update_data['AccountNumber'] + 20000000
response = accounts__c.upsert(data=update_data)
"""
Using Bulk API to create records in Salesforce
"""
## Bulk query can be used for retreving vast records such as 50000
예제 #5
0
    def sync_tasks(self, channel):
        self.slack_client.api_call(
            "chat.postMessage",
            channel=channel,
            text='Please wait a moment...'
        )

        is_session_valid = True

        try:
            self.sf.query_more("/services/data/v38.0/sobjects/", True)
        except:
            is_session_valid = False

        test_limit = 0

        if is_session_valid and test_limit < 10:
            try:
                sf_tasks = []
                sf_project_task = SFType('pse__Project_Task__c', self.session_id, SALESFORCE_URL)
                sf_project_task_assign = SFType('pse__Project_Task_Assignment__c', self.session_id, SALESFORCE_URL)
                float_api = FloatAPI()

                projects = float_api.get_projects()
                for project in projects:
                    m = re.search(r'(?<=-)\d+', project["name"])
                    if m is not None:
                        sf_project_id = m.group(0)
                        # float_tasks = float_api.test()
                        tmp_float_tasks = float_api.get_tasks_by_params(
                                            'project_id={}'.format(project["project_id"])
                                        )

                        float_tasks = []
                        float_task_hash = {}
                        for tmp_task in tmp_float_tasks:
                            tmp_user = float_api.get_person_by_id(tmp_task["people_id"])
                            task_name = tmp_task["task_id"]
                            if tmp_user['active'] == 1:
                                tmp_task["users"] = self.format_username(tmp_user["name"])
                                if task_name not in float_task_hash:
                                    float_task_hash[task_name] = tmp_task
                                    float_tasks.append(tmp_task)
                            # else:
                            #     first_start_date =  datetime.strptime(
                            #         float_task_hash[task_name]["start_date"],
                            #         '%Y-%m-%d'
                            #     ).strftime("%V")
                            #     second_start_date = datetime.strptime(
                            #         tmp_task["start_date"], '%Y-%m-%d'
                            #         ).strftime("%V")

                            #     if first_start_date == second_start_date:
                            #         float_task_hash[task_name]["users"] = self.format_username(float_task_hash[task_name]["users"]) + ', ' + self.format_username(tmp_user["name"])
                            #     else:
                            #         tmp_task["is_duplicate"] = True
                            #         float_task_hash[task_name] = tmp_task
                            #         float_tasks.append(tmp_task)
                        # if len(float_tasks) > 0:
                        #     if 'PR-207534' in project["name"]:
                        #     import pdb
                        #     pdb.set_trace()

                        if len(float_tasks) > 0:
                            # tags = float_api.get_project_by_id(float_tasks[0]["project_id"])["tags"]
                            sf_tasks = self.get_tasks_by_project_id('PR-'+sf_project_id)                                      
                            for float_task_key in float_task_hash.keys():
                                # fl_user = float_api.get_person_by_id(float_task["people_id"])
                                float_task = float_task_hash[float_task_key]
                                if 'is_duplicate' in float_task:
                                    project_name = 'No name'
                                    if project and 'name' in project:
                                        project_name = project["name"]

                                    self.slack_client.api_call(
                                        "chat.postMessage",
                                        channel=channel,
                                        text="Project: {} has two tasks. "\
                                            "Please manually sync the second in Salesforce, "\
                                            "or use a different task name".format(project["name"])
                                    )
                                else:
                                    # if 'PR-207534' in project["name"]:
                                    for sf_task in sf_tasks:
                                        if float_task["name"] == sf_task["Name"]:
                                            start_datetime = datetime.strptime(float_task['start_date'], '%Y-%m-%d') + timedelta(days=1)
                                            end_datetime = datetime.strptime(float_task['end_date'], '%Y-%m-%d') + timedelta(days=1)

                                            start_datetime_obj = eastern.localize(start_datetime).strftime("%Y-%m-%dT%H:%M:%S")
                                            end_datetime_obj = eastern.localize(end_datetime).strftime("%Y-%m-%dT%H:%M:%S")

                                            float_names = float_task["users"].replace('*', '').split(',')
                                            contacts_num = len(float_names)
                                            for username in float_names:
                                                float_username = username.strip()
                                                msg = ''
                                                params = {}
                                                # if sf_task['pse__Assigned_Resources__c'] != float_task["users"]:
                                                params["pse__Assigned_Resources__c"] = float_username
                                                params["pse__Assigned_Resources_Long__c"] = float_username
                                                msg = 'assigned resources '

                                                # if self.remove_delta(sf_task['pse__Start_Date_Time__c']) != start_datetime_obj.decode() or self.remove_delta(sf_task['pse__End_Date_Time__c']) != end_datetime_obj.decode():
                                                params['pse__Start_Date_Time__c'] = start_datetime_obj
                                                params['pse__End_Date_Time__c'] = end_datetime_obj
                                                msg = 'start & end time '

                                                contact_info = self.get_contact_id(float_username)
                                                d_project_task_asssign = {}
                                                if contact_info is not None:
                                                    if contact_info['is_active']:
                                                        d_project_task_asssign['pse__Resource__c'] = contact_info['Id']
                                                        d_project_task_asssign['resource_lookup__c'] = contact_info['Id']
                                                    else:
                                                        d_project_task_asssign['pse__External_Resource__c'] = contact_info['Id']

                                                    try:
                                                        result = sf_project_task.update(sf_task["Id"], params, False)
                                                        te_status = self.task_exist_in_assignment(sf_task["Id"])
                                                        ta_result = None
                                                        if te_status['is_exist']:
                                                            if contact_info['is_active']:
                                                                resource_id = contact_info['Id']
                                                            else:
                                                                resource_id = d_project_task_asssign['pse__External_Resource__c']
                                                            if resource_id != te_status['resource_id']:
                                                                # pdb.set_trace()
                                                                try:
                                                                    ta_result = sf_project_task_assign.update(te_status['Id'], d_project_task_asssign, False)
                                                                except Exception as e:
                                                                    print(e, project['name'], float_username, "##########")
                                                                    task_status_response = "{}: {} | {} | project {}".format(
                                                                        float_username,
                                                                        'User with same role is already assgined',
                                                                        float_task["name"],
                                                                        project["name"])
                                                                    self.slack_client.api_call(
                                                                        "chat.postMessage",
                                                                        channel=channel,
                                                                        text=task_status_response
                                                                    )
                                                        else:
                                                            # pdb.set_trace()
                                                            d_project_task_asssign['pse__Project_Task__c'] = sf_task['Id']
                                                            # d_project_task_asssign['pse__Project_ID__c'] = sf_task['Project_ID__c']
                                                            ta_result = sf_project_task_assign.create(d_project_task_asssign, False)
                                                        test_limit = test_limit + 1

                                                        task_status_response = ''
                                                        if result < 400 and ta_result is not None:
                                                            self.number_of_success = self.number_of_success + 1
                                                            task_status_response = "{} | {} | project {}".format(
                                                                msg,
                                                                float_task["name"],
                                                                project["name"])
                                                            self.slack_client.api_call(
                                                                "chat.postMessage",
                                                                channel=channel,
                                                                text=task_status_response
                                                            )
                                                    except Exception as e:
                                                        print(e)
                                                        continue
                                                else:
                                                    self.slack_client.api_call(
                                                        "chat.postMessage",
                                                        channel=channel,
                                                        text='Contact: {} doesn\'t exist'.format(float_username) 
                                                    )

            except Exception as e:
                self.slack_client.api_call(
                    "chat.postMessage",
                    channel=channel,
                    text=e.message
                )
        else:
            response = 'Session is incorrect or expired!'

        # Sends the response back to the channel
        self.slack_client.api_call(
            "chat.postMessage",
            channel=channel,
            text=response or 'Finished!'
        )
예제 #6
0
    def update_record(self, record_id=None, object_name=None, data=None):
        session_id = ConnectionString.ACCESS_TOKEN
        try:
            sf_obj = SFType(object_name, session_id, self.sf_config.SF_URL)
            result = sf_obj.update(record_id, data)
        except Exception as ex:
            result = ex
            print(repr(ex))
        return result


# import datetime
# from datetime import timedelta
# # sf = SFConnectAPI()
# #
# # query = "select id from Contact limit 10"
# # print(str(sf.get_access_token()))
# # username = "******"
# # password = "******"
# sf_instance = SFConnectAPI()
# emp = sf_instance.execute_soql("select id,Name from Attendance__c where date__c >={start_date} " \
#                                "AND date__c <={end_date}".format(start_date=datetime.date.today(),
#                                                                end_date=datetime.date.today() + timedelta(days=5) ))
# print(repr(emp['records']))

# import requests
#
# params = {
#     "grant_type": "password",
#     "client_id": ConnectionString.CONSUMER_KEY,  # Consumer Key
#     "client_secret": ConnectionString.CLIENT_SECRET,  # Consumer Secret
#     # "username": ConnectionString.USERNAME,  # The email you use to login
#     # "password": ConnectionString.PASSWORD,
#     "redirect_uri": "https://www.google.com"
# # Concat your password and your security token
# }
# r = requests.post("https://login.salesforce.com/services/oauth2/token", params=params)
# print(repr(r))
# access_token = r.json().get("access_token")
# instance_url = r.json().get("instance_url")
# print("Access Token:", access_token)
# print("Instance URL", instance_url)

# # access_token = '00D7F0000048jEa!ARcAQDqX99zhupkuv8RzVXYjEP7d_ZtcNQrMM2rK1O76mSvUt.UJF8ldlRzThVN3xXRmAjLzvC8yGZKUN7XBCK2aijl7t1ns'
#
# from simple_salesforce import Salesforce
# sf = Salesforce(instance='ap5.salesforce.com', session_id=access_token)
# result = sf.query("select id from Attendance__c")
# print(repr(result))<class 'tuple'>:
# sf_instance = SFConnectAPI()
# location = (77.2167, 28.6667)
# sf_instance.create_record( object_name='Resume_Google_Drive_Link__c',
#                            data={'Name__c': 'TEST RECORD 1',
#                                  'Contact_Number__c': '9936556447',
#                                  'Email__c': '*****@*****.**',
#                                  'Google_Drive_URL__c': 'https://drive.google.com/file/d/1Stu3UScJ6uy8V9zGa1rqVAGxNehlry6c/view',
#                                  'Position__c': 'Developer',
#                                  'Address__latitude__s': location[1],
#                                  'Address__longitude__s': location[0],
#                                  'City__c': 'Delhi',
#                                  } )
# conn = Salesforce(username=ConnectionString.USERNAME,
#                   password=ConnectionString.PASSWORD,
#                   sandbox=True)

# print(repr(conn))

# import requests
#
# data = {'client_secret': ConnectionString.CLIENT_SECRET,
#         'client_id': ConnectionString.CONSUMER_KEY,
#         'redirect_uri': ConnectionString.REDIRECT_URI}
# result = requests.post(' https://test.salesforce.com/services/oauth2/authorize?response_type=code', data=data)
# print(result.json())