class SalesforceInsertIntersection(Intersection): upsert = True object_api_name = None upsert_id_field = None SF_USERNAME = os.environ.get('SF_USERNAME') SF_PASSWORD = os.environ.get('SF_PASSWORD') SF_SECURITY_TOKEN = os.environ.get('SF_SECURITY_TOKEN') def __init__(self, *args, **kwargs): super(SalesforceInsertIntersection, self).__init__(*args, **kwargs) session = requests.Session() sf_instance = Salesforce(username=self.SF_USERNAME, password=self.SF_PASSWORD, security_token=self.SF_SECURITY_TOKEN, session=session) self.sf_type = SFType(self.object_api_name, sf_instance.session_id, sf_instance.sf_instance, sf_instance.sf_version, sf_instance.proxies) def process(self, message): if self.upsert: self.sf_type.upsert( '%s/%s' % (self.upsert_id_field, message.content.pop(self.upsert_id_field)), message.content) else: self.sf_type.create(message.content) self.ack(message)
class SalesforceInsertIntersection(Intersection): upsert = True object_api_name = None upsert_id_field = None SF_USERNAME = os.environ.get('SF_USERNAME') SF_PASSWORD = os.environ.get('SF_PASSWORD') SF_SECURITY_TOKEN = os.environ.get('SF_SECURITY_TOKEN') def __init__(self, *args, **kwargs): super(SalesforceInsertIntersection, self).__init__(*args, **kwargs) session = requests.Session() self.sf_instance = Salesforce( username=self.SF_USERNAME, password=self.SF_PASSWORD, security_token=self.SF_SECURITY_TOKEN, session=session ) self.sf_type = SFType(self.object_api_name, self.sf_instance.session_id, self.sf_instance.sf_instance, self.sf_instance.sf_version, self.sf_instance.proxies) def process(self, message): if self.upsert: self.sf_type.upsert( '%s/%s' % (self.upsert_id_field, message.content.pop(self.upsert_id_field)), message.content ) else: self.sf_type.create(message.content) self.ack(message)
def create_new_opportunity( self, close_date: str, opportunity_name: str, stage_name: str = "Closed Won", account_name: str = None, ) -> Any: """Create Salesforce Opportunity object. :param close_date: closing date for the Opportunity, format 'YYYY-MM-DD' :param opportunity_name: as string :param stage_name: needs to be one of the defined stages, defaults to "Closed Won" :param account_name: by default uses previously set account, defaults to None :return: created opportunity or False """ self._require_authentication() # "2020-04-03" if account_name: self.set_account(account_name=account_name) if self.account["Id"] is None: return False sfobject = SFType("Opportunity", self.session_id, self.instance) result = sfobject.create({ "CloseDate": close_date, "Name": opportunity_name, "StageName": stage_name, "Type": "Initial Subscription", "AccountId": self.account["Id"], }) self.logger.debug("create new opportunity: %s", result) return result.get("id") or False
def create_record(self, object_name=None, data=None): session_id = self.security_token try: sf_obj = SFType(object_name, session_id, ConnectionString.SF_URL) result = sf_obj.create(data) print(repr(result)) except Exception as ex: result = ex print(repr(ex)) return result
def create_record(self, object_name=None, data=None): # session_id = self.get_login_connection() session_id = ConnectionString.ACCESS_TOKEN try: sf_obj = SFType(object_name, session_id, self.sf_config.SF_URL) result = sf_obj.create(data) except Exception as ex: result = ex print(repr(ex)) return result
def create_salesforce_object(self, object_type: str, object_data: Any) -> dict: """Create Salesforce object by type and data. :param object_type: Salesforce object type :param object_data: Salesforce object data :raises SalesforceDataNotAnDictionary: when `object_data` is not dictionary :return: resulting object as dictionary """ self._require_authentication() if not isinstance(object_data, dict): raise SalesforceDataNotAnDictionary(object_data) salesforce_object = SFType(object_type, self.session_id, self.instance) result = salesforce_object.create(object_data) return dict(result)
def execute_dataloader_insert( self, input_object: Any, mapping_object: Any, object_type: str ) -> bool: """Keyword mimics Salesforce Dataloader 'insert' behaviour by taking in a `input_object`representing dictionary of data to input into Salesforce, a `mapping_object` representing dictionary mapping the input keys into Salesforce keys, an `object_type` representing Salesforce object which Datahandler will handle with `operation` type. Stores operation successes into `Salesforce.dataloader_success` array. Stores operation errors into `Salesforce.dataloader_errors`. These can be retrieved with keywords `get_dataloader_success_table` and `get_dataloader_error_table` which return corresponding data as `RPA.Table`. :param input_object: filepath or list of dictionaries :param mapping_object: filepath or dictionary :param object_type: Salesforce object type :return: True if operation is successful """ self._require_authentication() if not isinstance(mapping_object, (dict, Table)): mapping_dict = self.read_dictionary_from_file(mapping_object) else: mapping_dict = mapping_object input_iterable = self._get_input_iterable(input_object) sfobject = SFType(object_type, self.session_id, self.instance) self.dataloader_success = [] self.dataloader_errors = [] for item in input_iterable(): data_object = {} for key, value in mapping_dict[object_type].items(): data_object[value] = item[key] result = sfobject.create(data_object) if result["success"]: data_status = {"result_id": result["id"]} self.dataloader_success.append({**data_status, **item}) else: data_status = {"message": "failed"} self.dataloader_errors.append({**data_status, **item}) return True
def add_product_into_opportunity( self, product_name: str, quantity: int, opportunity_id: str = None, pricebook_name: str = None, custom_total_price: float = None, ) -> bool: """Add Salesforce Product into Opportunity. :param product_name: type of the product in the Pricelist :param quantity: number of products to add :param opportunity_id: identifier of Opportunity, default None :param pricebook_name: name of the pricelist, default None :param custom_total_price: price that overrides quantity and product price, default None :return: True is operation is successful or False """ self._require_authentication() if opportunity_id is None: return False if pricebook_name: products = self.get_products_in_pricelist(pricebook_name) else: products = self.get_products_in_pricelist(self.pricebook_name) sfobject = SFType("OpportunityLineItem", self.session_id, self.instance) if product_name in products.keys(): data_object = { "OpportunityId": opportunity_id, "PricebookEntryId": products[product_name]["pricebook_entry_id"], "Quantity": int(quantity), "TotalPrice": int(quantity) * products[product_name]["unit_price"], } if custom_total_price: data_object["TotalPrice"] = float(custom_total_price) result = sfobject.create(data_object) if result and bool(result["success"]): return True return False
def register(push_topic,access_token,instance,version=None): defaults = PushTopic._default_topic_properties() push_topic.update(defaults) version = version or push_topic['ApiVersion'] if not all(k in push_topic for k in ('Name','Query')): raise Exception('Missing Name and/or Query in for push topic') object_name = 'PushTopic' print 'push topic:{p}'.format(p=push_topic) instance = instance.replace('https://','').replace('http://','') sf_object = SFType(object_name=object_name, session_id=access_token, sf_instance=instance, sf_version=version) new_push_topic = sf_object.create(data=push_topic) if not new_push_topic['success']: raise Exception('Error occured while registering a new PushTopic' \ ':{p}'.format(p=push_topic['Name'])) return new_push_topic['id']
password='******', security_token='xxxxxxxxxxxxxxxxx', sandbox=False) testReading = SFType('testReadingPy__c', session_id=session_id, sf_instance='na17.salesforce.com', sf_version='32.0', proxies=None) def RCtime (RCpin): reading = 0 GPIO.setup(RCpin, GPIO.OUT) GPIO.output(RCpin, GPIO.LOW) time.sleep(0.1) GPIO.setup(RCpin, GPIO.IN) while (GPIO.input(RCpin) == GPIO.LOW): reading += 1 return 100-(reading/10) while True: dhtreader.init() output = dhtreader.read(type,pin) lightval = str(RCtime(17)) if output!=None: output=str(output) output=output[1:-1] output=output.translate(None, ',') output = output + ' ' + lightval a,b,c = output.split(" ") print a+b+c testReading.create({'Temperature_Reading__c' : a, 'Humidity_Reading__c' : b, 'Light_Reading__c' : c, 'Hidden_Sensor_Index__c' : 'xxxxxxxxxx'}) time.sleep(1800)
present = datetime.datetime.now() data = { 'Name': 'Account_Fightclub', 'CustomerPriority__c': 'High', 'Active__c': 'Yes', 'SLAExpirationDate__c': (present + datetime.timedelta(days=45)).isoformat() + 'Z' } # isformat gives the datetime format; timedelta is the difference & #in saleforce format u need to add 'Z' response = accounts__c.create( data ) #OrderedDict([('id', 'xxxxxxxxxxxx'),('xxxxxxxxxxxxx'), ('success', True), ('errors', [])]) # the id can be used in salesforce.com/id to view the record """ Parent Child Relationship Record creation (Creating 5 accounts and 5 oppurtunities and linking them) """ oppurtunity__c = SFType('Opportunity', session_id=session_id, sf_instance=instance) account = SFType('Account', session_id=session_id, sf_instance=instance) for i in range(1, 6): data_account = {'Name': 'Retail Account ' + str(i), 'Type': 'Start'} response_account = account.create(data_account)
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!' )