예제 #1
0
    def post(self, mine_guid, permit_guid, permit_amendment_guid=None):
        if permit_amendment_guid:
            raise BadRequest('Unexpected permit_amendement_guid.')

        permit = Permit.find_by_permit_guid(permit_guid)
        if not permit:
            raise NotFound('Permit does not exist.')

        if not str(permit.mine_guid) == mine_guid:
            raise BadRequest(
                'Permits mine_guid and provided mine_guid mismatch.')

        data = self.parser.parse_args()
        current_app.logger.info(f'creating permit_amendment with >> {data}')

        party = Party.find_by_party_guid(data.get('permittee_party_guid'))
        if not party:
            raise NotFound('Party not found')

        party_is_active_permittee = False

        permittees = MinePartyAppointment.find_by_permit_guid(permit_guid)

        for permittee in permittees:
            if permittee.end_date is None:
                if permittee.party_guid == party.party_guid:
                    party_is_active_permittee = True
                else:  # inactive old permittees
                    permittee.end_date = datetime.utcnow()
                    permittee.save()

        if not party_is_active_permittee:
            new_permittee = MinePartyAppointment.create(permit.mine_guid,
                                                        data.get(
                                                            'permittee_party_guid'), 'PMT',
                                                        datetime.utcnow(), None,
                                                        self.get_user_info(), permit_guid, True)
            new_permittee.save()

        new_pa = PermitAmendment.create(
            permit,
            data.get('received_date'),
            data.get('issue_date'),
            data.get('authorization_end_date'),
            data.get('permit_amendment_type_code', 'AMD'),
            description=data.get('description'))

        uploadedFiles = data.get('uploadedFiles', [])
        for newFile in uploadedFiles:
            new_pa_doc = PermitAmendmentDocument(
                document_name=newFile['fileName'],
                document_manager_guid=newFile['document_manager_guid'],
                mine_guid=permit.mine_guid,
            )
            new_pa.related_documents.append(new_pa_doc)
        new_pa.save()
        return new_pa
예제 #2
0
def setup_info(test_client):
    mpa = MinePartyAppointment(
        mine_party_appt_guid=TEST_MINE_PARTY_APPT_GUID,
        mine_guid=uuid.UUID(TEST_MINE_GUID),
        party_guid=uuid.UUID(TEST_PARTY_PER_GUID_1),
        mine_party_appt_type_code=TEST_MINE_PARTY_APPT_TYPE_CODE1,
        **DUMMY_USER_KWARGS)
    mpa.save()
    yield dict(mine_party_appointment=mpa)
    db.session.delete(mpa)
    db.session.commit()
def test_get_mine_party_appt_by_multiple_types(test_client, auth_headers):
    new_mpa = MinePartyAppointment(
        mine_party_appt_type_code=TEST_MINE_PARTY_APPT_TYPE_CODE2,
        party_guid=uuid.UUID(TEST_PARTY_PER_GUID_1),
        mine_guid=uuid.UUID(TEST_MINE_GUID))
    new_mpa.save()

    get_resp = test_client.get(
        f'/parties/mines?mine_guid={TEST_MINE_GUID}&types={TEST_MINE_PARTY_APPT_TYPE_CODE2}&types={TEST_MINE_PARTY_APPT_TYPE_CODE1}',
        headers=auth_headers['full_auth_header'])
    get_data = json.loads(get_resp.data.decode())
    assert get_resp.status_code == 200
    assert all(mpa['mine_guid'] == TEST_MINE_GUID for mpa in get_data)
    assert len(get_data) == 2
def setup_info(test_client):

    permittee = MinePartyAppointment(
        mine_party_appt_guid=uuid.uuid4(),
        mine_party_appt_type_code='PMT',
        party_guid=uuid.UUID(TEST_PARTY_PER_GUID_1),
        mine_guid=uuid.UUID(TEST_MINE_GUID),
        permit_guid=uuid.UUID(TEST_PERMIT_GUID_1))
    permittee.save()

    yield dict(permittee_guid=permittee.mine_party_appt_guid)

    db.session.delete(permittee)
    db.session.commit()
