Example #1
0
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)
    def update_sfdc_fulcrum_record(self, record):
        objectId = (_sfdcPrefix + record['form_id'] + '__c').replace('-', '_')
        sfdcObject = SFType(objectId, self.sfdc.session_id,
                            self.sfdc.sf_instance)
        recordExists = sfdcObject.get_by_custom_id(
            _sfdcPrefix + 'fulcrum_id__c', record['id'])
        if recordExists:
            ## Get Child Records
            for fieldId in record['form_values']:
                fieldValue = record['form_values'][fieldId]
                isListField = isinstance(fieldValue, list)
                if isListField == True:
                    complexFieldType = fieldValue[0]
                    isRepeatingSections = self.checkKey(
                        complexFieldType, 'form_values')
                    isJunctioonObject = self.checkKey(complexFieldType,
                                                      'record_id')
                    if isRepeatingSections == True:
                        objectId = _sfdcPrefix + record['form_id'][
                            0:13].replace('-', '_') + '_' + fieldId + '_d__c'
                        objectReferenceId = _sfdcPrefix + record['form_id'][
                            0:13].replace('-', '_') + '_' + fieldId + '_d__r'
                        sfdcInsertRecord = ''
                        for complexFieldValue in fieldValue:
                            detailRecordExists = sfdcObject.get_by_custom_id(
                                _sfdcPrefix + 'fulcrum_id__c',
                                complexFieldValue['id'])
                            if detailRecordExists:
                                sfdcRecordUpdate = generate_sfdc_fulcrum_detail_record(
                                    self, complexFieldValue)
                                print sfdcRecordUpdate
                                exit()

            else:
                self.create_sfdc_fulcrum_record(record)
Example #3
0
    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
Example #4
0
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)
Example #5
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
Example #6
0
    def get_salesforce_object_metadata(self, object_type: str) -> dict:
        """Get Salesfoce object metadata by type.

        :param object_type: Salesforce object type
        :return: object metadata as dictionary
        """
        self._require_authentication()
        salesforce_object = SFType(object_type, self.session_id, self.instance)
        return dict(salesforce_object.metadata())
Example #7
0
    def describe_salesforce_object(self, object_type: str) -> dict:
        """Get Salesfoce object description by type.

        :param object_type: Salesforce object type
        :return: object description as dictionary
        """
        self._require_authentication()
        salesforce_object = SFType(object_type, self.session_id, self.instance)
        return dict(salesforce_object.describe())
Example #8
0
    def refresh_from_sf(self):

        sf_obj = SFType(object_name=self.sf_object,
                        session_id=self.access_token,
                        sf_instance=self.instance,
                        sf_version=self.SF_VERSION)

        raw_sf_data = sf_obj.get(record_id=self.sf_id)
        self.sf_data = type(self).extract_sf_data(raw_sf_data)
Example #9
0
 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)
Example #10
0
    def get_salesforce_object_by_id(self, object_type: str, object_id: str) -> dict:
        """Get Salesforce object by id and type.

        :param object_type: Salesforce object type
        :param object_id: Salesforce object id
        :return: dictionary of object attributes
        """
        self._require_authentication()
        sfobject = SFType(object_type, self.session_id, self.instance)
        return sfobject.get(object_id)
Example #11
0
 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
Example #12
0
    def delete_salesforce_object(self, object_type: str, object_id: str) -> bool:
        """Delete Salesfoce object by type and id.

        :param object_type: Salesforce object type
        :param object_id: Salesforce object id
        :return: True if successful
        """
        self._require_authentication()
        salesforce_object = SFType(object_type, self.session_id, self.instance)
        result_code = salesforce_object.delete(object_id)
        return result_code == 204
Example #13
0
    def unregister(push_topic_id,access_token,instance,version=None):

        defaults = PushTopic._default_topic_properties()
        version = version or defaults['ApiVersion']
        object_name = 'PushTopic'
        instance = instance.replace('https://','').replace('http://','')
        sf_object = SFType(object_name=object_name,
                           session_id=access_token,
                           sf_instance=instance,
                           sf_version=version)

        return sf_object.delete(record_id=push_topic_id)
Example #14
0
def get_object(sf, obj_name):
    result = {}
    try:
        result['metadata'] = SFType(obj_name, sf.session_id, sf.sf_instance,
                                    sf.sf_version, sf.proxies).metadata()
        result['describe'] = SFType(obj_name, sf.session_id, sf.sf_instance,
                                    sf.sf_version, sf.proxies).describe()
    except SalesforceResourceNotFound:
        result['error'] = 'SalesforceResourceNotFound'
        logger.error('{} not found!'.format(obj_name))

    return result
