Beispiel #1
0
def query(q, dependent = None):
    result = None

    environment.parseSolConfig()
    creds = environment.getDependentCreds()

    if not dependent is None:
        creds = environment.getCreds(dependent)
        if creds is None:
            logger.critical("Could not read configuration for '%s'" % (dependent,))
            sys.exit(-1)

    if not creds["url"]:
        logger.critical("Url not specified in solenopsis configuration")
        sys.exit(-1)

    server_url = urlparse.urljoin(creds["url"], 'services/Soap/u/20.0')
    connection = beatbox.PythonClient(serverUrl=server_url)
    connection.login(creds["username"], '%s%s' % (creds["password"], creds["token"],))
    try:
        result = connection.query(q)
    except beatbox.SoapFaultError:
        logger.critical("Error with query\n %s" % sys.exc_info()[1])
        sys.exit(-1)
    return result
Beispiel #2
0
def convert_lead(lead, converted_status=None, **kwargs):
    """
    Convert `lead` using the `convertLead()` endpoint exposed
    by the SOAP API.

    The parameter `lead` is expected to be a Lead object that
    has not been converted yet.

	kwargs: additional optional parameters like `accountId` if the Lead should
		be merged with an existing Account. More info in
	https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_calls_convertlead.htm

    -- BEWARE --
    The current implementation won't work in case your `Contact`,
    `Account` or `Opportunity` objects have some custom **and**
    required fields. This arises from the fact that `convertLead()`
    is only meant to deal with standard Salesforce fields, so it does
    not really care about populating custom fields at insert time.

    One workaround is to map a custom required field in
    your `Lead` object to every custom required field in the target
    objects (i.e., `Contact`, `Opportunity` or `Account`). Follow the
    instructions at

    https://help.salesforce.com/apex/HTViewHelpDoc?id=customize_mapleads.htm

    for more details.
    """
    if not beatbox:
        raise RuntimeError("To use convert_lead, you'll need to install the Beatbox library.")

    accepted_kw = set(('accountId', 'contactId', 'doNotCreateOpportunity',
                      'opportunityName', 'overwriteLeadSource', 'ownerId',
                      'sendNotificationEmail'))
    assert all(x in accepted_kw for x in kwargs)
    if converted_status is None:
        db_alias = lead._state.db
        converted_status = connections[db_alias].introspection.converted_lead_status
    soap_client = beatbox.PythonClient()
    settings_dict = settings.DATABASES['salesforce']

    # By default `beatbox` will assume we are trying to log in with a
    # production account (i.e., using login.salesforce.com). If we want
    # to use a sandbox, then we need to explicitly set the login url of
    # our `beatbox` client.
    if "test.salesforce.com" in settings_dict['HOST']:
        soap_client.serverUrl = 'https://test.salesforce.com/services/Soap/u/33.0'
    soap_client.login(settings_dict['USER'], settings_dict['PASSWORD'])

    kwargs['leadId'] = lead.pk
    kwargs['convertedStatus'] = converted_status
    response = soap_client.convertLead(kwargs)

    ret = dict((x._name[1], str(x)) for x in response)
    
    if "errors" in str(ret):
        raise RuntimeError("The Lead conversion failed: {0}, leadId={1}".format(
                ret['errors'], ret['leadId']))

    return ret
Beispiel #3
0
    def run(self):

        try:
            service = beatbox.PythonClient()
            service.login(param.user_name, param.password)
            query_result = service.query(self.query)
            records = query_result['records']
            total_records = query_result['size']
            query_locator = query_result['queryLocator']

            while query_result['done'] is False and len(
                    records) < total_records:
                query_result = service.queryMore(query_locator)
                query_locator = query_result['queryLocator']
                records = records + query_result['records']

            table = pd.DataFrame(records)
            table.rename(columns={'type': 'object_type'}, inplace=True)

            table.to_csv(param.newpath + self.table_name + '.csv', index=False)

            # for tacking the invalid query locator error from salesforce
            param.exported_table.append(self.table_name)

            param.exported_file[self.table_name] = 1

        except Exception as e:
            print("Unable to access sales force, export error: %s" % str(e))
