예제 #1
0
def main(args):
    if len(args) != 3:
        print __doc__
        return

    url, key, log_name = args

    client = api.TokenClient(url, key, user_agent='refreshbooks/2.0')

    with open(log_name, 'r') as log_file:
        for line in log_file:
            m = re.search('^created payment (\d+)$', line.rstrip())
            if m:
                try:
                    client.payment.delete(payment_id=int(m.group(1)))
                    print 'deleted payment', m.group(1)
                except FailedRequest:
                    print 'FAILED deleting payment', m.group(1)
                continue

    with open(log_name, 'r') as log_file:
        for line in log_file:
            m = re.search('^created invoice (\d+)$', line.rstrip())
            if m:
                try:
                    client.invoice.delete(invoice_id=int(m.group(1)))
                    print 'deleted invoice', m.group(1)
                except FailedRequest:
                    print 'FAILED deleting invoice', m.group(1)
                continue
def main_program():
    api_caller = api.TokenClient(url, token)
    path = os.path.expanduser('~/Desktop/' + url + '_receipts/')
    receipts = []
    date = {}
    count = 1
    #Build a list of expense_ids
    expenses = list_all(api_caller.expense.list, 'expense')
    for expense in expenses:
        #Estabilsh the date in datetime format for an expense, accounting for exceptions
        datevar = get_datevar(expense.date)
        #Go through all expenses, check if they are within the date range and have a receipt.  If so, append to list.
        if expense.has_receipt == 1:
            if datecheck(datevar):
                receipts.append(expense.expense_id)
                #create a dictionary of ExpenseID:Date structure. Used for naming image files below.
                date[expense.expense_id] = str(expense.date)[0:10]

    #create a directory to dump the files, move into that directory
    ensure_dir(path)

    #capture receipt file
    for receipt_id in receipts:
        print count
        header, body = api_caller.receipt.get(expense_id=int(receipt_id))
        #check file type
        extension = get_file_type_extension(header)
        count = count + 1
        #write the image file to the current directory
        with open(
                ensure_file("%s-%s.%s" % (url, date[receipt_id], extension),
                            date[receipt_id], extension), 'wb') as f:
            f.write(body)
        if count % 50 == 0:
            time.sleep(1)
예제 #3
0
def get_client(debug=False):
    return api.TokenClient(app.config['FRESHBOOKS_URL'],
                           app.config['FRESHBOOKS_TOKEN'],
                           app.config['FRESHBOOKS_USER_AGENT'],
                           request_encoder=api.logging_request_encoder
                           if debug else api.default_request_encoder,
                           response_decoder=api.logging_response_decoder
                           if debug else api.default_response_decoder)
예제 #4
0
def main_program():
    api_caller = api.TokenClient(url, token)
    # get all the clients from our account
    all_clients = list_all(api_caller.client.list, 'client')
    client_name_list = []
    credit_list = []
    dict_test = {"Organization": "Balance"}
    
    #loop through each client
    for client in all_clients:
    	dict_test[client.organization]=client.credit
    
    print dict_test