def test_post_permit_amendment_with_date_params(test_client, db_session,
                                                auth_headers):
    permit_guid = PermitFactory().permit_guid
    party_guid = PartyFactory(company=True).party_guid

    data = {
        'permittee_party_guid':
        party_guid,
        'received_date':
        datetime.today().strftime('%Y-%m-%d'),
        'issue_date':
        datetime.today().strftime('%Y-%m-%d'),
        'authorization_end_date':
        (datetime.today() + timedelta(days=1)).strftime('%Y-%m-%d')
    }

    post_resp = test_client.post(f'/permits/{permit_guid}/amendments',
                                 json=data,
                                 headers=auth_headers['full_auth_header'])
    post_data = json.loads(post_resp.data.decode())

    permittees = MinePartyAppointment.find_by_permit_guid(permit_guid)

    assert post_resp.status_code == 200, post_resp.response
    assert post_data['permit_guid'] == str(permit_guid), str(post_data)
    assert post_data['received_date'] == data['received_date']
    assert post_data['issue_date'] == data['issue_date']
    assert post_data['authorization_end_date'] == data[
        'authorization_end_date']
    assert permittees[0].party_guid == party_guid

    #permit_amdendment is actually in db
    assert PermitAmendment.find_by_permit_amendment_guid(
        post_data['permit_amendment_guid'])
    def put(self, mine_guid, mine_party_appt_guid):
        parser = CustomReqparser()
        # Arguments required by MineDocument
        parser.add_argument('document_name', type=str, required=True)
        parser.add_argument('document_manager_guid', type=str, required=True)

        mine_party_appt = MinePartyAppointment.find_by_mine_party_appt_guid(
            mine_party_appt_guid)

        if not mine_party_appt:
            raise NotFound('Mine Party Appointment.')

        data = parser.parse_args()
        document_name = data.get('document_name')
        document_manager_guid = data.get('document_manager_guid')

        # Register new file upload
        mine_doc = MineDocument(mine_guid=mine_guid,
                                document_manager_guid=document_manager_guid,
                                document_name=document_name)

        if not mine_doc:
            raise BadRequest('Unable to register uploaded file as document')

        mine_doc.save()
        mine_party_appt.documents.append(mine_doc)
        mine_party_appt.save()
        return mine_party_appt
예제 #7
0
    def put(self, mine_party_appt_guid=None):
        if not mine_party_appt_guid:
            raise BadRequest('missing mine party appointment guid')

        data = self.parser.parse_args()
        mpa = MinePartyAppointment.find_by_mine_party_appt_guid(
            mine_party_appt_guid)
        if not mpa:
            raise NotFound('mine party appointment not found')

        for key, value in data.items():
            if key in ['party_guid', 'mine_guid']:
                continue
            elif key == "related_guid":
                mpa.assign_related_guid(data.get('related_guid'))
            else:
                setattr(mpa, key, value)
        try:
            mpa.save()
        except alch_exceptions.IntegrityError as e:
            if "daterange_excl" in str(e):
                mpa_type_name = mpa.mine_party_appt_type.description
                raise BadRequest(
                    f'Date ranges for {mpa_type_name} must not overlap.')

        return mpa.json()
예제 #8
0
def test_post_permit(test_client, db_session, auth_headers):
    mine = MineFactory()
    party_guid = PartyFactory(company=True).party_guid

    no_of_permits = len(mine.mine_permit)

    PERMIT_NO = 'mx-test-999'
    data = {
        'permittee_party_guid': str(party_guid),
        'permit_no': PERMIT_NO,
        'permit_status_code': 'O',
        'received_date': '1999-12-12',
        'issue_date': '1999-12-21',
        'authorization_end_date': '2012-12-02'
    }
    post_resp = test_client.post(f'/mines/{mine.mine_guid}/permits',
                                 headers=auth_headers['full_auth_header'],
                                 json=data)
    post_data = json.loads(post_resp.data.decode())

    updated_mine = Mine.find_by_mine_guid(str(mine.mine_guid))
    permittees = MinePartyAppointment.find_by_permit_guid(
        updated_mine.mine_permit[0].permit_guid)

    assert post_resp.status_code == 200
    assert updated_mine.mine_permit[0].permit_no == PERMIT_NO
    assert permittees[0].party_guid == party_guid
    assert len(updated_mine.mine_permit) == no_of_permits + 1
예제 #9
0
def setup_info(test_client):

    NON_EXISTENT_GUID = '8ef23184-02c4-4472-a912-380b5a0d9cae'

    permittee = MinePartyAppointment(
        mine_party_appt_guid=uuid.uuid4(),
        mine_party_appt_type_code='PMT',
        party_guid=uuid.UUID(TEST_PARTY_PER_GUID_1),
        mine_guid=uuid.UUID(TEST_MINE_GUID),
        permit_guid=uuid.UUID(TEST_PERMIT_GUID_1))
    permittee.save()

    yield dict(permittee_guid=str(permittee.mine_party_appt_guid), bad_guid=NON_EXISTENT_GUID)

    db.session.delete(permittee)
    db.session.commit()
def setup_info(test_client):
    mpa = MinePartyAppointment(
        mine_party_appt_guid=TEST_MINE_PARTY_APPT_GUID,
        mine_guid=uuid.UUID(TEST_MINE_GUID),
        party_guid=uuid.UUID(TEST_PARTY_PER_GUID_1),
        mine_party_appt_type_code=TEST_MINE_PARTY_APPT_TYPE_CODE1)
    mpa.save()

    mine_tsf1 = MineTailingsStorageFacility.create(
        mine_guid=TEST_MINE_GUID, tailings_facility_name='Tailings Facility 1')
    mine_tsf1.save()

    yield dict(mine_party_appointment=mpa, tsf1=mine_tsf1)

    db.session.query(MinePartyAppointment).delete()
    db.session.delete(mine_tsf1)
    db.session.commit()
예제 #11
0
def test_permittee_model_find_by_permit_guid(test_client, db_session,
                                             auth_headers):
    appt_guid = MinePartyAppointmentFactory(
        mine_party_appt_type_code='PMT').mine_party_appt_guid

    permittee = MinePartyAppointment.find_by_mine_party_appt_guid(
        str(appt_guid))
    assert permittee.mine_party_appt_guid == appt_guid
