Пример #1
0
def calculate_last_completed_fiscal_quarter(fiscal_year,
                                            as_of_date=current_fiscal_date()):
    """
    ENABLE_CARES_ACT_FEATURES TECH DEBT:  Make this work with new standardized, yet-to-be-named
    function.  There are currently several flavors flying around.  Waiting for one to land rather
    than creating another.

    Returns either the most recently completed fiscal quarter or None if it's too early in the
    fiscal year for the first quarter to be considered "completed".  Should always return None for
    future fiscal years.  as_of_date was intended for unit testing purposes, but who knows, maybe
    you'll find another use for it being the unquestionable genius that you are.
    """

    # Get the current fiscal year so that it can be compared against the FY in the request.
    day_difference = as_of_date - timedelta(days=SUBMISSION_WINDOW_DAYS)
    current_fiscal_date_adjusted = FiscalDateTime(day_difference.year,
                                                  day_difference.month,
                                                  day_difference.day)

    if fiscal_year == current_fiscal_date_adjusted.fiscal_year:
        current_fiscal_quarter = current_fiscal_date_adjusted.quarter
        # If it's currently the first quarter (or within SUBMISSION_WINDOW_DAYS days of the
        # first quarter), return None because it's too soon for there to be a completed quarter
        # for fiscal_year.
        if current_fiscal_quarter == 1:
            fiscal_quarter = None
        else:
            fiscal_quarter = current_fiscal_quarter - 1
    elif fiscal_year < current_fiscal_date_adjusted.fiscal_year:
        fiscal_quarter = 4
    else:
        # The future cannot have completed quarters unless you're into shady accounting.
        fiscal_quarter = None

    return fiscal_quarter
def calculate_last_completed_fiscal_quarter(fiscal_year,
                                            as_of_date=current_fiscal_date()):
    """
    Effectively a minimalistic implementation of generate_last_completed_fiscal_quarter.  Returns either
    the most recently completed fiscal quarter or None if it's too early in the fiscal year for the first
    quarter to be considered "completed".  Should always return None for future fiscal years.  as_of_date
    was intended for unit testing purposes, but who knows, maybe you'll find another use for it being the
    unquestionable genius that you are.
    """

    # Get the current fiscal year so that it can be compared against the FY in the request.
    day_difference = as_of_date - datetime.timedelta(
        days=SUBMISSION_WINDOW_DAYS)
    current_fiscal_date_adjusted = FiscalDateTime(day_difference.year,
                                                  day_difference.month,
                                                  day_difference.day)

    if fiscal_year == current_fiscal_date_adjusted.fiscal_year:
        current_fiscal_quarter = current_fiscal_date_adjusted.quarter
        # If it's currently the first quarter (or within SUBMISSION_WINDOW_DAYS days of the
        # first quarter), return None because it's too soon for there to be a completed quarter
        # for fiscal_year.
        if current_fiscal_quarter == 1:
            fiscal_quarter = None
        else:
            fiscal_quarter = current_fiscal_quarter - 1
    elif fiscal_year < current_fiscal_date_adjusted.fiscal_year:
        fiscal_quarter = 4
    else:
        # The future cannot have completed quarters unless you're into shady accounting.
        fiscal_quarter = None

    return fiscal_quarter
Пример #3
0
    def test_contains(self, a: FiscalQuarter, f: FiscalQuarter) -> None:
        assert a not in f
        assert f in f

        assert FiscalDateTime(2016, 8, 1, 0, 0, 0) in a
        assert datetime.datetime(2016, 8, 1, 0, 0, 0) in a
        assert FiscalDate(2016, 8, 1) in a
        assert datetime.date(2016, 8, 1) in a
