class StoreModel(db.Model): __tablename__ = "EMP" __table_args__ = {'extend_existing': True} #ROWID = db.Column(db.String, primary_key=True) EMPNO = db.Column(db.Numeric(asdecimal=False), primary_key=True) ENAME = db.Column(db.String(10)) JOB = db.Column(db.String(9)) MGR = db.Column(db.Numeric(asdecimal=False)) DATE_OF_BIRTH = db.Column(db.DateTime) SAL = db.Column(db.Numeric(asdecimal=False)) COMM = db.Column(db.Numeric(asdecimal=False)) DEPTNO = db.Column(db.Numeric(asdecimal=False)) #items = db.relationship("ItemModel", lazy="dynamic") def __init__(self, EMPNO, ENAME, JOB, MGR, DATE_OF_BIRTH, SAL, COMM, DEPTNO): #self.ROWID = ROWID self.EMPNO = EMPNO self.ENAME = ENAME self.JOB = JOB self.MGR = MGR self.DATE_OF_BIRTH = DATE_OF_BIRTH self.SAL = SAL self.COMM = COMM self.DEPTNO = DEPTNO def json(self): #return {"name":self.name, "items":[item.json() for item in self.items.all()], "opening_date":str(self.opening_date.date())} #, "date":self.date #self.items.all() use that bcz we used lazy="dynamic" in line 13 return { "id": self.EMPNO, "name": self.ENAME, "designation": self.JOB, "manager_id": self.MGR, "date_of_birth": str(self.DATE_OF_BIRTH.date()), "salary": self.SAL, "commission": self.COMM, "department_no": self.DEPTNO } @classmethod def find_by_name(cls, name, date): # print("inside find_by_name method...") # print(date) # print(type(date)) datetime_object = datetime.strptime(date, '%d-%m-%Y') #print("#####################",datetime_object) return cls.query.filter_by( ENAME=name, DATE_OF_BIRTH=datetime_object.date()).first( ) #alter coommand = return cls.query.filter_by(name=name).first() def save_to_db(self): #Here self = Object of item db.session.add(self) db.session.commit() def delete_from_db(self): #Here self = Object of item db.session.delete(self) db.session.commit()
class Payslip(db.Model): """ Payslip info """ __tablename__ = 'payslips' # Payslip details id = db.Column(db.Integer, primary_key=True) payment_period_start = db.Column(db.Date()) payment_period_end = db.Column(db.Date()) gross_income = db.Column(db.Numeric()) income_tax = db.Column(db.Numeric()) net_income = db.Column(db.Numeric()) super_amount = db.Column(db.Numeric()) # Foreign keys employee_id = db.Column(db.Integer, db.ForeignKey('employees.id')) def __init__(self, name, price, store_id): self.name = name self.price = price self.store_id = store_id def to_json(self): """ Convert Employee instance to JSON format """ return { 'firstName': self.user.first_name, 'lastName': self.user.last_name, 'payment_period_start': self.payment_period_start, 'payment_period_end': self.payment_period_end, 'gross_income': self.gross_income, 'income_tax': self.income_tax, 'net_income': self.net_income, 'super_amount': self.super_amount } def to_csv(self): """ Convert Employee instance to CSV format """ pass def save_to_db(self): db.session.add(self) db.session.commit() def delete_from_db(self): db.session.delete(self) db.session.commit()
class PlanModel(db.Model, BaseMethods): __tablename__ = 'plans' id = db.Column(db.Integer, primary_key=True) # Relationships patients = db.relationship('PatientModel', lazy='dynamic') doctors = db.relationship('DoctorModel', lazy='dynamic') name = db.Column(db.String(50)) shortName = db.Column(db.String(3)) description = db.Column(db.String(150)) acceptedPatients = db.Column(db.Integer) price = db.Column(db.Numeric(9, 3)) def __init__(self, name, short_name, description, accepted_patients, price): super(PlanModel, self).__init__() self.name = name self.shortName = short_name self.description = description self.acceptedPatients = accepted_patients self.price = price def __repr__(self): return 'Plan: %r' % self.name def json(self): return { 'id': self.id, 'name': self.name, 'shortName': self.shortName, 'description': self.description, 'acceptedPatients': self.acceptedPatients, 'price': float(self.price) }
class Product(db.Model): '''products table''' __tablename__ = 'products' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(80)) price = db.Column(db.Numeric(10, 2)) categories = db.relationship('Category', secondary=categories, lazy='subquery', backref=db.backref('productes', lazy=True)) orders = db.relationship("OrderProduct", back_populates="product") def __init__(self, name, price): self.name = name self.price = price def json(self): return { 'id': self.id, 'name': self.name, 'price': round(self.price, 2) } @classmethod def find_by_id(cls, _id): return cls.query.filter_by(id=_id).first() def save_to_db(self): db.session.add(self) db.session.commit()
class Order(db.Model): __tablename__ = "Order" order_id = db.Column(db.Integer, primary_key=True, nullable=False, name="OrderNo") buyer_id = db.Column(db.Integer, db.ForeignKey( 'Buyer.BuyerId'), nullable=False, name="BuyerId") seller_id = db.Column(db.Integer, db.ForeignKey( 'Seller.SellerId'), nullable=False, name="SellerId") good_id = db.Column(db.Integer, db.ForeignKey( 'Good.GoodID'), nullable=False, name="GoodID") numbers = db.Column(db.Integer, nullable=False, name="Numbers") order_state = db.Column(db.Integer, nullable=False, name="OrderState") order_time = db.Column(TIMESTAMP, nullable=False, name="OrderTime") pay_time = db.Column(TIMESTAMP, name="PayTime") deliver_time = db.Column(TIMESTAMP, name="DeliverTime") cancel_time = db.Column(TIMESTAMP, name="CancelTime") success_time = db.Column(TIMESTAMP, name="SuccessTime") amount = db.Column(db.Numeric(25, 2), nullable=False, name="Amount") def __init__(self, **obj): self.__dict__.update(obj) self.order_time = try_from_timestamp(self.order_time) self.pay_time = try_from_timestamp(self.pay_time) self.deliver_time = try_from_timestamp(self.deliver_time) self.success_time = try_from_timestamp(self.success_time) self.cancel_time = try_from_timestamp(self.cancel_time)
class PriceModel(db.Model): __tablename__ = 'price' idprice = db.Column('idprice', db.Integer, primary_key=True) amount = db.Column(db.Numeric(12, 2), server_default="0") # busroute_idbusroute_schedule = Column(ForeignKey('busroute_schedule.idbusroute_schedule')) company_idcompany = db.Column(db.Integer, db.ForeignKey('company.idcompany'))
class DiscountModel(db.Model): __tablename__ = 'discount' iddiscount = db.Column('iddiscount', db.Integer, primary_key=True) descripcion = db.Column(db.String(100)) status = db.Column(db.String(15)) amount = db.Column(db.Numeric(12, 2)) company_idcompany = db.Column(db.Integer, db.ForeignKey('company.idcompany'))
class CustomerResultModel(db.Model): # tell SQLAlchemy table name __tablename__ = 'customer_results' id = db.Column(db.Integer(), primary_key=True, autoincrement=True) probability_of_default_next_month = db.Column( db.Numeric(precision=2, scale=2, asdecimal=False, decimal_return_scale=None)) feedback_did_default = db.Column(db.Boolean(), nullable=True) # One to One bidirectional (one customer_result to one customer) # cascading: delete customers if delete customerresult (cascade on delete) (default value of cascade is save-update, merge) customer = db.relationship('CustomerModel', back_populates='customer_result', lazy='dynamic', cascade='delete, save-update, merge') last_updated = db.Column(db.TIMESTAMP(timezone=False)) def __init__(self, probability_of_default_next_month, feedback_did_default): self.probability_of_default_next_month = probability_of_default_next_month self.feedback_did_default = feedback_did_default self.last_updated = datetime.utcnow().strftime( '%Y-%m-%d %H:%M:%S') # generate createdAt date on our server def update_customer_result(self, probability_of_default_next_month, feedback_did_default): self.probability_of_default_next_month = probability_of_default_next_month self.feedback_did_default = feedback_did_default self.last_updated = datetime.utcnow().strftime( '%Y-%m-%d %H:%M:%S') # generate createdAt date on our server # calling json() method is slow when calling self.chat_posts.all() due to lazy='dynamic' relationship def json(self): return { 'id': self.id, 'probability_of_default_next_month': self.probability_of_default_next_month, 'feedback_did_default': self.feedback_did_default, 'last_updated': self.last_updated.strftime('%Y-%m-%d %H:%M:%S') } def save_to_db(self): db.session.add(self) db.session.commit() def delete_from_db(self): db.session.delete(self) db.session.commit() @classmethod def find_by_id(cls, _id): return cls.query.filter_by(id=_id).first()
class OrderProduct(db.Model): '''order_product table''' __tablename__ = 'order_product' order_id = db.Column(db.Integer, db.ForeignKey('orders.id'), primary_key=True) product_id = db.Column(db.Integer, db.ForeignKey('products.id'), primary_key=True) quantity = db.Column(db.Numeric(10, 2)) cost = db.Column(db.Numeric(10, 2)) product = db.relationship("Product", back_populates="orders") order = db.relationship("Order", back_populates="products") def __init__(self, quantity, cost=0): self.quantity = quantity self.cost = cost
class FundModel(db.Model): __tablename__ = 'tblFund' id = db.Column(db.Integer, primary_key=True) fundName = db.Column(db.String(80)) fundRaised = db.Column(db.String(80)) totalInvestment = db.Column(db.Numeric(23, 2)) dryPowder = db.Column(db.Numeric(23, 2)) companyList = db.relationship('CompanyModel', lazy='dynamic') moicList = db.relationship('MoicModel', lazy='dynamic') def __init__(self, fundName, fundRaised, totalInvestment): self.fundName = fundName self.fundRaised = fundRaised self.totalInvestment = totalInvestment self.dryPowder = self.fundRaised - self.totalInvestment def json(self): return { 'id': self.id, 'fundName': self.fundName, 'totalInvestment': self.totalInvestment, 'dryPowder': self.totalInvestment # 'companyList': [company.json() for company in self.companyList.all()], # 'moicList': [moic.json() for moic in self.moicList.all()] } @classmethod def find_by_name(cls, fundName): return cls.query.filter_by(fundName=fundName).first() @classmethod def find_all(cls): return cls.query.all() def save_to_db(self): db.session.add(self) db.session.commit() def delete_from_db(self): db.session.delete(self) db.session.commit()
class DeductionModel(ModelMixin, db.Model): __tablename__ = 'deduction' exclude_from_update = ('employee_id', 'is_active') id = db.Column(db.Integer, primary_key=True) start_date = db.Column(db.Date, nullable=False) end_date = db.Column(db.Date) deduction_per_payment_period = db.Column(db.Numeric(7, 2), nullable=False) payment_method = db.Column(PAYMENT_METHOD, nullable=False) deduct_in_december = db.Column(db.Boolean, nullable=False) is_active = db.Column(db.Boolean, nullable=False) employee_id = db.Column(db.Integer, db.ForeignKey('employee.id'), nullable=False, index=True) creditor_id = db.Column(db.Integer, db.ForeignKey('creditor.id'), nullable=False, index=True) deduction_details = db.relationship(DeductionDetailModel, backref='deduction', lazy='joined') def __init__(self, start_date, end_date, deduction_per_payment_period, payment_method, deduct_in_december, is_active, employee_id, creditor_id): self.start_date = start_date self.end_date = end_date self.deduction_per_payment_period = deduction_per_payment_period self.payment_method = payment_method self.deduct_in_december = deduct_in_december self.is_active = is_active self.employee_id = employee_id self.creditor_id = creditor_id @classmethod def find_by_id(cls, _id, user): from models.employee import EmployeeModel record = cls.query.filter_by(id=_id).first() if record: if EmployeeModel.find_by_id(record.employee_id, user): return record @classmethod def find_all(cls, user, employee_id): from models.employee import EmployeeModel records = cls.query.filter_by(employee_id=employee_id).all() if records and EmployeeModel.find_by_id(employee_id, user): return records
class Rate(db.Model): __tablename__ = 'rate' __table_args__ = ( db.UniqueConstraint('currency_id', 'date'), ) id = db.Column(db.Integer(), primary_key=True) currency_id = db.Column(db.Integer(), db.ForeignKey('currency.id'), nullable=False) date = db.Column(db.DateTime(timezone=True), nullable=False) rate = db.Column(db.Numeric(), nullable=False) volume = db.Column(db.Numeric(), nullable=False) @classmethod async def update_or_create(cls, currency_id, date, rate, volume) -> None: update_query = cls.update.values( rate=rate, volume=volume, ).where( and_(cls.currency_id == currency_id, cls.date == date), ) update, _ = await update_query.gino.status() if update == 'UPDATE 0': # TODO find a better way to check if nothing was found try: await cls.create(currency_id=currency_id, date=date, rate=rate, volume=volume) except asyncpg.UniqueViolationError: await update_query.gino.status() @classmethod async def get_last_rate(cls, currency_id): return await cls.query.where( and_(cls.currency_id == currency_id), ).order_by(cls.date.desc()).gino.first() @classmethod async def get_avg_volume(cls, currency_id: int, last_days=None): query = func.avg(cls.volume).select().where(cls.currency_id == currency_id) if last_days: last_days_dt = datetime.utcnow().replace( hour=0, minute=0, second=0, microsecond=0, ) - timedelta(days=last_days - 1) query = query.where(Rate.date >= last_days_dt) return await query.gino.scalar()
class MoicModel(db.Model): __tablename__ = 'tblMoic' id = db.Column(db.Integer, primary_key=True) BenchmarkTVPI = db.Column(db.String(80)) Quartile = db.Column(db.Numeric(23, 2)) Median = db.Column(db.Numeric(23, 2)) fund_id = db.Column(db.Integer, db.ForeignKey('tblFund.id')) fund = db.relationship('FundModel') def __init__(self, BenchmarkTVPI, Quartile, Median, fund_id): self.BenchmarkTVPI = name self.Quartile = Quartile self.Median = Median self.fund_id = fund_id def json(self): return { 'id': self.id, 'BenchmarkTVPI': self.BenchmarkTVPI, 'Quartile': self.Quartile, 'Median': self.Median, 'fund_id': self.fund_id } @classmethod def find_by_id(cls, id): return cls.query.filter_by(id=id).first() @classmethod def find_all(cls): return cls.query.all() def save_to_db(self): db.session.add(self) db.session.commit() def delete_from_db(self): db.session.delete(self) db.session.commit()
class PaymentDetailModel(ModelMixin, db.Model): __tablename__ = 'payment_detail' exclude_from_update = ('payment_id',) id = db.Column(db.Integer, primary_key=True) payment_type = db.Column(PAYMENT_TYPE, nullable=False) gross_payment = db.Column(db.Numeric(7, 2), nullable=False) ss_deduction = db.Column(db.Numeric(7, 2)) se_deduction = db.Column(db.Numeric(7, 2)) isr_deduction = db.Column(db.Numeric(7, 2)) payment_id = db.Column(db.Integer, db.ForeignKey('payment.id'), nullable=False, index=True) def __init__(self, payment_type, gross_payment, ss_deduction, se_deduction, isr_deduction, payment_id): self.payment_type = payment_type self.gross_payment = gross_payment self.ss_deduction = ss_deduction self.se_deduction = se_deduction self.isr_deduction = isr_deduction self.payment_id = payment_id @classmethod def find_by_id(cls, _id, user): from models.payment import PaymentModel record = cls.query.filter_by(id=_id).first() if record: if PaymentModel.find_by_id(record.payment_id, user): return record @classmethod def find_all(cls, user, payment_id): from models.payment import PaymentModel records = cls.query.filter_by(payment_id=payment_id).all() if records and PaymentModel.find_by_id(payment_id, user): return records
class SickNoteModel(ModelMixin, db.Model): __tablename__ = 'sick_note' exclude_from_update = ('employee_id', ) id = db.Column(db.Integer, primary_key=True) sick_note_date = db.Column(db.Date, nullable=False) number_of_hours_requested = db.Column(db.Numeric(5, 2), nullable=False) number_of_hours_approved = db.Column(db.Numeric(5, 2), nullable=False) date_received = db.Column(db.Date, nullable=False) employee_id = db.Column(db.Integer, db.ForeignKey('employee.id'), nullable=False, index=True) def __init__(self, sick_note_date, number_of_hours_requested, number_of_hours_approved, date_received, employee_id): self.sick_note_date = sick_note_date self.number_of_hours_requested = number_of_hours_requested self.number_of_hours_approved = number_of_hours_approved self.date_received = date_received self.employee_id = employee_id @classmethod def find_by_id(cls, _id, user): from models.employee import EmployeeModel record = cls.query.filter_by(id=_id).first() if record: if EmployeeModel.find_by_id(record.employee_id, user): return record @classmethod def find_all(cls, user, employee_id): from models.employee import EmployeeModel records = cls.query.filter_by(employee_id=employee_id).all() if records and EmployeeModel.find_by_id(employee_id, user): return records
class EmploymentPositionModel(ModelMixin, db.Model): __tablename__ = 'employment_position' __table_args__ = (UniqueConstraint('position_name_feminine', 'organization_id', name='employment_position_' 'p_name_feminine_' 'organization_id_uindex'), UniqueConstraint('position_name_masculine', 'organization_id', name='employment_position_' 'p_name_masculine_' 'organization_id_uindex')) exclude_from_update = ('organization_id', 'is_active') id = db.Column(db.Integer, primary_key=True) position_name_feminine = db.Column(db.String(80), nullable=False) position_name_masculine = db.Column(db.String(80), nullable=False) minimum_hourly_wage = db.Column(db.Numeric(8, 4)) is_active = db.Column(db.Boolean, nullable=False) organization_id = db.Column(db.Integer, db.ForeignKey('organization.id'), nullable=False, index=True) employees = db.relationship(EmployeeModel, backref='employment_position', lazy='joined') def __init__(self, position_name_feminine, position_name_masculine, minimum_hourly_wage, is_active, organization_id): self.position_name_feminine = position_name_feminine self.position_name_masculine = position_name_masculine self.minimum_hourly_wage = minimum_hourly_wage self.is_active = is_active self.organization_id = organization_id @classmethod def find_by_id(cls, _id, user): from models.organization import OrganizationModel record = cls.query.filter_by(id=_id).first() if record: if OrganizationModel.find_by_id(record.organization_id, user): return record @classmethod def find_all(cls, user): return cls.query.filter_by(organization_id=user.organization_id).all()
class Starship(db.Model): __tablename__ = "starships" id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String, nullable=False) hyperdrive = db.Column(db.Numeric(10, 2), nullable=True) def __init__(self, name, hyperdrive): self.name = name self.hyperdrive = hyperdrive def save_to_db(self): db.session.add(self) db.session.commit()
class Employee(db.Model): """ Employee info """ __tablename__ = 'employees' # Employee details id = db.Column(db.Integer, primary_key=True) first_name = db.Column(db.String(100)) last_name = db.Column(db.String(100)) annual_salary = db.Column(db.Integer()) super_rate = db.Column(db.Numeric()) # Relationships payslips = db.relationship('Payslip', backref=db.backref('employee', lazy='joined'), lazy='dynamic') def __init__(self, name): self.name = name def to_json(self): """ Convert an Employee instance to JSON format """ return { 'firstName': self.first_name, 'lastName': self.last_name, 'annualSalary': self.annual_salary, 'superRate': '{}%'.format(self.super_rate * 100), 'payslips': [payslip.json() for payslip in self.payslips.all()] } def save_to_db(self): """ Save Employee to database """ db.session.add(self) db.session.commit() def delete_from_db(self): """ Delete Employee from database """ db.session.delete(self) db.session.commit()
class StoreModel(db.Model): __tablename__ = "stexhdtl" __table_args__ = {'extend_existing': True} ROWID = db.Column(db.String, primary_key=True) CURCDE = db.Column(db.String(3)) VALDAT = db.Column(db.DateTime) MIDRAT = db.Column(db.Numeric(asdecimal=False)) #items = db.relationship("ItemModel", lazy="dynamic") def __init__(self, ROWID, CURCDE, VALDAT, MIDRAT): self.ROWID = ROWID self.CURCDE = CURCDE self.VALDAT = VALDAT self.MIDRAT = MIDRAT def json(self): #return {"name":self.name, "items":[item.json() for item in self.items.all()], "opening_date":str(self.opening_date.date())} #, "date":self.date #self.items.all() use that bcz we used lazy="dynamic" in line 13 return { "currency_code": self.CURCDE, "validation_date": str(self.VALDAT.date()), "mid_rate": self.MIDRAT } @classmethod def find_by_name(cls, name, date): # print("inside find_by_name method...") # print(date) # print(type(date)) datetime_object = datetime.strptime(date, '%d-%m-%Y') #print("#####################",datetime_object) return cls.query.filter_by( CURCDE=name, VALDAT=datetime_object.date()).first( ) #alter coommand = return cls.query.filter_by(name=name).first() def save_to_db(self): #Here self = Object of item db.session.add(self) db.session.commit() def delete_from_db(self): #Here self = Object of item db.session.delete(self) db.session.commit()
class DeductionDetailModel(ModelMixin, db.Model): __tablename__ = 'deduction_detail' exclude_from_update = ('deduction_id', ) id = db.Column(db.Integer, primary_key=True) deducted_amount = db.Column(db.Numeric(7, 2), nullable=False) payment_id = db.Column(db.Integer, db.ForeignKey('payment.id'), nullable=False, index=True) deduction_id = db.Column(db.Integer, db.ForeignKey('deduction.id'), nullable=False, index=True) def __init__(self, deducted_amount, payment_id, deduction_id): self.deducted_amount = deducted_amount self.payment_id = payment_id self.deduction_id = deduction_id @classmethod def find_by_id(cls, _id, user): from models.deduction import DeductionModel record = cls.query.filter_by(id=_id).first() if record: if DeductionModel.find_by_id(record.deduction_id, user): return record @classmethod def find_all(cls, user, payment_id): from models.payment import PaymentModel records = cls.query.filter_by(payment_id=payment_id).all() if records and PaymentModel.find_by_id(payment_id, user): return records
class IndicatorModel(db.Model, BaseMethods): __tablename__ = 'indicators' id = db.Column(db.Integer, primary_key=True) # Relationship patientId = db.Column(db.Integer, db.ForeignKey('patients.id', onupdate='CASCADE', ondelete='CASCADE'), nullable=False) patient = db.relationship('PatientModel') indicatorTypeId = db.Column(db.Integer, db.ForeignKey('indicators_type.id', onupdate='CASCADE', ondelete='CASCADE'), nullable=False) indicatorType = db.relationship('IndicatorTypeModel') indicatorsEntry = db.relationship('IndicatorEntryModel', lazy='dynamic') quantity = db.Column(db.Numeric(9, 3)) frequency = db.Column(db.String(200)) createdAt = db.Column(db.DateTime, nullable=False) def __init__(self, patient_id, indicator_typ_id, quantity, frequency, created_at): super(IndicatorModel, self).__init__() self.patientId = patient_id self.indicatorTypeId = indicator_typ_id self.quantity = quantity self.frequency = frequency self.createdAt = datetime.now().strftime('%Y-%m-%d %H:%M:%S') if (created_at is None) else created_at def __repr__(self): return 'Indicator %r' % self.frequency def json(self): return { 'id': self.id, 'patient': self.patient.json(), 'indicatorType': self.indicatorType.json(), 'quantity': self.quantity, 'frequency': self.frequency }
class EmployeeModel(ModelMixin, db.Model): __tablename__ = 'employee' exclude_from_update = () id = db.Column(db.Integer, primary_key=True) first_name = db.Column(db.String(40), nullable=False) second_name = db.Column(db.String(40)) first_surname = db.Column(db.String(40), nullable=False) second_surname = db.Column(db.String(40)) national_id_number = db.Column(db.String(20)) is_panamanian = db.Column(db.Boolean, nullable=False) date_of_birth = db.Column(db.Date, nullable=False) gender = db.Column(GENDER, nullable=False) address = db.Column(db.String(300), nullable=False) home_phone = db.Column(db.String(10)) mobile_phone = db.Column(db.String(10)) email = db.Column(db.String(50)) type_of_contract = db.Column(TYPE_OF_CONTRACT, nullable=False) employment_date = db.Column(db.Date, nullable=False) contract_expiration_date = db.Column(db.Date) termination_date = db.Column(db.Date) termination_reason = db.Column(TERMINATION_REASON) salary_per_payment_period = db.Column(db.Numeric(7, 2), nullable=False) representation_expenses_per_payment_period = db.Column(db.Numeric(7, 2), nullable=False) payment_method = db.Column(PAYMENT_METHOD, nullable=False) is_active = db.Column(db.Boolean, nullable=False, index=True) marital_status_id = db.Column(db.Integer, db.ForeignKey('marital_status.id'), nullable=False) department_id = db.Column(db.Integer, db.ForeignKey('department.id'), nullable=False, index=True) position_id = db.Column(db.Integer, db.ForeignKey('employment_position.id'), nullable=False, index=True) shift_id = db.Column(db.Integer, db.ForeignKey('shift.id'), nullable=False) emergency_contacts = db.relationship(EmergencyContactModel, backref='employee', lazy='joined') health_permits = db.relationship(HealthPermitModel, backref='employee', lazy='joined') passports = db.relationship(PassportModel, backref='employee', lazy='joined') uniform_requirements = db.relationship(UniformRequirementModel, backref='employee', lazy='joined') bank_accounts = db.relationship(BankAccountModel, backref='employee', lazy='joined') dependents = db.relationship(DependentModel, backref='employee', lazy='joined') payments = db.relationship(PaymentModel, backref='employee', lazy='joined') deductions = db.relationship(DeductionModel, backref='employee', lazy='joined') attendances = db.relationship(AttendanceModel, backref='employee', lazy='joined') sick_notes = db.relationship(SickNoteModel, backref='employee', lazy='joined') absence_authorizations = db.relationship(AbsenceAuthorizationModel, backref='employee', lazy='joined') def __init__(self, first_name, second_name, first_surname, second_surname, national_id_number, is_panamanian, date_of_birth, gender, address, home_phone, mobile_phone, email, type_of_contract, employment_date, contract_expiration_date, termination_date, termination_reason, salary_per_payment_period, representation_expenses_per_payment_period, payment_method, is_active, marital_status_id, department_id, position_id, shift_id): self.first_name = first_name self.second_name = second_name self.first_surname = first_surname self.second_surname = second_surname self. national_id_number = national_id_number self.is_panamanian = is_panamanian self.date_of_birth = date_of_birth self.gender = gender self.address = address self.home_phone = home_phone self.mobile_phone = mobile_phone self.email = email self.type_of_contract = type_of_contract self.employment_date = employment_date self.contract_expiration_date = contract_expiration_date self.termination_date = termination_date self.termination_reason = termination_reason self.salary_per_payment_period = salary_per_payment_period self.representation_expenses_per_payment_period = \ representation_expenses_per_payment_period self.payment_method = payment_method self.is_active = is_active self.marital_status_id = marital_status_id self.department_id = department_id self.position_id = position_id self.shift_id = shift_id @classmethod def find_by_id(cls, _id, user): from models.department import DepartmentModel record = cls.query.filter_by(id=_id).first() if record: if DepartmentModel.find_by_id(record.department_id, user): return record @classmethod def find_all(cls, user): from models.department import DepartmentModel departments = DepartmentModel.find_all(user) d_ids = [department.id for department in departments] return cls.query.filter(cls.department_id.in_(d_ids)).all()
class ShiftModel(ModelMixin, db.Model): __tablename__ = 'shift' __table_args__ = (UniqueConstraint('shift_name', 'organization_id', name='shift_shift_name_organization_id_' 'uindex'), ) exclude_from_update = ('organization_id', 'is_active') id = db.Column(db.Integer, primary_key=True) shift_name = db.Column(db.String(80), nullable=False) weekly_hours = db.Column(db.Numeric(3, 1), nullable=False) is_rotating = db.Column(db.Boolean, nullable=False) payment_period = db.Column(PAYMENT_PERIOD, nullable=False) rotation_start_hour = db.Column(db.Time) rotation_end_hour = db.Column(db.Time) break_length = db.Column(db.Time, nullable=False) is_break_included_in_shift = db.Column(db.Boolean, nullable=False) fixed_start_hour_monday = db.Column(db.Time) fixed_start_break_hour_monday = db.Column(db.Time) fixed_end_break_hour_monday = db.Column(db.Time) fixed_end_hour_monday = db.Column(db.Time) fixed_start_hour_tuesday = db.Column(db.Time) fixed_start_break_hour_tuesday = db.Column(db.Time) fixed_end_break_hour_tuesday = db.Column(db.Time) fixed_end_hour_tuesday = db.Column(db.Time) fixed_start_hour_wednesday = db.Column(db.Time) fixed_start_break_hour_wednesday = db.Column(db.Time) fixed_end_break_hour_wednesday = db.Column(db.Time) fixed_end_hour_wednesday = db.Column(db.Time) fixed_start_hour_thursday = db.Column(db.Time) fixed_start_break_hour_thursday = db.Column(db.Time) fixed_end_break_hour_thursday = db.Column(db.Time) fixed_end_hour_thursday = db.Column(db.Time) fixed_start_hour_friday = db.Column(db.Time) fixed_start_break_hour_friday = db.Column(db.Time) fixed_end_break_hour_friday = db.Column(db.Time) fixed_end_hour_friday = db.Column(db.Time) fixed_start_hour_saturday = db.Column(db.Time) fixed_start_break_hour_saturday = db.Column(db.Time) fixed_end_break_hour_saturday = db.Column(db.Time) fixed_end_hour_saturday = db.Column(db.Time) fixed_start_hour_sunday = db.Column(db.Time) fixed_start_break_hour_sunday = db.Column(db.Time) fixed_end_break_hour_sunday = db.Column(db.Time) fixed_end_hour_sunday = db.Column(db.Time) rest_day = db.Column(DAYS_OF_WEEK) is_active = db.Column(db.Boolean, nullable=False) organization_id = db.Column(db.Integer, db.ForeignKey('organization.id'), nullable=False, index=True) employees = db.relationship(EmployeeModel, backref='shift', lazy='joined') def __init__(self, shift_name, weekly_hours, is_rotating, payment_period, break_length, is_break_included_in_shift, is_active, organization_id, **kwargs): self.shift_name = shift_name self.weekly_hours = weekly_hours self.is_rotating = is_rotating self.payment_period = payment_period self.break_length = break_length self.is_break_included_in_shift = is_break_included_in_shift self.is_active = is_active self.organization_id = organization_id if self.is_rotating: self.rotation_start_hour = kwargs.get('rotation_start_hour', time(0)) self.rotation_end_hour = kwargs.get('rotation_end_hour', time(12, 59, 59)) else: self.fixed_start_hour_monday = kwargs.get( 'fixed_start_hour_monday') self.fixed_start_break_hour_monday = kwargs.get( 'fixed_start_break_hour_monday') self.fixed_end_break_hour_monday = kwargs.get( 'fixed_end_break_hour_monday') self.fixed_end_hour_monday = kwargs.get('fixed_end_hour_monday') self.fixed_start_hour_tuesday = kwargs.get( 'fixed_start_hour_tuesday') self.fixed_start_break_hour_tuesday = kwargs.get( 'fixed_start_break_hour_tuesday') self.fixed_end_break_hour_tuesday = kwargs.get( 'fixed_end_break_hour_tuesday') self.fixed_end_hour_tuesday = kwargs.get('fixed_end_hour_tuesday') self.fixed_start_hour_wednesday = kwargs.get( 'fixed_start_hour_wednesday') self.fixed_start_break_hour_wednesday = kwargs.get( 'fixed_start_break_hour_wednesday') self.fixed_end_break_hour_wednesday = kwargs.get( 'fixed_end_break_hour_wednesday') self.fixed_end_hour_wednesday = kwargs.get( 'fixed_end_hour_wednesday') self.fixed_start_hour_thursday = kwargs.get( 'fixed_start_hour_thursday') self.fixed_start_break_hour_thursday = kwargs.get( 'fixed_start_break_hour_thursday') self.fixed_end_break_hour_thursday = kwargs.get( 'fixed_end_break_hour_thursday') self.fixed_end_hour_thursday = kwargs.get( 'fixed_end_hour_thursday') self.fixed_start_hour_friday = kwargs.get( 'fixed_start_hour_friday') self.fixed_start_break_hour_friday = kwargs.get( 'fixed_start_break_hour_friday') self.fixed_end_break_hour_friday = kwargs.get( 'fixed_end_break_hour_friday') self.fixed_end_hour_friday = kwargs.get('fixed_end_hour_friday') self.fixed_start_hour_saturday = kwargs.get( 'fixed_start_hour_saturday') self.fixed_start_break_hour_saturday = kwargs.get( 'fixed_start_break_hour_saturday') self.fixed_end_break_hour_saturday = kwargs.get( 'fixed_end_break_hour_saturday') self.fixed_end_hour_saturday = kwargs.get( 'fixed_end_hour_saturday') self.fixed_start_hour_sunday = kwargs.get( 'fixed_start_hour_sunday') self.fixed_start_break_hour_sunday = kwargs.get( 'fixed_start_break_hour_sunday') self.fixed_end_break_hour_sunday = kwargs.get( 'fixed_end_break_hour_sunday') self.fixed_end_hour_sunday = kwargs.get('fixed_end_hour_sunday') self.rest_day = kwargs.get('rest_day') @classmethod def find_by_id(cls, _id, user): from models.organization import OrganizationModel record = cls.query.filter_by(id=_id).first() if record: if OrganizationModel.find_by_id(record.organization_id, user): return record @classmethod def find_all(cls, user): return cls.query.filter_by(organization_id=user.organization_id).all()
class Buyer(db.Model): __tablename__ = "Buyer" buyer_id = db.Column(db.Integer, primary_key=True, nullable=False, name="BuyerId") username = db.Column(db.String(40), nullable=False, name="UserName") balance = db.Column(db.Numeric(25, 2), nullable=False, name="Balance")
class StoreModel(db.Model): __tablename__ = "KGDCL_API" __table_args__ = {'extend_existing': True} # ROWID = db.Column(db.String, primary_key=True) CUSCODE = db.Column(db.String(), primary_key=True) # , primary_key=True NAME = db.Column(db.String()) MOBILE = db.Column(db.String()) BILL_MONTH = db.Column(db.String()) BILL_YEAR = db.Column(db.String()) GASS_BILL = db.Column(db.Numeric()) SURCHARGE = db.Column(db.Numeric()) METER_CHARGE = db.Column(db.Numeric()) TOTAL_BILL = db.Column(db.Numeric()) LAST_PAYMENT_DATE = db.Column(db.DateTime) #items = db.relationship("ItemModel", lazy="dynamic") def __init__(self, CUSCODE, NAME, MOBILE, BILL_MONTH, BILL_YEAR, GASS_BILL, SURCHARGE, METER_CHARGE, TOTAL_BILL, LAST_PAYMENT_DATE): # self.ROWID = ROWID self.CUSCODE = CUSCODE self.NAME = NAME self.MOBILE = MOBILE self.BILL_MONTH = BILL_MONTH self.BILL_YEAR = BILL_YEAR self.GASS_BILL = GASS_BILL self.SURCHARGE = SURCHARGE self.METER_CHARGE = METER_CHARGE self.TOTAL_BILL = TOTAL_BILL self.LAST_PAYMENT_DATE = LAST_PAYMENT_DATE def json(self): #return {"name":self.name, "items":[item.json() for item in self.items.all()], "opening_date":str(self.opening_date.date())} #, "date":self.date #self.items.all() use that bcz we used lazy="dynamic" in line 13 return { "Customer Name": self.NAME, "Bill Month": self.BILL_MONTH, "Bill Year": self.BILL_YEAR, "Gas Bill": int(self.GASS_BILL), "Surcharge": int(self.SURCHARGE), "Meter Charge": int(self.METER_CHARGE), "Total Bill Amount": int(self.TOTAL_BILL), "Last Payment Date": str(self.LAST_PAYMENT_DATE.date()) } @classmethod def find_by_name(cls, name, date): # print("inside find_by_name method...") # print(date) # print(type(date)) # datetime_object = datetime.strptime(date, '%d-%m-%Y') #print("#####################",datetime_object) return cls.query.filter_by(CUSCODE=name, MOBILE=date).first( ) #alter coommand = return cls.query.filter_by(name=name).first() def save_to_db(self): #Here self = Object of item db.session.add(self) db.session.commit() def delete_from_db(self): #Here self = Object of item db.session.delete(self) db.session.commit()
class PatientModel(db.Model, BaseMethods): __tablename__ = 'patients' id = db.Column(db.Integer, primary_key=True) # Relationships userId = db.Column(db.Integer, db.ForeignKey('users.id', onupdate='CASCADE', ondelete='CASCADE'), nullable=False) user = db.relationship('UserModel') planId = db.Column(db.Integer, db.ForeignKey('plans.id', onupdate='CASCADE', ondelete='CASCADE'), nullable=False) plan = db.relationship('PlanModel') appointments = db.relationship('AppointmentModel', lazy='dynamic') memberships = db.relationship('MembershipModel', lazy='dynamic') prescriptions = db.relationship('PrescriptionModel', lazy='dynamic') indicators = db.relationship('IndicatorModel', lazy='dynamic') age = db.Column(db.Integer, nullable=False) bloodType = db.Column(db.String(3)) weight = db.Column(db.Numeric(9, 3)) sex = db.Column(db.String(10)) height = db.Column(db.Numeric(9, 3)) createdAt = db.Column(db.DateTime, nullable=False) updatedOn = db.Column(db.DateTime) status = db.Column(db.String(3), server_default='ACT') def __init__(self, user_id, plan_id, age, blood_type, weight, sex, height, created_at, updated_on, status): super(PatientModel, self).__init__() self.userId = user_id self.planId = plan_id self.age = age self.bloodType = blood_type self.weight = weight self.sex = sex self.height = height self.createdAt = datetime.now().strftime('%Y-%m-%d %H:%M:%S') if ( created_at is None) else created_at self.updatedOn = datetime.now().strftime('%Y-%m-%d %H:%M:%S') if ( updated_on is None) else updated_on self.status = status def __repr__(self): return 'Patient: %r' % self.age def json(self): return { 'id': self.id, 'user': self.user.json(is_long=True), 'plan': self.plan.json(), 'age': self.age, 'bloodType': self.bloodType, 'weight': float(self.weight), 'sex': self.sex, 'height': float(self.height), 'status': self.status } @classmethod def find_by_user_id(cls, user_id): return cls.query.filter_by(userId=user_id).first()
class StoreModel(db.Model): # __tablename__ = "STCODMAS3" __tablename__ = "STCODMAS" __table_args__ = {'extend_existing': True} #ROWID = db.Column(db.String, primary_key=True) #EMPNO = db.Column(db.Numeric(asdecimal=False), primary_key=True) HARCOD = db.Column(db.String(3), primary_key=True) SOFCOD = db.Column(db.String(6), primary_key=True) CODDES = db.Column(db.String(200)) CORCOD = db.Column(db.String(20)) AMOUNT = db.Column(db.Numeric(asdecimal=False)) MANHRS = db.Column(db.Numeric(asdecimal=False)) RTDNON = db.Column(db.String(1)) OPRSTAMP = db.Column(db.String(6)) TIMSTAMP = db.Column(db.DateTime) #Date object SECCOD = db.Column(db.String(8)) ACTFLG = db.Column(db.String(1)) SEQNUM = db.Column(db.Numeric(asdecimal=False)) INTRT_CHGFLG = db.Column(db.String(1)) REQUIRE_FLG = db.Column(db.String(1)) ODRSRL = db.Column(db.Numeric(asdecimal=False)) EFFDAT = db.Column(db.DateTime) #Date object #items = db.relationship("ItemModel", lazy="dynamic") def __init__(self, HARCOD, SOFCOD, CODDES, CORCOD, AMOUNT, MANHRS, RTDNON, OPRSTAMP, TIMSTAMP, SECCOD, ACTFLG, SEQNUM, INTRT_CHGFLG, REQUIRE_FLG, ODRSRL, EFFDAT): #self.ROWID = ROWID self.HARCOD = HARCOD self.SOFCOD = SOFCOD self.CODDES = CODDES self.CORCOD = CORCOD self.AMOUNT = AMOUNT self.MANHRS = MANHRS self.RTDNON = RTDNON self.OPRSTAMP = OPRSTAMP self.TIMSTAMP = TIMSTAMP self.SECCOD = SECCOD self.ACTFLG = ACTFLG self.SEQNUM = SEQNUM self.INTRT_CHGFLG = INTRT_CHGFLG self.REQUIRE_FLG = REQUIRE_FLG self.ODRSRL = ODRSRL self.EFFDAT = EFFDAT def json(self): #return {"name":self.name, "items":[item.json() for item in self.items.all()], "opening_date":str(self.opening_date.date())} #, "date":self.date #self.items.all() use that bcz we used lazy="dynamic" in line 13 # Date Value Handle For GET Method if (self.EFFDAT == None) or (self.TIMSTAMP == None): my_EFFDAT = str(self.EFFDAT) my_TIMSTAMP = str(self.TIMSTAMP) else: my_EFFDAT = str(self.EFFDAT.date()) my_TIMSTAMP = str(self.TIMSTAMP) return { "HARCOD": self.HARCOD, "SOFCOD": self.SOFCOD, "CODDES": self.CODDES, "CORCOD": self.CORCOD, "AMOUNT": self.AMOUNT, "MANHRS": self.MANHRS, "RTDNON": self.RTDNON, "OPRSTAMP": self.OPRSTAMP, "TIMSTAMP": my_TIMSTAMP, "SECCOD": self.SECCOD, "ACTFLG": self.ACTFLG, "SEQNUM": self.SEQNUM, "INTRT_CHGFLG": self.INTRT_CHGFLG, #, "REQUIRE_FLG": self.REQUIRE_FLG, "ODRSRL": self.ODRSRL, "EFFDAT": my_EFFDAT } #.date() @classmethod def find_by_name(cls, name, date): # print("inside find_by_name method...") # print(date) # print(type(date)) #datetime_object = datetime.strptime(date, '%d-%m-%Y') #print("#####################",datetime_object) return cls.query.filter_by(HARCOD=name, SOFCOD=date).first( ) #alter coommand = return cls.query.filter_by(name=name).first() def save_to_db(self): #Here self = Object of item db.session.add(self) db.session.commit() def delete_from_db(self): #Here self = Object of item db.session.delete(self) db.session.commit()
class CompanyModel(db.Model): __tablename__ = 'tblCompany' id = db.Column(db.Integer, primary_key=True) companyName = db.Column(db.String(400)) roundSize = db.Column(db.Numeric(23, 2)) postMoney = db.Column(db.Numeric(23, 2)) preMoneyVal = db.Column(db.Numeric(23, 2)) postMoneyVal = db.Column(db.Numeric(23, 2)) investmentCost = db.Column(db.Numeric(23, 2)) equity = db.Column(db.Numeric(23, 2)) HQ = db.Column(db.String(80)) fundId = db.Column(db.Integer) fund_id = db.Column(db.Integer, db.ForeignKey('tblFund.id')) vertical_id = db.Column(db.Integer, db.ForeignKey('tblSeries.id')) series_id = db.Column(db.Integer, db.ForeignKey('tblVertical.id')) seriesTbl = db.relationship('SeriesModel') verticalTbl = db.relationship('VerticalModel') fundTbl = db.relationship('FundModel') def __init__(self, companyName, roundSize, preMoneyVal, investmentCost, equity, HQ): self.companyName = companyName self.roundSize = roundSize self.preMoneyVal = preMoneyVal self.postMoney = preMoneyVal + roundSize self.investmentCost = investmentCost self.equity = equity self.HQ = HQ def json(self): return { 'id': self.id, 'companyName': self.companyName, 'roundSize': self.roundSize, 'preMoneyValue': self.preMoneyVal, 'postMoney': self.postMoney, 'investmentCost': self.investmentCost, 'equity': self.equity, 'HQ': self.HQ, 'series_id': self.series_id, 'vertical_id': self.vertical_id, 'fund_id': self.fund_id } @classmethod def find_by_name(cls, name): return cls.query.filter_by(name=name).first() @classmethod def find_by_id(cls, id): return cls.query.filter_by(id=id).first() @classmethod def find_all(cls): return cls.query.all() def save_to_db(self): db.session.add(self) db.session.commit() def delete_from_db(self): db.session.delete(self) db.session.commit()