예제 #12
0
 def get(self, mine_party_appt_guid=None):
     relationships = request.args.get('relationships')
     relationships = relationships.split(',') if relationships else []
     if mine_party_appt_guid:
         mpa = MinePartyAppointment.find_by_mine_party_appt_guid(
             mine_party_appt_guid)
         if not mpa:
             raise NotFound('Mine Party Appointment not found')
         result = mpa.json(relationships=relationships)
     else:
         mine_guid = request.args.get('mine_guid')
         party_guid = request.args.get('party_guid')
         types = request.args.getlist('types')  #list
         mpas = MinePartyAppointment.find_by(
             mine_guid=mine_guid,
             party_guid=party_guid,
             mine_party_appt_type_codes=types)
         result = [x.json(relationships=relationships) for x in mpas]
     return result
예제 #13
0
파일: permit.py 프로젝트: parc-jason/mds
    def post(self, mine_guid):
        data = self.parser.parse_args()

        mine = Mine.find_by_mine_guid(mine_guid)
        if not mine:
            raise NotFound(
                'There was no mine found with the provided mine_guid.')

        party = Party.find_by_party_guid(data.get('permittee_party_guid'))
        if not party:
            raise NotFound('Party not found')

        permit = Permit.find_by_permit_no(data.get('permit_no'))
        if permit:
            raise BadRequest("That permit number is already in use.")

        uploadedFiles = data.get('uploadedFiles', [])

        permit = Permit.create(mine.mine_guid, data.get('permit_no'),
                               data.get('permit_status_code'))

        amendment = PermitAmendment.create(
            permit,
            data.get('received_date'),
            data.get('issue_date'),
            data.get('authorization_end_date'),
            'OGP',
            description='Initial permit issued.')

        db.session.add(permit)
        db.session.add(amendment)

        for newFile in uploadedFiles:
            new_pa_doc = PermitAmendmentDocument(
                document_name=newFile['fileName'],
                document_manager_guid=newFile['document_manager_guid'],
                mine_guid=permit.mine_guid,
            )
            amendment.related_documents.append(new_pa_doc)
        db.session.commit()

        permittee_start_date = data.get('issue_date'),
        permittee = MinePartyAppointment.create(
            mine.mine_guid,
            data.get('permittee_party_guid'),
            'PMT',
            start_date=permittee_start_date,
            processed_by=self.get_user_info(),
            permit_guid=permit.permit_guid)
        db.session.add(permittee)
        db.session.commit()

        return permit
예제 #14
0
    def delete(self, party_guid):
        party = Party.find_by_party_guid(party_guid)
        if not party:
            raise NotFound(f'Party guid with "{party_guid}" not found.')

        mine_party_appts = MinePartyAppointment.find_by_party_guid(party_guid)
        for mine_party_appt in mine_party_appts:
            mine_party_appt.deleted_ind = True
            mine_party_appt.save()

        party.deleted_ind = True
        party.save()
        return ('', 204)
예제 #15
0
    def delete(self, mine_party_appt_guid=None):
        if not mine_party_appt_guid:
            raise BadRequest('Expected mine party appointment guid.')

        data = self.parser.parse_args()
        mpa = MinePartyAppointment.find_by_mine_party_appt_guid(
            mine_party_appt_guid)
        if not mpa:
            raise NotFound('Mine party appointment not found.')

        mpa.deleted_ind = True
        mpa.save()

        return ('', 204)
예제 #16
0
def test_post_mine_manager_happy_after(test_client, auth_headers, setup_info):
    test_data = {
        'mine_guid': TEST_MINE_GUID,
        'party_guid': TEST_PARTY_PER_GUID_1,
        'mine_party_appt_type_code': "MMG",
        'start_date':
        str(INIT_START_DATE + MM_APPT_LENGTH + timedelta(days=1)),
        'end_date': str(INIT_END_DATE + MM_APPT_LENGTH + timedelta(days=1)),
    }
    post_resp = test_client.post('/parties/mines',
                                 data=test_data,
                                 headers=auth_headers['full_auth_header'])
    post_data = json.loads(post_resp.data.decode())
    assert post_resp.status_code == 200, post_resp.response
    #clean-up
    new_mpa = MinePartyAppointment.find_by_mine_party_appt_guid(
        post_data["mine_party_appt_guid"])
    db.session.delete(new_mpa)
    db.session.commit()
예제 #17
0
def setup_info(test_client):
    mine_manager_1 = MinePartyAppointment(
        mine_guid=uuid.UUID(TEST_MINE_GUID),
        party_guid=uuid.UUID(TEST_PARTY_PER_GUID_1),
        mine_party_appt_type_code='MMG',
        start_date=INIT_START_DATE,
        end_date=INIT_END_DATE,
        processed_by='update_user')
    mine_manager_1.save()

    mine_manager_2 = MinePartyAppointment(
        mine_guid=uuid.UUID(TEST_MINE_GUID),
        party_guid=uuid.UUID(TEST_PARTY_PER_GUID_1),
        mine_party_appt_type_code='MMG',
        start_date=INIT_START_DATE + timedelta(days=500),
        end_date=INIT_END_DATE + timedelta(days=500),
        processed_by='update_user')
    mine_manager_2.save()

    yield dict(mine_manager_1=mine_manager_1, mine_manager_2=mine_manager_2)

    db.session.delete(mine_manager_1)
    db.session.delete(mine_manager_2)
    db.session.commit()
예제 #18
0
def test_party_appt_model_find_by_party_guid(db_session):
    party_guid = MinePartyAppointmentFactory().party.party_guid

    mpas = MinePartyAppointment.find_by_party_guid(str(party_guid))
    assert len(mpas) == 1
    assert mpas[0].party_guid == party_guid
예제 #19
0
def test_mine_party_appt_to_csv(db_session):
    mpa = MinePartyAppointmentFactory()

    csv = MinePartyAppointment.to_csv([mpa], ['processed_by', 'processed_on'])
    second_row = str(mpa.processed_by) + ',' + str(mpa.processed_on)
    assert csv == "processed_by,processed_on\n" + second_row
예제 #20
0
def test_party_appt_model_find_by(db_session):
    batch_size = 3
    MinePartyAppointmentFactory.create_batch(size=batch_size)

    mine_party_appts = MinePartyAppointment.find_by()
    assert len(mine_party_appts) == batch_size
예제 #21
0
    def post(self, mine_guid, permit_guid, permit_amendment_guid=None):
        if permit_amendment_guid:
            raise BadRequest('Unexpected permit_amendement_guid.')

        permit = Permit.find_by_permit_guid(permit_guid)
        if not permit:
            raise NotFound('Permit does not exist.')

        if not str(permit.mine_guid) == mine_guid:
            raise BadRequest('Permits mine_guid and provided mine_guid mismatch.')

        data = self.parser.parse_args()
        current_app.logger.info(f'creating permit_amendment with >> {data}')

        party = Party.find_by_party_guid(data.get('permittee_party_guid'))
        if not party:
            raise NotFound('Party not found')

        permittees = MinePartyAppointment.find_by_permit_guid(permit_guid)
        if not permittees:
            raise NotFound('Party appointments not found')

        permit_issue_datetime = data.get('issue_date')
        # convert permit_issue_date to a date object to compare with permittee start_date,
        #Both dates are stored in the DB as Dates, and are being converted to SQLAlchemy dateTimes in the modals, but for some reason being returned as Python Dates.
        permit_issue_date = datetime.date(permit_issue_datetime)
        is_historical_permit = False

        new_end_dates = MinePartyAppointment.find_appointment_end_dates(
            permit_guid, permit_issue_date)

        for permittee in permittees:
            # check if the new appointment is older than the current appointment, if so create a new permittee appointment
            if permittee.start_date > permit_issue_date:
                is_historical_permit = True
            else:
                # if the amendment is the newest, change the end dates of the other appointments
                position = new_end_dates.index(permittee.start_date)
                if new_end_dates.index(permittee.start_date) == 0:
                    permittee.save()
                else:
                    permittee.end_date = new_end_dates[position - 1]
                    permittee.save()

        permittee_start_date = permit_issue_date
        position = new_end_dates.index(permit_issue_date)
        permittee_end_date = new_end_dates[position - 1] if is_historical_permit else None

        # create a new appointment, so every amendment is associated with a permittee
        new_permittee = MinePartyAppointment.create(
            permit.mine_guid,
            data.get('permittee_party_guid'),
            'PMT',
            self.get_user_info(),
            start_date=permittee_start_date,
            end_date=permittee_end_date,
            permit_guid=permit_guid)

        new_permittee.save()
        new_pa = PermitAmendment.create(
            permit,
            data.get('received_date'),
            data.get('issue_date'),
            data.get('authorization_end_date'),
            data.get('permit_amendment_type_code', 'AMD'),
            description=data.get('description'))

        uploadedFiles = data.get('uploadedFiles', [])
        for newFile in uploadedFiles:
            new_pa_doc = PermitAmendmentDocument(
                document_name=newFile['fileName'],
                document_manager_guid=newFile['document_manager_guid'],
                mine_guid=permit.mine_guid,
            )
            new_pa.related_documents.append(new_pa_doc)

        new_pa.save()
        return new_pa