Пример #4
0
def generate_last_completed_fiscal_quarter(fiscal_year, fiscal_quarter=None):
    """ Generate the most recently completed fiscal quarter """

    # Get the current fiscal year so that it can be compared against the FY in the request
    current_fiscal_date = FiscalDateTime.today()
    day_difference = current_fiscal_date - datetime.timedelta(days=45)
    current_fiscal_date_adjusted = FiscalDateTime(day_difference.year,
                                                  day_difference.month,
                                                  day_difference.day)

    # Attempting to get data for current fiscal year (minus 45 days)
    if fiscal_year == current_fiscal_date_adjusted.fiscal_year:
        current_fiscal_quarter = current_fiscal_date_adjusted.quarter
        # If a fiscal quarter has been requested
        if fiscal_quarter:
            # If the fiscal quarter requested is not yet completed (or within 45 days of being completed), error out
            if current_fiscal_quarter <= fiscal_quarter:
                raise InvalidParameterException(
                    "Requested fiscal year and quarter must have been completed over 45 "
                    "days prior to the current date.")
        # If no fiscal quarter has been requested
        else:
            # If it's currently the first quarter (or within 45 days of the first quarter), throw an error
            if current_fiscal_quarter == 1:
                raise InvalidParameterException(
                    "Cannot obtain data for current fiscal year. At least one quarter must "
                    "be completed for over 45 days.")
            # roll back to the last completed fiscal quarter if it's any other quarter
            else:
                fiscal_quarter = current_fiscal_quarter - 1
    # Attempting to get data for any fiscal year before the current one (minus 45 days)
    elif fiscal_year < current_fiscal_date_adjusted.fiscal_year:
        # If no fiscal quarter has been requested, give the fourth quarter of the year requested
        if not fiscal_quarter:
            fiscal_quarter = 4
    else:
        raise InvalidParameterException(
            "Cannot obtain data for future fiscal years or fiscal years that have not "
            "been active for over 45 days.")

    # get the fiscal date
    fiscal_date = FiscalQuarter(fiscal_year, fiscal_quarter).end
    fiscal_date = datetime.datetime.strftime(fiscal_date, '%Y-%m-%d')

    return fiscal_date, fiscal_quarter
    def _parse_and_validate_request(self, request_dict):
        """ Validate the Request object includes the required fields """
        fy_range = [str(i) for i in range(2001, FiscalDateTime.today().year + 1)]
        last_fy = str(SubmissionAttributes.last_certified_fy()) or str(FiscalDateTime.today().year)
        request_settings = [
            {
                "key": "sort",
                "name": "sort",
                "type": "object",
                "optional": True,
                "object_keys": {
                    "field": {
                        "type": "enum",
                        "enum_values": ["budgetary_resources", "managing_agency", "account_name", "account_number"],
                        "optional": True,
                        "default": "budgetary_resources",
                    },
                    "direction": {"type": "enum", "enum_values": ["asc", "desc"], "optional": True, "default": "asc"},
                },
                "default": {"field": "budgetary_resources", "direction": "asc"},
            },
            {"key": "page", "name": "page", "type": "integer", "default": 1, "min": 1, "optional": True},
            {"key": "limit", "name": "limit", "type": "integer", "default": 10, "min": 1, "max": 100, "optional": True},
            {
                "key": "filters",
                "name": "filters",
                "type": "object",
                "optional": True,
                "object_keys": {
                    "agency_identifier": {
                        "name": "agency_identifier",
                        "type": "text",
                        "text_type": "search",
                        "optional": True,
                    },
                    "fy": {"type": "enum", "enum_values": fy_range, "optional": True, "default": last_fy},
                },
                "default": {"fy": last_fy},
            },
            {"key": "keyword", "name": "keyword", "type": "text", "text_type": "search", "optional": True},
        ]

        validated_request_data = TinyShield(request_settings).block(request_dict)
        validated_request_data["filters"]["fy"] = validated_request_data["filters"].get("fy", last_fy)
        return validated_request_data
Пример #6
0
    def test_start(self, a: FiscalDay, c: FiscalDay) -> None:
        assert a.start == FiscalYear(a.fiscal_year).start
        assert c.start == FiscalDateTime(2016, 9, 30, 0, 0, 0)

        with fiscalyear.fiscal_calendar(*US_FEDERAL):
            assert a.start == datetime.datetime(2015, 10, 1, 0, 0, 0)

        with fiscalyear.fiscal_calendar(*UK_PERSONAL):
            assert a.start == datetime.datetime(2016, 4, 6, 0, 0, 0)
Пример #7
0
    def test_contains(self, a: FiscalMonth, b: FiscalMonth,
                      d: FiscalQuarter) -> None:
        assert b in b
        assert a not in d
        assert b in b

        assert FiscalDateTime(2015, 10, 1, 0, 0, 0) in a
        assert datetime.datetime(2015, 10, 1, 0, 0, 0) in a
        assert FiscalDate(2015, 10, 1) in a
        assert datetime.date(2015, 10, 1) in a
Пример #8
0
    def test_contains(self, a: FiscalYear, b: FiscalYear, c: FiscalYear,
                      d: FiscalYear) -> None:
        assert b in b
        assert c not in a
        assert c in b
        assert d in b

        assert FiscalDateTime(2016, 1, 1, 0, 0, 0) in a
        assert datetime.datetime(2016, 1, 1, 0, 0, 0) in a
        assert FiscalDate(2016, 1, 1) in a
        assert datetime.date(2016, 1, 1) in a
    def _parse_and_validate_request(self, request_dict):
        """ Validate the Request object includes the required fields """
        fy_range = [str(i) for i in range(2001, FiscalDateTime.today().year + 1)]
        last_fy = str(SubmissionAttributes.last_certified_fy()) or str(FiscalDateTime.today().year)
        request_settings = [
            {'key': 'sort', 'name': 'sort', 'type': 'object', 'optional': True, 'object_keys': {
                'field': {'type': 'enum', 'enum_values': ['budgetary_resources', 'managing_agency', 'account_name',
                                                          'account_number'],
                          'optional': True, 'default': 'budgetary_resources'},
                'direction': {'type': 'enum', 'enum_values': ['asc', 'desc'], 'optional': True, 'default': 'asc'},
            }, 'default': {'field': 'budgetary_resources', 'direction': 'asc'}},
            {'key': 'page', 'name': 'page', 'type': 'integer', 'default': 1, 'min': 1, 'optional': True},
            {'key': 'limit', 'name': 'limit', 'type': 'integer', 'default': 10, 'min': 1, 'max': 100, 'optional': True},
            {'key': 'filters', 'name': 'filters', 'type': 'object', 'optional': True, 'object_keys': {
                'fy': {'type': 'enum', 'enum_values': fy_range, 'optional': True, 'default': last_fy},
            }, 'default': {'fy': last_fy}},
            {'key': 'keyword', 'name': 'keyword', 'type': 'text', 'text_type': 'search', 'optional': True}
        ]

        validated_request_data = TinyShield(request_settings).block(request_dict)
        return validated_request_data
def fiscal_year_check(sheet: Worksheet, fisc_year_start_idx: int, row_idx: int,
                      prev_date: datetime, new_date: datetime, summaries: list,
                      force_ytd_summary: bool) -> int:
    new_fiscal_year = FiscalDateTime(new_date.year, new_date.month,
                                     new_date.day).fiscal_year
    prev_fiscal_year = FiscalDateTime(prev_date.year, prev_date.month,
                                      prev_date.day).fiscal_year

    if (new_fiscal_year > prev_fiscal_year) or force_ytd_summary:

        sheet.cell(row_idx, COLUMNS["Date"]).value = "END OF FINANCIAL YEAR " + \
            str(prev_fiscal_year-1) + "-" + str(prev_fiscal_year)

        for column_name in ["Capital gain <= 1 year", "Capital gain > 1 year"]:
            col_letter = cell.get_column_letter(COLUMNS[column_name])
            formula = "=sum(" + col_letter + str(fisc_year_start_idx) + ":" \
                + col_letter + str(row_idx - 1) + ")"
            sheet.cell(row_idx, COLUMNS[column_name]).value = formula

        net_capital_gain_formula = "=" + cell.get_column_letter(COLUMNS["Capital gain <= 1 year"]) + str(row_idx) \
            + "+(" + cell.get_column_letter(COLUMNS["Capital gain > 1 year"]) + str(row_idx) +"/2)"
        sheet.cell(
            row_idx,
            COLUMNS["Net capital gain"]).value = net_capital_gain_formula

        for column_name in COLUMNS:
            sheet.cell(row_idx, COLUMNS[column_name]).style = "Accent1"

        # summaries.append({
        #     "fiscal_year_end": prev_fiscal_year,
        #     "brokerage_ref": col_letter + str(row_idx),
        #     "capital_gain_ref": cap_gain_letter + str(row_idx),
        #     "is_ytd_only": force_ytd_summary
        #     })

        return row_idx + 1, row_idx + 1
    return row_idx, fisc_year_start_idx
