Example #1
0
 def _set_dates(self, filing):
     # Filing Date
     filing_datetime = LegislationDatetime.as_legislation_timezone(self._filing.filing_date)
     hour = filing_datetime.strftime('%I').lstrip('0')
     filing['filing_date_time'] = filing_datetime.strftime(f'%B %-d, %Y at {hour}:%M %p Pacific Time')
     # Effective Date
     effective_date = filing_datetime if self._filing.effective_date is None \
         else LegislationDatetime.as_legislation_timezone(self._filing.effective_date)
     effective_hour = effective_date.strftime('%I').lstrip('0')
     filing['effective_date_time'] = effective_date.strftime(f'%B %-d, %Y at {effective_hour}:%M %p Pacific Time')
     filing['effective_date'] = effective_date.strftime('%B %-d, %Y')
     # Recognition Date
     if self._business:
         recognition_datetime = LegislationDatetime.as_legislation_timezone(self._business.founding_date)
         recognition_hour = recognition_datetime.strftime('%I').lstrip('0')
         filing['recognition_date_time'] = \
             recognition_datetime.strftime(f'%B %-d, %Y at {recognition_hour}:%M %p Pacific Time')
     # For Annual Report - Set AGM date as the effective date
     if self._filing.filing_type == 'annualReport':
         agm_date_str = filing.get('annualReport', {}).get('annualGeneralMeetingDate', None)
         if agm_date_str:
             agm_date = datetime.fromisoformat(agm_date_str)
             filing['agm_date'] = agm_date.strftime('%B %-d, %Y')
             # for AR, the effective date is the AGM date
             filing['effective_date'] = agm_date.strftime('%B %-d, %Y')
         else:
             filing['agm_date'] = 'No AGM'
     if filing.get('correction'):
         original_filing = Filing.find_by_id(filing.get('correction').get('correctedFilingId'))
         original_filing_datetime = LegislationDatetime.as_legislation_timezone(original_filing.filing_date)
         original_filing_hour = original_filing_datetime.strftime('%I').lstrip('0')
         filing['original_filing_date_time'] = original_filing_datetime. \
             strftime(f'%B %-d, %Y at {original_filing_hour}:%M %p Pacific Time')
Example #2
0
def get_filing_info(filing_id: str) -> (Filing, dict, dict, str, str):
    """Get filing info for the email."""
    filing = Filing.find_by_id(filing_id)
    business = (filing.json)['filing']['business']

    filing_date = datetime.fromisoformat(filing.filing_date.isoformat())
    leg_tmz_filing_date = LegislationDatetime.as_legislation_timezone(filing_date)
    hour = leg_tmz_filing_date.strftime('%I').lstrip('0')
    leg_tmz_filing_date = leg_tmz_filing_date.strftime(f'%B %d, %Y {hour}:%M %p Pacific Time')

    effective_date = datetime.fromisoformat(filing.effective_date.isoformat())
    leg_tmz_effective_date = LegislationDatetime.as_legislation_timezone(effective_date)
    hour = leg_tmz_effective_date.strftime('%I').lstrip('0')
    leg_tmz_effective_date = leg_tmz_effective_date.strftime(f'%B %d, %Y {hour}:%M %p Pacific Time')

    return filing, business, leg_tmz_filing_date, leg_tmz_effective_date