예제 #22
0
def setup_data(session):
    # Clear data
    clear_data(session)

    # Insert Region Code
    for region_code_value, display_order_value in zip(
            TEST_REGION_CODES, TEST_REGION_CODE_DISPLAY_ORDER):
        region_code = MineRegionCode(mine_region_code=region_code_value,
                                     description=TEST_REGION_DESCRIPTION,
                                     display_order=display_order_value,
                                     **DUMMY_USER_KWARGS)
        region_code.save()

    # Insert Mine Tenure Types
    for code, description in zip(TEST_MINE_TENURE_TYPE_CODES,
                                 TEST_MINE_TENURE_TYPE_DESCRIPTIONS):
        mine_tenure_type_code = MineTenureTypeCode(mine_tenure_type_code=code,
                                                   description=description,
                                                   **DUMMY_USER_KWARGS)
        mine_tenure_type_code.save()

    # Insert Mine Disturbance Codes
    for code, description in zip(TEST_MINE_DISTURBANCE_CODES,
                                 TEST_MINE_DISTURBANCE_DESCRIPTIONS):
        mine_disturbance_code = MineDisturbanceCode(mine_disturbance_code=code,
                                                    description=description,
                                                    **DUMMY_USER_KWARGS)
        mine_disturbance_code.save()

    # Insert Mine Commodity Codes
    for code, description in zip(TEST_MINE_COMMODITY_CODES,
                                 TEST_MINE_COMMODITY_DESCRIPTIONS):
        mine_commodity_code = MineCommodityCode(mine_commodity_code=code,
                                                description=description,
                                                **DUMMY_USER_KWARGS)
        mine_commodity_code.save()

    # Test Mine Data
    mine_identity = MineIdentity(mine_guid=uuid.UUID(TEST_MINE_GUID),
                                 **DUMMY_USER_KWARGS)
    mine_detail = MineDetail(mine_detail_guid=uuid.UUID(TEST_MINE_DETAIL_GUID),
                             mine_guid=uuid.UUID(TEST_MINE_GUID),
                             mine_no=TEST_MINE_NO,
                             mine_name=TEST_MINE_NAME,
                             mine_region=TEST_REGION_CODE,
                             **DUMMY_USER_KWARGS)
    mine_identity.save()
    mine_detail.save()

    # Test Mine Type
    mine_type = MineType(mine_type_guid=uuid.UUID(TEST_MINE_TYPE_GUID),
                         mine_guid=uuid.UUID(TEST_MINE_GUID),
                         mine_tenure_type_code=TEST_MINE_TENURE_TYPE_CODES[0],
                         active_ind=True,
                         **DUMMY_USER_KWARGS)
    mine_type.save()

    # Test Mine Type Detail
    mine_type_detail = MineTypeDetail(
        mine_type_detail_xref_guid=uuid.UUID(TEST_MINE_TYPE_DETAIL_GUID),
        mine_type_guid=uuid.UUID(TEST_MINE_TYPE_GUID),
        mine_disturbance_code=TEST_MINE_DISTURBANCE_CODES[0],
        active_ind=True,
        **DUMMY_USER_KWARGS)
    mine_type_detail.save()

    # Test Tenure Data
    tenure = MineralTenureXref(
        mineral_tenure_xref_guid=uuid.UUID(TEST_TENURE_GUID),
        mine_guid=uuid.UUID(TEST_MINE_GUID),
        tenure_number_id=TEST_TENURE_ID,
        **DUMMY_USER_KWARGS)
    tenure.save()

    # Test Location Data
    mine_location = MineLocation(
        mine_location_guid=uuid.UUID(TEST_LOCATION_GUID),
        mine_guid=uuid.UUID(TEST_MINE_GUID),
        latitude=TEST_LAT_1,
        longitude=TEST_LONG_1,
        effective_date=datetime.today(),
        expiry_date=datetime.today(),
        **DUMMY_USER_KWARGS)
    mine_location.save()

    # Test Person Type Codes
    for k, v in PARTY_STATUS_CODE.items():
        party_code = PartyTypeCode(party_type_code=v,
                                   description=v,
                                   **DUMMY_USER_KWARGS)
        party_code.save()
    session.commit()

    # Test Operation Codes
    for k, v in MINE_OPERATION_STATUS.items():
        mine_operation_status_code = MineOperationStatusCode(
            mine_operation_status_code=v['value'],
            description=v['label'],
            **DUMMY_USER_KWARGS)
        mine_operation_status_code.save()
    for k, v in MINE_OPERATION_STATUS_REASON.items():
        mine_operation_status_reason_code = MineOperationStatusReasonCode(
            mine_operation_status_reason_code=v['value'],
            description=v['label'],
            **DUMMY_USER_KWARGS)
        mine_operation_status_reason_code.save()
    for k, v in MINE_OPERATION_STATUS_SUB_REASON.items():
        mine_operation_status_sub_reason_code = MineOperationStatusSubReasonCode(
            mine_operation_status_sub_reason_code=v['value'],
            description=v['label'],
            **DUMMY_USER_KWARGS)
        mine_operation_status_sub_reason_code.save()

    session.commit()

    # Test Person Data
    person = Party(party_guid=uuid.UUID(TEST_PARTY_PER_GUID_1),
                   first_name=TEST_PARTY_PER_FIRST_NAME_1,
                   party_name=TEST_PARTY_PER_PARTY_NAME_1,
                   email=TEST_PARTY_PER_EMAIL_1,
                   phone_no=TEST_PARTY_PER_PHONE_1,
                   phone_ext=TEST_PARTY_PER_PHONE_EXT_1,
                   party_type_code=TEST_PARTY_TYPE,
                   **DUMMY_USER_KWARGS)
    person.save(commit=False)
    person2 = Party(party_guid=uuid.UUID(TEST_PARTY_PER_GUID_2),
                    first_name=TEST_PARTY_PER_FIRST_NAME_2,
                    party_name=TEST_PARTY_PER_PARTY_NAME_2,
                    email=TEST_PARTY_PER_EMAIL_2,
                    phone_no=TEST_PARTY_PER_PHONE_2,
                    phone_ext=TEST_PARTY_PER_PHONE_EXT_2,
                    party_type_code=TEST_PARTY_TYPE,
                    **DUMMY_USER_KWARGS)
    person2.save(commit=False)
    person3 = Party(party_guid=uuid.UUID(TEST_PARTY_PER_GUID_3),
                    first_name=TEST_PARTY_PER_FIRST_NAME_3,
                    party_name=TEST_PARTY_PER_PARTY_NAME_3,
                    email=TEST_PARTY_PER_EMAIL_3,
                    phone_no=TEST_PARTY_PER_PHONE_3,
                    phone_ext=TEST_PARTY_PER_PHONE_EXT_3,
                    party_type_code=TEST_PARTY_TYPE,
                    **DUMMY_USER_KWARGS)
    person3.save(commit=False)
    party_org = Party(party_guid=uuid.UUID(TEST_PARTY_ORG_GUID),
                      party_name=TEST_PARTY_ORG_NAME,
                      email=TEST_PARTY_ORG_EMAIL,
                      phone_no=TEST_PARTY_ORG_PHONE,
                      phone_ext=TEST_PARTY_ORG_EXT,
                      party_type_code=TEST_ORG_TYPE,
                      **DUMMY_USER_KWARGS)
    party_org.save()
    # Test Manager Data
    manager = MgrAppointment(mgr_appointment_guid=uuid.UUID(TEST_MANAGER_GUID),
                             party_guid=uuid.UUID(TEST_PARTY_PER_GUID_1),
                             mine_guid=uuid.UUID(TEST_MINE_GUID),
                             effective_date=datetime.today() -
                             timedelta(days=10),
                             **DUMMY_USER_KWARGS)
    manager.save()

    # Test Permit Status Codes
    for permit_code_value in TEST_PERMIT_STATUS_CODES:
        permit_code = PermitStatusCode(
            permit_status_code=permit_code_value,
            description=TEST_PERMIT_STATUS_CODE_NAME_1,
            **DUMMY_USER_KWARGS)
        permit_code.save()

    # Test Permit Data
    permit = Permit(permit_guid=TEST_PERMIT_GUID_1,
                    mine_guid=TEST_MINE_GUID,
                    permit_no=TEST_PERMIT_NO_1,
                    permit_status_code=TEST_PERMIT_STATUS_CODE_1,
                    received_date=datetime.today(),
                    issue_date=datetime.today(),
                    **DUMMY_USER_KWARGS)
    permit.save()

    # Test Permittee Data
    permittee = Permittee(permittee_guid=uuid.UUID(TEST_PERMITTEE_GUID),
                          permit_guid=uuid.UUID(TEST_PERMIT_GUID_1),
                          party_guid=uuid.UUID(TEST_PARTY_PER_GUID_1),
                          **DUMMY_USER_KWARGS)
    permittee.save()

    required_document_due_date_type1 = RequiredDocumentDueDateType(
        req_document_due_date_type=TEST_REQUIRED_REPORT_DUE_DATE_TYPE[0],
        req_document_due_date_description=
        TEST_REQUIRED_REPORT_DUE_DATE_DESCRIPTION[0],
        **DUMMY_USER_KWARGS)
    required_document_due_date_type1.save()

    required_document_due_date_type2 = RequiredDocumentDueDateType(
        req_document_due_date_type=TEST_REQUIRED_REPORT_DUE_DATE_TYPE[1],
        req_document_due_date_description=
        TEST_REQUIRED_REPORT_DUE_DATE_DESCRIPTION[1],
        **DUMMY_USER_KWARGS)
    required_document_due_date_type2.save()

    required_document_category1 = RequiredDocumentCategory(
        req_document_category_guid=TEST_REQUIRED_REPORT_CATEGORY_TAILINGS_GUID,
        req_document_category=TEST_REQUIRED_REPORT_CATEGORY_TAILINGS)
    required_document_category1.save()

    required_document_category2 = RequiredDocumentCategory(
        req_document_category_guid=TEST_REQUIRED_REPORT_CATEGORY_OTHER_GUID,
        req_document_category=TEST_REQUIRED_REPORT_CATEGORY_OTHER)
    required_document_category2.save()

    required_document1 = RequiredDocument(
        req_document_guid=uuid.UUID(TEST_REQUIRED_REPORT_GUID1),
        req_document_name=TEST_REQUIRED_REPORT_NAME1,
        req_document_category_guid=TEST_REQUIRED_REPORT_CATEGORY_TAILINGS_GUID,
        req_document_due_date_type=TEST_REQUIRED_REPORT_DUE_DATE_TYPE[0],
        req_document_due_date_period_months=12,
        **DUMMY_USER_KWARGS)
    required_document1.save()

    required_document2 = RequiredDocument(
        req_document_guid=uuid.UUID(TEST_REQUIRED_REPORT_GUID2),
        req_document_name=TEST_REQUIRED_REPORT_NAME2,
        req_document_category_guid=TEST_REQUIRED_REPORT_CATEGORY_TAILINGS_GUID,
        req_document_due_date_type=TEST_REQUIRED_REPORT_DUE_DATE_TYPE[0],
        req_document_due_date_period_months=12,
        **DUMMY_USER_KWARGS)
    required_document2.save()

    required_document3 = RequiredDocument(
        req_document_guid=uuid.UUID(TEST_REQUIRED_REPORT_GUID3),
        req_document_name=TEST_REQUIRED_REPORT_NAME3,
        req_document_category_guid=TEST_REQUIRED_REPORT_CATEGORY_OTHER_GUID,
        req_document_due_date_type=TEST_REQUIRED_REPORT_DUE_DATE_TYPE[1],
        req_document_due_date_period_months=12,
        **DUMMY_USER_KWARGS)
    required_document3.save()

    expected_document1 = MineExpectedDocument(
        exp_document_guid=uuid.UUID(TEST_EXPECTED_DOCUMENT_GUID1),
        req_document_guid=uuid.UUID(TEST_REQUIRED_REPORT_GUID1),
        mine_guid=TEST_MINE_GUID,
        exp_document_name=TEST_EXPECTED_DOCUMENT_NAME1,
        due_date=datetime.strptime('1984-06-18', '%Y-%m-%d'),
        received_date=datetime.strptime('1984-06-18', '%Y-%m-%d'),
        **DUMMY_USER_KWARGS)
    expected_document1.save()

    mine_tsf1 = MineTailingsStorageFacility(
        mine_tailings_storage_facility_guid=
        TEST_TAILINGS_STORAGE_FACILITY_GUID1,
        mine_guid=TEST_MINE_GUID,
        mine_tailings_storage_facility_name=
        TEST_TAILINGS_STORAGE_FACILITY_NAME1,
        **DUMMY_USER_KWARGS)
    mine_tsf1.save()

    mpat1 = MinePartyAppointmentType(
        mine_party_appt_type_code=TEST_MINE_PARTY_APPT_TYPE_CODE1,
        description=TEST_MINE_PARTY_APPT_TYPE_DESCRIPTION1,
        **DUMMY_USER_KWARGS)
    mpat1.save()

    mpat2 = MinePartyAppointmentType(
        mine_party_appt_type_code=TEST_MINE_PARTY_APPT_TYPE_CODE2,
        description=TEST_MINE_PARTY_APPT_TYPE_DESCRIPTION2,
        **DUMMY_USER_KWARGS)
    mpat2.save()

    mpat3 = MinePartyAppointmentType(mine_party_appt_type_code='EOR',
                                     description='Engineer of Record',
                                     **DUMMY_USER_KWARGS)
    mpat3.save()

    mpa = MinePartyAppointment(
        mine_party_appt_guid=TEST_MINE_PARTY_APPT_GUID,
        mine_guid=uuid.UUID(TEST_MINE_GUID),
        party_guid=uuid.UUID(TEST_PARTY_PER_GUID_1),
        mine_party_appt_type_code=TEST_MINE_PARTY_APPT_TYPE_CODE1,
        **DUMMY_USER_KWARGS)
    mpa.save()

    mine_doc1 = MineDocument(
        mine_guid=uuid.UUID(TEST_MINE_GUID),
        document_name=TEST_MINE_DOCUMENT_NAME1,
        document_manager_guid=TEST_DOCUMENT_MANAGER_FILE_GUID,
        **DUMMY_USER_KWARGS)
    mine_doc1.mine_expected_document.append(expected_document1)
    mine_doc1.save()