def generate_last_completed_fiscal_quarter(fiscal_year, fiscal_quarter=None):
    """ Generate the most recently completed fiscal quarter """

    # Get the current fiscal year so that it can be compared against the FY in the request
    current_fiscal_date = FiscalDateTime.today()
    day_difference = current_fiscal_date - datetime.timedelta(days=45)
    current_fiscal_date_adjusted = FiscalDateTime(day_difference.year, day_difference.month, day_difference.day)

    # Attempting to get data for current fiscal year (minus 45 days)
    if fiscal_year == current_fiscal_date_adjusted.fiscal_year:
        current_fiscal_quarter = current_fiscal_date_adjusted.quarter
        # If a fiscal quarter has been requested
        if fiscal_quarter:
            # If the fiscal quarter requested is not yet completed (or within 45 days of being completed), error out
            if current_fiscal_quarter <= fiscal_quarter:
                raise InvalidParameterException("Requested fiscal year and quarter must have been completed over 45 "
                                                "days prior to the current date.")
        # If no fiscal quarter has been requested
        else:
            # If it's currently the first quarter (or within 45 days of the first quarter), throw an error
            if current_fiscal_quarter == 1:
                raise InvalidParameterException("Cannot obtain data for current fiscal year. At least one quarter must "
                                                "be completed for over 45 days.")
            # roll back to the last completed fiscal quarter if it's any other quarter
            else:
                fiscal_quarter = current_fiscal_quarter - 1
    # Attempting to get data for any fiscal year before the current one (minus 45 days)
    elif fiscal_year < current_fiscal_date_adjusted.fiscal_year:
        # If no fiscal quarter has been requested, give the fourth quarter of the year requested
        if not fiscal_quarter:
            fiscal_quarter = 4
    else:
        raise InvalidParameterException("Cannot obtain data for future fiscal years or fiscal years that have not "
                                        "been active for over 45 days.")

    # get the fiscal date
    fiscal_date = FiscalQuarter(fiscal_year, fiscal_quarter).end
    fiscal_date = datetime.datetime.strftime(fiscal_date, '%Y-%m-%d')

    return fiscal_date, fiscal_quarter
Пример #12
0
from botocore.exceptions import ClientError
from googleapiclient.errors import HttpError
from pydrive.auth import GoogleAuth, AuthError
from pydrive.drive import GoogleDrive
from pydrive.files import ApiRequestError, FileNotUploadedError
from pydrive.settings import InvalidConfigError

LOGGER = logging.getLogger()
LOGGER.setLevel(logging.WARNING)

GDRIVE_SNS_TOPIC_ARN = env.get('GDRIVE_SNS_TOPIC_ARN')
SNS = boto3.client('sns')
DDB = boto3.resource('dynamodb', region_name='us-east-1')

fiscalyear.START_MONTH = 4
FISCAL_YEAR = FiscalDateTime.now()


class WorthRetryingException(Exception):
    '''Base error class for exceptions worth retrying'''


class GDriveAuthError(WorthRetryingException):
    '''General authentication error'''
    # Worth retrying until we discover which errors are impossible to rectify


class TemporaryGlitch(WorthRetryingException):
    '''Idempotent Glitch error class'''

Пример #13
0
 def a(self) -> FiscalDateTime:
     return FiscalDateTime(2017, 1, 1, 0, 0, 0)
Пример #14
0
                "ID": "<your PayPal client ID here>",
                "Secret": "<your PayPal secret here>"
            }))

    print(
        "No PayPal SDK credentials available. Please add credentials details to {cred_file}",
        file=sys.stderr)

else:
    # Creating an environment
    environment = LiveEnvironment(client_id=CREDS["ID"],
                                  client_secret=CREDS["Secret"])
    client = PayPalHttpClient(environment)

    setup_fiscal_calendar(start_month=7)
    dt_from = FiscalYear(FiscalDateTime.now().fiscal_year).start.astimezone(
        tz.tzlocal())
    dt_to = FiscalDateTime.now().astimezone(tz.tzlocal())

    request = TransactionRequest(dt_from, dt_to)

    transactions = request.execute(client)

    header = [
        "Date", "Transaction Commodity", "Deposit", "Price", "Quantity",
        "Balance", "Num", "Description", "Notes", "Partner", "Transfer Account"
    ]
    print(",".join(header))

    for t in transactions:  #response.result.transaction_details:
        id = t.transaction_info.transaction_id  # @ReservedAssignment
Пример #15
0
 def b(self) -> FiscalDateTime:
     return FiscalDateTime(2017, 11, 15, 12, 4, 30)
Пример #16
0
def current_fiscal_date() -> FiscalDateTime:
    """FiscalDateTime.today() returns calendar date! Add 3 months to convert to fiscal"""
    return FiscalDateTime.today() + relativedelta(months=3)
Пример #17
0
def current_fiscal_date() -> FiscalDateTime:
    return FiscalDateTime.today()