Example #1
0
    def Run(self,
            start=0,
            end=-1,
            browser=False,
            date=Dates.empty(),
            lookBack=1):
        self.userDate = date
        self.beginDate = Dates.previousMonth(self.userDate, lookBack)
        if browser:
            try:
                self.UI.OpenBrowser(Configuration().getBrowserTitle(),
                                    Configuration().getBrowserPath())
            except Exception as e:
                raise Exception("OpenBrowser: " + str(e))

        if end == -1:
            end = len(self.processMap)
        else:
            self.shouldClose = False

        for i in range(start, end):
            func, error = self.processMap[i]
            try:
                func()
            except Exception as e:
                raise Exception(error + ": " + str(e))

        if not self.shouldClose:
            return
        if browser:
            try:
                self.UI.CloseBrowser()
            except Exception as e:
                raise Exception("CloseBrowser: " + str(e))
Example #2
0
    def Calculate(self, monthTransactions):

        self.currentTransactions = monthTransactions
        income = self.sumIncome()
        expenses = self.sumExpenses()
        spending = self.processTransactions()
        remaining = income - expenses - spending["total"]
        forcast = income - expenses - spending["projected"]

        topSpends = self.GetSortedTransactions(max_count=6)
        date = Dates(self.currentTransactions[0]["date"].month,
                     self.currentTransactions[0]["date"].year)

        result = {
            "income": income,
            "spending": spending,
            "topSpends": topSpends,
            "expenses": expenses,
            "forecast": forcast,
            "threshold": self.budgetData["savingsThreshold"],
            "remaining": remaining,
            "date": date
        }

        #if this is a past budget, lets write out the data
        if not date.isCurrentMonthAndYear():
            self.history.Store(spending['total'], remaining, date)
        return result
Example #3
0
    def build_timecard_block():
        """Builds a time card block via user-supplied data"""
        in_date = input("Enter the date (mm/dd): ")
        out_date = Dates.build_date(in_date)

        clock_in = input("What time did you clock in? ")
        in_t = Dates.build_time(clock_in, out_date.today().month, out_date.today().day)

        clock_out = input("What time did you clock out? ")
        out_t = Dates.build_time(clock_out, out_date.today().month, out_date.today().day)

        return TimeCardBlock(out_date, in_t, out_t)
Example #4
0
 def Run(self, simulate=False, date=Dates.empty(), lookBack=1):
     os.makedirs(os.getcwd()+'\\'+ self.name, exist_ok=True)
     if self.bankWeb == None or self.bankParser == None:
         raise Exception("Bank or parser not defined")
     if not simulate:
         self.bankWeb.Run(date=date, lookBack=lookBack)
     self.bankParser.Run(date=date)
Example #5
0
def get_datetime():
    """Get and Build out date time string"""
    local_tz = pytz.timezone('US/Central')
    # set now as current time
    now = datetime.now()
    now = now.replace(tzinfo=pytz.utc).astimezone(local_tz)
    # set and format hour month and period (am/pm)
    hour = datetime.strftime(now, '%-I')
    month = datetime.strftime(now, '%B')
    period = datetime.strftime(now, '%p')

    if period == 'AM':
        period = 'a m'
    else:
        pass

    minute = now.minute
    # uses dates dict in dates file to change int day to ordinal
    day = Dates.get(now.day)

    if minute == 0:
        minute = 'o clock'
    elif minute < 10:
        minute = 'o {}'.format(minute)
    else:
        pass

    # builds time string
    time_str = 'Today is {} {}. The current time is {} {} {}. '.format(
        month, day, hour, minute, period)

    return str(time_str)
Example #6
0
 def __init__(self, output=None, date=Dates.empty()):
     self.date = date
     self.budgetData = Configuration().getBudget()
     self.transactions = []
     self.outputFile = output
     self.outFileCount = 0
     self.history = History()
Example #7
0
 def Run(self, date=Dates.empty()):
     self.userDate = date
     try:
         self.transactions = self.processHTML()
         if self.transactions == None:
             raise
     except Exception as e:
         raise Exception("Could not read HTML data: " + str(e))
    def get(self):
		userName = None
		if self.request.cookies.get('our_token'):    #the cookie that should contain the access token!
			userName = Employee.checkToken(self.request.cookies.get('our_token'))

		
		template_variables = {}
		
		if userName:
			template_variables['userName'] = userName.userName
			dates =  Dates(template_variables)
			template_variables = dates.nextTwoWeeks()
				
	

			html = template.render("web/templates/ConstrainsInputPage.html", template_variables)
			self.response.write(html)
Example #9
0
 def firstTime(self, **kwargs):
     with open('Config\\configuration.json', mode='r') as f:
         jData = f.read()
     self.data = json.loads(jData)
     if "settings" not in self.data:
         self.addSettings({
             "lookBackMonths": 1,
             "currentDate": Dates.empty()
         })
     else:
         if "lookBackMonths" not in self.data["settings"]:
             self.addSettings({"lookBackMonths": 1})
         if "currentDate" not in self.data["settings"]:
             self.addSettings({"currentDate": Dates.empty()})
         else:
             date = Dates.string(self.data["settings"]["currentDate"])
             self.addSettings({"currentDate": date})
 def Run(self, simulate=False, date=Dates.empty(), lookBack=1):
     if not simulate:
         GUI().OpenBrowser(Configuration().getBrowserTitle(),
                           Configuration().getBrowserPath())
     for bank in self.banks:
         bank.Run(simulate=simulate, date=date, lookBack=lookBack)
         self.transactions.extend(bank.GetTransactions())
     if not simulate:
         GUI().CloseBrowser()
Example #11
0
    def calculate_hours_worked():
        """Calculates the number of hours (and minutes) worked so far"""
        time_worked = None
        for b in TimeCard.timecard_blocks:
            if time_worked is None:
                time_worked = b.get_delta()
            else:
                time_worked += b.get_delta()

        # Use method to convert time_worked to desired output format
        hours_worked = Dates.convert_timedelta(time_worked)
        print('\nHours worked (Rounded to nearest six minutes):')
        print(hours_worked)

        remaining = timedelta(hours=TimeCard.min_hours) - time_worked
        hours_left = Dates.convert_timedelta(remaining)
        hl_max = Dates.convert_timedelta((remaining + timedelta(minutes=3)))
        print('Hours Remaining (Rounded to nearest six minutes):')
        print(hours_left, 'to', hl_max)

        TimeCard.calculate_clockout_time(remaining)
Example #12
0
    def Run(self, transactions):
        self.SortTransactions(transactions)

        results = []
        if len(self.transactions) == 0:
            return
        if len(self.transactions[0]) == 0:
            return
        earliestDate = Dates(self.transactions[0][0]["date"].month,
                             self.transactions[0][0]["date"].year)
        months = Dates.monthDifference(self.date, earliestDate)

        for index in range(0, len(months)):
            if len(self.transactions) < index + 1:
                trans = [{
                    "date": months[index].getDate(),
                    "amount": 0,
                    "empty": True
                }]
            else:
                trans = self.transactions[index]
            currentDate = months[index]
            if currentDate > self.date:
                break
            val = self.Calculate(trans)
            if self.history.needsPosted(
                    currentDate) or currentDate == self.date:
                results.append(val)

        # for trans in self.transactions:
        #     if (len(trans) == 0):
        #         continue
        #     currentDate = Dates(trans[0]["date"].month, trans[0]["date"].year)
        #     if currentDate > self.date:
        #         break
        #     val = self.Calculate(trans)
        #     if self.history.needsPosted(currentDate) or currentDate == self.date:
        #        results.append(val)
        return results
Example #13
0
    def tick(self,
             simulate=False,
             date=Dates.empty(),
             lookBack=Configuration().getSettings()["lookBackMonths"]):
        print("Doing tick")
        processor = TransactionProcessor()
        try:
            processor.Run(simulate=simulate, date=date, lookBack=lookBack)
        except:
            self.errorLog.append(
                "----------------------------------------------------")
            self.errorLog.extend(traceback.format_exc().splitlines())
            self.errorLog.append(
                "----------------------------------------------------")
            for l in self.errorLog:
                print(l)
            return False

        budget = Budget(date=date, output="C:\\tmp\\trans.csv")
        results = budget.Run(processor.GetTransactions())
        Email().Run(results)
        return True
Example #14
0
    def processTransactions(self):
        total = 0
        if self.outputFile != None:
            base = os.path.splitext(self.outputFile)[0]
            base = base + '-' + str(self.outFileCount) + os.path.splitext(
                self.outputFile)[1]
            self.outFileCount += 1
            f = open(base, mode="w")
            t = sorted(self.currentTransactions, key=lambda x: x["amount"])
        else:
            t = self.currentTransactions
        for trans in t:
            if "empty" in trans:
                continue
            if self.outputFile != None:
                f.write('"{}", {}\n'.format(trans["description"],
                                            trans["amount"]))
            if not self.ignored(trans["description"]):
                total += trans["amount"]
        if self.outputFile != None:
            f.close()

        #is this month over?
        now = Dates.empty()
        then = self.currentTransactions[0]["date"]
        oldDate = Dates(then.month, then.year)
        days = oldDate.pastDays() + oldDate.remainingDays()
        if (now > Dates(then.month, then.year)):
            average = total / days
            projection = total
        else:  #we are working with an incomplete month, use history
            average = total / self.date.pastDays()
            dailyProjection = self.history.calculateWeightedAverage(
                average, self.date)
            projection = dailyProjection * self.date.remainingDays() + total

        result = {
            "total": total,
            "dailyAverage": average,
            "projected": projection
        }
        return result
Example #15
0
 def indexOf(self, date):
     for i in range(0, len(self.data)):
         if Dates.string(self.data[i]['date']) == date:
             return i
     return -1
Example #16
0
cmdLineParser.add_argument("-p",
                           "--port",
                           action="store",
                           type=int,
                           dest="port",
                           default=7497,
                           help="The TCP port to use")
args = cmdLineParser.parse_args()
print("Using args", args)

# IB allows a max of 30 requests / 10 minutes.
# If necessary, we wait for the time here
max_request_per_ten_minutes = 29

# NY Stock Exchange operates between 9:30 AM and 4:00 PM
dates = Dates()
day = '2020-07-18'
initial_date = day + 'T09:33'
final_date = day + 'T16:03'
frequency = '3T'
start_hour = '9:31'
final_hour = '16:00'
dates_list = dates.obtain_dates(initial_date, final_date, frequency,
                                start_hour, final_hour)
print(dates_list)
print(len(dates_list))
# exit()

app = IBapi()
app.connect("127.0.0.1", args.port, 0)
Example #17
0
from Document import Document
from Phones import Phones
from Dates import Dates
from Cep_access import AddressSearch
import requests

cpf = Document.generate_document("01234567890")
print(cpf)

cnpj = Document.generate_document("33969298000100")
print(cnpj)

phone = Phones(554988423605)
print(phone)

date = Dates()
print(date.week_day())
print(date.formated_create_moment)
print(date.create_time())

cep = AddressSearch("89567026")
print(cep)
bairro, cidade, uf = cep.get_via_cep()
print(bairro, cidade, uf)
Example #18
0
 def Run(self, data, date=Dates.empty()):
     self.date = date
     for item in data:
         self.processMonth(item)
     self.history.writeData()
Example #19
0
 def isValid(self, dateStr):
     if Dates.string(dateStr) > Dates.empty():
         return False
     return True
Example #20
0
 def get_delta(self):
     """Calculates the timedelta of the time card block"""
     end_rounded = Dates.round_time(self.end_time)
     start_rounded = Dates.round_time(self.start_time)
     return end_rounded - start_rounded
Example #21
0
from Dates import Dates

#creazione oggetto data
c = Dates.now()
d = Dates(2011,1,3)

#Print date in default mode
print "date object: %s" % (d)

#Convert date to string
print "date ISO format and time HHMM 24h: %s" % (c.format('ISO',"HM"))
print "date ISO format: %s" % (c.format_date('ISO'))
print "time HHMM 24h format: %s" % (c.format_time('HM'))
print "date DMY format and time HHMM 12h: %s" % (c.format('DMY',"hms"))
print "date DMY format and time HHMM 24h: %s" % (c.format('DMY',"HMS"))

#Convert string to date and print
print "date ISO format: %s" % (d.convert_date('2011-01-03','ISO').format_date('ISO'))
#Convert string to date, assign to a variable, then print it
e = d.convert('2013-12-31 03:43:01 PM','ISO',"hms")
print "date MDY format and time HHMMSS 24h: %s" % (e.format('MDY',"HMS"))

#short and full month name in current language
print "short month name (system lang): %s" % (c.month_name())
print "full month name (system lang): %s" % (c.month_name(short=False))

#short and full dqy name in current language
print "short month name (english): %s" % (e.weekday_name(short=True,locate='en_US'))
print "full month name (russian): %s" % (e.weekday_name(short=False,locate='ru_RU.UTF8'))
print "full month name (chinese): %s" % (e.weekday_name(short=False,locate='zh_CN.utf8'))