예제 #5
0
def main():
    config = ConfigParser.RawConfigParser({'domain' : 'example.freshbooks.com', 
                                           'apitoken' : 'put your api token here'})
    if os.path.exists(INIFILE):
        config.read(INIFILE)
    else:
        sys.exit("unable to fine %s config file. aborting" % INIFILE)
    if config.has_section('General'):
        domain = config.get('General', 'domain')
        apitoken = config.get('General', 'apitoken')
    else:
        sys.exit('%s is missing the [General] section. aborting' % INIFILE)
    if domain == 'example.freshbooks.com' or apitoken == 'put your api token here':
        sys.exit('You must define "domain" and "apitoken" in the %s config file. aborting' % INIFILE)
    if not os.path.isdir('data'):
        os.mkdir('data')
    c = api.TokenClient(
        domain,
        apitoken,
        user_agent='freshbooks_export/1.0'
    )

    typelist = ['invoice',
                'client',
                'payment',
                'recurring',
                'item',
                'estimate']

    for typename in typelist:
        f = open('data/%ss.txt' % typename, 'w')
        f.write(process(getattr(c, typename), '%ss' % typename, typename))
        f.close()

    try:
        repo = git.Repo("data")
        assert repo.bare == False
    except git.exc.InvalidGitRepositoryError:
        repo = git.Repo.init("data")
        assert repo.bare == False
    repo.index.add(['%ss.txt' % typename for typename in typelist])
    if len(repo.heads) == 0:
        # this repo has no commits
        repo.index.commit("freshbooks_export detected a change. committing %s" % time.strftime('%Y-%m-%dT%H:%M:%S'))
    elif len(repo.head.commit.diff(None)) > 0:
        # something has changed in our working copy
        repo.index.commit("freshbooks_export detected a change. committing %s" % time.strftime('%Y-%m-%dT%H:%M:%S'))
예제 #6
0
    def check(self):
        client = api.TokenClient(shared.fresh_user,
                                 shared.fresh_key,
                                 user_agent='Nebri/1.0')

        now = datetime.now()

        invoice_response = client.invoice.list()

        invoice_names = []

        for invoice in invoice_response.invoices.invoice:
            if (invoice.status != 'paid' and float(str(invoice.amount)) > 3000
                    and (now - datetime.strptime(
                        invoice.date, '%Y-%m-%d %H:%M:%S')).days >= 3):
                invoice_names.append(invoice.invoice_id)

        if invoice_names:
            self.invoice_names = invoice_names
            return True

        return False
예제 #7
0
 def __init__(self):
     self.c = api.TokenClient(config.FRESHBOOKS_SITE_DOMAIN,
                              config.FRESHBOOKS_API_TOKEN,
                              user_agent='Freshbooks to Toggl Sync')
예제 #8
0
import random
from faker import Factory
from refreshbooks import api

##### GLOBALS ######
USERNAME = os.environ.get('FRESHBOOKS_USERNAME', 'YOUR FRESHBOOKS USERNAME')
API_TOKEN = os.environ.get('FRESHBOOKS_API_TOKEN',
                           'YOUR FRESHBOOKS v1.0 TOKEN')

NUMBER_OF_CLIENTS_TO_CREATE = 3
NUMBER_OF_INVOICES_TO_CREATE = 5
##### GLOBALS ######

##### SETTINGS ####
c = api.TokenClient('%s.freshbooks.com' % USERNAME,
                    API_TOKEN,
                    user_agent='Example/1.0')
faker = Factory.create()

##### SETTINGS ####