Example #15
0
    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)
Example #16
0
    def _gen_schema(sftype_obj: SFType):
        """
        Generates a list of field/column names on this Table, as well
        as a dictionary with field/column names as keys and data types
        and front-end labels for that field/column.

        Args:
            sftype_obj: A simple_salesforce.SFType object with
                a describe() method that contains 'fields' as a key.

        Returns: A list of field/column api_names and a dictionary
            containing information about said field/columns.

        """
        cols = []
        schema = dict()
        cust_field_ct = 0
        for f in sftype_obj.describe()['fields']:
            name = f['name']
            custom = f['custom']
            if custom:
                cust_field_ct += 1
            schema[name] = dict(label=f['label'],
                                type=f['type'],
                                custom=custom)
            cols.append(name)
        return Record(cols), Record(schema), len(cols), cust_field_ct
Example #17
0
 def get_sf_fields(self, url, sfobj_api=None, dummy=False):
     """
     :param url:
     :param sfobj_api:
     :param dummy:
     :return sf_object_fields:
     """
     import json
     if sfobj_api:
         sftype_object = SFType(sfobj_api,
                                session_id=self.security_token,
                                sf_instance=url)
         describe = sftype_object.describe(headers=None)
         sf_object_fields = describe['fields']
         return sf_object_fields
     return None