Beispiel #4
0
 def __init__(self, wsdl_url="", username="", password=""):
     logger.info("Creating %s instance. url : %s, user : %s" % (self.__class__.__name__,
                                                                wsdl_url, username))
     self.username = username
     self.password = password
     self.security_token = ""
     self.status = ""
     self.priority = ""
     self.contact_id = ""
     self.account_id = ""
     self.ticket_number = ""
     self.service = beatbox.PythonClient()
Beispiel #5
0
def convert_lead(lead, converted_status="Qualified - converted"):
    """
    Convert `lead` using the `convertLead()` endpoint exposed
    by the SOAP API.

    The parameter `lead` is expected to be a Lead object that
    has not been converted yet.

    -- BEWARE --
    The current implementation won't work in case your `Contact`,
    `Account` or `Opportunity` objects have some custom **and**
    required fields. This arises from the fact that `convertLead()`
    is only meant to deal with standard Salesforce fields, so it does
    not really care about populating custom fields at insert time.

    One workaround is to map a custom required field in
    your `Lead` object to every custom required field in the target
    objects (i.e., `Contact`, `Opportunity` or `Account`). Follow the
    instructions at

    https://help.salesforce.com/apex/HTViewHelpDoc?id=customize_mapleads.htm

    for more details.
    """
    if not beatbox:
        raise RuntimeError(
            "To use convert_lead, you'll need to install the Beatbox library.")

    soap_client = beatbox.PythonClient()
    settings_dict = settings.DATABASES['salesforce']

    # By default `beatbox` will assume we are trying to log in with a
    # production account (i.e., using login.salesforce.com). If we want
    # to use a sandbox, then we need to explicitly set the login url of
    # our `beatbox` client.
    if "test.salesforce.com" in settings_dict['HOST']:
        soap_client.serverUrl = 'https://test.salesforce.com/services/Soap/u/33.0'
    soap_client.login(settings_dict['USER'], settings_dict['PASSWORD'])

    response = soap_client.convertLead({
        'leadId': lead.pk,
        'convertedStatus': converted_status,
    })

    ret = dict((x._name[1], str(x)) for x in response)

    if "errors" in str(ret):
        raise RuntimeError(
            "The Lead conversion failed: {0}, leadId={1}".format(
                ret['errors'], ret['leadId']))

    return ret
    def __init__(self, server_url="", username="", password="", security_token=""):
        logger.info("Creating %s instance. url : %s, user : %s" % (self.__class__.__name__,
                                                                   server_url, username))
        self.username = username
        self.password = password
        self.security_token = security_token
        self.service = beatbox.PythonClient()
        self.service.login(username, password + security_token)

        self.accounts = {}
        self.contacts = {}
        self.statuses = {}
        self.priorities = {}
Beispiel #7
0
def login_beatbox():
    # login to SF via beatbox
    # SF user/pass
    sf_user = ''
    sf_token = ''
    sf_pass = ''
    sf_pass_token = sf_pass + sf_token

    # instantiate object & login
    sf = beatbox._tPartnerNS
    svc = beatbox.PythonClient()
    svc.login(sf_user, sf_pass_token)
    dg = svc.describeGlobal()
    return svc
Beispiel #8
0
 def getConnection(self):
     self.sf = beatbox._tPartnerNS
     self.svc = beatbox.PythonClient()
     beatbox.gzipRequest = False
     if self.credential["url"] == "test":
         self.svc.serverUrl = self.svc.serverUrl.replace('login.', 'test.')
     try:
         self.svc.login(self.credential["username"],
                        self.credential["password"])
         return self.svc
     except Exception as e:
         self.log.AppendText(str(e))
         self.log.AppendText("\n")
         return None
Beispiel #9
0
def login_beatbox_sandbox():
    # SANDBOX
    sf_user = '******'
    sf_token = 'lxKxphtvkKUQzuK6fmXnhUTL'
    sf_pass = '******'
    sf_pass_token = sf_pass + sf_token

    # instantiate object & login
    sf = beatbox._tPartnerNS
    svc = beatbox.PythonClient()
    # login to Sandbox
    svc.serverUrl = 'https://test.salesforce.com/services/Soap/u/20.0'
    svc.login(sf_user, sf_pass_token)
    return svc
Beispiel #10
0
def login_beatbox():
    # login to SF via beatbox
    # SF user/pass
    sf_user = '******'
    sf_token = 'TFAB49jVswWVquu75y9nAklhl'
    sf_pass = '******'
    sf_pass_token = sf_pass + sf_token

    # instantiate object & login
    sf = beatbox._tPartnerNS
    svc = beatbox.PythonClient()
    svc.login(sf_user, sf_pass_token)
    dg = svc.describeGlobal()
    return svc