##### CREATE CLIENTS ####
def create_clients():
    global i, response
    for i in range(0, NUMBER_OF_CLIENTS_TO_CREATE):
        faker.name()
        response = c.client.create(client=dict(
            first_name=faker.first_name(),
            last_name=faker.last_name(),
            email=faker.email(),
예제 #9
0
def main(args):
    if len(args) != 4:
        print __doc__
        return

    csv_name, url, key, client_id = args

    if not os.path.isfile(csv_name):
        print 'Could not find csv', csv_name
        return

    if not re.search(r'^\w+\.freshbooks\.com$', url):
        print 'URL should be in the format something.freshbooks.com'
        return

    if not re.search(r'^[0-9a-fA-F]{10,}$', key):
        print 'Key invalid'
        return

    if not re.search(r'^[0-9a-fA-F]{10,}$', key):
        print 'Key invalid'
        return
    try:
        client_id = int(client_id)
    except ValueError:
        print 'client_id invalid'
        return

    invoices, payments = [], []

    # invoices_response = client.invoice.list() # <request method="invoice.list" />
    # for invoice in invoices_response.invoices.invoice:
    #     # print "Invoice %s total: %s" % (
    #     #     invoice.note,
    #     #     invoice.amount
    #     # )
    #     for c in invoice.iterchildren():
    #         print c.tag, c.text
    #     break

    # return

    with open(csv_name, 'r') as csv_file:

        reader = csv.DictReader(csv_file)
        for i, row in enumerate(reader):
            if i == 0:
                for field in CHECK_FIELDS:
                    if field not in row:
                        print 'CSV invalid, missing field', field
                        return

            # skip withdrawals
            if 'T_ACH_WITHDRAWAL_DESC' in row[FIELD_PAY_DESC]:
                continue

            amt = float(row[FIELD_AMT])

            # skip expenses
            if amt <= 0.0:
                continue

            invoices.append(
                dict(client_id=str(client_id),
                     date=parse_date(row[FIELD_DATE_INV]).strftime('%Y-%m-%d'),
                     lines=[
                         api.types.line(name='Elance Invoice %s' %
                                        row[FIELD_INV_NUM],
                                        unit_cost='%0.2f' % amt,
                                        quantity='1')
                     ]))
            payments.append(
                dict(date=parse_date(
                    row[FIELD_DATE_PAID]).strftime('%Y-%m-%d'),
                     amount='%0.2f' % amt,
                     type='Credit'))

    client = api.TokenClient(url, key, user_agent='elance2freshbooks/0.1')
    for invoice, payment in zip(invoices, payments):

        invoice_resp = client.invoice.create(invoice=invoice)
        print 'created invoice', invoice_resp.invoice_id

        payment['invoice_id'] = invoice_resp.invoice_id
        payment_resp = client.payment.create(payment=payment)
        print 'created payment', payment_resp.payment_id
예제 #10
0
__author__ = 'David Dworin'

from refreshbooks import api

c = api.TokenClient('YOUR_SITE_ADDRESS.freshbooks.com',
                    'YOUR_API_TOKEN',
                    user_agent='DavidsChaseExpenseFixer/1.0')

expenses = c.expense.list(page='100')
print "There are %s pages of expenses." % (expenses.expenses.attrib['pages'], )
for i in range(1, int(expenses.expenses.attrib['pages']) + 1):
    expenses = c.expense.list(page=str(i))
    for myexpense in expenses.expenses.expense:
        print "Expense(%s) Notes: %s Vendor: %s" % (
            myexpense.expense_id, str(
                myexpense.notes).strip(), myexpense.vendor)
        if (myexpense.vendor == ''):
            print "Fixing the Vendor on Expense %s" % (myexpense.expense_id)
            response = c.expense.update(
                expense=dict(expense_id=myexpense.expense_id,
                             vendor=str(myexpense.notes).strip()))

print "All Done!"
예제 #11
0
import inflect
from refreshbooks import api as refreshbooks

my_redmine_user_id = 22
noop = False

timezone = pytz.timezone("Australia/Brisbane")
inflector = inflect.engine()

redmine_url = os.environ["REDMINE_URL"]
redmine_key = os.environ["REDMINE_KEY"]
redmine_client = redmine.Redmine(redmine_url, key=redmine_key, version=1.4)

freshbooks_host = os.environ["FRESHBOOKS_HOST"]
freshbooks_key = os.environ["FRESHBOOKS_KEY"]
freshbooks_client = refreshbooks.TokenClient(freshbooks_host, freshbooks_key)

redmine_id_regex = re.compile("^Redmine ID: (\d+)$", re.MULTILINE)

project_lookup = dict()
task_lookup = dict()
time_entry_lookup = dict()


def freshbooks_items(item_name, **kwargs):
    '''Iterates over collection of items from `item_name` from all pages.'''
    collection = inflector.plural(item_name)
    page = 1
    num_pages = None
    while True:
        if num_pages and page == num_pages:
예제 #12
0
	def __init__(self, url, token):
		self.client = api.TokenClient(
			url,
			token,
			user_agent='%s/%s' % (APP_NAME, VERSION)
		)