Example #18
0
    def upsert_salesforce_object(self, object_type: str, object_id: str,
                                 object_data: Any) -> bool:
        """Upsert 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.upsert(object_id, object_data)
        return result_code == 204
Example #19
0
 def getFieldType(self,*args):
     sf = Salesforce(username=self.username, password=self.password, security_token=self.security_token)
     session_id = sf.session_id
     instance = sf.sf_instance
     type = {}
     ls=[]
     #session_id, instance = SalesforceLogin(self.username, self.password, self.security_token, True)
     for sObject in args:
         adapter = mongoadapter.adapter()
         sObject_type = sObject + "_type"
         collection = adapter.createColletion(sObject_type)
         print sObject_type
         sObjectName = SFType(sObject,session_id,instance)
         for y in sObjectName.describe()['fields']:
             type[y['name']] = y['type']
         ls.append(adapter.insert_posts(collection, type))
     return ls
Example #20
0
 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)
Example #21
0
    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
Example #22
0
    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
Example #23
0
    def CreateSOQL(self, tablename):
        """
		Create the Select Statement for the tablename passed to this function
		"""
        if True:
            try:
                logging.info('Creating SOQL for table: ' + tablename)
                SFObj = self.getConnectSF()
                SFTypeName = SFType(tablename, SFObj.session_id,
                                    SFObj.sf_instance)
                description = SFTypeName.describe()
                field_names = [
                    field['name'] for field in description['fields']
                ]
                return 'SELECT {} FROM {}'.format(','.join(field_names),
                                                  tablename)

            except Exception as e:
                return 'FATAL_ERROR: while Creating SQL \nError Reason: ' + str(
                    e)
Example #24
0
def sf_tbl_detail(env, tblname):
    response = {}
    [err, err_msg, sf] = sf_conn(env)
    if (err == 0):
        try:
            obj = SFType(tblname, sf.session_id, sf.sf_instance, sf.sf_version)
            lst_meta = (obj.metadata()).get('objectDescribe')
            ord_dict = obj.describe()
            full_col_header = [
                'ColumnName', 'Label', 'datatype', 'length,precision',
                'IsUpdateable', 'IsNullable', 'restrictedPicklist'
            ]
            full_col_values = [[
                field["name"], field["label"], field["type"],
                str(field["length"]) + ',' + str(field["precision"]),
                bool_convert(field["updateable"]),
                bool_convert(field["nillable"]),
                bool_convert(field["restrictedPicklist"])
            ] for field in ord_dict["fields"]]
            response["table"] = tblname
            response["columns"] = full_col_header
            response["data"] = full_col_values
            response["error"] = 0
            response["qRows"] = 0
            response["error_msg"] = ""
        except:
            response["table"] = ""
            response["columns"] = ""
            response["data"] = ""
            response["error"] = 1
            response["qRows"] = 0
            response["error_msg"] = str(
                sys.exc_info()[1]).split("Response content")[1][1:]
    else:
        response["table"] = ""
        response["columns"] = ""
        response["data"] = ""
        response["error"] = err
        response["qRows"] = 0
        response["error_msg"] = err_msg
    return (response)
Example #25
0
    def getFieldType(self,sObject):
        sf = Salesforce(instance_url=self.instance_url, session_id=self.session_id)
        session_id = sf.session_id
        instance = sf.sf_instance
        type = {}
        ls=[]
        adapter = mongoadapter.adapter()
        sObject_type = sObject + "_type"
        collection = adapter.createColletion(sObject_type)
        print sObject_type
        sObjectName = SFType(sObject,session_id,instance)
        for y in sObjectName.describe()['fields']:
            type[y['name']] = y['type']
        ls.append(type)
        return ls

#sfdc = sfdcdatafetch('*****@*****.**','mammoth1234$','N0OF2max8RxHHoZkY4AB96uih')
#sfdc = sfdcdatafetch('*****@*****.**','mammoth1234$','oy4po3ssdQ8UJieOpxL4sYjN')
#print sfdc.returnsObject()
#sfdc.getFieldType('Campaign__c', 'Account')
#sfdc.getTableData('Campaign__c')
Example #26
0
 def getTableData(self,sObject):
     sf = Salesforce(instance_url=self.instance_url, session_id=self.session_id)
     session_id = sf.session_id
     instance = sf.sf_instance
     query = "Select "
     sObjectName = SFType(sObject,session_id,instance)
     for x in sObjectName.describe()['fields']:
         query = query + x['name'] + ","
     query = query[:-1] + " from " + sObjectName.name
     #print query
     res = sf.query_all(query)
     records = res['records']
     ls = []
     adapter = mongoadapter.adapter()
     collection = adapter.createColletion(sObject)
     for x in records:
         data = {}
         for y in sObjectName.describe()['fields']:
             data[y['name']] = x[y['name']]
             #print data
         #print data
         ls.append(adapter.insert_posts(collection, data))
     return ls
Example #27
0
    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']
Example #28
0
def sf_tbl_desc(env, tblname):
    response = {}
    [err, err_msg, sf] = sf_conn(env)

    if (err == 0):
        try:
            obj = SFType(tblname, sf.session_id, sf.sf_instance, sf.sf_version)
            lst_meta = (obj.metadata()).get('objectDescribe')
            ord_dict = obj.describe()
            col_lst = ord_dict.get('fields')
            column_names = [field["name"].lower() for field in col_lst]
            response["error"] = 0
            response["error_msg"] = ""
            response["column_names"] = column_names
        except:
            response["error"] = 1
            response["qRows"] = []
            response["error_msg"] = str(
                sys.exc_info()[1]).split("Response content")[1][1:]
    else:
        response["error"] = err
        response["column_names"] = []
        response["error_msg"] = err_msg
    return (response)
Example #29
0
 def getTableData(self,*args):
     sf = Salesforce(username=self.username, password=self.password, security_token=self.security_token)
     session_id = sf.session_id
     instance = sf.sf_instance
     query = "Select "
     #session_id, instance = SalesforceLogin(self.username, self.password, self.security_token, True)
     for sObject in args:
         sObjectName = SFType(sObject,session_id,instance)
         for x in sObjectName.describe()['fields']:
             query = query + x['name'] + ","
         query = query[:-1] + " from " + sObjectName.name
         print query
         res = sf.query_all(query)
         records = res['records']
         ls = []
         data = {}
         adapter = mongoadapter.adapter()
         collection = adapter.createColletion(sObject)
         for x in records:
             for y in sObjectName.describe()['fields']:
                 data[y['name']] = x[y['name']]
             print data
             ls.append(adapter.insert_posts(collection, data))
     return ls
Example #30
0
# print salesforce version
# print(sf.sf_version)

for item in dir(sf):
    if not item.startswith('-'):
        if (isinstance(getattr(sf, item), str)):
            print('Property Name:{0};Value"{1}'.format(item, getattr(sf,
                                                                     item)))

metadata_org = sf.describe()
# print(metadata_org.keys())
print(metadata_org['encoding'])
print(metadata_org['maxBatchSize'])
print(metadata_org['sobjects'])
df_sobjects = pd.DataFrame(metadata_org['sobjects'])
df_sobjects.to_csv('org metadata info.csv', index=False)

# method 1
account = sf.account
print(type(account))
account_metadata = account.describe()
print(type(account_metadata))
df_account_metadata = pd.DataFrame(account_metadata.get('fields'))
df_account_metadata.to_csv('account_metadata.csv', index=False)

# method2
contact = SFType('Contact', session_id, instance)
contact_metadata = contact.describe()
df_contact_metadata = pd.DataFrame(contact_metadata.get('fields'))
df_contact_metadata.to_csv('contact_metadata.csv', index=False)
from simple_salesforce import Salesforce
from simple_salesforce import SalesforceLogin
from simple_salesforce import SFType

GPIO.setmode(GPIO.BCM)

type = 11
pin = 24

sf = Salesforce(username='******', 
	password='******', security_token='xxxxxxxxxx', sandbox=False)

session_id, instance = SalesforceLogin(username='******', 
	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()
Example #32
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)
"""
Filename: salesforce_records.py
Working with record management in Salesforce with Python
"""

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

set_option('display.max_columns', 50)

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)

# sf = Salesforce(instance=instance, session_id=session_id)

# metadata = DataFrame(sf.describe()['sobjects'])
# metadata.to_csv(r'C:\Users\mjgri\Programming\Salesforce\salesforce_venv' + '\\metadata.csv')

sAccount = SFType('account', session_id=session_id, sf_instance=instance)

sAccount_meta = DataFrame(sAccount.describe()['fields'])
sAccount_meta.to_csv(r'C:\Users\mjgri\Programming\Salesforce\salesforce_venv' + '\\Account_Metadata.csv')
Example #34
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())
Example #35
0
from simple_salesforce import Salesforce
from simple_salesforce import SFType
import local
import json

__author__ = 'asitm9'

if __name__ == '__main__':
    sf = Salesforce(username=local.username,
                    password=local.password,
                    security_token=local.security_token)
    # print sf.Contact.describe()
    SFType('Account',
           sf.session_id,
           sf.sf_instance,
           sf_version=sf.sf_version,
           proxies=sf.proxies,
           session=sf.session).describe()
Example #36
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!'
        )
Example #37
0
def describe_sobject(sobjectname):
    sobject = SFType(sobjectname,
                     session_id=sf.session_id,
                     sf_instance=sf.sf_instance)

    return sobject.describe()
df_sobjects = pd.DataFrame(metadata_org['sobjects'])
df_sobjects.to_csv(
    'metadata_info.csv', index=False
)  #this file contains objects of SaleForce along with its properties

####  how to extract salesforce object meta data information

# Method 1
account = sf2.account
account_metadata = account.describe()
df_account_metadata = pd.DataFrame(account_metadata.get('fields'))
df_account_metadata.to_csv('account_metadata_info.csv', index=False)

# Method2 if we know the object name for example project__C ; we dont have this record so it will not be found
projectc = SFType('Project__c', session_id, instance)
project_metadata = projectc.describe()
df_project_metdata = pd.DataFrame(project_metadata.get('fields'))

#%%
"""""" """""" """""" """""" """" Fetcing records from SalesForce to Python """ """""" """""" """""" """""" """"""

# Below SQL query is fetched from Saleforce Developer Console

value = ['Energy', 'Banking']
querySOQL = "SELECT Id ,Type, Industry FROM Account where Industry in ('{0}')".format(
    "','".join(value))

#'query()' & 'query_more()'  does not return archive records
#'query_all()' will return all archive and non archive records
Example #39
0
print(metadata_org['maxBatchSize'])
#print(metadata_org['sobjects'])
print(type(metadata_org['sobjects']))

# to store the huge list in pandas
df_sobjects = pd.DataFrame(metadata_org['sobjects'])
print(df_sobjects)

#pd.set_option('display.max_columns',100)
#pd.set_option('display.max_rows',500)
#pd.set_option('display.min_rows',500)
#pd.set_option('display.max_colwidth',150)
#pd.set_option('display.width',120)
#pd.set_option('expand_frame_repr',True)

df_sobjects.to_csv('Org Metadata info Salesforce.csv', index=False)

# To get extract SALESFORCE Meta data objects Value & API
# Method 1
accounts = sf.account
type(accounts)
accounts_metadata = accounts.describe()
df_account_metadata = pd.DataFrame(accounts_metadata.get('fields'))
df_account_metadata.to_csv('Account Object Metadata.csv', index=False)

# Method 2

project = SFType('Project__c', session_id, instance)
project_metadata = project.describe()
df_project_metadata = pd.DataFrame(project_metadata.get('fields'))
df_project_metadata.to_csv('Project Object Metadata.csv', index=False)