Beispiel #11
0
 def __init__(self, connector_param, batch_size=1000):
     self.svc = beatbox.PythonClient()
     if (not self.svc):
         print('no connection')
         return
     self.batch_size = batch_size
     logging.info('Process created for batch size {0} '.format(batch_size))
     if connector_param.url_prefix != '':
         self.svc.serverUrl = self.svc.serverUrl.replace('login.', connector_param.url_prefix)
     try:
         self.login_result = self.svc.login(connector_param.username, connector_param.password)
         logging.info('Connected to instance {0}'.format(self.svc.serverUrl))
         print('Connected to instance {0}'.format(self.svc.serverUrl))
     except:
         print(sys.exc_info()[1])
Beispiel #12
0
    def post(self):
        # Retrieve username and password from post data
        username = self.request.get('uid')
        password = self.request.get('pwd')

        # Attempt a login
        self.sforce = beatbox.PythonClient()
        try:
            login_result = self.sforce.login(username, password)
        except beatbox.SoapFaultError, errorInfo:
            path = os.path.join(os.path.dirname(__file__),
                                'templates/simple_login_failed.html')
            self.response.out.write(
                template.render(
                    path, {
                        'errorCode': errorInfo.faultCode,
                        'errorString': errorInfo.faultString
                    }))
Beispiel #13
0
def verifyLogin(self):
    """
    Insure that we have a session id or have a login username and can use it
    store our session info in memcache
    """
    username = self.request.get('uid')
    password = self.request.get('pwd')
    memcache.set_multi({'username': username, 'password': password})
    self.sforce = beatbox.PythonClient()
    login_result = None
    try:

        login_result = self.sforce.login(username, password)

    except beatbox.SoapFaultError, errorInfo:
        memcache.set_multi({
            'errorCode': errorInfo.faultCode,
            'errorString': errorInfo.faultString
        })
    def updateApplicationFiles(self):
        with open('../settings.json') as data_file:
            projectSettings = json.load(data_file)
        service = beatbox.PythonClient()  # instantiate the object
        service.serverUrl = str(projectSettings["SF_SERVER_URL"]
                                )  # login using your sf credentials
        service.login(str(projectSettings["SF_ORG_USER"]),
                      str(projectSettings["SF_ORG_PASSWORD"])
                      )  # save the sub applications to be updated

        # Map appFileId--> Attachment Id
        attsByParentIds = {}
        # App files with inserted attachments
        appFilesToUpdate = []

        # Read attachments.txt in order to get the parent object associated to the attachments.
        with open("../atts.txt", "r") as f:
            for line in f:
                # You may also want to remove whitespace characters like `\n` at the end of each line.
                aux = line.strip().split(",")
                attsByParentIds[aux[0]] = aux[1]
                appFilesToUpdate.append({
                    "Id": aux[0],
                    "S3_File_Name__c": None,
                    "S3_Uploaded__c": False,
                    "type": "Application_File__c"
                })

        corruptAtts = []
        with open("../attsCorrupt.txt", "r") as f:
            for line in f:
                # You may also want to remove whitespace characters like `\n` at the end of each line.
                corruptAtts.append(line.strip())

        # Remove app files with corrupt attachments 'cause we do not want to update them.
        for appFile in appFilesToUpdate:
            for corruptF in corruptAtts:
                if appFile["Id"] == corruptF:
                    appFilesToUpdate.remove(appFile)

        # Update app files.
        if appFilesToUpdate > 0:
            self.dmlOperations(appFilesToUpdate, attsByParentIds, service)
Beispiel #15
0
import beatbox
import datetime

service = beatbox.PythonClient()
service.serverUrl = 'https://test.salesforce.com/services/Soap/u/20.0'
service.login('username', 'password')

dt = datetime.datetime(2015, 5, 1, 8, 0, 0)

with open('/input/file/path', 'r') as input_file:
    object_ids = []
    for line in input_file:
        object_ids.append(line.strip())

output_file = open('/output/file/path', 'w')

object_name = 'Insertion_Order__c'