예제 #23
0
    def post(self, mine_party_appt_guid=None):
        if mine_party_appt_guid:
            raise BadRequest('unexpected mine party appointment guid')
        data = self.parser.parse_args()

        end_current = data.get('end_current')
        mine_party_appt_type_code = data.get('mine_party_appt_type_code')
        related_guid = data.get('related_guid')
        mine_guid = data.get('mine_guid')
        start_date = data.get('start_date')

        if end_current:
            if mine_party_appt_type_code == "EOR":
                current_mpa = MinePartyAppointment.find_current_appointments(
                    mine_guid=mine_guid,
                    mine_party_appt_type_code=mine_party_appt_type_code,
                    mine_tailings_storage_facility_guid=related_guid)
            elif mine_party_appt_type_code == "PMT":
                current_mpa = MinePartyAppointment.find_current_appointments(
                    mine_guid=mine_guid,
                    mine_party_appt_type_code=mine_party_appt_type_code,
                    permit_guid=related_guid)
            else:
                current_mpa = MinePartyAppointment.find_current_appointments(
                    mine_guid=mine_guid,
                    mine_party_appt_type_code=mine_party_appt_type_code)
            if len(current_mpa) > 1:
                raise BadRequest(
                    'There is currently more than one active appointment.')
            current_mpa[0].end_date = start_date - timedelta(days=1)
            current_mpa[0].save()
        new_mpa = MinePartyAppointment(
            mine_guid=mine_guid,
            party_guid=data.get('party_guid'),
            mine_party_appt_type_code=mine_party_appt_type_code,
            start_date=start_date,
            end_date=data.get('end_date'),
            processed_by=self.get_user_info())

        if new_mpa.mine_party_appt_type_code == "EOR":
            new_mpa.assign_related_guid(related_guid)
            if not new_mpa.mine_tailings_storage_facility_guid:
                raise AssertionError(
                    'mine_tailings_storage_facility_guid must be provided for Engineer of Record'
                )
            #TODO move db foreign key constraint when services get separated
            pass

        if new_mpa.mine_party_appt_type_code == "PMT":
            new_mpa.assign_related_guid(related_guid)
            if not new_mpa.permit_guid:
                raise AssertionError(
                    'permit_guid must be provided for Permittee')
            #TODO move db foreign key constraint when services get separated
            pass
        try:
            new_mpa.save()
        except alch_exceptions.IntegrityError as e:
            if "daterange_excl" in str(e):
                mpa_type_name = MinePartyAppointmentType.find_by_mine_party_appt_type_code(
                    data.get('mine_party_appt_type_code')).description
                raise BadRequest(
                    f'Date ranges for {mpa_type_name} must not overlap')
        return new_mpa.json()
예제 #24
0
def test_permittee_model_find_by_permit_guid(test_client, auth_headers):
    permittee = MinePartyAppointment.find_by_mine_party_appt_guid(TEST_PERMITTEE_GUID)
    assert str(permittee.mine_party_appt_guid) == TEST_PERMITTEE_GUID
예제 #25
0
def test_party_appt_model_find_by_party_guid(test_client, setup_info,
                                             auth_headers):
    mpas = MinePartyAppointment.find_by_party_guid(TEST_PARTY_PER_GUID_1)
    assert all(str(mpa.party_guid) == TEST_PARTY_PER_GUID_1 for mpa in mpas)
예제 #26
0
def test_party_appt_model_find_by_mine_guid(test_client, setup_info,
                                            auth_headers):
    mpas = MinePartyAppointment.find_by_mine_guid(TEST_MINE_GUID)
    assert all(str(mpa.mine_guid) == TEST_MINE_GUID for mpa in mpas)
예제 #27
0
def test_mine_party_appt_to_csv(test_client, setup_info, auth_headers):
    record = MinePartyAppointment.query.first()
    csv = MinePartyAppointment.to_csv([record],
                                      ['processed_by', 'processed_on'])
    second_row = str(record.processed_by) + ',' + str(record.processed_on)
    assert csv == "processed_by,processed_on\n" + second_row