def validate_effective_date(business: Business, cod: Dict) -> List:
    """Return an error or warning message based on the effective date validation rules.

    Rules: (text from the BA rules document)
        - The effective date of change cannot be in the future.
        - The effective date cannot be a date prior to their Incorporation Date.
        - The effective date of change cannot be a date that is farther in the past
            than a previous COD filing (standalone or AR).
        - The effective date can be the same effective date as another COD filing
            (standalone or AR). If this is the case:
        - COD filing that was filed most recently is the most current director information.
    """
    msg = []

    # get effective datetime string from filing
    try:
        effective_datetime_str = cod['filing']['header']['effectiveDate']
    except KeyError:
        return {'error': babel('No effective date provided.')}

    # convert string to datetime
    try:
        effective_datetime_utc = datetime.fromisoformat(effective_datetime_str)
    except ValueError:
        return {'error': babel('Invalid ISO format for effective date.')}

    # check if effective datetime is in the future
    if effective_datetime_utc > datetime.utcnow():
        msg.append({'error': babel('Filing cannot have a future effective date.')})

    # convert to legislation timezone and then get date only
    effective_date_leg = LegislationDatetime.as_legislation_timezone(effective_datetime_utc).date()

    # check if effective date is before their incorporation date
    founding_date_leg = LegislationDatetime.as_legislation_timezone(business.founding_date).date()
    if effective_date_leg < founding_date_leg:
        msg.append({'error': babel('Effective date cannot be before businesses founding date.')})

    # check if effective date is before their most recent COD or AR date
    last_cod_filing = Filing.get_most_recent_legal_filing(business.id,
                                                          Filing.FILINGS['changeOfDirectors']['name'])
    if last_cod_filing:
        last_cod_date_leg = LegislationDatetime.as_legislation_timezone(last_cod_filing.effective_date).date()
        if effective_date_leg < last_cod_date_leg:
            msg.append({'error': babel('Effective date cannot be before another Change of Director filing.')})

    return msg
Example #4
0
def as_effective_date(date_time: datetime) -> datetime:
    """Convert date_time to an effective date with 0 time in the legislation timezone, same as the UI does."""
    # 1. convert to legislation datetime
    # 2. zero out the time
    # 3. convert back to a UTC datetime
    date_time = LegislationDatetime.as_legislation_timezone(date_time)
    date_time = date_time.replace(hour=0, minute=0, second=0, microsecond=0)
    return LegislationDatetime.as_utc_timezone(date_time)
Example #5
0
 def _populate_business_info_to_filing(filing: Filing, business: Business):
     founding_datetime = LegislationDatetime.as_legislation_timezone(
         business.founding_date)
     hour = founding_datetime.strftime('%I')
     business_json = business.json()
     business_json['formatted_founding_date_time'] = \
         founding_datetime.strftime(f'%B %-d, %Y at {hour}:%M %p Pacific Time')
     business_json['formatted_founding_date'] = founding_datetime.strftime(
         '%B %-d, %Y')
     filing.filing_json['filing']['business'] = business_json
     filing.filing_json['filing']['header']['filingId'] = filing.id
Example #6
0
 def _populate_business_info_to_filing(filing: Filing, business: Business):
     founding_datetime = LegislationDatetime.as_legislation_timezone(business.founding_date)
     hour = founding_datetime.strftime('%I')
     if filing.transaction_id:
         business_json = VersionedBusinessDetailsService.get_business_revision(filing.transaction_id, business)
     else:
         business_json = business.json()
     business_json['formatted_founding_date_time'] = \
         founding_datetime.strftime(f'%B %-d, %Y at {hour}:%M %p Pacific Time')
     business_json['formatted_founding_date'] = founding_datetime.strftime('%B %-d, %Y')
     filing.filing_json['filing']['business'] = business_json
     filing.filing_json['filing']['header']['filingId'] = filing.id
def _get_receipt(business: Business, filing: Filing, token):
    """Get the receipt for the filing."""
    if filing.status not in (
            Filing.Status.PAID,
            Filing.Status.COMPLETED,
            Filing.Status.CORRECTED,
    ):
        return {}, HTTPStatus.BAD_REQUEST

    effective_date = None
    if filing.storage.effective_date.date() != filing.storage.filing_date.date(
    ):
        effective_date = (LegislationDatetime.as_legislation_timezone(
            filing.storage.effective_date).strftime(OUTPUT_DATE_FORMAT))

    headers = {'Authorization': 'Bearer ' + token}

    url = f'{current_app.config.get("PAYMENT_SVC_URL")}/{filing.storage.payment_token}/receipts'
    receipt = requests.post(
        url,
        json={
            'corpName':
            business.legal_name if business else filing.storage.temp_reg,
            'filingDateTime': (LegislationDatetime.as_legislation_timezone(
                filing.storage.filing_date).strftime(OUTPUT_DATE_FORMAT)),
            'effectiveDateTime':
            effective_date if effective_date else '',
            'filingIdentifier':
            str(filing.id),
            'businessNumber':
            business.tax_id if business and business.tax_id else ''
        },
        headers=headers)

    if receipt.status_code != HTTPStatus.CREATED:
        current_app.logger.error('Failed to get receipt pdf for filing: %s',
                                 filing.id)

    return receipt.content, receipt.status_code
Example #8
0
 def _format_incorporation_data(self, filing, report_type):
     filing['header']['reportType'] = report_type
     filing['header']['filingId'] = self._filing.id
     filing_datetime = LegislationDatetime.as_legislation_timezone(
         self._filing.filing_date)
     effective_date_time = LegislationDatetime.as_legislation_timezone(
         self._filing.effective_date)
     effective_hour = effective_date_time.strftime('%I')
     filing_hour = filing_datetime.strftime('%I')
     filing['header']['effective_date_time'] = \
         effective_date_time.strftime(f'%B %-d, %Y at {effective_hour}:%M %p Pacific Time')
     filing['header']['filing_date_time'] = \
         filing_datetime.strftime(f'%B %-d, %Y at {filing_hour}:%M %p Pacific Time')
     filing['filing_date_time'] = filing_datetime.strftime(
         f'%B %d, %Y {filing_hour}:%M %p Pacific Time')
     self._format_address(filing['incorporationApplication']['offices']
                          ['registeredOffice']['deliveryAddress'])
     self._format_address(filing['incorporationApplication']['offices']
                          ['registeredOffice']['mailingAddress'])
     self._format_address(filing['incorporationApplication']['offices']
                          ['recordsOffice']['deliveryAddress'])
     self._format_address(filing['incorporationApplication']['offices']
                          ['recordsOffice']['mailingAddress'])
     self._format_directors(filing['incorporationApplication']['parties'])
def test_validate_cod_basic(session, test_name, now, delivery_region_1,
                            delivery_country_1, delivery_region_2,
                            delivery_country_2, expected_code, expected_msg):  # pylint: disable=too-many-arguments
    """Assert that a basic COD can be validated."""
    # setup
    identifier = 'CP1234567'
    founding_date = now - datedelta.YEAR
    business = Business(identifier=identifier,
                        last_ledger_timestamp=founding_date,
                        founding_date=founding_date)

    # convert 'now' to an effective date with 0 time in the legislation timezone, same as the UI does
    effective_date = LegislationDatetime.as_legislation_timezone(now)
    effective_date = effective_date.replace(hour=0,
                                            minute=0,
                                            second=0,
                                            microsecond=0)
    effective_date = LegislationDatetime.as_utc_timezone(effective_date)

    f = copy.deepcopy(FILING_HEADER)
    f['filing']['header']['date'] = now.date().isoformat()
    f['filing']['header']['effectiveDate'] = effective_date.isoformat()
    f['filing']['header']['name'] = 'changeOfDirectors'
    f['filing']['business']['identifier'] = identifier

    cod = copy.deepcopy(CHANGE_OF_DIRECTORS)
    cod['directors'][0]['deliveryAddress'][
        'addressCountry'] = delivery_country_1
    cod['directors'][0]['deliveryAddress']['addressRegion'] = delivery_region_1
    cod['directors'][1]['deliveryAddress'][
        'addressCountry'] = delivery_country_2
    cod['directors'][1]['deliveryAddress']['addressRegion'] = delivery_region_2
    f['filing']['changeOfDirectors'] = cod

    # perform test
    with freeze_time(now):
        err = validate(business, f)
        if err:
            print(err.msg)

    # validate outcomes
    if expected_code:
        assert err.code == expected_code
        assert lists_are_equal(err.msg, expected_msg)
    else:
        assert err is None
Example #10
0
 def _set_dates(self, filing):
     filing_datetime = LegislationDatetime.as_legislation_timezone(
         self._filing.filing_date)
     hour = filing_datetime.strftime('%I').lstrip('0')
     filing['filing_date_time'] = filing_datetime.strftime(
         f'%B %d, %Y {hour}:%M %p Pacific Time')
     # Get the effective date
     effective_date = filing_datetime if self._filing.effective_date is None \
         else self._filing.effective_date
     # TODO: best: custom date/time filters in the report-api. Otherwise: a subclass for filing-specific data.
     if self._filing.filing_type == 'annualReport':
         agm_date_str = filing.get('annualReport',
                                   {}).get('annualGeneralMeetingDate', None)
         if agm_date_str:
             agm_date = datetime.fromisoformat(agm_date_str)
             filing['agm_date'] = agm_date.strftime('%B %d, %Y')
             # for AR, the effective date is the AGM date
             filing['effective_date'] = agm_date.strftime('%B %d, %Y')
         else:
             filing['agm_date'] = 'No AGM'
     elif self._filing.filing_type in ('changeOfAddress',
                                       'changeOfDirectors'):
         # for standalone filings, the effective date comes from the filing data
         filing['effective_date'] = effective_date.strftime('%B %d, %Y')
def _replace_file_with_certified_copy(_bytes, business, key):
    open_pdf_file = io.BytesIO(_bytes)
    pdf_reader = PyPDF2.PdfFileReader(open_pdf_file)
    pdf_writer = PyPDF2.PdfFileWriter()
    pdf_writer.appendPagesFromReader(pdf_reader)
    output_original_pdf = io.BytesIO()
    pdf_writer.write(output_original_pdf)
    output_original_pdf.seek(0)

    registrar_info = RegistrarInfo.get_registrar_info(business.founding_date)
    registrars_signature = registrar_info['signatureAndText']
    pdf_service = PdfService()
    registrars_stamp = \
        pdf_service.create_registrars_stamp(registrars_signature,
                                            LegislationDatetime.as_legislation_timezone(business.founding_date),
                                            business.identifier)
    certified_copy = pdf_service.stamp_pdf(output_original_pdf,
                                           registrars_stamp,
                                           only_first_page=True)

    MinioService.put_file(key, certified_copy,
                          certified_copy.getbuffer().nbytes)

    return key
Example #12
0
    def json(self):
        """Return the Business as a json object.

        None fields are not included.
        """
        ar_min_date, ar_max_date = self.get_ar_dates((
            self.last_ar_year if self.last_ar_year else self.founding_date.year
        ) + 1)
        d = {
            'arMinDate':
            ar_min_date.isoformat(),
            'arMaxDate':
            ar_max_date.isoformat(),
            'foundingDate':
            self.founding_date.isoformat(),
            'goodStanding':
            self.good_standing,
            'hasRestrictions':
            self.restriction_ind,
            'identifier':
            self.identifier,
            'lastAnnualGeneralMeetingDate':
            datetime.date(self.last_agm_date).isoformat()
            if self.last_agm_date else '',
            'lastAnnualReportDate':
            datetime.date(self.last_ar_date).isoformat()
            if self.last_ar_date else '',
            'lastLedgerTimestamp':
            self.last_ledger_timestamp.isoformat(),
            'lastAddressChangeDate':
            '',
            'lastDirectorChangeDate':
            '',
            'lastModified':
            self.last_modified.isoformat(),
            'legalName':
            self.legal_name,
            'legalType':
            self.legal_type,
            'nextAnnualReport':
            LegislationDatetime.as_legislation_timezone_from_date(
                self.next_anniversary).astimezone(timezone.utc).isoformat(),
        }

        if self.last_coa_date:
            d['lastAddressChangeDate'] = datetime.date(
                LegislationDatetime.as_legislation_timezone(
                    self.last_coa_date)).isoformat()
        if self.last_cod_date:
            d['lastDirectorChangeDate'] = datetime.date(
                LegislationDatetime.as_legislation_timezone(
                    self.last_cod_date)).isoformat()

        if self.dissolution_date:
            d['dissolutionDate'] = datetime.date(
                self.dissolution_date).isoformat()
        if self.fiscal_year_end_date:
            d['fiscalYearEndDate'] = datetime.date(
                self.fiscal_year_end_date).isoformat()
        if self.tax_id:
            d['taxId'] = self.tax_id

        return d