コード例 #1
0
ファイル: views.py プロジェクト: sssh9300662/DjangoPractice
def query_activation(request):
    sf = Salesforce(username='******',
                    password='******',
                    security_token='TmFxKN2zOWl1RPjZrgaKLmOA',
                    sandbox=True)
    # ====== get request param ======================
    contract_name = request.POST['contract_name']
    # ===== get contract by name =====================
    query = "SELECT Id, Whitelist_Override_For__c, End_User__c FROM Contracts_Custom__c where Name='%s'" % (
        contract_name)
    contract = sf.query(query)['records'][0]
    contract_id = contract.get('Id')
    end_user = contract.get('End_User__c')
    # ==== get account data ========================
    account = sf.Account.get(end_user)
    # ==== get command data ======================
    command_query = "Select Name, Status__c, Action__c from CI_Command__c WHERE Contract__c='%s' order by CreatedDate desc" % (
        contract_id)
    commands = sf.query(command_query)['records']

    return render(
        request, "query_activation_result.html", {
            'contract_name': contract_name,
            'account': account.get('Name'),
            'commands': commands
        })
コード例 #2
0
class Dashboard(object):
    def __init__(self, active_users, query_string):

        self.credentials = sfconf.credentials
        self.active_users = active_users
        self.query_string = query_string
        self.sf = Salesforce(
            username=self.credentials["username"],
            password=self.credentials["password"],
            security_token=self.credentials["security_token"],
        )

    def get_salesforce_data(self):

        query_results = self.sf.query(self.query_string % self.active_users)
        query_results = query_results["records"]
        result = {}
        users = self.sf.query("SELECT id, Name FROM User WHERE isActive = true")
        users = users["records"]
        user_names = {}
        sales_names = []
        print query_results

        for user in users:
            user_names[user["Id"]] = user["Name"]

        for query_result in query_results:
            if user_names.has_key(query_result["OwnerId"]):
                result[user_names[query_result["OwnerId"]]] = query_result["expr0"]
                sales_names.append(user_names[query_result["OwnerId"]])

        return result, sales_names
コード例 #3
0
def test_where_bool_query():
    salesforce = Salesforce(**MOCK_CREDS)

    response = salesforce.Opportunity.create({"Name": "Opp 1", "IsDeleted": True})
    deleted_opp_id = response["id"]
    response = salesforce.Opportunity.create({"Name": "Opp 2", "IsDeleted": False})
    active_opp_id = response["id"]

    results = salesforce.query(
        f"SELECT Id, Name, IsDeleted FROM Opportunity WHERE IsDeleted = true"
    )
    records = results["records"]
    assert len(records) == 1
    deleted_record = records[0]
    assert deleted_record["Name"] == "Opp 1"
    assert deleted_record["Id"] == deleted_opp_id
    assert deleted_record["IsDeleted"]

    results = salesforce.query(
        f"SELECT Id, Name, IsDeleted FROM Opportunity WHERE IsDeleted = false"
    )
    records = results["records"]
    assert len(records) == 1
    active_record = records[0]
    assert active_record["Name"] == "Opp 2"
    assert active_record["Id"] == active_opp_id
    assert not active_record["IsDeleted"]

    results = salesforce.query(f"SELECT Id FROM Opportunity")
    records = results["records"]
    assert len(records) == 2
コード例 #4
0
ファイル: salesforce.py プロジェクト: erwinjulius/actforce
def search_organizations(request):

    sf = Salesforce(instance_url=request.session['sf_instance'], session_id=request.session['sf_session'])

    orgname = u"%{orgname}%".format(orgname=clean(request.GET['orgname'])) if request.GET['orgname'] else settings.DEFAULT_ORG_NAME

    sforg_query = u"SELECT Id, Name FROM Account WHERE Name LIKE '{orgname}'".format(orgname=orgname)

    if 'orgid' in request.GET and request.GET['orgid'] != u'' and request.GET['orgid'] != settings.DEFAULT_ORG_ID:
        print type(request.GET['orgid'])
        sforg_query = sforg_query + u" OR Id = '{orgid}'".format(orgid=clean(request.GET['orgid']))

    sforg_query = sforg_query + u" LIMIT 7"

    hashkey = base64.b64encode(str(sforg_query.__hash__()))

    sfresults = cache.get('orgsearch-%s' % hashkey)
    if sfresults == None:
        try:
            sfresults = sf.query(sforg_query)
        except SalesforceExpiredSession:
            sf = refresh_token(request)
            sfresults = sf.query(sforg_query)
        cache.set('orgsearch-%s' % hashkey, sfresults, 30)

    records = sfresults['records']

    result = {}
    for x in records:
        result.update({x['Id']: x['Name']})

    return HttpResponse(json.dumps(result), content_type="application/json")
コード例 #5
0
ファイル: register.py プロジェクト: cbaron/bih
def index():
    sf = Salesforce( username=u, password=p, security_token=k )

    if request.vars.id == None:
        redirect( URL(a='bih',c='default',f='index') )

    users = sf.query(\
        ''.join( [ "Select ID, Date_of_First_Login__c ",
                   "FROM BIH_USER__C" ] ) )['records']

    result = [ ]

    try:
        record = sf.query(\
            ''.join( [ "Select ID, Date_of_First_Login__c, First_Name__c, Last_Name__c, Email__c, ",
                       "(Select BIH_BUS__R.ID, BIH_BUS__R.NAME FROM TEAM_Members__r) ",
                       "FROM BIH_USER__C WHERE ID = '", request.vars.id, "'" ] ) )['records'][0]

        if record['Date_of_First_Login__c'] is not None:
            redirect( URL(a='bih',c='default',f='index') )

        session.userId = record['Id']

        if record['Team_Members__r'] is not None:
          session.busId = record['Team_Members__r']['records'][0]['BIH_Bus__r']['Id']

        return dict( user = dict(
            id = record['Id'],
            firstName = record['First_Name__c'],
            lastName = record['Last_Name__c'],
            emailAddress = record['Email__c'] ) )
    except:
        redirect( URL(a='bih',c='default',f='index') )
コード例 #6
0
def futureInstallEmail():
    opsShared = {}
    token = boxToken()
    headers =  {'Authorization': 'Bearer ' + token}
    for item in opsBox:
      url = 'https://api.box.com/2.0/folders/'+opsBox[item]
      data = {"shared_link": {"access": "open"}}
      response = requests.put(url, headers=headers, data=json.dumps(data))
      if response.status_code == 200:
          opsShared[item] = str(response.json()['shared_link']['url'])
      else:
        print item + ' shared link broken'

    sf = Salesforce(username='******', password='******', security_token='yWlJG8lAKCq1pTBkbBMSVcKg')

    recipients = ['*****@*****.**','*****@*****.**','*****@*****.**','*****@*****.**','*****@*****.**','*****@*****.**','*****@*****.**','*****@*****.**','*****@*****.**','*****@*****.**','*****@*****.**']
    # recipients = ['*****@*****.**','*****@*****.**'] 
    msg = MIMEMultipart()
    today = str(datetime.today())[:10]
    msg.preamble = 'Multipart massage.\n'

    if datetime.today().weekday() == 4:
      msg['Subject'] = "Install On " + str(datetime.today() + timedelta(2))[:10] + "(Sun) - " + str(datetime.today() + timedelta(4))[:10] + "(Tue)"
      response = sf.query("SELECT interaction__c.Contact__r.Accountnumber__c, interaction__c.Contact__r.County__c, interaction__c.Contact__r.Name, interaction__c.Contact__r.Address__c, interaction__c.Contact__r.City_State_Zip__c, ScheduledDate__c, Canceled__c, interaction__c.Contact__r.LASERCA__Home_State__c FROM interaction__c WHERE interaction__c.Opportunity__r.InstallDate__c = Null and Subject__c = 'Installation' AND ScheduledDate__c = NEXT_N_DAYS:4 AND ScheduledDate__c != TOMORROW AND Canceled__c = false ORDER BY interaction__c.Contact__r.County__c")
    else:
      msg['Subject'] = "Install On " + str(datetime.today() + timedelta(2))[:10] + "(" + calendar.day_name[(datetime.today() + timedelta(2)).weekday()][:3] + ")"
      response = sf.query("SELECT interaction__c.Contact__r.Accountnumber__c, interaction__c.Contact__r.County__c, interaction__c.Contact__r.Name, interaction__c.Contact__r.Address__c, interaction__c.Contact__r.City_State_Zip__c, ScheduledDate__c, Canceled__c, interaction__c.Contact__r.LASERCA__Home_State__c FROM interaction__c WHERE interaction__c.Opportunity__r.InstallDate__c = Null and Subject__c = 'Installation' AND ScheduledDate__c = NEXT_N_DAYS:2 AND ScheduledDate__c != TOMORROW AND Canceled__c = false ORDER BY interaction__c.Contact__r.County__c")

    msgBody = "<p>We have "+str(len(response['records']))+" upcoming scheduled installations. Links access to install packs</p>"
    msgBody = msgBody + '<table style="width:600px;border:1px solid black;margin-bottom:20px;padding-top:7px;padding-bottom:7px"><tr><th style="text-decoration:underline;width:25%;text-align:left">Warehouse</th><th style="text-decoration:underline;width:75%;text-align:left">Address</th></tr>'
    from collections import OrderedDict
    tomorrowInstall=OrderedDict()
    tomorrowInstall['Suffolk']=[]
    tomorrowInstall['Nassau']=[]
    tomorrowInstall['Kings']=[]
    tomorrowInstall['Queens']=[]
    tomorrowInstall['Richmond']=[]
    tomorrowInstall['Massachussets']=[]
    for item in response['records']:
      try:
        tomorrowInstall[item['Contact__r']['County__c']].append(item['Contact__r']['Accountnumber__c'] + ' ' + item['Contact__r']['Name'] + ' - ' + item['Contact__r']['Address__c'] + ', ' + item['Contact__r']['City_State_Zip__c']) if item['Contact__r']['LASERCA__Home_State__c'] <> 'MA' else tomorrowInstall['Massachussets'].append(item['Contact__r']['Accountnumber__c'] + ' ' + item['Contact__r']['Name'] + ' - ' + item['Contact__r']['Address__c'] + ', ' + item['Contact__r']['City_State_Zip__c'])
      except:
        tomorrowInstall['Massachussets'].append(item['Contact__r']['Accountnumber__c'] + ' ' + item['Contact__r']['Name'] + ' - ' + item['Contact__r']['Address__c'] + ', ' + item['Contact__r']['City_State_Zip__c'])
    for county in tomorrowInstall:
      # msgBody = msgBody + "<tr><td><a href='" + opsShared[county] + "'>" + county + ':</a><td>'
      if tomorrowInstall[county] <> []:
        for item in tomorrowInstall[county]:
          msgBody = msgBody + "<tr><td><a href='" + opsShared[county] + "'>" + county + ':</a><td>' + item + '</tr></td>'
      else:
        msgBody = msgBody + "<tr><td><a href='" + opsShared[county] + "'>" + county + ':</a><td>No Scheduled Installation.</tr></td>'
      # msgBody = msgBody + '\n'
    msgBody = msgBody + '</table>'

    part = MIMEText(msgBody, 'html')
    msg.attach(part)

    pythonSendEmail(msg, recipients)
コード例 #7
0
    def post(self, request, format=None):
        """
        Adds the necessary account and contact data to Salesforce if they do not exist.
        """

        sf = Salesforce(instance_url=settings.SALESFORCE_URL,
                        username=settings.SALESFORCE_USERNAME,
                        password=settings.SALESFORCE_PASSWORD,
                        security_token=settings.SALESFORCE_TOKEN)

        contact_id = ''
        account_id = ''

        contacts_query = ("SELECT Id,AccountId,FirstName,LastName,Email "
                          "FROM Contact WHERE Email = '{}'").format(request.data['email'])
        contacts = sf.query(contacts_query)
        if contacts['totalSize'] > 0:
            contact_id = contacts['records'][0]['Id']
            account_id = contacts['records'][0]['AccountId']
        else:
            account_query = "SELECT Id,Name FROM Account WHERE Name = '{}'".format(
                request.data['institution_name'])
            accounts = sf.query(account_query)
            if accounts['totalSize'] == 0:
                result = sf.Account.create({'Name': request.data['institution_name']})
                account_id = result['id']
            else:
                account_id = accounts['records'][0]['Id']

            country_codes = dict((value, key) for key, value in dict(countries).items())

            contact = sf.Contact.create({
                'FirstName': request.data['first_name'],
                'LastName': request.data['last_name'],
                'AccountId': account_id,
                'Email': request.data['email'],
                'MailingStreet':
                    request.data['address_1'] + '\n ' + request.data.get('address_2', ''),
                'MailingCity': request.data['city'],
                'MailingPostalCode': request.data['postcode'],
                'MailingCountryCode': country_codes[request.data['country']],
            })
            contact_id = contact['id']

        if contact_id and account_id:
            user = User.objects.get(username=request.data['email'])

            details = CRMAccount(contact_identifier=contact_id,
                                 account_identifier=account_id,
                                 user=user)
            details.save()

            user = User.objects.get(username=request.data['email'])

            s = UserSerializer(user)
            return Response(s.data)
        return Response({'No CRM data added to account'})
