예제 #1
0
def pollAirtableForUpdates():
    availableBases = [e for e in BaseNamesInUsage.objects.all()]
    # get entries from Airtable
    for availableBase in availableBases:
        if (datetime.now(pytz.timezone("US/Eastern")).date() -
                availableBase.date) > timedelta(days=30):
            availableBase.delete()
            availableBases.remove(availableBase)

    bases = [[
        pollBaseForUpdates(base.base_id, base.base_name), base.base_name
    ] for base in availableBases]

    # update Salesforce
    url = 'https://tribecabeverage.salesforce.com/airtablewebhook/'
    myobj = [{
        "base_name": base_name,
        "stops": putInSalesforceStyleJSON(base_data)
    } for base_data, base_name in bases]
    post = {
        "method": "ROUTE_UPDATE",
        "data": myobj,
        "updateDate": str(datetime.now(pytz.timezone("US/Eastern")).date())
    }
    print("post is: " + str(post))
    sf = Salesforce(username=os.environ["SALESFORCE_OAUTH_USERNAME"],
                    password=os.environ["SALESFORCE_OAUTH_PASSWORD"],
                    security_token=os.environ['SALESFORCE_SECURITY_TOKEN'])
    sf.apexecute("airtablewebhook", method="POST", data=post)
    return post
예제 #2
0
def send_donation_info(name, amount, project, address=''):
    if not settings.SFDC_ACCOUNT:
        return
    try:
        res = None
        payload = {
            'donorName': name,
            'projectName': project,
            'donationAmount': amount,
            'donorAddress': address
        }
        sf = Salesforce(username=settings.SFDC_ACCOUNT,
                        password=settings.SFDC_PASSWORD,
                        security_token=settings.SFDC_TOKEN)
        logger.info('send donation to SFDC with data: %s', payload)
        res = sf.apexecute(settings.SFDC_REVOLV_DONATION,
                           method='POST',
                           data=payload)
        if res.lower() != 'success':
            raise SFDCException(res)
        logger.info('SFDC donation: success.')
    except Exception as e:
        logger.error('SFDC donation: ERROR for name: %s and data: %s, res: %s',
                     name,
                     payload,
                     res,
                     exc_info=True)
        send_donation_info.retry(args=[name, amount, project, address],
                                 countdown=INTERVAL,
                                 exc=e,
                                 max_retries=MAX_RETRIES)
def main():
    args = parse_command_args()

    with AsyncRobot(args.serial, enable_face_detection=True) as vector:
        vector.behavior.say_text("I am ready for the next customer.")
        connection = Salesforce(username=os.environ['SF_USERNAME'],
                                password=os.environ['SF_PASSWORD'],
                                security_token=os.environ['SF_TOKEN'])
        result = connection.apexecute('nextcustomer', method='GET', data=None)
예제 #4
0
파일: sfdc.py 프로젝트: deedee/revolv
def send_signup_info( name, email, address=''):
    try:
        res = None
        payload = {'donorName': name, 'email': email, 'donorAddress': address}
        sf = Salesforce(username=SFDC_ACCOUNT, password=SFDC_PASSWORD, security_token=SFDC_TOKEN)
        logger.info('send sign-up to SFDC with data: %s', payload)
        res = sf.apexecute(SFDC_REVOLV_SIGNUP, method='POST', data=payload)
        if res.lower() != 'success':
            raise SFDCException(res)
        logger.info('SFDC sign-up: sucess.')
    except Exception as e:
        logger.error('SFDC sign-up: ERROR for name: %s and data: %s, res: %s', name, payload, res, exc_info=True)
        send_signup_info.retry(args=[name, email, address], countdown=INTERVAL, exc=e, max_retries=MAX_RETRIES)
예제 #5
0
파일: sfdc.py 프로젝트: Kamikace/revolv
def send_donation_info(name, amount, project, address=''):
    if not settings.SFDC_ACCOUNT:
        return
    try:
        res = None
        payload = {'donorName': name, 'projectName': project, 'donationAmount': amount, 'donorAddress': address}
        sf = Salesforce(username=SFDC_ACCOUNT, password=SFDC_PASSWORD, security_token=SFDC_TOKEN)
        logger.info('send donation to SFDC with data: %s', payload)
        res = sf.apexecute(SFDC_REVOLV_DONATION, method='POST', data=payload)
        if res.lower() != 'success':
            raise SFDCException(res)
        logger.info('SFDC donation: success.')
    except Exception as e:
        logger.error('SFDC donation: ERROR for name: %s and data: %s, res: %s', name, payload, res, exc_info=True)
        send_donation_info.retry(args=[name, amount, project, address], countdown=INTERVAL, exc=e,
                                 max_retries=MAX_RETRIES)
예제 #6
0
def send_signup_info(name, email, address=''):
    if not settings.SFDC_ACCOUNT:
        return
    try:
        res = None
        payload = {'donorName': name, 'email': email, 'donorAddress': ''}
        sf = Salesforce(
            username=settings.SFDC_ACCOUNT,
            security_token=settings.SFDC_TOKEN,
            password=settings.SFDC_PASSWORD
        )
        logger.info('send sign-up to SFDC with data: %s', payload)
        res = sf.apexecute(settings.SFDC_REVOLV_SIGNUP, method='POST', data=payload)
        if res.lower() != 'success':
            raise SFDCException(res)
        logger.info('SFDC sign-up: sucess.')
    except Exception as e:
        logger.error('SFDC sign-up: ERROR for name: %s and data: %s, res: %s', name, payload, res, exc_info=True)
예제 #7
0
def send_signup_info(name, email, address=''):
    try:
        res = None
        payload = {'donorName': name, 'email': email, 'donorAddress': address}
        sf = Salesforce(username=SFDC_ACCOUNT,
                        password=SFDC_PASSWORD,
                        security_token=SFDC_TOKEN)
        logger.info('send sign-up to SFDC with data: %s', payload)
        res = sf.apexecute(SFDC_REVOLV_SIGNUP, method='POST', data=payload)
        if res.lower() != 'success':
            raise SFDCException(res)
        logger.info('SFDC sign-up: sucess.')
    except Exception as e:
        logger.error('SFDC sign-up: ERROR for name: %s and data: %s, res: %s',
                     name,
                     payload,
                     res,
                     exc_info=True)
        send_signup_info.retry(args=[name, email, address],
                               countdown=INTERVAL,
                               exc=e,
                               max_retries=MAX_RETRIES)
__author__ = 'Brad'
from simple_salesforce import Salesforce
import json
sf = Salesforce( username='******', password='******', security_token='vnWYJMNtLbDPL9NY97JP9tJ5', sandbox=True)
print sf

metricData ={
    "patientId": "DCE-2762",
    "timestamp": "6/11/2015 12:00 AM",

    "roomPercentages": [
        {
            "room": "Bathroom",
            "percentage": 100
        },
        {
            "room": "Livingroom",
            "percentage": 100
        },
        {
            "room": "Kitchen",
            "percentage": 100
        }
    ]
}
print metricData
result = sf.apexecute('FMMetrics/insertMetrics', method='POST', data=metricData)
print result
예제 #9
0
config = configparser.ConfigParser()
config.read('config.ini')
hostname = socket.gethostname()
print(hostname + ' running as user: '******'SALESFORCE']['USERNAME'])

#Declare GPIO Setup
GPIO.setmode(GPIO.BOARD)
GPIO.setup(12, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

# Connect to Salesforce
sf = Salesforce(username=config['SALESFORCE']['USERNAME'],
                password=config['SALESFORCE']['PASSWORD'],
                security_token=config['SALESFORCE']['TOKEN'],
                domain=config['SALESFORCE']['DOMAIN'])
# Fetch train IP
device = sf.apexecute('Device/Train', method='GET')
trainIp = device['Last_Known_IP__c']
print('Train last known IP: ' + trainIp)
trainStopUrl = 'http://' + trainIp + ':8080/api/train/stop'

print('Scanning...')
try:
    while True:
        sensorValue = GPIO.input(12)
        if sensorValue == 1:
            print('Stopping train')
            time.sleep(float(config['TRAIN']['STOP_DELAY']))

            payload = {'sender': hostname}
            headers = {'content-type': 'application/json'}
            response = None
from simple_salesforce import Salesforce
import requests

session = requests.Session()

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

account = sf.Account.get('0017F00000LkvYHQAZ')

payload = {"name": "from Python"}
sf.apexecute('testRestServiceForAWS/test', method='POST', data=payload)
class EventProcessing:

    def __init__(self, database, database_name, username='******', password='******', security_token='rUrhVtWfeJAcZ6Wf1S7XZml4', sandbox=True):

        self.dataB = MySQLdb.connect(host=database[0], user=database[1], passwd=database[2])
        self.cur = self.dataB.cursor()
        self.databaseName = database_name
        self.patient_id = self.databaseName[1:]
        self.length = 30*86400
        self.data = []
        self.sf = Salesforce(username=username, password=password, security_token=security_token, sandbox=sandbox)


    def set_event_length(self, length):
        """

        @param length: double(days)
        @return:true
        """
        self.length = length*86400
        return True

    def get_event_data(self, data_type, table_name):
        """
        @param data_type: str of the column selected, pass * for all data in table
        @param table_name: str of the name of the table
        @return: Double tuple of steps
        """
        current_date = self.get_current_date()
        date_from_length = current_date-self.length
        sql = 'SELECT '+data_type+' FROM '+self.databaseName+'.'+table_name+' WHERE datetime >= '+str(date_from_length)
        self.cur.execute(sql)
        event_data = self.cur.fetchall()
        if len(event_data) == 0:
            return []
        else:
            return list(zip(*event_data)[0])

    @staticmethod
    def get_current_date(self):
        """

        @return:returns the current date in seconds from the epoch
        """
        epoch = datetime.datetime.utcfromtimestamp(0)
        current_date = datetime.datetime.now()
        current_date = current_date-epoch
        current_date = current_date.total_seconds()
        return current_date

    def upload_to_sales_force(self, apex_list):

        event_dict = {
            "metric": apex_list[0],
            "severity": apex_list[1],
            "metricValue": apex_list[2],
            "message": apex_list[3]
        }

        json_dict = {
            "patientId": self.patient_id,
            "event": event_dict
        }

        result = self.sf.apexecute('FMEvent/insertEvents', method='POST', data=json_dict)

        return result

    def upload_to_database(self, event_data):
        """

        @param event_data: List of event data referenced to objnamelist
        @return:True on success
        """

        # Create event table in database if it does not yet exist
        try:
            table_string = ''
            for i in self.objnamelist:
                # Splice out __c in object names
                table_string += i[0:-3] + ' VARCHAR(255),'

            sql = "CREATE TABLE " + self.databaseName + "." + "Events (datetime DOUBLE NOT NULL,"+table_string+" PRIMARY KEY(datetime))"
            self.cur.execute(sql)

        except MySQLdb.Error:
            print "Event Table found in database: "+self.databaseName

            try:
                # Try to see if we can resize the event table

                #Get number of columns
                sql = "SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE table_schema = '"+self.databaseName+"' AND table_name = 'Events' "
                self.cur.execute(sql)
                columns = int(list(self.cur.fetchall())[0][0])

                #Build list of new columns to add
                tables = ""
                if columns < len(self.objnamelist)+1:
                    for i in range(0, len(self.objnamelist)-(columns-1)):
                        tables += "ADD COLUMN "+self.objnamelist[columns+i-1][0:-3]+" VARCHAR(255),"
                    tables = tables[0:-1]

                    #add new columns to table
                    sql = "ALTER TABLE "+self.databaseName+".Events "+tables
                    self.cur.execute(sql)
                    self.dataB.commit()

            except:
                print(sys.exc_info())
                print "Select Error"

        try:
            tables_string = ''
            # add in additional %s for datetime
            s_string = '%s,'

            # Create list of tables in db and %s string for insert
            for i in self.objnamelist:
                tables_string += i[0:-3] + ','
                s_string += '%s,'

            # Remove trailing , from string
            s_string = s_string[0:-1]
            tables_string = tables_string[0:-1]

            # Create sql insert string
            sql = "INSERT INTO " + self.databaseName + "." + "Events (datetime,"+tables_string+") VALUES ("+s_string + ")"
            insert_list = event_data
            insert_list.insert(0, self.get_current_date())

            # Convert all elements to string for upload
            for i, z in enumerate(insert_list):
                insert_list[i] = str(z)

            # Upload and commit to db
            self.cur.execute(sql, tuple(insert_list))
            self.dataB.commit()
            return True

        except MySQLdb.Error:
            print 'Event insert into database '+self.databaseName+' has failed.'
            return False
class MetricsClass(AnalysisProcessingClass):

    def __init__(self, database, patient_id, table_name, metric_type):
        logging.warning('Watch out!')
        super(MetricsClass, self).__init__(database=database,
                                           patient_id=patient_id,
                                           type_name=metric_type,
                                           table_name=table_name)
        self.patient_id = patient_id
        self.metric_type   = self.typename
        self.sf = Salesforce(username='******',
                             password='******',
                             security_token='vnWYJMNtLbDPL9NY97JP9tJ5',
                             sandbox=True)

        if not self.table_exists(self.database_name, 'metricsprofile'):
            self.create_table(database_name = self.database_name,
                              table_name    = 'metricsprofile',
                              column_names  = ['table_name', 'type_name', 'timestamp'],
                              column_types  = ['VARCHAR(100)', 'VARCHAR(100) NOT NULL PRIMARY KEY', 'BIGINT(20)'])

    def poll_data(self, start_window):
        """
        Returns the data between the time frame specified
        :return:
        """

        if not self.fetch_from_database(database_name = self.database_name,
                                        table_name    = self.table_name,
                                        to_fetch      = 'analysis_data',
                                        where         = ['start_window', '=', start_window]):
            return []
        else:
            metric_data = self.fetchall()

        if len(metric_data) == 0:
            return []
        else:
            return pickle.loads(zip(*list(zip(*metric_data)))[0][0])

    def get_latest_data_stamp(self):
        if not self.fetch_from_database(database_name = self.database_name,
                                        table_name    = self.table_name,
                                        to_fetch      = 'start_window',
                                        order_by      = ['start_window', 'DESC'],
                                        limit         = 1):
            return []
        else:
            latest_data = self.fetchall()

        if len(latest_data) == 0:
            return []
        else:
            return zip(*list(zip(*latest_data)))[0][0]

    def read_timestamp(self):
        """
        Reads in the timestamp of the last processed data
        :return: Timestamp if exists, otherwise NULL
        """
        if not self.fetch_from_database(database_name = self.database_name,
                                        table_name    = 'metricsprofile',
                                        to_fetch      = 'timestamp',
                                        where         = [['table_name', self.table_name], ['type_name', self.typename]]):
            # If no analysisprofile database exists then return the start timestamp
            return self.read_start_stamp()

        else:
            # If timestamp column does exist in analysis profile, return it if it has length,
            # otherwise return the start_stamp
            timestamp = self.fetchall()

            if len(timestamp) == 0:
                # If no timestamp in timestamp column, return start_stamp
                return self.read_start_stamp()

            else:
                # If timestamp exists in timestamp column, return that
                timestamp = list(zip(*timestamp))[0][0]
                return timestamp

    def write_timestamp(self, timestamp):
        """
        Write the latest timestamp, in this case it means the end of a window
        :param timestamp:
        :return:
        """
        return self.insert_into_database(database_name       = self.database_name,
                                         table_name          = 'metricsprofile',
                                         column_names        = ['table_name', 'type_name', 'timestamp'],
                                         values              = [self.table_name, self.typename, timestamp],
                                         on_duplicate_update = [ 2 ])

    def upload_to_database(self, start_window, end_window, metric):
        """
        Uploads the metric to the database ['VARCHAR(100) NOT NULL PRIMARY KEY', 'FLOAT']
        :return:
        """
        self.create_table(database_name= self.database_name,
                          table_name   = self.metric_type,
                          column_names = ['start_window', 'end_window', 'metric'],
                          column_types = ['VARCHAR(100) NOT NULL PRIMARY KEY', 'VARCHAR(100) NOT NULL', 'FLOAT'])
        self.insert_into_database(database_name = self.database_name,
                                  table_name    = self.metric_type,
                                  column_names  = ['start_window', 'end_window', 'metric'],
                                  values        = [start_window, end_window, metric])
        return True

    def upload_to_salesforce(self, timestamp, metric):
        """
        Uploads the metric to salesforce
        :return:
        """
        metric_data = {
            "patientId": self.patient_id,
            "timestamp": self.utc_to_datetime(timestamp).strftime('%x'),
            "metricList":[
            {
                "metric": self.metric_type,
                "metricValue": metric
            }]
        }
        self.sf.apexecute('FMMetrics/insertMetrics', method='POST', data=metric_data)
        return True

    def run(self):
        """

        :return:
        """
        timestamp = self.read_timestamp
        # If no timestamp found, break the analysis code. Bad Profile!
        if timestamp is None: return False

        windows = self.get_stamp_windows()
        for i in windows:
            start_stamp = i[0]
            end_stamp = i[1]
            data = self.poll_data(start_stamp)
            if data != []:
                windowed_data  = self.split_to_windows(data)
                metric = self.process_data(windowed_data)
                self.upload_to_database(start_stamp, end_stamp, metric)
                self.upload_to_salesforce(start_stamp, metric)
                self.write_timestamp(start_stamp)
                return True
예제 #13
0
class SalesforceLogicSource(BaseLogicSource):

    def initialize(self, params):
        self.sfdc = Salesforce(username=SFDC_USERNAME,
                               password=SFDC_PASSWORD,
                               security_token=SFDC_TOKEN)

        self.channel_id = params['channel_id'][0]
        self.requester = '@' + params['user_name'][0]
        self.command = None
        if 'text' in params:
            self.command = params['text'][0]

    def __sfdc_rest_call(self, resource):
        return self.sfdc.apexecute('handleTTTCommand',
                                   method='POST',
                                   data={'resource': resource,
                                         'channelId': self.channel_id,
                                         'requestor':self.requester,
                                         'command': self.command
                                         })

    def __generate_response(self, response_map):
        print('*** RESPONSE: ',response_map);
        game_response_type = response_map['game_response_type']
        values = response_map['values'].split(',')
        slack_response_type = None
        if "slack_response_type" in response_map:
            slack_response_type = response_map["slack_response_type"]
        else:
            slack_response_type = 'Ephemeral'

        response = None
        if 'response' in response_map:
            response = response_map['response']

        return RMB.respond(None,
                           game_response_type=game_response_type,
                           values=values,
                           slack_response_type=slack_response_type,
                           response=response)



    def new_game(self):
        response = self.__sfdc_rest_call('/ttt')
        return self.__generate_response(response['body'])


    def game_help(self):
        super().game_help()
        """Help handler which provides information about the game and how to play it.

           :return:
        """
        return RMB.respond(None,
                               game_response_type='help_text',
                               values=[])

    def accept_game(self):
        response = self.__sfdc_rest_call('/ttt-accept')
        return self.__generate_response(response['body'])

    def decline_game(self):
        response = self.__sfdc_rest_call('/ttt-decline')
        return self.__generate_response(response['body'])

    def display_board(self):
        response = self.__sfdc_rest_call('/ttt-board')
        return self.__generate_response(response['body'])

    def play_move(self):
        response = self.__sfdc_rest_call('/ttt-move')
        return self.__generate_response(response['body'])

    def end_game(self):
        response = self.__sfdc_rest_call('/ttt-end')
        return self.__generate_response(response['body'])
예제 #14
0
    'a027000000RIuryAAD', 'a027000000RIurUAAT', 'a027000000RIurtAAD',
    'a023900000UPD2tAAH', 'a023900000UPD2yAAH', 'a023900000UPD33AAH',
    'a023900000UQkYOAA1', 'a023900000UOxIPAA1'
]

# time definitions
one_day = datetime.timedelta(days=1)
utc_zone = pytz.timezone('UTC')
est_zone = pytz.timezone('US/Eastern')
now_utc_naive = datetime.datetime.utcnow()
now_utc_aware = utc_zone.localize(now_utc_naive)
now_est_aware = now_utc_aware.astimezone(est_zone)
today_12am_est = now_est_aware.replace(hour=0, minute=0, second=0)

# fetch data from Salesforce
metrics_today = sf.apexecute('metricsdashboard?period=TODAY')
metrics_tw = sf.apexecute('metricsdashboard?period=THIS_WEEK')
sets_today = sf.query(
    "select scheduleddate__c, lead__r.county__c, lead__r.LASERCA__Home_State__c, lead__r.ambassador__c, lead__r.hq_rep__c, lead__r.lead_source_hierarchy__c from interaction__c where createddate = today and subject__c = 'Closer Appointment' and lead__c != null"
)["records"]
appts_tmrw = sf.query(
    "select scheduleddate__c, lead__r.county__c, lead__r.LASERCA__Home_State__c, lead__r.ambassador__c, lead__r.hq_rep__c, lead__r.lead_source_hierarchy__c from interaction__c where scheduleddate__c = tomorrow and subject__c = 'Closer Appointment' and canceled__c = false and lead__c != null"
)["records"]
cads_tmrw = sf.query(
    "select scheduleddate__c, lead__r.county__c, lead__r.LASERCA__Home_State__c, lead__r.ambassador__c, lead__r.hq_rep__c, lead__r.lead_source_hierarchy__c from interaction__c where scheduleddate__c = tomorrow and subject__c = 'CAD Appointment' and canceled__c = false and contact__c != null"
)["records"]
outcomes = sf.query(
    "select outcome__c from interaction__c where interactiondate__c = today and subject__c = 'CAD Appointment'"
)["records"]

# key totals
class MetricsClass(multiprocessing.Process, DatabaseWrapper):

    def __init__(self, database, patient_id, table_name, metric_type):
        logging.warning('Watch out!')
        multiprocessing.Process.__init__(self)
        DatabaseWrapper.__init__(self, database)
        self.database_name = '_' + patient_id
        self.table_name    = table_name
        self.metric_type   = metric_type
        self.sf = Salesforce(username='******',
                             password='******',
                             security_token='V6oPmGSaXW6Q5cv8MAEhLqCK',
                             sandbox=True)

    @staticmethod
    def get_day_window():
        """
        Returns the window between the current day and the last day
        :return:
        """
        current_date = datetime.datetime.now()
        start_window = datetime.datetime(current_date.year,
                                         current_date.month,
                                         current_date.day,
                                         current_date.hour) - datetime.timedelta(hours=12)
        start_window = start_window.strftime('%y-%m-%dT%H:%M:%S.%f')
        start_window = GenericFileUploader.timestamp_to_UTC(start_window)

        end_window   = datetime.datetime(current_date.year, current_date.month, current_date.day)
        end_window   = end_window.strftime('%y-%m-%dT%H:%M:%S.%f')
        end_window   = GenericFileUploader.timestamp_to_UTC(end_window)

        return start_window, end_window

    def poll_data(self, start_window, end_window):
        """
        Returns the data between the time frame specified
        :return:
        """

        if not self.fetch_from_database(database_name = self.database_name,
                                        table_name    = self.table_name,
                                        where         = [['timestamp', '<', start_window],
                                                         ['timestamp', '>=', end_window]],
                                        order_by      = ['timestamp', 'ASC']):
            return []
        else:
            metric_data = self.fetchall()

        if len(metric_data) == 0:
            return []
        else:
            return zip(*list(zip(*metric_data)))

    @abc.abstractmethod
    def process_data(self, data, start_window):
        """
        Returns the processed metric
        :param data:
        :return:
        """
        return

    def upload_to_database(self, metric, metric_names, metric_types):
        """
        Uploads the metric to the database ['VARCHAR(100) NOT NULL PRIMARY KEY', 'FLOAT']
        :return:
        """
        self.create_table(database_name= self.database_name,
                          table_name   = self.metric_type,
                          column_names = metric_names,
                          column_types = metric_types)
        self.insert_into_database(database_name = self.database_name,
                                  table_name    = self.metric_type,
                                  column_names  = ['timestamp', 'metric'],
                                  values        = metric)
        return True

    def upload_to_salesforce(self, metric):
        """
        Uploads the metric to salesforce
        :return:
        """
        metric_data = {
            "patientId": self.database_name[1:],
            "metricList": [{
                "metric": self.metric_type,
                "metricValue": metric[1]}
            ]
        }
        self.sf.apexecute('FMMetrics/insertMetrics', method='POST', data=metric_data)
        return True

    def run(self):
        """

        :return:
        """
        start_window, end_window = MetricsClass.get_day_window()
        data = self.poll_data(start_window, end_window)
        metric, metric_names, metric_types = self.process_data(data, start_window)
        self.upload_to_database(metric, metric_names, metric_types)
        self.upload_to_salesforce(metric)
        return True