예제 #28
0
def test_party_appt_model_find_by(test_client, setup_info, auth_headers):
    mine_party_appts = MinePartyAppointment.find_by()
    assert len(mine_party_appts) == MinePartyAppointment.query.count()
예제 #29
0
def test_permittee_model_find_by_permit_guid(test_client, setup_info, auth_headers):
    permittee = MinePartyAppointment.find_by_mine_party_appt_guid(setup_info.get('permittee_guid'))
    assert str(permittee.mine_party_appt_guid) == setup_info.get('permittee_guid')
예제 #30
0
    def post(self, permit_guid=None, permit_amendment_guid=None):
        if not permit_guid:
            return self.create_error_payload(
                400, 'Permit_guid must be provided'), 400
        if permit_amendment_guid:
            return self.create_error_payload(
                400, 'unexpected permit_amendement_id'), 400

        permit = Permit.find_by_permit_guid(permit_guid)
        if not permit:
            return self.create_error_payload(404, 'permit does not exist'), 404

        data = self.parser.parse_args()
        current_app.logger.info(f'creating permit_amendment with >> {data}')

        received_date = data.get('received_date')
        issue_date = data.get('issue_date')
        authorization_end_date = data.get('authorization_end_date')
        permit_amendment_type_code = data.get('permit_amendment_type_code',
                                              'AMD')
        description = data.get('description')
        uploadedFiles = data.get('uploadedFiles', [])

        party = Party.find_by_party_guid(data.get('permittee_party_guid'))
        if not party:
            raise NotFound('Party not found')

        party_is_active_permittee = False

        permittees = MinePartyAppointment.find_by_permit_guid(permit_guid)

        for permittee in permittees:
            if permittee.end_date is None:
                if permittee.party_guid == party.party_guid:
                    party_is_active_permittee = True
                else:  # inactive old permittees
                    permittee.end_date = datetime.utcnow()
                    permittee.save()

        if not party_is_active_permittee:
            new_permittee = MinePartyAppointment.create(
                permit.mine_guid, data.get('permittee_party_guid'), 'PMT',
                datetime.utcnow(), None, self.get_user_info(), permit_guid,
                True)
            new_permittee.save()

        try:
            new_pa = PermitAmendment.create(permit,
                                            received_date,
                                            issue_date,
                                            authorization_end_date,
                                            permit_amendment_type_code,
                                            description=description)

            for newFile in uploadedFiles:
                new_pa_doc = PermitAmendmentDocument(
                    document_name=newFile['fileName'],
                    document_manager_guid=newFile['document_manager_guid'],
                    mine_guid=permit.mine_guid,
                )
                new_pa.documents.append(new_pa_doc)
            new_pa.save()
        except Exception as e:
            return self.create_error_payload(500, 'Error: {}'.format(e)), 500
        return new_pa.json()