class MineVerifiedStatus(Base): __tablename__ = 'mine_verified_status' mine_verified_status_id = db.Column(db.Integer, primary_key=True, server_default=FetchedValue()) mine_guid = db.Column(UUID(as_uuid=True), db.ForeignKey('mine.mine_guid')) healthy_ind = db.Column(db.Boolean, nullable=False, server_default=FetchedValue()) verifying_user = db.Column(db.String, nullable=False, default=User().get_user_username) verifying_timestamp = db.Column(db.DateTime, nullable=False, server_default=FetchedValue()) update_user = db.Column(db.String(60), nullable=False, default=User().get_user_username, onupdate=User().get_user_username) update_timestamp = db.Column(db.DateTime, nullable=False, server_default=FetchedValue(), onupdate=datetime.datetime.now) mine = db.relationship('Mine', backref=backref("verified_status", uselist=False, lazy='joined'), lazy='select', uselist=False) def json(self): return { 'mine_guid': str(self.mine_guid), 'mine_name': self.mine.mine_name, 'healthy': self.healthy_ind, 'verifying_user': self.verifying_user, 'verifying_timestamp': str(self.verifying_timestamp) } @classmethod def find_by_mine_guid(cls, mine_guid): try: uuid.UUID(mine_guid, version=4) return cls.query.filter_by(mine_guid=mine_guid).first() except ValueError: return None @classmethod def find_by_user_id(cls, user_id): return cls.query.filter_by(verifying_user=user_id).all()
class MineComment(Base, AuditMixin): __tablename__ = "mine_comment" mine_comment_id = db.Column(db.Integer, primary_key=True, server_default=FetchedValue()) mine_comment_guid = db.Column(UUID(as_uuid=True), nullable=False, server_default=FetchedValue()) mine_guid = db.Column(db.Integer, db.ForeignKey('mine.mine_guid'), nullable=False) mine_comment = db.Column(db.String, nullable=False) deleted_ind = db.Column(db.Boolean, nullable=False, default=False) comment_user = db.Column(nullable=False, default=User().get_user_username) comment_datetime = db.Column(db.DateTime, nullable=False, default=datetime.utcnow) def __repr__(self): return '<MineComment %r>' % self.mine_comment_guid @classmethod def create(cls, mine, mine_comment, add_to_session=True): new_comment = cls(mine_comment=mine_comment) mine.comments.append(new_comment) if add_to_session: new_comment.save(commit=False) return new_comment @classmethod def find_by_guid(cls, _id): return cls.query.filter_by(mine_comment_guid=_id).filter_by(deleted_ind=False).first() @classmethod def find_by_mine_guid(cls, _id): return cls.query.filter_by(mine_guid=_id).filter_by(deleted_ind=False).all()
def test_get_user_info(test_client): User._test_mode = False auth_token = jwt.create_jwt(VIEW_ONLY_AUTH_CLAIMS, TOKEN_HEADER) with mock.patch.object(jwt, 'get_token_auth_header', return_value=auth_token): assert User().get_user_raw_info() == VIEW_ONLY_AUTH_CLAIMS
def send_payment_document(self, doc, prf_file): if not Config.PRF_FROM_EMAIL or not Config.PRF_TO_EMAIL: current_app.logger.warning('Email addresses required for emailing finance are not set!') from_email = Config.PRF_FROM_EMAIL # For more useful testing purposes, if this value is not set, use the email of the current user to_email = Config.PRF_TO_EMAIL if not to_email: to_email = User().get_user_email() current_app.logger.warning( f'Finance recipient email is not set! Using the email of the current user instead: {to_email}' ) total_amount = '{0:.2f}'.format(doc.content["total_payment"]) subject = f'{doc.content["po_number"]}, {doc.content["supplier_name"]}, {doc.content["invoice_number"]}, {total_amount}' payment_details_rows_html = '' for payment_detail in doc.content['payment_details']: amount = '{0:.2f}'.format(payment_detail["amount"]) payment_details_rows_html += f'<tr><td>{payment_detail["agreement_number"]}</td><td>{payment_detail["unique_id"]}</td><td style="text-align: right;">{amount}</td></tr>' payment_details_total_row_html = f'<tr><th>Total Amount</th><td></td><td style="text-align: right;">{total_amount}</td></tr>' payment_details_table_html = f''' <tr><th style="vertical-align: top;">Payment Details</th><td><table><th>Agreement Number</th><th>Unique ID</th><th>Amount</th></tr> {payment_details_rows_html} {payment_details_total_row_html}</table></td>''' table_style = '<style>td, th { padding-right: 50px; } th { text-align: left; }</style>' prf_content_html = f''' {table_style} <h4>Payment Request Form</h4> <table> <tr><th>PO Number</th><td>{doc.content["po_number"]}</td></tr> <tr><th>Supplier Name</th><td>{doc.content["supplier_name"]}</td></tr> <tr><th>Supplier Address</th><td>{doc.content["supplier_address"]}</td></tr> <tr><th>Invoice Date</th><td>{doc.content["invoice_date"]}</td></tr> <tr><th>Invoice Number</th><td>{doc.invoice_number}</td></tr> <tr><td><br /></td></tr> {payment_details_table_html} <tr><td><br /></td></tr> <tr><th>Qualified Receiver Names</th><td>{doc.content["qualified_receiver_name"]}</td></tr> <tr><th>Expense Authority Name</th><td>{doc.content["expense_authority_name"]}</td></tr> <tr><th>Date Payment Authorized</th><td>{doc.content["date_payment_authorized"]}</td></tr> <tr><th>Account Coding</th><td>{doc.content["account_coding"]}</td></tr> </table>''' html_body = f'{prf_content_html}<br /><p>I approve payment for the following attached Payment Request Form under the Dormant Sites Reclamation Program.</p>' current_app.logger.info(html_body) attachment = prf_file filename = doc.document_name self.send_email(to_email, from_email, subject, html_body, '', attachment, filename)
def put(self, mine_guid): data = self.parser.parse_args() healthy = data.get('healthy') if healthy is None: raise BadRequest('"healthy" parameter not provided') mine_verified_status = MineVerifiedStatus.find_by_mine_guid(mine_guid) if not mine_verified_status: mine_verified_status = MineVerifiedStatus( mine_guid=mine_guid, verifying_user=User().get_user_username(), verifying_timestamp=datetime.now()) if healthy: mine_verified_status.verifying_user = User().get_user_username() mine_verified_status.verifying_timestamp = datetime.now() mine_verified_status.healthy_ind = healthy mine_verified_status.save() return mine_verified_status
def get(self): user_name = User().get_user_username() mine_query = Mine.query.filter_by( deleted_ind=False).join(Subscription).filter_by( user_name=user_name) sort_criteria = [{ 'model': 'Mine', 'field': 'mine_name', 'direction': 'asc' }] mine_query = apply_sort(mine_query, sort_criteria) mines = mine_query.all() return mines
class BondHistory(Base): __tablename__ = "bond_history" bond_history_id = db.Column(db.Integer, primary_key=True, server_default=FetchedValue()) bond_id = db.Column(db.Integer, db.ForeignKey('bond.bond_id'), nullable=False) amount = db.Column(db.Numeric(14, 2), nullable=False) bond_type_code = db.Column(db.String) issue_date = db.Column(db.DateTime) permit_no = db.Column(db.String) permit_guid = db.Column(UUID(as_uuid=True)) payer_name = db.Column(db.String) payer_party_guid = db.Column(UUID(as_uuid=True)) bond_status_code = db.Column(db.String) reference_number = db.Column(db.String) institution_name = db.Column(db.String) institution_street = db.Column(db.String) institution_city = db.Column(db.String) institution_province = db.Column(db.String) institution_postal_code = db.Column(db.String) note = db.Column(db.String) project_id = db.Column(db.String) update_user = db.Column(db.String, nullable=False, default=User().get_user_username, onupdate=User().get_user_username) update_timestamp = db.Column(db.DateTime, nullable=False, default=datetime.utcnow, onupdate=datetime.utcnow) def __repr__(self): return '<BondHistory %r>' % self.bond_id
class PartyOrgBookEntity(AuditMixin, Base): __tablename__ = 'party_orgbook_entity' party_orgbook_entity_id = db.Column(db.Integer, primary_key=True) registration_id = db.Column(db.String, nullable=False, unique=True) registration_status = db.Column(db.Boolean, nullable=False) registration_date = db.Column(db.DateTime, nullable=False) name_id = db.Column(db.Integer, nullable=False, unique=True) name_text = db.Column(db.String, nullable=False, unique=True) credential_id = db.Column(db.Integer, nullable=False, unique=True) party_guid = db.Column(UUID(as_uuid=True), db.ForeignKey('party.party_guid'), nullable=False, unique=True) association_user = db.Column(db.DateTime, nullable=False, default=User().get_user_username) association_timestamp = db.Column(db.DateTime, nullable=False, server_default=FetchedValue()) def __repr__(self): return '<PartyOrgBookEntity %r>' % self.party_orgbook_entity_id @classmethod def find_by_party_guid(cls, party_guid): return cls.query.filter_by(party_guid=party_guid).first() @classmethod def find_by_credential_id(cls, credential_id): return cls.query.filter_by(credential_id=credential_id).first() @classmethod def create(cls, registration_id, registration_status, registration_date, name_id, name_text, credential_id, party_guid): party_orgbook_entity = cls(registration_id=registration_id, registration_status=registration_status, registration_date=registration_date, name_id=name_id, name_text=name_text, credential_id=credential_id, party_guid=party_guid) party_orgbook_entity.save() return party_orgbook_entity
def create(cls, now_application, application_progress_status_code, add_to_session=True): existing_progress = next( (na for na in now_application.application_progress if na.application_progress_status_code == application_progress_status_code), None) if existing_progress: raise AssertionError( f'{now_application} already has application progress of {application_progress_status_code}' ) progress = cls( application_progress_status_code=application_progress_status_code, start_date=datetime.utcnow(), created_by=User().get_user_username(), ) now_application.application_progress.append(progress) if add_to_session: progress.save(commit=False) return progress
def put(self, application_guid, work_id): # Validate this contracted work item. application = Application.find_by_guid(application_guid) validate_application_contracted_work(application, work_id) # Get the contracted work payment. payment = ContractedWorkPayment.find_by_work_id(work_id) if not payment: raise BadRequest( 'The applicant must submit payment information for this work item before its audit status can be changed' ) # Update the contracted work payment's audit data. audit_data = request.json payment.audit_ind = audit_data['audit_ind'] payment.audit_user = User().get_user_username() payment.audit_timestamp = datetime.utcnow() payment.save() return '', 200
def post(self, document_type_code): document_type = NOWApplicationDocumentType.query.get( document_type_code) if not document_type: raise NotFound('Document type not found') if not document_type.document_template: raise BadRequest(f'Cannot generate a {document_type.description}') data = self.parser.parse_args() template_data = data['template_data'] ##ENFORCE READ-ONLY CONTEXT DATA enforced_data = [ x for x in document_type.document_template._form_spec_with_context( data['now_application_guid']) if x.get('read-only', False) ] for enforced_item in enforced_data: if template_data.get( enforced_item['id']) != enforced_item['context-value']: current_app.logger.debug( f'OVERWRITING ENFORCED key={enforced_item["id"]}, value={template_data.get(enforced_item["id"])} -> {enforced_item["context-value"]}' ) template_data[enforced_item['id']] = enforced_item['context-value'] token = uuid.uuid4() # For now, we don't have a "proper" means of authorizing communication between our microservices, so this temporary solution # has been put in place to authorize with the document manager (pass the authorization headers into the token and re-use them # later). A ticket (MDS-2744) to set something else up as been created. cache.set( NOW_DOCUMENT_DOWNLOAD_TOKEN(token), { 'document_type_code': document_type_code, 'now_application_guid': data['now_application_guid'], 'template_data': template_data, 'username': User().get_user_username(), 'authorization_header': request.headers['Authorization'] }, TIMEOUT_5_MINUTES) return {'token': token}
def create_for_current_user(cls, mine_guid, add_to_session=True): user_name = User().get_user_username() subscription = cls(mine_guid=mine_guid, user_name=user_name) if add_to_session: subscription.save(commit=False) return subscription
def find_subscription_for_current_user_by_id(cls, mine_guid): user_name = User().get_user_username() return Subscription.query.filter_by(mine_guid=mine_guid).filter_by( user_name=user_name).first()
class MineReport(Base, AuditMixin): __tablename__ = "mine_report" mine_report_id = db.Column(db.Integer, primary_key=True, server_default=FetchedValue()) mine_report_guid = db.Column(UUID(as_uuid=True), server_default=FetchedValue(), nullable=False) mine_report_definition_id = db.Column( db.Integer, db.ForeignKey('mine_report_definition.mine_report_definition_id'), nullable=False) mine_report_definition = db.relationship('MineReportDefinition', lazy='joined') mine_report_definition_guid = association_proxy( 'mine_report_definition', 'mine_report_definition_guid') report_name = association_proxy('mine_report_definition', 'report_name') mine_guid = db.Column(UUID(as_uuid=True), db.ForeignKey('mine.mine_guid'), nullable=False) mine = db.relationship('Mine', lazy='joined') mine_name = association_proxy('mine', 'mine_name') mine_region = association_proxy('mine', 'mine_region') major_mine_ind = association_proxy('mine', 'major_mine_ind') permit_id = db.Column(db.Integer, db.ForeignKey('permit.permit_id')) permit = db.relationship('Permit', lazy='selectin') permit_guid = association_proxy('permit', 'permit_guid') received_date = db.Column(db.DateTime) due_date = db.Column(db.DateTime) submission_year = db.Column(db.Integer) deleted_ind = db.Column(db.Boolean, server_default=FetchedValue(), nullable=False) mine_report_submissions = db.relationship( 'MineReportSubmission', lazy='joined', order_by='asc(MineReportSubmission.mine_report_submission_id)', uselist=True) created_by_idir = db.Column(db.String, nullable=False, default=User().get_user_username) # The below hybrid properties/expressions exist solely for filtering and sorting purposes. @hybrid_property def mine_report_status_code(self): if self.mine_report_submissions: return self.mine_report_submissions[ -1].mine_report_submission_status_code else: return None @mine_report_status_code.expression def mine_report_status_code(cls): return select([ MineReportSubmission.mine_report_submission_status_code ]).where(MineReportSubmission.mine_report_id == cls.mine_report_id).order_by( desc(MineReportSubmission.mine_report_submission_id) ).limit(1).as_scalar() @hybrid_property def mine_report_status_description(self): if self.mine_report_submissions: return MineReportSubmissionStatusCode.find_by_mine_report_submission_status_code( self.mine_report_status_code).description else: return None @mine_report_status_description.expression def mine_report_status_description(cls): return select([MineReportSubmissionStatusCode.description]).where( and_( MineReportSubmission.mine_report_id == cls.mine_report_id, MineReportSubmissionStatusCode. mine_report_submission_status_code == MineReportSubmission. mine_report_submission_status_code)).order_by( desc( MineReportSubmission.mine_report_submission_id)).limit( 1).as_scalar() def __repr__(self): return '<MineReport %r>' % self.mine_report_guid @classmethod def create(cls, mine_report_definition_id, mine_guid, due_date, received_date, submission_year, permit_id=None, add_to_session=True): mine_report = cls(mine_report_definition_id=mine_report_definition_id, mine_guid=mine_guid, due_date=due_date, received_date=received_date, submission_year=submission_year, permit_id=permit_id) if add_to_session: mine_report.save(commit=False) return mine_report @classmethod def find_by_mine_guid(cls, _id): try: uuid.UUID(_id, version=4) return cls.query.filter_by(mine_guid=_id).filter_by( deleted_ind=False).all() except ValueError: return None @classmethod def find_by_mine_report_guid(cls, _id): try: uuid.UUID(_id, version=4) return cls.query.filter_by(mine_report_guid=_id).first() except ValueError: return None @classmethod def find_by_mine_guid_and_category(cls, _id, category): try: uuid.UUID(_id, version=4) reports = cls.query.filter_by(mine_guid=_id).all() return [ r for r in reports if category.upper() in [ c.mine_report_category.upper() for c in r.mine_report_definition.categories ] ] except ValueError: return None
def save(self, commit=True): self.last_updated_by = User().get_user_username() self.last_updated_date = datetime.utcnow() super(NOWApplication, self).save(commit)