コード例 #8
0
def test_where_query_with_dates(monkeypatch):
    salesforce = Salesforce(**MOCK_CREDS)

    monkeypatch.setattr(where_module, "date", JamesDOB)

    salesforce.bulk.Lead.insert(
        [
            {
                "Name": "James Hetfield",
                "Title": "Metallica's Frontman",
                "DOB__c": "1963-08-03",
            },
            {
                "Name": "Lars Ulrich",
                "Title": "Metallica's Drummer",
                "DOB__c": "1963-12-26",
            },
            {
                "Name": "Kirk Hammet",
                "Title": "Metallica's Lead Guitarist",
                "DOB__c": None,
            },
            {
                "Name": "Robert Trujillo",
                "Title": "Metallica's Bassist",
                "DOB__c": "1964-10-23",
            },
        ]
    )

    results = salesforce.query(f"SELECT Name FROM Lead WHERE DOB__c = {TODAY}")
    records = results["records"]
    assert len(records) == 1
    record = records[0]
    assert record["Name"] == "James Hetfield"

    monkeypatch.setattr(where_module, "date", DayBeforeLarsDOB)

    results = salesforce.query(f"SELECT Name FROM Lead WHERE DOB__c = {TOMORROW}")
    records = results["records"]
    assert len(records) == 1
    record = records[0]
    assert record["Name"] == "Lars Ulrich"

    monkeypatch.setattr(where_module, "date", DayAfterLarsDOB)

    results = salesforce.query(f"SELECT Name FROM Lead WHERE DOB__c = {YESTERDAY}")
    records = results["records"]
    assert len(records) == 1
    record = records[0]
    assert record["Name"] == "Lars Ulrich"

    results = salesforce.query(f"SELECT Name FROM Lead WHERE DOB__c > {YESTERDAY}")
    records = results["records"]
    assert len(records) == 1
    record = records[0]
    assert record["Name"] == "Robert Trujillo"
コード例 #9
0
ファイル: routes.py プロジェクト: certasun/achAPP
def pvwatts():
    if request.method == "GET":
        return "GET"
    if request.method == "POST":
        proj_ID = request.json['id']
        print(proj_ID)
    sf = Salesforce(sf_user_sand_update, app_settings['SF-PASS'], sf_update_san_token, domain = 'test')
    query = sf.query("select Name, ID, (select MailingAddress from contacts) from account where ID IN (select Account__c from project__c where project__c.Id  = '"+proj_ID+"')")
    pp.pprint(query)
    if query['totalSize'] == 0:
        return '', 300
    if query['records'][0]['Contacts']['totalSize'] == 0:
        return '', 404
    street = query['records'][0]['Contacts']['records'][0]['MailingAddress']['street']
    city = query['records'][0]['Contacts']['records'][0]['MailingAddress']['city']
    zip = query['records'][0]['Contacts']['records'][0]['MailingAddress']['postalCode']
    state = query['records'][0]['Contacts']['records'][0]['MailingAddress']['state']
    address  = street + " " + city + " " + state + " " + zip
    query1 = sf.query("select Array_1_Tilt__c, Array_2_Tilt__c, Array_3_Tilt__c, Array_4_Tilt__c, Array_5_Tilt__c, Array_6_Tilt__c, Array_1_Modules__c, Array_2_Modules__c, Array_3_Modules__c, Array_4_Modules__c, Array_5_Modules__c, Array_6_Modules__c, Array_1_Module_DC_W__c, Array_2_Module_DC_W__c, Array_3_Module_DC_W__c, Array_4_Module_DC_W__c, Array_5_Module_DC_W__c, Array_6_Module_DC_W__c, Array_1_Azimuth__C, Array_2_Azimuth__c, Array_3_Azimuth__c, Array_4_Azimuth__c, Array_5_Azimuth__c, Array_6_Azimuth__c from project__c where ID = '"+proj_ID+"'")
    for i in range(6):
        if query1['records'][0]['Array_'+str(i+1)+'_Azimuth__c'] == None:
            size = i
            break
    if 'size' not in locals() and 'size' not in globals():
        size = 6
    solar_arrays = list()
    for i in range(size):
        solar_array_dict = {'Module DC W': query1['records'][0]['Array_'+str(i+1)+'_Module_DC_W__c'],
                            'Azimuth' : query1['records'][0]['Array_'+str(i+1)+'_Azimuth__c'],
                            'Tilt': query1['records'][0]['Array_'+str(i+1)+'_Tilt__c'],
                            'Modules': query1['records'][0]['Array_'+str(i+1)+"_Modules__c"]}
        solar_arrays.append(solar_array_dict)
    summation = 0
    for row in solar_arrays:
        tilt = row['Tilt']
        azimuth = row['Azimuth']
        DC_system_size = (row['Module DC W'] * row['Modules'])/1000
        with requests.Session() as s:
            params = {"address": address,
                        "api_key" : "c2jzpeSv7ZfiBwc2eCrEv3gdoAjkQA5lNhUsjVor",
                        "system_capacity" : DC_system_size,
                        "module_type" : 1,
                        "losses" : 14.08,
                        "array_type" : 1,
                        "tilt" : tilt,
                        "azimuth" : azimuth
                        }
            url = " https://developer.nrel.gov/api/pvwatts/v6.json"
            r = s.get(url, params = params)
            json =  r.json()
            ac_annual = json['outputs']['ac_annual']
            summation = summation + ac_annual
    #sf.project__c.update(proj_ID, {'Year_1_PV_Watts_Prod_Est_kWh__c': summation})
    print(summation)
    return '', 200
コード例 #10
0
def test_order_by_query():
    salesforce = Salesforce(**MOCK_CREDS)

    salesforce.bulk.Account.insert(
        [
            {"Name": "Google", "AlexaRanking__c": 1},
            {"Name": "YouTube", "AlexaRanking__c": 2},
            {"Name": "Facebook", "AlexaRanking__c": 7},
        ]
    )

    results = salesforce.query("SELECT Name FROM Account ORDER BY Name ASC")
    records = results["records"]

    record1 = records[0]
    record2 = records[1]
    record3 = records[2]

    assert record1["Name"] == "Facebook"
    assert record2["Name"] == "Google"
    assert record3["Name"] == "YouTube"

    results = salesforce.query("SELECT Name FROM Account ORDER BY Name DESC")
    records = results["records"]

    record1 = records[0]
    record2 = records[1]
    record3 = records[2]

    assert record3["Name"] == "Facebook"
    assert record2["Name"] == "Google"
    assert record1["Name"] == "YouTube"

    # not possible, but let's pretend
    salesforce.Account.create(
        {"Name": "Google dupe", "AlexaRanking__c": 1},
    )

    results = salesforce.query(
        "SELECT Name FROM Account ORDER BY AlexaRanking__c ASC, Name DESC"
    )
    records = results["records"]

    record1 = records[0]
    record2 = records[1]
    record3 = records[2]
    record4 = records[3]

    assert record1["Name"] == "Google dupe"
    assert record2["Name"] == "Google"
    assert record3["Name"] == "YouTube"
    assert record4["Name"] == "Facebook"
コード例 #11
0
def test_where_complex_query():
    salesforce = Salesforce(**MOCK_CREDS)

    response = salesforce.SomeFamousPerson__c.create(
        {"Name": "Quentin Tarantino", "Title": "Director"}
    )
    tarantino_id = response["id"]
    response = salesforce.SomeFamousPerson__c.create(
        {"Name": "Steven Spielberg", "Title": "Director"}
    )
    spielberg_id = response["id"]
    response = salesforce.SomeFamousPerson__c.create(
        {"Name": "Amy Adams", "Title": "Actor"}
    )
    adams_id = response["id"]

    results = salesforce.query(
        f"SELECT Id, Name FROM SomeFamousPerson__c WHERE Name = 'Quentin Tarantino' OR Name = 'Amy Adams'"
    )
    records = results["records"]
    assert len(records) == 2
    record = records[0]
    assert record["Id"] == tarantino_id
    record = records[1]
    assert record["Id"] == adams_id

    results = salesforce.query(
        f"SELECT Id, Name FROM SomeFamousPerson__c WHERE (Title = 'Director' OR Name = 'Amy Adams') AND Id != null"
    )
    records = results["records"]
    assert len(records) == 3
    record = records[0]
    assert record["Id"] == tarantino_id
    record = records[1]
    assert record["Id"] == spielberg_id
    record = records[2]
    assert record["Id"] == adams_id

    results = salesforce.query(
        f"SELECT Id, Name FROM SomeFamousPerson__c WHERE (Title = 'Actor' OR Title = 'Director') AND Name = null"
    )
    records = results["records"]
    assert len(records) == 0

    results = salesforce.query(
        f"SELECT Id, Name FROM SomeFamousPerson__c WHERE (Title = 'Actor' OR Title = 'Director') AND (Name != null AND Name = 'Quentin Tarantino')"
    )
    records = results["records"]
    assert len(records) == 1
    record = records[0]
    assert record["Id"] == tarantino_id
コード例 #12
0
class sForce:
    def __init__(self):
        self.sf = Salesforce(username='******',
                             password='******',
                             security_token='Akkdxr4TF0sdRtDR9gEHiYEU')
        self.end = datetime.datetime.now(pytz.UTC)
        self.today = datetime.datetime.now()

    def importRecords(self, queryConditions):
        allRecords = []
        records = self.sf.query(queryConditions)
        for i in records['records']:
            allRecords.append(i['Id'])
        print(allRecords)
        return allRecords

    def grabAllBookingsPerUnit(self, unitId, numOfDays):
        daysAgo = self.today - datetime.timedelta(days=numOfDays)
        daysAgo = daysAgo.strftime("%Y-%m-%d")
        queryConditions = "SELECT Id FROM Booking__c WHERE Reservation_Status__c = '1' and Don_t_Block_RU_Calendar__c = False and Unit_RU_property_ID__c = " + unitId + " and CalendarEndDate__c > " + daysAgo
        return self.importRecords(queryConditions)

    def grabAllActiveMainUnits(self):
        queryConditions = "SELECT Id FROM Unit__c WHERE Active__c = True and Main_Unit__c = True"
        return self.importRecords(queryConditions)

    def updateBookingRecord(self, sfId, updateDict):
        try:
            self.sf.Booking__c.update(sfId, updateDict)
            print("booking record: ", sfId, " Has been updated")
        except Exception as e:
            print("booking record couldn't update due to an error: ")
            print(e)
コード例 #13
0
def main():
    sf = Salesforce(username='******',
                    password='******',
                    security_token='token')
    response = sf.query(
        "SELECT Id, Name FROM Contact WHERE FirstName = 'Edmond'")
    print(response)
コード例 #14
0
def main():

    credentials = sfconf.credentials
    sf = Salesforce(username = credentials['username'], password = credentials['password'],\
                                 security_token = credentials['security_token'])


    sales_managers_profile_id = '00eb0000000YXJL'
    users = sf.query('SELECT Id, Name FROM User WHERE profileid = \'%s\' AND isActive = true ' % sales_managers_profile_id)

    active_users = []
    users = users['records']

    for user in users:
        active_users.append(str(user['Id']))

    active_users = str(active_users).replace('[','(').replace(']',')')

    funding_by_users_query = "SELECT AccountId__r.ownerid, sum(amount__c) FROM AForexEvent__c WHERE EventType__c = 'funding' \
                              AND DateTimeOfEvent__c = THIS_MONTH AND AccountId__r.ownerid in %s GROUP BY ROLLUP(AccountId__r.ownerid)"

    withdrawal_by_users_query = "SELECT AccountId__r.ownerid, sum(amount__c) FROM AForexEvent__c WHERE EventType__c = 'Withdrawal' \
                                 AND DateTimeOfEvent__c = THIS_MONTH AND AccountId__r.ownerid in %s GROUP BY ROLLUP(AccountId__r.ownerid)"

    converted_leads_by_users_query = "SELECT Account__r.ownerid, count(Incentive_Deposit_Amount__c) FROM  Wallet__c WHERE First_Funding_Date__c = THIS_MONTH \
                                      AND Incentive_Deposit_Amount__c > 95 AND Account__r.ownerid in %s GROUP BY ROLLUP(Account__r.ownerid)"

    sum_of_incentive_deposites_by_users_query = "SELECT Account__r.ownerid, sum(Incentive_Deposit_Amount__c) FROM  Wallet__c \
                                                 WHERE First_Funding_Date__c = THIS_MONTH AND Account__r.ownerid in %s GROUP BY ROLLUP(Account__r.ownerid)"


    outbount_calls_to_accounts_by_users_query = "SELECT OwnerId, Count(Id)From Task WHERE \
     (Who.Type in ('Account', 'Contact') OR What.Type in ('Account', 'Contact')) \
     AND type = 'Outbound Call'  \
     AND result__c in ('1 Talked - Substantial', '2 Talked - Brief', '3 Talked - Callback Requested', '4 Reached Associate') \
     AND status = 'Завершено' \
     AND ActivityDate = THIS_MONTH \
     AND OwnerId in %s \
     GROUP BY ROLLUP(OwnerId)"

    outbount_calls_to_leads_by_users_query = "SELECT OwnerId, Count(Id)From Task WHERE \
     (Who.Type in ('Lead') OR What.Type in ('Lead')) \
     AND type = 'Outbound Call'  \
     AND result__c in ('1 Talked - Substantial', '2 Talked - Brief', '3 Talked - Callback Requested', '4 Reached Associate') \
     AND status = 'Завершено' \
     AND ActivityDate = THIS_MONTH \
     AND OwnerId in %s \
     GROUP BY ROLLUP(OwnerId)"

    funding_by_users, funding_user_names = Dashboard(active_users, funding_by_users_query).get_salesforce_data()
    withdrawal_by_users, withdrawal_user_names = Dashboard(active_users, withdrawal_by_users_query).get_salesforce_data()
    converted_leads_by_users, converted_leads_user_names = Dashboard(active_users, converted_leads_by_users_query).get_salesforce_data()
    sum_of_incentive_deposites_by_users,  sum_of_incentive_user_names = Dashboard(active_users, sum_of_incentive_deposites_by_users_query).get_salesforce_data()
    outbount_calls_to_accounts_by_users, outbount_calls_to_accounts_user_names = Dashboard(active_users, outbount_calls_to_accounts_by_users_query).get_salesforce_data()
    outbount_calls_to_leads_by_users, outbount_calls_to_leads_user_names = Dashboard(active_users, outbount_calls_to_leads_by_users_query).get_salesforce_data()

    return funding_by_users, funding_user_names, withdrawal_by_users, withdrawal_user_names, \
           converted_leads_by_users, converted_leads_user_names, sum_of_incentive_deposites_by_users,  sum_of_incentive_user_names, \
           outbount_calls_to_accounts_by_users, outbount_calls_to_accounts_user_names, \
           outbount_calls_to_leads_by_users, outbount_calls_to_leads_user_names
コード例 #15
0
class SalesforceHelper(object):
    def __init__(self):
        self.sf = Salesforce(password=os.environ.get('SFDC_PASSWORD'),
                             username=os.environ.get('SFDC_USERNAME'),
                             security_token=os.environ.get('SFDC_TOKEN'))

        # Cache the possible ParentIds that we'll post Chatter feed items to.
        # For the purposes of our demonstration, We'll use Users, Groups, and Accounts only.
        self.parent_ids = []
        soql_queries = [
            "SELECT Id FROM User WHERE IsActive = True AND UserType = 'Standard'",
            "SELECT Id FROM CollaborationGroup WHERE CollaborationType = 'Public' AND IsArchived = False AND NetworkId = null",
            "SELECT Id FROM Account",
        ]
        for query in soql_queries:
            result = self.sf.query(query)
            ids = [x['Id'] for x in result['records']]
            self.parent_ids.extend(ids)

            # Also store the user IDs.
            if " FROM User " in query:
                self.user_ids = ids

    def get_random_parent(self):
        return random.choice(self.parent_ids)

    def get_random_user(self):
        return random.choice(self.user_ids)

    def post_feed_item(self, data):
        return self.sf.FeedItem.create(data)

    def post_comment(self, data):
        return self.sf.FeedComment.create(data)
コード例 #16
0
ファイル: utils.py プロジェクト: john2world/Ring1leads
def count_records(program):
    query = translate_program_to_soql(program, count_only=True)

    # fetch count
    program.source.token.refresh()  # TODO: Source.count_records
    conn = Salesforce(session_id=program.source.token.access_token,
                      instance_url=program.source.token.instance_url,
                      sandbox=program.source.token.is_sandbox)

    try:
        count = conn.query(query)['totalSize']
    except SalesforceError as e:
        raise Exception({
            'type': 'salesforceerror',
            'data': e.content[0],
        })
    except RequestException:
        raise Exception({
            'type': 'connectionerror',
        })
    except:
        raise Exception({
            'type': 'unknown',
        })
    else:
        return count
コード例 #17
0
ファイル: getpricebooks.py プロジェクト: sqilz/LIMS-Backend
def get_pricebooks():
    sf = Salesforce(instance_url=settings.SALESFORCE_URL,
                    username=settings.SALESFORCE_USERNAME,
                    password=settings.SALESFORCE_PASSWORD,
                    security_token=settings.SALESFORCE_TOKEN)

    pricebooks = PriceBook.objects.all()
    for pb in pricebooks:
        pricebook = sf.Pricebook2.get(pb.identifier)
        query = ("SELECT Id,Name,ProductCode,UnitPrice,IsActive FROM PricebookEntry "
                 "WHERE Pricebook2Id = '{}'").format(pb.identifier)
        remote_prices = sf.query(query)

        price_list, created = PriceBook.objects.get_or_create(name=pricebook['Name'])

        for item in remote_prices['records']:
            price, created = Price.objects.get_or_create(code=item['ProductCode'],
                                                         defaults={
                'name': item['Name'],
                'price': item['UnitPrice'],
                'identifier': item['Id']
            })
            price.name = item['Name']
            price.price = item['UnitPrice']
            price.identifier = item['Id']
            price.save()

            price_list.prices.add(price)
コード例 #18
0
    def post(self, request, format=None):
        if settings.ENABLE_CRM:
            crm_project_ids = request.data.get('crm_ids', None)

            if crm_project_ids:
                projects = CRMProject.objects.filter(id__in=crm_project_ids)

                crm_identifiers = ["'" + p.project_identifier + "'" for p in projects.all()]

                sf = Salesforce(instance_url=settings.SALESFORCE_URL,
                                username=settings.SALESFORCE_USERNAME,
                                password=settings.SALESFORCE_PASSWORD,
                                security_token=settings.SALESFORCE_TOKEN)
                crm_project_query = ("SELECT o.Id,o.Name,o.Description,o.CreatedDate,"
                                     "o.Project_Status__c "
                                     "FROM Opportunity o "
                                     "WHERE o.Id IN ({})").format(", ".join(crm_identifiers))
                crm_project_data = sf.query(crm_project_query)
                if crm_project_data['totalSize'] > 0:
                    records = crm_project_data['records']
                    for record in records:
                        try:
                            proj = CRMProject.objects.get(project_identifier=record['Id'])
                        except:
                            pass
                        else:
                            proj.name = record['Name']
                            proj.description = record['Description']
                            proj.status = record['Project_Status__c']
                            proj.save()
                    return Response({'message': 'Projects updated'})
                return Response({'message': 'No projects found on CRM system'}, status=404)
            return Response({'message': 'Please provide a list of CRM project IDs'}, status=400)
        return Response({'message': 'CRM is currently disabled'}, status=501)
コード例 #19
0
ファイル: routes.py プロジェクト: certasun/achAPP
def customer_not_verified_encode_upload_send(customer_create_request_body):
    #instantiate a connection to salesforce
    sf = Salesforce(app_settings['SF-USER'] +".plaidtest", app_settings['SF-PASS'], app_settings['SF-TOKEN'], domain = 'test')
    query = sf.query("select Name, ID, (select id, Name from projects__r) from account where ID IN (select AccountId from contact where contact.email  = '" +customer_create_request_body['email']+ "')")
    name = query['records'][0]['Name']
    proj_ID = query['records'][0]['Projects__r']['records'][0]['Id']
    # call the plaid api auth endpoint to retrieve the user bank account number and routing number
    auth_response = client.Auth.get(session['access_token'])
    #this for loop is used so that we can go through all bank accounts associated with the login the user entered and match it
    # with the accocunt they clicked in the GUI so we can get the correct account number
    for i in range(len(auth_response['numbers']['ach'])):
        #this statement will only run when the accountID matches the account in the plaid auth response
        if auth_response['numbers']['ach'][i]['account_id'] == session['ACCOUNT_ID']:
            #set local variable for bank account number
            account_num = auth_response['numbers']['ach'][i]['account']
            #set local variable for vank routing number
            routing_num = auth_response['numbers']['ach'][i]['routing']
            #put the bank accounts routing number into salesforce in the encrypted field created for the account number
            sf.project__c.update(proj_ID, {'Bank_Account_Number__c': account_num})
            #put the routing number into salesforce in the encrypted field created for the routing number
            sf.project__c.update(proj_ID, {'Routing_Number__c': routing_num})
            #this will send an email to the address in the first parameter including information about the customer who could not be verified, this works
            # as an alert that the payment must be done MANUALLY
            email_sender("*****@*****.**", "verification fail", name + " proj ID: " + str(proj_ID), 0)
    return
コード例 #20
0
ファイル: routes.py プロジェクト: certasun/achAPP
def landing_page():
    #open an API connection to salesforce
    sf = Salesforce(app_settings['SF-USER'] +".plaidtest", app_settings['SF-PASS'], app_settings['SF-TOKEN'], domain = 'test')
    #instantiate the form that will be displayed on the PAGE
    #in this case the form will have 1 inpute which will be the email
    #and a submit button
    form = nameForm()
    #if the form is validated after submit button is hit this statement will execute
    if form.validate_on_submit():
        #clear all session variables so their are no data integrity issues
        session.clear()
        #get the email that was entered into the form
        email = form.name.data
        #query salesforce for the project associated with the contact that holds that email
        query = sf.query("select Name, ID, (select id, Name from projects__r) from account where ID IN (select AccountId from contact where contact.email  = '" +email+ "')")
        #statement is executed if there is no contact with that email or the contact with that email has no associated projects
        if query['totalSize'] == 0 or query['records'][0]['Projects__r'] == None:
            #redirect them to the invalidName page so a error message will appear telling them that the email is invalid and allowingg them to re enter their email
            return redirect(url_for('InvalidName'))
        #this statement will execute if the contact that holds the entered email has more than one project associated with it
        elif query['records'][0]['Projects__r']['totalSize'] > 1:
            #set a session variable to hold the email
            session['email'] = email
            #redirect to a page that gives a list of project names associated with that email so that the user will be able to chose which project they are looking to make a payment for
            return redirect(url_for('multipleRecords', email = email))
        #If the contact that holds that email has exactly one project associated with it this statement will execute
        elif query['records'][0]['Projects__r']['totalSize'] == 1:
            #again set a session variable to hold the email
            session['email'] = email
            #redirect user to method that will get all the info on the project and then display the user their payment portal
            return redirect(url_for('passObjID', id = query['records'][0]['Projects__r']['records'][0]['Id']))
    #index3.html is the landing page html document
    return render_template('index3.html', form = form)
コード例 #21
0
ファイル: routes.py プロジェクト: certasun/achAPP
def InvalidName():
    #instantiate a connetion to salesforce
    sf = Salesforce(app_settings['SF-USER'] +".plaidtest", app_settings['SF-PASS'], app_settings['SF-TOKEN'], domain = 'test')
    #instantiate the form
    thisform = nameForm()
    #this statement will run if the form validates after the submit button is pressed
    if thisform.validate_on_submit():
        #data taken from the input in the form
        email = thisform.name.data
        #query salesforce in order to get the project Id and some account information
        query = sf.query("select Name, ID, (select id, Name from projects__r) from account where ID IN (select AccountId from contact where contact.email  = '" +email+ "')")
        #if there is either no contact associated with that email or no project associated with the contact that holds that email this statement will run
        if query['totalSize'] == 0 or query['records'][0]['Projects__r'] == None:
            #this will redirect the user to the same form and an error message will be displayed saying the email was invalid and they will be prompted for email again
            return redirect(url_for('InvalidName'))
        #this statement will run only when there are more than 1 projects associated with the contact that holds that email
        elif query['records'][0]['Projects__r']['totalSize'] > 1:
            #set a session variable to hold the email address
            session['email'] = email
            #redirect to a page that lists all the projects under than contact so customer can choose
            return redirect(url_for('multipleRecords', email = email, query = query))
        #this statement will run if there is exactly one project associated with that email address
        elif query['records'][0]['Projects__r']['totalSize'] == 1:
            #set a session variable to hold that email
            session['email'] = email
            #you successfully have a project Id now so you can move on tp the payment portal for that ID
            return redirect(url_for('passObjID', id = query['records'][0]['Projects__r']['records'][0]['Id']))
    return render_template('Invalid.html', form = thisform)
コード例 #22
0
ファイル: routes.py プロジェクト: certasun/achAPP
def runQueriesID(name, fname, lname, id):
    #instantiate a connection to SALESFORCE
    sf = Salesforce(app_settings['SF-USER'] +".plaidtest", app_settings['SF-PASS'], app_settings['SF-TOKEN'], domain = 'test')
    # create an ACCOUNT object from the parameters
    thisAccount = ACCOUNT(name, fname, lname)
    #query salesforce for the payment information on this project
    query = sf.query("select Name, id, Cash_Down_pmt__c, Cash_Down_Pmt_Status__c, Permit_pmt__C, Cash_Permit_Pmt_Status__c, Cash_final_Pmt__c, Cash_final_pmt_status__c from Project__c where id = '" + id + "'")
    #set the rest of the varicables for the ACCOUNT object ###########################################
    thisAccount.ID = query['records'][0]['Id']
    thisAccount.dp = query['records'][0]['Cash_Down_Pmt__c']
    thisAccount.dpSTAT = setFrontEndStatus(query['records'][0]['Cash_Down_Pmt_Status__c'])
    thisAccount.pp = query['records'][0]['Permit_Pmt__c']
    thisAccount.ppSTAT = setFrontEndStatus(query['records'][0]['Cash_Permit_Pmt_Status__c'])
    thisAccount.fp = query['records'][0]['Cash_Final_Pmt__c']
    thisAccount.fpSTAT = setFrontEndStatus(query['records'][0]['Cash_Final_Pmt_Status__c'])
    ####################################################################################################
    #want to find which of the three possible payments needs to be paid next and set it as the next duepayment
    if thisAccount.dpSTAT == app_settings['DUE_STATUS'] or thisAccount.dpSTAT == app_settings['NOT_DUE_STATUS'] or thisAccount.dpSTAT == ' ':
        thisAccount.duePayment = app_settings['DOWN_PAYMENT_CONST']
        return thisAccount
    elif thisAccount.ppSTAT == app_settings['DUE_STATUS'] or thisAccount.ppSTAT == app_settings['NOT_DUE_STATUS'] or thisAccount.ppSTAT == ' ':
        thisAccount.duePayment = app_settings['PERMIT_PAYMENT_CONST']
        return thisAccount
    elif thisAccount.fpSTAT == app_settings['DUE_STATUS'] or thisAccount.fpSTAT == app_settings['NOT_DUE_STATUS'] or thisAccount.fpSTAT == ' ':
        thisAccount.duePayment = app_settings['FINAL_PAYMENT_CONST']
        return thisAccount
    else:
        thisAccount.duePayment = "NA"
    return thisAccount
コード例 #23
0
def query(message, qstring):
    sf = Salesforce(password=settings.SFDC_PASSWORD,
                    username=settings.SFDC_USERNAME,
                    security_token=settings.SFDC_SECURITY_TOKEN)

    out = sf.query(qstring)
    message.reply(json.dumps(out['records']))
コード例 #24
0
def test_where_comparison_query(operator, number, expected):
    salesforce = Salesforce(**MOCK_CREDS)

    response = salesforce.bulk.Lead.insert(
        [
            {
                "Name": "Kurt Cobain",
                "Title": "Nirvana Guitarist",
                "Human_Score__c": 100,
            },
            {"Name": "Paris Hilton", "Title": "no one knows"},
        ]
    )
    sfdc_id = response[0]["id"]

    results = salesforce.query(
        f"SELECT Id, Name, Human_Score__c FROM Lead WHERE Human_Score__c {operator} {number}"
    )
    records = results["records"]
    assert len(records) == expected

    if expected > 0:
        record = records[0]
        assert record["Id"] == sfdc_id
        assert record["Name"] == "Kurt Cobain"
        assert record["Human_Score__c"] == 100
コード例 #25
0
def test_query_with_parent_object_attribute():
    salesforce = Salesforce(**MOCK_CREDS)

    response = salesforce.Account.create({"Name": "Google", "Website": "google.com"})
    account_id = response["id"]

    response = salesforce.Contact.create(
        {
            "FirstName": "Sundar",
            "LastName": "Pichai",
            "Account": account_id,
            "Title": "CEO",
        }
    )
    contact_id = response["id"]

    results = salesforce.query(
        "SELECT Id, Title, FirstName, LastName, Account.Name FROM Contact"
    )
    records = results["records"]

    assert len(records) == 1
    record = records[0]
    assert record["Id"] == contact_id
    assert record["FirstName"] == "Sundar"
    assert record["LastName"] == "Pichai"
    assert record["Title"] == "CEO"
    assert record["Account"]["Name"] == "Google"
コード例 #26
0
ファイル: salesforce.py プロジェクト: zy964c/python-zulip-api
def query_salesforce(arg: str, salesforce: simple_salesforce.Salesforce, command: Dict[str, Any]) -> str:
    arg = arg.strip()
    qarg = arg.split(' -', 1)[0]
    split_args = []  # type: List[str]
    raw_arg = ''
    if len(arg.split(' -', 1)) > 1:
        raw_arg = ' -' + arg.split(' -', 1)[1]
        split_args = raw_arg.split(' -')
    limit_num = 5
    re_limit = re.compile('-limit \d+')
    limit = re_limit.search(raw_arg)
    if limit:
        limit_num = int(limit.group().rsplit(' ', 1)[1])
        logging.info('Searching with limit {}'.format(limit_num))
    query = default_query
    if 'query' in command.keys():
        query = command['query']
    object_type = object_types[command['object']]
    res = salesforce.query(query.format(
        object_type['fields'], object_type['table'], qarg, limit_num))
    exclude_keys = []  # type: List[str]
    if 'exclude_keys' in command.keys():
        exclude_keys = command['exclude_keys']
    force_keys = []  # type: List[str]
    if 'force_keys' in command.keys():
        force_keys = command['force_keys']
    rank_output = False
    if 'rank_output' in command.keys():
        rank_output = command['rank_output']
    show_all_keys = 'show' in split_args
    if 'show_all_keys' in command.keys():
        show_all_keys = command['show_all_keys'] or 'show' in split_args
    return format_result(res, exclude_keys=exclude_keys, force_keys=force_keys, rank_output=rank_output, show_all_keys=show_all_keys)
コード例 #27
0
ファイル: file.py プロジェクト: OumaimaChmissi/SalesforceApi
def hello_world(id):
   sf = Salesforce(
   username= "", 
   password='', 
   security_token='') # Add your information here
   sessionId = sf.session_id
   instance = sf.sf_instance
   print ('sessionId: ' + sessionId)
   #r = requests.get("https://vast-escarpment-63477.herokuapp.com/")
   #print(r.content)
   attachment = sf.query("SELECT Id, Name,ParentId FROM Attachment where Id='" + id + "' LIMIT 1")
   #SELECT Id, Name, Body ,ParentId, Parent.Type FROM Attachment where Parent.Type = 'Contact'
   filename=attachment['records'][0]['Name']
   fileid=attachment['records'][0]['Id']
   fileparentid=attachment['records'][0]['ParentId']
   print('filename: ' + filename)
   print('fileid: ' + fileid)
   response = requests.get('https://' + instance + '/services/data/v39.0/sobjects/Attachment/' + fileid + '/body',
                           headers = { 'Content-Type': 'application/text', 'Authorization': 'Bearer ' + sessionId })

   f1 = open(filename, "wb")
   f1.write(response.content)
   f1.close()
   print('output file: '  + os.path.realpath(f1.name))
   response.close()
   data = ResumeParser(os.path.realpath(f1.name)).get_extracted_data()
   # Parse JSON into an object with attributes corresponding to dict keys.
   cand_dict=json.dumps(data)
   print(cand_dict)
   x = json.loads(cand_dict)

   #print (x["name"])
   class candidate:
     def __init__(self, name, email,skills):
       self.name = name
       self.email = email
       self.skills = skills

   c1 = candidate(x["name"], x["email"],x["skills"])
   print(c1.name)
   print(c1.email)
   print(c1.skills)

   a=json.dumps(c1.name)
   a =a.replace('"', '')

   c=json.dumps(c1.email)
   c =c.replace('"', '')
   c=c.lstrip()
   c=c.lstrip()
   print (c)
   b=json.dumps(c1.skills)
   b =b.replace('"', '')
   b =b.replace('[', '')
   b =b.replace(']', '')
  
   #sf.Contact.create({'LastName':a,'Email':c, 'Skills__c':b,'Record_Typess__c':'Candidat'})
   sf.Contact.update(fileparentid,{'Skills__c':b})
   return b
コード例 #28
0
ファイル: routes.py プロジェクト: certasun/achAPP
def get_proj_from_sf(email):
    #instantiate salesforce connection
    sf = Salesforce(sf_user +".plaidtest", sf_pass, sf_token, domain = 'test')
    #query salesforce databse for proj_ID
    query = sf.query("select Name, (select id, Name from projects__r) from account where ID IN (select AccountId from contact where contact.email  = '"+email+"')")
    #set a local variable for the project ID quiered from salesforce to be returned by this method
    proj_ID = query['records'][0]['Projects__r']['records'][0]['Id']
    return proj_ID
コード例 #29
0
def test_where_query_with_complex_date_tokens():
    salesforce = Salesforce(**MOCK_CREDS)

    salesforce.bulk.Lead.insert(
        [
            {
                "Name": "John Doe",
                "Title": "Person",
                "DOB__c": datetime.date.today().isoformat(),
            },
            {
                "Name": "Jane Doe",
                "Title": "Person",
                "DOB__c": (datetime.date.today() - relativedelta(months=1)).isoformat(),
            },
            {
                "Name": "Jim Doe",
                "Title": "Person",
                "DOB__c": (datetime.date.today() + relativedelta(months=1)).isoformat(),
            },
        ]
    )

    results = salesforce.query(f"SELECT Name FROM Lead WHERE DOB__c = THIS_MONTH")
    records = results["records"]
    assert len(records) == 1
    record = records[0]
    assert record["Name"] == "John Doe"

    results = salesforce.query(f"SELECT Name FROM Lead WHERE DOB__c = LAST_MONTH")
    records = results["records"]
    assert len(records) == 1
    record = records[0]
    assert record["Name"] == "Jane Doe"

    results = salesforce.query(f"SELECT Name FROM Lead WHERE DOB__c = NEXT_MONTH")
    records = results["records"]
    assert len(records) == 1
    record = records[0]
    assert record["Name"] == "Jim Doe"

    results = salesforce.query(f"SELECT Name FROM Lead WHERE DOB__c < THIS_MONTH")
    records = results["records"]
    assert len(records) == 1
    record = records[0]
    assert record["Name"] == "Jane Doe"
コード例 #30
0
ファイル: sfdc_get_user.py プロジェクト: nsuhara/sfdc-RestApi
def main():
    sf = Salesforce(username=USERNAME,
                    password=PASSWORD,
                    security_token=SECURITY_TOKEN,
                    sandbox=False)
    res = sf.query(
        'SELECT Id, Name, LastLoginDate FROM User WHERE Name =\'nsuhara\'')
    print(json.dumps(res, indent=4))
コード例 #31
0
ファイル: tennis.py プロジェクト: tegeling/raspiforce
def setup():
	#
	# Declare global variables
	#
	global myRegId
	global myUsername
	global myPassword
	global myToken
	global contactid
	global subject
	global ws
	global adxl

	#
	# setup Raspberry Pi ADXL345
	# see http://shop.pimoroni.com/products/adafruit-triple-axis-accelerometer
	#
	if not simulation_mode:
		adxl = adxl345.ADXL345()
		#adxl.setRange(adxl345.RANGE_2G)
		adxl.setRange(adxl345.RANGE_16G)

	#
	# Read configuration from file
	#
	config = ConfigParser.RawConfigParser()
	config.read('salesforce_login.cfg')

	#
	# Establish Websockt connection for monitoring chat service
	#
	if chat_mode:
		ws_url = config.get('Chat', 'ws_url')
		ws = create_connection(ws_url)


	#
	# Lookup Salesforce demo org credentials and configuration
	#
	sf_lookup = Salesforce(username=config.get('Salesforce', 'username'), password=config.get('Salesforce', 'password'), security_token=config.get('Salesforce', 'security_token'))
	result = sf_lookup.query("SELECT Id, Username__c, Password__c, Security_Token__c, Case_Contact_Id__c, Case_Subject__c FROM Raspberry_Pi_Demo__c WHERE Active__c = true AND Raspi_Hostname__c = " + config.get('Host', 'hostname'))

	#
	# Register new demo run
	#
	myRegId = result.get('records')[0].get('Id')	
	sf_lookup.Raspberry_Pi_Demo_Registration__c.create({'Raspberry_Pi_Demo__c':myRegId,'Status__c':'connected'})

	myUsername = result.get('records')[0].get('Username__c')
	myPassword =  result.get('records')[0].get('Password__c')
	myToken = result.get('records')[0].get('Security_Token__c')

	contactid = result.get('records')[0].get('Case_Contact_Id__c')
	subject = result.get('records')[0].get('Case_Subject__c')

	if chat_mode:
		chat("Sensor","Connection established.")
コード例 #32
0
ファイル: http_redirect.py プロジェクト: dinobot/duty-reports
def application(caseid):
    if caseid in kvs:
        url = sf_url + '/console#%2f' + kvs[caseid]
    else:
        sf = Salesforce(instance_url=sf_url, username=sf_usr, password=sf_pwd, security_token=sf_tkn)
        for case in sf.query("SELECT Id from Case where CaseNumber = '%d'" % int(caseid))['records']:
          kvs[caseid] = case['Id']
          url = sf_url + '/console#%2f' + case['Id']
    return redirect(url, code=301)
コード例 #33
0
def dostuff():
    sf_object = Salesforce(username='******',
                           password='******',
                           security_token='bFnog0nT6653hMwx3lRzkKjnY',
                           sandbox=False)

    accounts = sf_object.query("select Id from Account")
    for account in accounts['records']:
        print(account)
コード例 #34
0
def futureInstall():
    headers =  {'Authorization': 'Bearer ' + boxToken()}
    for region in opsBox:
      json_r = requests.get('https://api.box.com/2.0/folders/' + opsBox[region] + '/items?limit=1000', headers=headers).json()
      for file in json_r['entries']:
        json_r = requests.delete('https://api.box.com/2.0/files/' + file['id'], headers=headers)

    sf = Salesforce(username='******', password='******', security_token='yWlJG8lAKCq1pTBkbBMSVcKg')

    if datetime.today().weekday() == 4:
      response = sf.query("SELECT interaction__c.Contact__r.Accountnumber__c, interaction__c.Contact__r.County__c, interaction__c.Contact__r.Name, interaction__c.Contact__r.Address__c, interaction__c.Contact__r.City_State_Zip__c, ScheduledDate__c, Canceled__c FROM interaction__c WHERE interaction__c.Opportunity__r.InstallDate__c = Null and Subject__c = 'Installation' AND ScheduledDate__c = NEXT_N_DAYS:4 AND ScheduledDate__c != TOMORROW AND Canceled__c = false ORDER BY ScheduledDate__c")
    else:
      response = sf.query("SELECT interaction__c.Contact__r.Accountnumber__c, interaction__c.Contact__r.County__c, interaction__c.Contact__r.Name, interaction__c.Contact__r.Address__c, interaction__c.Contact__r.City_State_Zip__c, ScheduledDate__c, Canceled__c FROM interaction__c WHERE interaction__c.Opportunity__r.InstallDate__c = Null and Subject__c = 'Installation' AND ScheduledDate__c = NEXT_N_DAYS:2 AND ScheduledDate__c != TOMORROW AND Canceled__c = false ORDER BY interaction__c.Contact__r.County__c")
    print json.dumps(response, indent=4, sort_keys=True)
    installList = []
    for item in response['records']:
      installList.append(item['Contact__r']['Accountnumber__c'])
    futureInstallData(installList)
    print 'Job Done.'
コード例 #35
0
def getContact(email, dni, return_list=False):
    limit = 100 if return_list else 2
    ret = []
    sf = Salesforce(**settings.SF_AUTH)
    response = sf.query("""
        SELECT {} 
        FROM Contact 
        WHERE Email ='{}'
        AND s360a__ContactCodes__c = 'Active Donor'
        LIMIT {} """.format(comma_params, email, limit))
    objects = response['records']
    if len(objects) == 1 and not return_list:
        return objects[0]
    else:
        ret += objects
    response = sf.query("""
        SELECT {} 
        FROM Contact 
        WHERE DNI__c ='{}'
        AND s360a__ContactCodes__c = 'Active Donor'
        LIMIT {} """.format(comma_params, dni, limit))
    objects = response['records']
    if len(objects) == 1 and not return_list:
        return objects[0]
    else:
        ret += objects
    response = sf.query("""
        SELECT {}
        FROM Contact 
        WHERE DNI__c ='{}'
        AND s360a__ContactCodes__c = 'Active Donor'
        AND  Email ='{}' 
        LIMIT {} """.format(comma_params, dni, email, limit))
    objects = response['records']
    if len(objects) == 1:
        return objects[0]
    else:
        ret += objects
    if ret and not return_list:
        raise MultipleContactsError()
    return ret
コード例 #36
0
ファイル: routes.py プロジェクト: certasun/achAPP
def multipleRecords(email):
    #instantiate a connection to salesforce
    sf = Salesforce(app_settings['SF-USER'] +".plaidtest", app_settings['SF-PASS'], app_settings['SF-TOKEN'] , domain = 'test')
    #query salesfore for the account and projects data associated with that contact
    query = sf.query("select Name, ID, (select id, Name from projects__r) from account where ID IN (select AccountId from contact where contact.email  = '" +email+ "')")
    #instantiate a list to hold projects
    accountList = list()
    #for loop that will go through all of the projects and create dictionaries holding there ID's and names and append them to the above list so they may be sent to the front end to be displayed to the customer
    for i in range(query['records'][0]['Projects__r']['totalSize']):
        account_dict = {'Name':query['records'][0]['Projects__r']['records'][i]['Name'], 'ID': query['records'][0]['Projects__r']['records'][i]['Id']}
        accountList.append(account_dict)
    return render_template('multipleRecordsNew.html', accounts = accountList)
コード例 #37
0
def get_contacts2(access_token, instance_url):
    records_list=[]
    try:
        sf = Salesforce(instance_url=instance_url, session_id= access_token)
        records = sf.query("SELECT Name FROM Contact")
        records = records['records']
        for rows in records:
            print(records)
            records_list.append(rows)
    except Exception as e:
        logging.info("Exception %s is raised ", str(e))
    return records_list
コード例 #38
0
ファイル: case_handle.py プロジェクト: dinobot/duty-reports
def application():
    caseid = request.args.get('text', '')
    if caseid in kvs:
        url = sf_url + '/console#%2f' + kvs[caseid].get('id')
        title = kvs[caseid].get('title')
    else:
        sf = Salesforce(instance_url=sf_url, username=sf_usr, password=sf_pwd, security_token=sf_tkn)
        for case in sf.query("SELECT Id, Subject from Case where CaseNumber = '%d'" % int(caseid))['records']:
          kvs[caseid] = {'id': case['Id'], 'title': prepare_json_data(case['Subject'])}
          url = sf_url + '/console#%2f' + case['Id']
          title = prepare_json_data(case['Subject'])
    return '{"response_type": "in_channel", "attachments": [{"title": "'+title+'","title_link": "'+url+'",}]}', 200, {'Content-Type': 'application/json'}
コード例 #39
0
def test_basic_query():
    salesforce = Salesforce(**MOCK_CREDS)

    salesforce.Contact.create({"Name": "Ozzy Osbourne"})

    results = salesforce.query("SELECT Id, Name FROM Contact LIMIT 1")
    records = results["records"]

    assert len(records) == 1
    record = records[0]
    assert record["Id"]
    assert record["Name"] == "Ozzy Osbourne"
コード例 #40
0
ファイル: views.py プロジェクト: donaldrivard/mrbelvedere
def get_oauth_user(oauth):
    """ Fetches the user info from the org """
    if not oauth or not oauth.get('access_token', None):
        return 'Not connected'
    sf = Salesforce(instance_url = oauth['instance_url'], session_id = oauth['access_token'], sandbox = oauth.get('sandbox',False))
    # Parse user id from id which ends in /ORGID/USERID
    user_id = oauth['id'].split('/')[-1]

    #user = sf.User.get(user_id)
    res = sf.query("SELECT Id, Username, Profile.PermissionsModifyAllData from User WHERE Id='%s'" % user_id)
    user = res['records'][0];
    return user
コード例 #41
0
	def salesforceUpload(self,information):
		# we are making safe connection with salesforce by passing account information
		sf = Salesforce(username=information['salesforceUserName'], password=information['salesforcepassword'], security_token=information['salesforcesecurityToken'])
		# we are getting session id here
		sessionId = sf.session_id
	
		flag = 0
		# we are querying all folders in your salesforce account
		documentQuery = sf.query("SELECT ID,Name FROM folder")
		# we are traversing all folders and fetching the folderid for our target folder which is SpringCM
		for f in documentQuery['records']:
			if (information['targetFoldername'] == f['Name']):
				folderid = f['Id']
				flag = 1
				print "folder found"
				break

		if flag ==0:
			loggerFile.write("Module salesforceUpload:folder not found")
			loggerFile.write("\n")
			print "folder not found"
			print "Leaving this program"
			return 0
		body = ""
		# here we are opening our xml file and encoding into base4..this is required to send files to salesforce
		with open(information['filename'], "r") as f:
			body = base64.b64encode(f.read())

		# Rest API post method call.. using requests post method
		# here we are sending parameters:
		#first one is url
		#second one is header, with content type as json
		#third one is our actual data
		response = requests.post('https://%s.salesforce.com/services/data/v24.0/sobjects/Document/' % information['salesforceinstance'],
		    headers = { 'Content-Type': 'application/json', 'Authorization': 'Bearer %s' % sessionId },
		    data = json.dumps({
				'FolderId':folderid,
			'Name': information['filename'],
			'body': body
		    })
		)
		#printing the response output
		print response.text
		json_data = json.loads(response.text)
		if(json_data['success']== True):
			return 1
		else:
			loggerFile.write("Module salesforceUpload:Upload Failed")
			loggerFile.write("\n")
			return 0
コード例 #42
0
ファイル: OpenCase.py プロジェクト: rhquant/Travis
def statuscheck():
    global done
    uname = input(str("Enter Username: "******"Enter password: "******"Enter API key: "))
    sf=Salesforce(username=uname, password=pword, security_token=key)
    cid_ask = input(str("Enter Case Number to get Status: " ))
    try:
        a=sf.query("SELECT Status, Owner.Name FROM case where CaseNumber = '{0}'".format(cid_ask))
        status = a['records'][0]['Status']
        owner = a['records'][0]['Owner']['Name']
        print("Case {0} is owned by {1} and is in status {2}".format(cid_ask, owner, status))
        done = True
    except:
        print("The case number you have entered is invalid.")
コード例 #43
0
    def get(self, request, format=None):
        """
        Lists all projects on Salesforce.
        """

        search = request.query_params.get('search', '')

        sf = Salesforce(instance_url=settings.SALESFORCE_URL,
                        username=settings.SALESFORCE_USERNAME,
                        password=settings.SALESFORCE_PASSWORD,
                        security_token=settings.SALESFORCE_TOKEN)

        projects_query = ("SELECT Id,Name,Description,CreatedDate FROM Opportunity "
                          "WHERE Name LIKE '%{}%'").format(search)
        projects = sf.query(projects_query)
        return Response(projects['records'])
コード例 #44
0
class SF(Resource):
    def __init__(self):
        self.sf = Salesforce(
            username=os.environ.get('SF_USER'),
            password=os.environ.get('SF_PASS'),
            security_token=os.environ.get('SF_TOKEN'),
            sandbox=True)
        return

    def get_team(self):
        dict = self.sf.query("SELECT Username, Title, FirstName, LastName, MobilePhone, Email, City "
                        "FROM User WHERE "
                        "(Title = 'Developer Evangelist' "
                        "OR Title = 'Community Guy' "
                        "OR Title = 'Developer Communications Director') "
                        "AND IsActive = True")
        team_items = {}
        team = []
        ret = "Team Size: " + str(dict[u'totalSize']) + " "
        for i in range(dict[u'totalSize']):
            dict2 = dict[u'records'][i]
            # This is unique and in the form of an email, this will be our ID
            team_items['ID'] = str(dict2[u'Username'])
            team_items['Type'] = str(dict2[u'Title'])
            team_items['FirstName'] = str(dict2[u'FirstName'])
            team_items['LastName'] = str(dict2[u'LastName'])
            # There is also the option to get the SendGrid landline phone + Extension
            # TODO: get rid of the string conversion and make sure this value exists for all team members
            team_items['Phone'] = str(dict2[u'MobilePhone'])
            team_items['Email'] = str(dict2[u'Email'])
            # TODO: get rid of the string conversion and make sure this value exists for all team members
            team_items['HomeCity'] = str(dict2[u'City'])
            team.append(team_items)
            team_items={}
        return team

    def put_relationship(self):
        return self.sf.Lead.create({
            'FirstName':'Testy',
            'LastName':'McTesterton',
            'Company':'SendGrid',
            'Monthly_Email_Volume__c':'2.5M to 10M',
            'Type__c':'Reseller',
            'Status':'Existing Customer',
            'LeadSource':'Corporate Event',
            'Developer_Relations_Rep__c':'*****@*****.**'
        })
コード例 #45
0
ファイル: views.py プロジェクト: GETLIMS/LIMS-Backend
    def post(self, request, format=None):
        if settings.ENABLE_CRM:
            crm_project_ids = request.data.get('crm_ids', None)

            if crm_project_ids:
                projects = CRMProject.objects.filter(id__in=crm_project_ids)

                crm_identifiers = ["'" + p.project_identifier + "'" for p in projects.all()]

                sf = Salesforce(instance_url=settings.SALESFORCE_URL,
                                username=settings.SALESFORCE_USERNAME,
                                password=settings.SALESFORCE_PASSWORD,
                                security_token=settings.SALESFORCE_TOKEN)
                crm_project_query = ("SELECT o.Id,o.Name,o.Description,o.CreatedDate,"
                                     "o.Project_Status__c "
                                     "FROM Opportunity o "
                                     "WHERE o.Id IN ({})").format(", ".join(crm_identifiers))
                crm_project_data = sf.query(crm_project_query)
                if crm_project_data['totalSize'] > 0:
                    records = crm_project_data['records']
                    for record in records:
                        try:
                            proj = CRMProject.objects.get(project_identifier=record['Id'])
                        except:
                            pass
                        else:
                            proj.name = record['Name']
                            proj.description = record['Description']
                            proj.status = record.get('Project_Status__c', '')
                            proj.save()
                            # Get project and update status
                            projects = proj.project_set.all()
                            for p in projects:
                                if record.get('Project_Status__c', '') != '':
                                    ps = record.get('Project_Status__c')
                                    try:
                                        project_status = ProjectStatus.objects.get(name=ps)
                                    except ObjectDoesNotExist:
                                        project_status = ProjectStatus.objects.create(name=ps)
                                    p.status = project_status
                                    p.save()
                    return Response({'message': 'Projects updated'})
                return Response({'message': 'No projects found on CRM system'}, status=404)
            return Response({'message': 'Please provide a list of CRM project IDs'}, status=400)
        return Response({'message': 'CRM is currently disabled'}, status=501)
コード例 #46
0
ファイル: helpers.py プロジェクト: GETLIMS/LIMS-Backend
def CRMCreateContact(request, serialized_data):
    """
    Creates an accountless contact on the CRM system if they don't exist.
    """
    sf = Salesforce(instance_url=settings.SALESFORCE_URL,
                    username=settings.SALESFORCE_USERNAME,
                    password=settings.SALESFORCE_PASSWORD,
                    security_token=settings.SALESFORCE_TOKEN)

    contact_id = ''
    account_id = ''

    contacts_query = ("SELECT Id,AccountId,FirstName,LastName,Email "
                      "FROM Contact WHERE Email = '{}'").format(serialized_data['email'])
    contacts = sf.query(contacts_query)
    if contacts['totalSize'] > 0:
        contact_id = contacts['records'][0]['Id']
        account_id = contacts['records'][0]['AccountId']
    else:
        country_codes = dict((value, key) for key, value in dict(countries).items())
        contact = sf.Contact.create({
            'FirstName': serialized_data['first_name'],
            'LastName': serialized_data['last_name'],
            'AccountId': account_id,
            'Email': serialized_data['email'],
            'MailingStreet':
                serialized_data['address_1'] + '\n ' + serialized_data.get('address_2', ''),
            'MailingCity': serialized_data['city'],
            'MailingPostalCode': serialized_data['postcode'],
            'MailingCountryCode': country_codes[serialized_data['country']],
        })
        contact_id = contact['id']

    if contact_id:
        user = User.objects.get(email=serialized_data['email'])

        details = CRMAccount(contact_identifier=contact_id,
                             user=user)
        if account_id:
            details.account_identifier = account_id
        details.save()

        return details
    return False
コード例 #47
0
ファイル: views.py プロジェクト: seungjulee/theForce
def index(request):
	if not request.user.is_anonymous():
		return HttpResponseRedirect("/loggedin")
	else:
		c = {}
		c.update(csrf(request))
		sf = Salesforce(username='******', password='******', security_token='GxJyxvdyKRkWqIySzha8w7xT')
		contact = sf.query("SELECT Id, CloseDate, CreatedDate, Amount FROM Opportunity")
		records = contact["records"]
		i,a,t,close = [],[],[],[]
		for item in records:
			i.append(item["Id"])
			a.append(item["Amount"])
			close.append(item["CloseDate"])
			t.append(item["CreatedDate"])		
		
		lst = [{'ID': d[0], 'Amount': d[1], 'CloseDate': d[2], 'CreatedDate': d[3]} for d in zip(i, a, close, t)]
		c['contact'] = lst
		return render_to_response('index.html', c)
コード例 #48
0
ファイル: views.py プロジェクト: GETLIMS/LIMS-Backend
    def get(self, request, format=None):
        """
        Lists all projects on Salesforce.
        """

        if settings.ENABLE_CRM:
            search = request.query_params.get('search', '')
            pk = request.query_params.get('id', None)
            sf = Salesforce(instance_url=settings.SALESFORCE_URL,
                            username=settings.SALESFORCE_USERNAME,
                            password=settings.SALESFORCE_PASSWORD,
                            security_token=settings.SALESFORCE_TOKEN)

            if pk is not None:
                projects_query = ("SELECT Id,Name,Description,Project_Status__c, CreatedDate "
                                  "FROM Opportunity WHERE Id = '{}'").format(pk)
            else:
                projects_query = ("SELECT Id,Name,Description,Project_Status__c, CreatedDate "
                                  "FROM Opportunity WHERE Name LIKE '%{}%'").format(search)
            projects = sf.query(projects_query)
            return Response({'results': projects['records'],
                             'meta': {'count': len(projects['records'])}})
        return Response({'message': 'CRM is currently disabled'}, status=501)
コード例 #49
0
ファイル: views.py プロジェクト: GETLIMS/LIMS-Backend
    def post(self, request, format=None):
        if settings.ENABLE_CRM:
            crm_account_ids = request.data.get('crm_ids', None)

            if crm_account_ids:
                accounts = CRMAccount.objects.filter(id__in=crm_account_ids)

                crm_identifiers = ["'" + p.contact_identifier + "'" for p in accounts.all()]

                sf = Salesforce(instance_url=settings.SALESFORCE_URL,
                                username=settings.SALESFORCE_USERNAME,
                                password=settings.SALESFORCE_PASSWORD,
                                security_token=settings.SALESFORCE_TOKEN)

                contacts_query = ("SELECT c.Id,c.AccountId,c.FirstName,c.LastName,c.Email,a.Name "
                                  "FROM Contact c, c.Account a WHERE c.Id IN ({})").format(
                                 ",".join(crm_identifiers))

                contacts = sf.query(contacts_query)
                if contacts['totalSize'] > 0:
                    records = contacts['records']
                    for record in records:
                        try:
                            account = CRMAccount.objects.get(contact_identifier=record['Id'])
                        except:
                            pass
                        else:
                            account.account_identifier = record['AccountId']
                            account.contact_identifier = record['Id']
                            if record['Account']:
                                account.account_name = record['Account']['Name']
                            account.save()
                    return Response({'message': 'CRM accounts updated'})
                return Response({'message': 'No accounts found on CRM system'}, status=404)
            return Response({'message': 'Please provide a list of CRM account IDs'}, status=400)
        return Response({'message': 'CRM is currently disabled'}, status=501)
コード例 #50
0
ファイル: views.py プロジェクト: zaki-yama/quick-force-python
    def get(self, request, *args, **kwargs):
        if not is_setup():
            return redirect(reverse('app:setup'))

        connection = SalesforceOAuth2(
                client_id=os.environ.get('CONSUMER_KEY'),
                client_secret=os.environ.get('CONSUMER_SECRET'),
                redirect_uri=REDIRECT_URI)

        if 'code' in request.GET:
            res = connection.get_token(request.GET['code'])
            for k, v in res.items():
                logger.debug('%s: %r' % (k, v))

            sf = Salesforce(
                    instance_url=res['instance_url'],
                    session_id=res['access_token'])
            res = sf.query('SELECT id, name, type, industry, rating FROM Account')
            records = res['records']
            return render(request, self.template_name, {'records': records})
        else:
            auth_url = connection.authorize_url(scope='full')
            logger.debug('redirect to: {}'.format(auth_url))
            return redirect(auth_url)
コード例 #51
0
ファイル: views.py プロジェクト: GETLIMS/LIMS-Backend
    def post(self, request, format=None):
        """
        Links a CRMProject (creating it if not exists) to Project
        """

        if settings.ENABLE_CRM:
            crm_identifier = request.data.get('identifier', None)
            project_id = request.data.get('id', None)
            record = None

            if crm_identifier and project_id:

                try:
                    crm_project = CRMProject.objects.get(project_identifier=crm_identifier)
                except ObjectDoesNotExist:
                    sf = Salesforce(instance_url=settings.SALESFORCE_URL,
                                    username=settings.SALESFORCE_USERNAME,
                                    password=settings.SALESFORCE_PASSWORD,
                                    security_token=settings.SALESFORCE_TOKEN)
                    crm_project_query = ("SELECT o.Id,o.Name,o.Description,o.CreatedDate,a.id,"
                                         "o.Project_Status__c,a.name,"
                                         "(SELECT Id,ContactId,c.name,c.email "
                                         "FROM OpportunityContactRoles cr, "
                                         "cr.Contact c WHERE IsPrimary=True) "
                                         "FROM Opportunity o, o.Account a "
                                         "WHERE o.Id = '{}'").format(crm_identifier)
                    crm_project_data = sf.query(crm_project_query)
                    if crm_project_data['totalSize'] > 0:
                        record = crm_project_data['records'][0]

                        try:
                            contact_identifier = record['OpportunityContactRoles'][
                                'records'][0]['ContactId']
                        except:
                            return Response(
                                {'message':
                                 'CRM Project does not have an associated contact role'},
                                status=400)
                        else:
                            try:
                                crm_account = CRMAccount.objects.get(
                                    user__email=record['OpportunityContactRoles'][
                                        'records'][0]['Contact']['Email'],
                                    account_identifier=record['Account']['Id'])
                            except ObjectDoesNotExist:

                                contact_name = record['OpportunityContactRoles'][
                                    'records'][0]['Contact']['Name']
                                contact_email = record['OpportunityContactRoles'][
                                    'records'][0]['Contact']['Email']

                                first_name, last_name = contact_name.rsplit(' ', 1)
                                username = first_name[0] + last_name

                                try:
                                    u = User.objects.get(email=contact_email)
                                except User.DoesNotExist:
                                    u = User.objects.create_user(
                                        username,
                                        email=contact_email
                                    )

                                    u.first_name = first_name
                                    u.last_name = last_name
                                    u.save()

                                crm_account = CRMAccount(
                                    contact_identifier=contact_identifier,
                                    account_identifier=record['Account']['Id'],
                                    account_name=record['Account']['Name'],
                                    user=u
                                )
                                crm_account.save()

                        crm_project = CRMProject(
                            project_identifier=crm_identifier,
                            name=record['Name'],
                            description=record['Description'],
                            date_created=record['CreatedDate'],
                            status=record.get('Project_Status__c', ''),
                            account=crm_account
                        )
                        crm_project.save()
                    else:
                        return Response(
                            {'message': 'Project on CRM with the identifier {} does no exist'.
                                format(crm_identifier)}, status=404)
                try:
                    project = Project.objects.get(pk=project_id)
                except ObjectDoesNotExist:
                    return Response(
                        {'message': 'Project with ID {} does not exist'.format(project_id)},
                        status=404)

                project.crm_project = crm_project

                if record and record.get('Project_Status__c', '') != '' and \
                   record.get('Project_Status__c') is not None:
                    ps = record.get('Project_Status__c')
                    try:
                        project_status = ProjectStatus.objects.get(name=ps)
                    except ObjectDoesNotExist:
                        project_status = ProjectStatus.objects.create(name=ps)
                    project.status = project_status

                project.save()
            return Response({'message': 'CRM Project linked to Project {}'.format(project_id)})
        return Response({'message': 'CRM is currently disabled'}, status=501)
コード例 #52
0
class SFDC(object):

    def __init__(self, user_name, password, token):

        self.user_name = user_name
        self.password = password
        self.token = token
        self.sf = None

    def setSession(self, instance, sessionId):
        self.sf = Salesforce(instance=instance + '.salesforce.com', session_id=sessionId)

    def login(self):
        '''Connect to Salesforce API'''
     
        request = u"""<?xml version="1.0" encoding="utf-8" ?>
        <env:Envelope xmlns:xsd="http://www.w3.org/2001/XMLSchema"
                xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                xmlns:env="http://schemas.xmlsoap.org/soap/envelope/">
            <env:Body>
                <n1:login xmlns:n1="urn:partner.soap.sforce.com">
                    <n1:username>""" + self.user_name + """</n1:username>
                    <n1:password>""" + self.password + self.token + """</n1:password>
                </n1:login>
            </env:Body>
        </env:Envelope>"""
       
        encoded_request = request.encode('utf-8')
        url = "https://login.salesforce.com/services/Soap/u/30.0"
       
        headers = {"Content-Type": "text/xml; charset=UTF-8",
                   "SOAPAction": "login"}
                                 
        response = requests.post(url=url,
                                 headers = headers,
                                 data = encoded_request,
                                 verify=False)

        return unicode(response.text)

    def query_contacts(self, emails):
        formatted_emails = "'" + "','".join(filter(None, emails)) + "'"
        query = "SELECT Id, Email, Name FROM CONTACT WHERE Email In (%s)" % formatted_emails
        query_results = self.sf.query(query)
        return query_results['records']

    def query_usage_history_types(self):
        query = "SELECT Id, Name FROM User_Usage_History_Event_Type__c"
        query_results = self.sf.query(query)
        return query_results['records']

    def json_to_xml_rows(self, updates, fields):
        data = {}
        for i in range(0, len(updates), 10000):

            XML = ''

            for record in updates[i:i+10000]:

                XML += u"""<sObject>"""
                for field in fields.keys():
                    XML += """<""" + fields[field] + """>""" + str(record[field]) + """</""" + fields[field] + """>"""

                XML += """</sObject>\n            """

            data[i] = XML
        return data



    def query_objects(self, updates, objects, fields, externalId = None):
        '''Look for and format Salesforce objects to be updated with Mixpanel data'''

        emails = [email if email is not None else '' for email in updates.keys()]
        formatted_emails = "'" + "','".join(filter(None, emails)) + "'"

        query = "SELECT Id, Email, " + externalId + " FROM " + objects + " WHERE Email In (%s)" % formatted_emails
        query_results = self.sf.query(query)

        sfdc_total = query_results.items()[0][1]
        print '# ' + objects + 's matching Mixpanel People: %d' % sfdc_total 

        records = query_results.items()[2][1]

        data = {}

        for i in range(0, sfdc_total, 10000):

            XML = ''

            for record in records[i:i+10000]:

                length = len(record.items())
                mp_update_id = record.items()[length-1][1]
                email = record.items()[length-2][1]
                Id = record.items()[length-3][1]

                XML += u"""<sObject><Id>""" + Id + """</Id>"""
                for field in fields.keys():
                    XML += """<""" + fields[field] + """>""" + updates[email][field] + """</""" + fields[field] + """>"""

                XML += """<""" + externalId + """>""" + mp_update_id + """</""" + externalId + """>"""

                XML += """</sObject>\n            """

            data[i] = XML

        return data

    def create_job(self, instance, sessionId, operation, object, contentType, externalId = None):
        '''Create a job in Salesforce to prepare for data load'''

        if externalId is not None: 
            request = u"""<?xml version="1.0" encoding="UTF-8"?>
            <jobInfo xmlns="http://www.force.com/2009/06/asyncapi/dataload">
                <operation>""" + operation + """</operation>
                <object>"""+ object + """</object>
                <externalIdFieldName>""" + externalId + """</externalIdFieldName>
                <contentType>""" + contentType + """</contentType>
            </jobInfo>"""
        else:
            request = u"""<?xml version="1.0" encoding="UTF-8"?>
            <jobInfo xmlns="http://www.force.com/2009/06/asyncapi/dataload">
                <operation>""" + operation + """</operation>
                <object>"""+ object + """</object>
                <contentType>""" + contentType + """</contentType>
            </jobInfo>"""

        encoded_request = request.encode('utf-8')
        url = "https://" + instance + ".salesforce.com/services/async/30.0/job"

        headers = {"X-SFDC-Session": sessionId,
                   "Content-Type": "application/xml; charset=UTF-8"}
                                 
        response = requests.post(url=url,
                                 headers = headers,
                                 data = encoded_request,
                                 verify=False)

        return unicode(response.text)

    def add_batch(self, instance, sessionId, jobId, objects):
        '''Add one "batch" of data to Salesforce job'''

        request = u"""<?xml version="1.0" encoding="UTF-8"?>
        <sObjects xmlns="http://www.force.com/2009/06/asyncapi/dataload">
            """ + objects + """
        </sObjects>"""
     
        encoded_request = request.encode('utf-8')
        url = "https://" + instance + "-api.salesforce.com/services/async/30.0/job/" + jobId + "/batch"
       
        headers = {"X-SFDC-Session": sessionId,
                   "Content-Type": "application/xml; charset=UTF-8"}

                                 
        response = requests.post(url=url,
                                 headers = headers,
                                 data = encoded_request,
                                 verify=False)
     
        return unicode(response.text)

    def close_job(self, instance, sessionId, jobId):
        '''Close Salesforce data load job'''
     
        request = u"""<?xml version="1.0" encoding="UTF-8"?>
        <jobInfo xmlns="http://www.force.com/2009/06/asyncapi/dataload">
            <state>Closed</state>
        </jobInfo>"""
     
        encoded_request = request.encode('utf-8')
        url = "https://" + instance + ".salesforce.com/services/async/30.0/job/" + jobId
       
        headers = {"X-SFDC-Session": sessionId,
                   "Content-Type": "application/xml; charset=UTF-8"}
                                 
        response = requests.post(url=url,
                                 headers = headers,
                                 data = encoded_request,
                                 verify=False)
     
        return unicode(response.text)
コード例 #53
0
ファイル: tests.py プロジェクト: openstax/openstax-cms
 def test_database_query(self):
     sf = SimpleSalesforce(**settings.SALESFORCE)
     contact_info = sf.query(
         "SELECT Id FROM Contact WHERE Accounts_ID__c = '0'")
     self.assertEqual(
         contact_info['records'][0]['Id'], u'003U000001erXyqIAE')
コード例 #54
0
    conn.request("POST", slack_hook, params)
    res = conn.getresponse()
    conn.close()
    return res.status, res.reason


# Main loop for processing tickets
while True:
    # In case we don't find some known tickets in the list,
    # we mark them as not new anymore
    for t in ntickets:
        ntickets[t]['stillnew'] = False

    # Searching for all tickets with "New" status and processing
    for case in sf.query(("SELECT Id, Subject, Severity_Level__c, "
                          "CaseNumber, AccountId FROM Case WHERE "
                          "Status = 'New'"))['records']:
        if case['Id'] in ntickets:
            # If the ticket is already already known...

            if case['Severity_Level__c'] is not None:
                nsev = int(case['Severity_Level__c'][-1])
            else:
                print("%s is an alert and has no severity. Treating as Sev3" %
                      case['CaseNumber'])
                nsev = 3

            ntickets[case['Id']]['stillnew'] = True
            ntickets[case['Id']]['wait'] += poll_rate

            if ntickets[case['Id']]['wait'] >= sev_wait[nsev-1]:
コード例 #55
0
# begin 
sf = Salesforce(username='******', password='******', security_token='tbd')



while 1:
	print 'Please choose from the following:'
	print 'q to quit, a for accounts, c for contacts'
	#next = sys.stdin.read(1)
	next = getch()
	if next == 'q' or next == 'g':
		break;
	elif next == 'c' or next == 's':
		divider = 'Contacts'
		header = "\tName\t\tEmail"
		records = sf.query("SELECT Id, Name, Email FROM Contact")
		records = records['records']
		value = 'Email'
	elif next == 'a':
		divider = 'Accounts'
		header = "\tName\t\tPhone"
		records = sf.query("SELECT Id, Name, Phone FROM Account")
		records = records['records']
		value = 'Phone'
	else:
		print "No valid input"
		print
		continue


	print "SELECT Id, Name, Email FROM Contact"
コード例 #56
0
    def post(self, request, format=None):
        """
        Links a CRMProject (creating it if not exists) to Project
        """

        crm_identifier = request.data.get('identifier', None)
        project_id = request.data.get('id', None)

        if crm_identifier and project_id:

            try:
                crm_project = CRMProject.objects.get(project_identifier=crm_identifier)
            except ObjectDoesNotExist:
                sf = Salesforce(instance_url=settings.SALESFORCE_URL,
                                username=settings.SALESFORCE_USERNAME,
                                password=settings.SALESFORCE_PASSWORD,
                                security_token=settings.SALESFORCE_TOKEN)
                crm_project_query = ("SELECT o.Id,o.Name,o.Description,o.CreatedDate,a.id,"
                                     "a.name,(SELECT Id,ContactId,c.name,c.email "
                                     "FROM OpportunityContactRoles cr, "
                                     "cr.Contact c) FROM Opportunity o, o.Account a "
                                     "WHERE o.Id = '{}'").format(crm_identifier)
                crm_project_data = sf.query(crm_project_query)  # Opportunity.get(crm_identifier)
                pprint.pprint(crm_project_data)
                if crm_project_data['totalSize'] > 0:
                    record = crm_project_data['records'][0]

                    try:
                        crm_account = CRMAccount.objects.get(
                            account_identifier=record['Account']['Id'])
                    except ObjectDoesNotExist:
                        try:
                            contact_identifier = record['OpportunityContactRoles'][
                                'records'][0]['ContactId']
                        except:
                            return Response(
                                {'message':
                                 'CRM Project does not have an associated contact role'},
                                status=400)

                        contact_name = record['OpportunityContactRoles'][
                            'records'][0]['Contact']['Name']
                        contact_email = record['OpportunityContactRoles'][
                            'records'][0]['Contact']['Email']

                        try:
                            u = User.objects.get(username=contact_email)
                        except:
                            first_name, last_name = contact_name.rsplit(' ', 1)
                            u = User.objects.create_user(
                                contact_email,
                                email=contact_email
                            )

                            u.first_name = first_name
                            u.last_name = last_name
                            u.save()

                        crm_account = CRMAccount(
                            contact_identifier=contact_identifier,
                            account_identifier=record['Account']['Id'],
                            account_name=record['Account']['Name'],
                            user=u
                        )
                        crm_account.save()

                    crm_project = CRMProject(
                        project_identifier=crm_identifier,
                        name=record['Name'],
                        description=record['Description'],
                        date_created=record['CreatedDate'],
                        account=crm_account
                    )
                    crm_project.save()
                else:
                    return Response(
                        {'message': 'Project on CRM with the identifier {} does no exist'.format(
                            crm_identifier)}, status=404)
            try:
                project = Project.objects.get(pk=project_id)
            except ObjectDoesNotExist:
                return Response(
                    {'message': 'Project with ID {} does not exist'.format(project_id)},
                    status=404)

            project.crm_project = crm_project
            project.save()
        return Response({'message': 'CRM Project linked to Project {}'.format(project_id)})
コード例 #57
0
ファイル: run_apex_tests.py プロジェクト: stanlemon/CumulusCI
def run_tests():
    username = os.environ.get('SF_USERNAME')
    password = os.environ.get('SF_PASSWORD')
    serverurl = os.environ.get('SF_SERVERURL')
    test_name_match = os.environ.get('APEX_TEST_NAME_MATCH', '%_TEST')
    test_name_exclude = os.environ.get('APEX_TEST_NAME_EXCLUDE', '')
    namespace = os.environ.get('NAMESPACE', None)
    poll_interval = int(os.environ.get('POLL_INTERVAL', 10))
    debug = os.environ.get('DEBUG_TESTS',False) in ['true','True']
    debug_logdir = os.environ.get('DEBUG_LOGDIR')
    json_output = os.environ.get('TEST_JSON_OUTPUT', None)
    junit_output = os.environ.get('TEST_JUNIT_OUTPUT', None)
    
    if namespace:
        namespace = "'{0}'".format(namespace,)
    else:
        namespace = 'null'
    
    sandbox = False
    if serverurl.find('test.salesforce.com') != -1:
        sandbox = True
    
    sf = Salesforce(username=username, password=password, security_token='', sandbox=sandbox, sf_version='32.0')
    
    # Change base_url to use the tooling api
    sf.base_url = sf.base_url + 'tooling/'
    
    # Split test_name_match by commas to allow multiple class name matching options
    where_name = []
    for pattern in test_name_match.split(','):
        if pattern:
            where_name.append("Name LIKE '{0}'".format(pattern))

    # Add any excludes to the where clause
    where_exclude = []
    for pattern in test_name_exclude.split(','):
        if pattern:
            where_exclude.append("(NOT Name LIKE '{0}')".format(pattern,))
   
    # Get all test classes for namespace
    query = "SELECT Id, Name FROM ApexClass WHERE NamespacePrefix = {0}".format(namespace,)
    if where_name:
        query += " AND ({0})".format(' OR '.join(where_name),)
    if where_exclude:
        query += " AND {0}".format(' AND '.join(where_exclude),)

    print "Running Query: {0}".format(query,)
    sys.stdout.flush()

    res = sf.query_all(query)

    print "Found {0} classes".format(res['totalSize'],)
    sys.stdout.flush()

    if not res['totalSize']:
        return {'Pass': 0, 'Fail': 0, 'CompileFail': 0, 'Skip': 0}
    
    classes_by_id = {}
    classes_by_name = {}
    trace_id = None
    results_by_class_name = {}
    classes_by_log_id = {}
    logs_by_class_id = {}
    
    for cls in res['records']:
        classes_by_id[cls['Id']] = cls['Name']
        classes_by_name[cls['Name']] = cls['Id']
        results_by_class_name[cls['Name']] = {}

    # If debug is turned on, setup debug traces for all test classes
    if debug:
        print 'Setting up trace flag to capture debug logs'

        # Get the User's id to set a TraceFlag
        res_user = sf.query("Select Id from User where Username = '******'".format(username,))
        user_id = res_user['records'][0]['Id']
        
        # Set up a simple-salesforce sobject for TraceFlag using the tooling api
        TraceFlag = sf.TraceFlag
        TraceFlag.base_url = (u'https://{instance}/services/data/v{sf_version}/tooling/sobjects/{object_name}/'
                     .format(instance=sf.sf_instance,
                             object_name='TraceFlag',
                             sf_version=sf.sf_version))

        # First, delete any old trace flags still lying around
        tf_res = sf.query('Select Id from TraceFlag')
        if tf_res['totalSize']:
            for tf in tf_res['records']:
                TraceFlag.delete(tf['Id'])
    
        expiration = datetime.datetime.now() + datetime.timedelta(1)
        res = TraceFlag.create({
            'ApexCode': 'Info',
            'ApexProfiling': 'Debug',
            'Callout': 'Info',
            'Database': 'Info',
            'ExpirationDate': expiration.isoformat(),
            #'ScopeId': user_id,
            'System': 'Info',
            'TracedEntityId': user_id,
            'Validation': 'Info',
            'Visualforce': 'Info',
            'Workflow': 'Info',
        })
        trace_id = res['id']

        print 'Created TraceFlag for user'
    
    # Run all the tests
    print "Queuing tests for execution..."
    sys.stdout.flush()
    job_id = sf.restful('runTestsAsynchronous', params={'classids': ','.join(classes_by_id.keys())})
    
    # Loop waiting for the tests to complete
    while True:
        res = sf.query_all("SELECT Id, Status, ApexClassId FROM ApexTestQueueItem WHERE ParentJobId = '{0}'".format(job_id,))
        counts = {
            'Queued': 0,
            'Processing': 0,
            'Aborted': 0,
            'Completed': 0,
            'Failed': 0,
            'Preparing': 0,
            'Holding': 0,
        }
        for item in res['records']:
            counts[item['Status']] += 1
    
        # If all tests have run, break from the loop
        if not counts['Queued'] and not counts['Processing']:
            print ''
            print '-------------------------------------------------------------------------------'
            print 'Test Results'
            print '-------------------------------------------------------------------------------'
            sys.stdout.flush()
            break
        
        print 'Completed: %(Completed)s  Processing: %(Processing)s  Queued: %(Queued)s' % counts
        sys.stdout.flush()
        sleep(poll_interval)
    
    # Get the test results by method
    res = sf.query_all("SELECT StackTrace,Message, ApexLogId, AsyncApexJobId,MethodName, Outcome, ApexClassId, TestTimestamp FROM ApexTestResult WHERE AsyncApexJobId = '{0}'".format(job_id,))
    
    counts = {
        'Pass': 0,
        'Fail': 0,
        'CompileFail': 0,
        'Skip': 0,
    }
    for result in res['records']:
        class_name = classes_by_id[result['ApexClassId']]
        results_by_class_name[class_name][result['MethodName']] = result
        counts[result['Outcome']] += 1
        if debug and result['ApexLogId']:
            classes_by_log_id[result['ApexLogId']] = result['ApexClassId']
    
    # Fetch debug logs if debug is enabled
    if debug:
        log_ids = "('{0}')".format("','".join([str(id) for id in classes_by_log_id.keys()]),)
        res = sf.query_all("SELECT Id, Application, DurationMilliseconds, Location, LogLength, LogUserId, Operation, Request, StartTime, Status from ApexLog where Id in {0}".format(log_ids,))
        for log in res['records']:
            class_id = classes_by_log_id[log['Id']]
            class_name = classes_by_id[class_id]
            logs_by_class_id[class_id] = log
            # Fetch the debug log file
            body_url = '{0}sobjects/ApexLog/{1}/Body'.format(sf.base_url, log['Id'])
            resp = sf.request.get(body_url, headers=sf.headers)
            log_file = class_name + '.log'
            if debug_logdir:
                log_file = debug_logdir + os.sep + log_file
            f = open(log_file, 'w')
            f.write(resp.content)
            f.close()

            # Parse stats from the log file
            f = open(log_file, 'r')
            method_stats = parse_log(class_name, f)
            
            # Add method stats to results_by_class_name
            for method, info in method_stats.items():
                results_by_class_name[class_name][method].update(info)

        # Delete the trace flag
        TraceFlag.delete(trace_id)

    # Build an OrderedDict of results
    test_results = []

    class_names = results_by_class_name.keys()
    class_names.sort()
    for class_name in class_names:
        class_id = classes_by_name[class_name]
        duration = None
        if debug and class_id in logs_by_class_id:
            duration = int(logs_by_class_id[class_id]['DurationMilliseconds']) * .001
            print 'Class: {0} ({1}s)'.format(class_name, duration)
        else:
            print 'Class: {0}'.format(class_name,)
        sys.stdout.flush()

        method_names = results_by_class_name[class_name].keys()
        method_names.sort()
        for method_name in method_names:
            result = results_by_class_name[class_name][method_name]

            test_results.append({
                'Children': result.get('children', None),
                'ClassName': decode_to_unicode(class_name),
                'Method': decode_to_unicode(result['MethodName']),
                'Message': decode_to_unicode(result['Message']),
                'Outcome': decode_to_unicode(result['Outcome']),
                'StackTrace': decode_to_unicode(result['StackTrace']),
                'Stats': result.get('stats', None),
                'TestTimestamp': result.get('TestTimestamp', None),
            })
            
            # Output result for method
            if debug and json_output and result.get('stats') and 'duration' in result['stats']:
                # If debug is enabled and we're generating the json output, include duration with the test
                print u'   {0}: {1} ({2}s)'.format(
                    result['Outcome'], 
                    result['MethodName'], 
                    result['stats']['duration']
                )
            else:
                print u'   {Outcome}: {MethodName}'.format(**result)

            if debug and not json_output:
                print u'     DEBUG LOG INFO:'
                stats = result.get('stats',None)
                if not stats:
                    print u'       No stats found, likely because of debug log size limit'
                else:
                    stat_keys = stats.keys()
                    stat_keys.sort()
                    for stat in stat_keys:
                        try:
                            value = stats[stat]
                            output = u'       {0} / {1}'.format(value['used'], value['allowed'])
                            print output.ljust(26) + stat
                        except:
                            output = u'       {0}'.format(stats[stat],)
                            print output.ljust(26) + stat
    
            # Print message and stack trace if failed
            if result['Outcome'] in ['Fail','CompileFail']:
                print u'   Message: {Message}'.format(**result)
                print u'   StackTrace: {StackTrace}'.format(**result)
            sys.stdout.flush()
    
    print u'-------------------------------------------------------------------------------'
    print u'Passed: %(Pass)s  Fail: %(Fail)s  Compile Fail: %(CompileFail)s  Skipped: %(Skip)s' % counts
    print u'-------------------------------------------------------------------------------'
    sys.stdout.flush()
    
    if counts['Fail'] or counts['CompileFail']:
        print u''
        print u'Failing Tests'
        print u'-------------'
        print u''
        sys.stdout.flush()

        counter = 0
        for result in test_results:
            if result['Outcome'] not in ['Fail','CompileFail']:
                continue
            counter += 1
            print u'{0}: {1}.{2} - {3}'.format(counter, result['ClassName'], result['Method'], result['Outcome'])
            print u'  Message: {0}'.format(result['Message'],)
            print u'  StackTrace: {0}'.format(result['StackTrace'],)
            sys.stdout.flush()

    if json_output:
        f = codecs.open(json_output, encoding='utf-8', mode='w')
        f.write(json.dumps(test_results))
        f.close()

    if junit_output:
        f = codecs.open(junit_output, encoding='utf-8', mode='w')
        f.write('<testsuite tests="{0}">\n'.format(len(test_results)),)
        for result in test_results:
            testcase = '  <testcase classname="{0}" name="{1}"'.format(result['ClassName'], result['Method'])
            if 'Stats' in result and result['Stats'] and 'duration' in result['Stats']:
                testcase = '{0} time="{1}"'.format(testcase, result['Stats']['duration'])
            if result['Outcome'] in ['Fail','CompileFail']:
                testcase = '{0}>\n'.format(testcase,)
                testcase = '{0}    <failure type="{1}">{2}</failure>\n'.format(
                    testcase, 
                    cgi.escape(result['StackTrace']), 
                    cgi.escape(result['Message']),
                )
                testcase = '{0}  </testcase>\n'.format(testcase,)
            else:
                testcase = '{0} />\n'.format(testcase,)
            f.write(testcase)

        f.write('</testsuite>')
        f.close()
        

    return counts
コード例 #58
0
ファイル: sfSample.py プロジェクト: silverskyvicto/sfSample
from simple_salesforce import Salesforce

# ログイン
sf = Salesforce(username='******', password='******', security_token='<YOUR_SECURITY_TOKEN>')

cList = sf.query("SELECT Id, LastName, FirstName, Email FROM Contact")
print(cList)
sf.Contact.metadata()