for object_id in object_ids:
    query_result = service.query('SELECT Id, \
                                         First_Live_Date__c \
                                  FROM {} \
                                  WHERE Id = \'{}\''.format(object_name, object_id))
    records = query_result['records']

    if not records:
        continue

    record = records[0]

    if record['First_Live_Date__c'] is None or record['First_Live_Date__c'] > dt:
Beispiel #16
0
 def setUp(self):
     self.svc = svc = beatbox.PythonClient()
     svc.login(sfconfig.USERNAME, sfconfig.PASSWORD)
     self._todelete = list()
def sfdc_connection():

    sfdc_conn = beatbox.PythonClient()
    data = fetch_json_data('sfdc_prod')
    sfdc_conn.login(data['username'], data['password'])
    return sfdc_conn
Beispiel #18
0
else:
    print "Table droped successfully"

conn.execute('''create table sfields
                            (sobject_id int not null,
                             sobject_name text not null,
                             sobject_label text not null,
                             field_name text,
                             field_type text,
                             field_length int,
                             field_precision int,
                             field_referenceto text,
                             field_scale int);''')
print "Table created successfully"

svc = beatbox.PythonClient()
beatbox.gzipRequest = False
svc.serverUrl = svc.serverUrl.replace('login.', 'test.')
login = svc.login('sfdc username', 'pw')
dg = svc.describeGlobal()
print(dg.keys())
input = raw_input('continue running? ')
if input == 'yes':
    object_list = dg['sobjects']
    for i, ol in enumerate(object_list):
        sql = "insert into sobjects (id, name, label, labelPlural, activateable) values (%d, '%s', '%s', '%s', '%s')" \
                % (i+1, ol.name, ol.label, ol.labelPlural, ol.activateable)
        conn.execute(sql)
        pass
    conn.commit()
    print "Records created successfully"
Beispiel #19
0
def Client():
    bbox = beatbox.PythonClient()
    bbox.useSession(memcache.get('sessionId'), memcache.get('serverUrl'))
    return bbox
 def setUp(self):
     self.svc = svc = beatbox.PythonClient(
         serverUrl='https://www.salesforce.com/services/Soap/u/15.0')
     svc.login(sfconfig.USERNAME, sfconfig.PASSWORD)
     self._todelete = list()
Beispiel #21
0
# To change this license header, choose License Headers in Project Properties.
# To change this template file, choose Tools | Templates
# and open the template in the editor.
from RestoreAttachmentUtility import RestoreAttachmentUtility
import beatbox
import json

with open('settings.json') as data_file:
    projectSettings = json.load(data_file)
service = beatbox.PythonClient()  # instantiate the object
service.serverUrl = str(
    projectSettings["SF_SERVER_URL"])  # login using your sf credentials
service.login(str(projectSettings["SF_ORG_USER"]),
              str(projectSettings["SF_ORG_PASSWORD"]))

startPoint = RestoreAttachmentUtility()
appFiles = startPoint.getAppFiles(service)
if len(appFiles) > 0:
    startPoint.processAppFiles(appFiles, service, projectSettings)
Beispiel #22
0
 def setUp(self):
     from beatbox._beatbox import DEFAULT_SERVER_URL
     self.svc = svc = beatbox.PythonClient(serverUrl=DEFAULT_SERVER_URL)
     svc.login(sfconfig.USERNAME, sfconfig.PASSWORD)
     self._todelete = list()
Beispiel #23
0
market_source = pd.read_csv(
    "/Volumes/public/Marketing/Growth Marketing/Analytics/Weekly Attribution/Master Attribution Files/Leads_Source_Master.csv"
)
# market_source = pd.read_excel("/Volumes/public/Marketing/Growth Marketing/Analytics/Weekly Attribution/Master Attribution Files/Leads_Source_Master.csv"

# In[361]:

market_source.columns = ['Application ID', 'marketing_source']

# In[362]:

market_source.head()

# In[363]:

service = b.PythonClient()

# In[364]:

service = b.PythonClient()
service.login('*****@*****.**',
              '4!SurvivordZMer7R46ySy7NgXlpTsMZUx')

# In[365]:

query_result = service.query(
    "Select Application_ID__c,Referral_Partner_Account_Owner__c,Status,Loan_Process_Started__c, Referral_Partners_eMail__c, Referrer_Name__c,Utm_Source__c,Lead_Closed_Reason__c,CreatedDate from lead where RecordType.Name = 'loan' "
)

# In[366]: