class Order(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    payment_method = db.Column(db.String(10))
    shipping_method = db.Column(db.String(10))
    date_placed = db.Column(db.Date())
    date_delivered = db.Column(db.Date())
    price = db.Column(db.Float)

    account_id = db.Column(db.String(100), db.ForeignKey('account.email'))
    account = db.relationship('Account',
                              backref=db.backref('orders', lazy='dynamic'))

    def __init__(self,
                 payment_method,
                 shipping_method,
                 account,
                 date_placed=None,
                 date_delivered=None):
        self.payment_method = payment_method
        self.shipping_method = shipping_method
        self.date_placed = datetime.now()
        self.date_delivered = self.date_placed + timedelta(days=10)
        self.account = account

    def __repr__(self):
        return '<Order %r>' % self.account_id
예제 #2
0
class Shift(db.Model):
    __tablename__ = "shifts"
    day = db.Column(db.Date(), primary_key=True)
    staff_id = db.Column(db.String(), primary_key=True)
    start_time = db.Column(db.Time(), nullable=False)
    end_time= db.Column(db.Time(), nullable=False)
    
    def get_monthly_shift(target_month, end_target):
        monthly_shift = Shift.query.join(Staff, Shift.staff_id==Staff.staff_id) \
                .add_columns(Shift.day, Staff.nickname, Shift.start_time, Shift.end_time) \
                .filter(Shift.day.between(target_month, end_target)).order_by(Shift.start_time).all()
        return monthly_shift

    def get_daily_shift(target_date):
        daily_shift = Shift.query.join(Staff, Shift.staff_id==Staff.staff_id) \
                .add_columns(Shift.day, Staff.staff_id, Staff.nickname, Shift.start_time, Shift.end_time) \
                .filter(Shift.day==target_date).order_by(Shift.start_time, Staff.staff_id).all()
        return daily_shift
    
    def add_shift(target_date, staff_id, start_time, end_time):
        shift = Shift(day=target_date, staff_id=staff_id, start_time=start_time, end_time=end_time)
        db.session.add(shift)
        db.session.commit()
    
    def del_shift(target_date, staff_id):
        db.session.query(Shift).filter(Shift.day==target_date, Shift.staff_id==staff_id).delete()
        db.session.commit()
예제 #3
0
class NonDate(db.Model):
	__tablename__="nondates"
	id = db.Column(db.Integer, primary_key=True,autoincrement=True)
	greg = db.Column(db.Date())
	hdate_str = db.Column(db.String())
	hdate_str_heb = db.Column(db.String())
	student = db.relationship("Student",uselist=False)
	student_id = db.Column(db.Integer,db.ForeignKey('students.id'))
예제 #4
0
class Pessoa(db.Model):
    __tablename__ = 'pessoas'

    id = db.Column(db.Integer, primary_key=True)
    nome = db.Column(db.String())
    cpf = db.Column(db.String())
    datanascimento = db.Column(db.Date())
    email = db.Column(db.String())
    telefones = db.relationship('Telefone', backref='telefones')
예제 #5
0
class Movie(db.Model):
    def __init__(self, title, release_date):
        self.title = title
        self.release_date = release_date

    title = db.Column(db.String(64), nullable=False, unique=True)
    release_date = db.Column(db.Date(), nullable=False, unique=False)
    actors = db.relationship("Actor",
                             secondary=movies_actors,
                             back_populates="movies")
예제 #6
0
class Article(db.Base):
    __tablename__ = 'articles'

    id = db.Column(db.String(50),
                   primary_key=True,
                   default=lambda: str(uuid.uuid4()))
    owner_id = db.Column(db.String(50), nullable=False)
    owner_type = db.Column(db.String(10), nullable=False)
    url = db.Column(db.String(2048), nullable=False)
    title = db.Column(db.String(512), nullable=False)
    summary = db.Column(db.String(200))
    date = db.Column(db.Date())

    def __init__(self):
        pass

    def __str__(self):
        return f'{self.url} : {self.title}'
class News(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(1000))
    content = db.Column(db.String(2000))
    date_issued = db.Column(db.Date())

    publisher_name = db.Column(db.String(100), db.ForeignKey('publisher.name'))
    publisher = db.relationship('Publisher',
                                backref=db.backref('news', lazy='dynamic'))

    def __init__(self, title, content, date_issued, publisher):
        self.title = title
        self.content = content
        self.date_issued = date_issued
        self.publisher = publisher

    def __repr__(self):
        return self.title
예제 #8
0
파일: data.py 프로젝트: berserkwarwolf/FQM
class Serial(db.Model):
    __tablename__ = "serials"
    id = db.Column(db.Integer, primary_key=True)
    number = db.Column(db.Integer)
    timestamp = db.Column(db.DateTime(), index=True, default=datetime.utcnow)
    date = db.Column(db.Date(), default=datetime.utcnow().date)
    name = db.Column(db.String(300), nullable=True)
    n = db.Column(db.Boolean)
    p = db.Column(db.Boolean)
    # stands for proccessed , which be modified after been processed
    pdt = db.Column(db.DateTime())
    # Fix: adding pulled by feature to tickets
    pulledBy = db.Column(db.Integer)
    office_id = db.Column(db.Integer, db.ForeignKey('offices.id'))
    task_id = db.Column(db.Integer, db.ForeignKey('tasks.id'))

    def __init__(self, number=100,
                 office_id=1,
                 task_id=1, pulledBy = 01,
                 name=None, n=False, p=False):
예제 #9
0
class User(db.Model, UserMixin):
    """
	User model building off of flask-registration
	"""
    __tablename__ = 'user'
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(60))
    password = db.Column(db.String())
    last_login_at = db.Column(db.DateTime())
    current_login_at = db.Column(db.DateTime())
    last_login_ip = db.Column(db.String())
    current_login_ip = db.Column(db.String())
    login_count = db.Column(db.Integer())
    created = db.Column(db.Date())
    company = db.Column(db.String)
    apis = db.relationship('API',
                           secondary=apis,
                           backref=db.backref('apis', lazy='dynamic'))
    active = db.Column(db.Boolean())
    confirmed_at = db.Column(db.DateTime())
    roles = db.relationship('Role',
                            secondary=roles_users,
                            backref=db.backref('user'))
    onboarded = db.Column(db.Boolean(), default=False)
    returning_visitors = db.relationship('GoogleAnalyticsReturningVisitors',
                                         secondary=returning_visitors,
                                         backref=db.backref('user'))
    signups = db.relationship('GoogleAnalyticsSignups',
                              secondary=signups,
                              backref=db.backref('user'))

    def __repr__(self):
        return '<User %s>' % self.email

    def as_dict(self):
        return {
            'email': self.email,
            'roles': [str(role) for role in self.roles],
            'onboarded': self.onboarded
        }
예제 #10
0
class API1(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    countrycode = db.Column(db.String(4))
    date = db.Column(db.Date())
    cases = db.Column(db.Integer())
    deaths = db.Column(db.Integer())
    recovered = db.Column(db.Integer())

    def __init__(self, countrycode, date, cases, deaths, recovered):
        self.countrycode = countrycode
        self.date = date
        self.cases = cases
        self.deaths = deaths
        self.recovered = recovered

    def __repr__(self):
        return '<Country %r>' % self.countrycode

    def as_dict(self):
        dictionary = {
            c.name: getattr(self, c.name)
            for c in self.__table__.columns
        }
        return dictionary
예제 #11
0
class UserReading(db.Model):
    __tablename__ = 'UserReading'
    id = db.Column(db.Integer, primary_key=True)
    userId = db.Column(db.String())
    readingRate = db.Column(db.Integer)
    currentBook = db.Column(db.String())
    currentChp = db.Column(db.Integer)
    nextBook = db.Column(db.String())
    nextChp = db.Column(db.Integer)
    today = db.Column(db.Date())
    offset = db.Column(db.Integer)

    def __init__(self, userId):
        self.userId = userId
        self.readingRate = None
        self.currentBook = None
        self.currentChp = None
        self.nextBook = None
        self.nextChp = None
        self.today = None
        self.offset = None

    def __repr__(self):
        return '<id {}>'.format(self.id)
예제 #12
0
class AttendanceModel(db.Model):
    __tablename__ = "attendances"

    id = db.Column(db.Integer, primary_key=True)
    student_id = db.Column(db.Integer,
                           db.ForeignKey("students.id"),
                           nullable=False)
    school_id = db.Column(db.Integer,
                          db.ForeignKey("schools.id"),
                          nullable=False)
    grade = db.Column(
        db.Enum("KG",
                "G-1",
                "G-2",
                "G-3",
                "G-4",
                "G-5",
                "G-6",
                "G-7",
                "G-8",
                "G-9",
                "G-10",
                "G-11",
                "G-12",
                name="grade"))
    year = db.Column(db.Integer, nullable=False)
    enrolled_date = db.Column(db.Date(), nullable=True)
    school = relationship("SchoolModel", foreign_keys=[school_id])
    student = relationship("StudentModel", foreign_keys=[student_id])

    def __init__(self, student_id: str, school_id: str, grade: str, year: str,
                 enrolled_date: date) -> None:
        self.student_id = student_id
        self.school_id = school_id
        self.grade = grade
        self.year = year
        self.enrolled_date = enrolled_date

    def __repr__(self):
        return f"<Attendance for student id:  {self.student_id}>"

    def attendance_dict(self, school: SchoolModel, student: StudentModel):
        """
        Return object data for viewing easily serializable format
        :param school:
        :param student:
        :return:
        """
        return {
            "id": self.id,
            "grade": self.grade,
            "year": self.year,
            "enrolled_date": self.enrolled_date.strftime("%d-%m-%Y"),
            "school": school.school_dict(),
            "student": student.student_dict()
        }

    @staticmethod
    def create_attendance(new_attendance) -> bool:
        """
        create new_attendance
        :param new_attendance:
        :return: bool
        """
        try:
            db.session.add(new_attendance)
            db.session.commit()
            return new_attendance.id
        except SQLAlchemyError as error:
            db.session.rollback()
            raise error

    @staticmethod
    def get_all_attendance() -> List[AttendanceModel]:
        """
        get all Attendance records
        :return: Attendance list
        """
        try:
            return db.session.query(AttendanceModel, SchoolModel, StudentModel).\
                filter(AttendanceModel.school_id == SchoolModel.id).\
                filter(AttendanceModel.student_id == StudentModel.id).all()
        except SQLAlchemyError as error:
            raise error

    @staticmethod
    def get_attendance_by_id(attendance_id: int) -> List[AttendanceModel]:
        """
        get all Attendance records
        :param attendance_id
        :return: Attendance list
        """
        try:
            return db.session.query(AttendanceModel, SchoolModel, StudentModel). \
                filter(AttendanceModel.school_id == SchoolModel.id). \
                filter(AttendanceModel.student_id == StudentModel.id).\
                filter(AttendanceModel.id == attendance_id)
        except SQLAlchemyError as error:
            raise error

    @staticmethod
    def delete_attendance_by_id(attendance_id: int) -> bool:
        """
        delete Attendance by id
        :param attendance_id:
        :return:
        """
        try:
            if not db.session.query(AttendanceModel).filter(
                    AttendanceModel.id == attendance_id).delete():
                return False
            db.session.commit()
            return True
        except SQLAlchemyError as error:
            db.session.rollback()
            raise error

    @staticmethod
    def update_attendance(attendance_id: int,
                          attendance: AttendanceModel) -> bool:
        """
        update attendance info by id
        :param attendance_id:
        :param attendance:
        :return: bool
        """
        try:
            target_attendance = db.session.query(AttendanceModel).filter(
                AttendanceModel.id == attendance_id).first()
            if not target_attendance:
                raise SQLCustomError("No record for requested attendance")
            target_attendance.student_id = attendance.student_id
            target_attendance.school_id = attendance.school_id
            target_attendance.grade = attendance.grade
            target_attendance.year = attendance.year
            target_attendance.enrolled_date = attendance.enrolled_date
            db.session.commit()
            return True
        except SQLAlchemyError as error:
            db.session.rollback()
            raise error
예제 #13
0
class Stat(db.Model):
    __tablename__ = 'stat'
    id = db.Column(db.Integer, primary_key=True)
    profile_id = db.Column(db.Integer, db.ForeignKey('profile.id'))
    rank = db.Column(db.Integer)
    stat_date = db.Column(db.Date())
예제 #14
0
class StudentModel(db.Model):
    __tablename__ = "students"

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String())
    deactivated_at = db.Column(db.DateTime(), nullable=True)
    birth_date = db.Column(db.Date(), nullable=True)
    father_name = db.Column(db.UnicodeText())
    mother_name = db.Column(db.UnicodeText())
    parents_occupation = db.Column(db.Text())
    photo = db.Column(db.Text())
    address_id = db.Column(db.Integer,
                           db.ForeignKey("addresses.id"),
                           nullable=False)
    address = relationship("AddressModel", foreign_keys=[address_id])

    def __init__(self, name: str, deactivated_at: datetime, birth_date: date,
                 father_name: str, mother_name: str, parents_occupation: str,
                 photo: str, address_id: int):
        self.name = name
        self.deactivated_at = deactivated_at
        self.birth_date = birth_date
        self.father_name = father_name
        self.mother_name = mother_name
        self.parents_occupation = parents_occupation
        self.photo = photo
        self.address_id = address_id

    def __repr__(self):
        return f"<Student {self.name}>"

    def student_dict(self) -> Dict[str, Any]:
        """
        Return object data in easily serializable format
        """
        return {
            "id":
            self.id,
            "name":
            self.name,
            "deactivated_at":
            self.deactivated_at.strftime("%d-%m-%Y")
            if self.deactivated_at else "",
            "birth_date":
            self.birth_date.strftime("%d-%m-%Y") if self.birth_date else "",
            "father_name":
            self.father_name,
            "mother_name":
            self.mother_name,
            "parents_occupation":
            self.parents_occupation,
            "photo":
            self.photo,
            "address": {
                "id": self.address_id,
                "division": self.address.division,
                "district": self.address.district,
                "township": self.address.township,
                "street_address": self.address.street_address
            }
        }

    @staticmethod
    def get_student_by_id(student_id: int) -> Optional[StudentModel]:
        """
        get student by id
        :param student_id:
        :return: student info
        """
        try:
            return db.session.query(StudentModel). \
                join(AddressModel). \
                filter(StudentModel.id == student_id).first()
        except SQLAlchemyError as error:
            raise error

    @staticmethod
    def get_students_by_name(name) -> List[StudentModel]:
        """
        get students by name (as name is not unique, multiple records can be returned)
        :param name:
        :return: student info list
        """
        try:
            return db.session.query(StudentModel).join(AddressModel).filter(
                StudentModel.name == name)
        except SQLAlchemyError as error:
            raise error

    @staticmethod
    def get_students_by_birth_date(birth_date) -> List[StudentModel]:
        """
        get students by birth_date (as birth_date is not unique, multiple records can be returned)
        :param birth_date:
        :return: student info list
        """
        try:
            return db.session.query(StudentModel).join(AddressModel).filter(
                StudentModel.birth_date == birth_date)
        except SQLAlchemyError as error:
            raise error

    @staticmethod
    def get_all_students(page) -> Pagination:
        """
        get all students
        :return: students list of dict
        """
        try:
            return db.session.query(StudentModel).join(AddressModel).\
                paginate(page=page, error_out=False)
        except SQLAlchemyError as error:
            raise error

    @staticmethod
    def get_all_student_address(page) -> Pagination:
        """
        get all school address for get all address API
        :params page
        :return
        """
        try:
            return db.session.query(AddressModel, StudentModel). \
                filter(AddressModel.id == StudentModel.address_id).filter(
                AddressModel.type == "student").paginate(page=page, error_out=False)
        except SQLAlchemyError as error:
            raise error

    @staticmethod
    def create_student(new_student):
        """
        create new student
        :param new_student:
        :return: bool
        """
        try:
            db.session.add(new_student)
            db.session.commit()
            return new_student.id
        except SQLAlchemyError as error:
            db.session.rollback()
            raise error

    @staticmethod
    def update_student(student_id, student) -> bool:
        """
        update student info by id
        :param student_id:
        :param student:
        :return: bool
        """
        try:
            target_student = db.session.query(StudentModel).filter(
                StudentModel.id == student_id).first()
            if not target_student:
                raise SQLCustomError("No record for requested student")
            target_student.name = student.name
            target_student.deactivated_at = student.deactivated_at
            target_student.birth_date = student.birth_date
            target_student.father_name = student.father_name
            target_student.mother_name = student.mother_name
            target_student.parents_occupation = student.parents_occupation
            target_student.photo = student.photo
            target_student.address_id = student.address_id
            db.session.commit()
            return True
        except SQLAlchemyError as error:
            db.session.rollback()
            raise error

    @staticmethod
    def delete_student(student_id) -> bool:
        """
        delete student by id
        :param student_id:
        :return: bool
        """
        try:
            if not db.session.query(StudentModel).filter(
                    StudentModel.id == student_id).delete():
                return False
            db.session.commit()
            return True
        except SQLAlchemyError as error:
            db.session.rollback()
            raise error
예제 #15
0
class StudentModel(db.Model):
    __tablename__ = "students"

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String())
    deactivated_at = db.Column(db.DateTime(), nullable=True)
    birth_date = db.Column(db.Date(), nullable=True)
    father_name = db.Column(db.UnicodeText())
    mother_name = db.Column(db.UnicodeText())
    parents_occupation = db.Column(db.Text())
    address_id = db.Column(db.Integer, db.ForeignKey("addresses.id"), nullable=False)
    address = relationship("AddressModel", foreign_keys=[address_id])

    def __init__(self, name: str,
                 deactivated_at: datetime, birth_date: date, father_name: str, mother_name: str,
                 parents_occupation: str, address_id: int):
        self.name = name
        self.deactivated_at = deactivated_at
        self.birth_date = birth_date
        self.father_name = father_name
        self.mother_name = mother_name
        self.parents_occupation = parents_occupation
        self.address_id = address_id

    def __repr__(self):
        return f"<Student {self.name}>"

    def student_dict(self) -> Dict[str, Any]:
        """
        Return object data in easily serializable format
        """
        return {
            "id": self.id,
            "name": self.name,
            "deactivated_at": self.deactivated_at.strftime("%d-%m-%Y") if self.deactivated_at else "",
            "birth_date": self.birth_date.strftime("%d-%m-%Y") if self.birth_date else "",
            "father_name": self.father_name,
            "mother_name": self.mother_name,
            "parents_occupation": self.parents_occupation,
            "address": {
                "id": self.address_id,
                "division": self.address.division,
                "district": self.address.district,
                "township": self.address.township,
                "street_address": self.address.street_address
            }
        }

    @staticmethod
    def create_student(new_student):
        """
        create new student
        :param new_student:
        :return: bool
        """
        try:
            db.session.add(new_student)
            db.session.commit()
            return True
        except SQLAlchemyError as e:
            # to put log
            return False
예제 #16
0
class Student(db.Model):
	__tablename__ = "students"
	id = db.Column(db.Integer(),primary_key=True)
	school = db.relationship("School",back_populates ="students",uselist=False)
	hebSchool = db.relationship("HebSchool",back_populates ="students",uselist=False) #way to make non-list?
	dob  = db.Column(db.Date())
	email=db.Column(db.String())
	childName=db.Column(db.String())
	ranking_main=db.Column(db.Integer())
	ranking_familyMinyan=db.Column(db.Integer())
	ranking_torahInTheRound=db.Column(db.Integer())
	atVenue = db.Column(db.Boolean())
	over200 = db.Column(db.Boolean())
	accommodation_other = db.Column(db.Text)
	twin = db.Column(db.Boolean())
	school_id = db.Column(db.Integer,db.ForeignKey('schools.id'))
	hebSchool_id = db.Column(db.Integer,db.ForeignKey('hebschools.id'))
	nonDates = db.relationship("NonDate",back_populates="student",uselist=True)
	birthdayDD =db.Column(db.Text)
	bmDD = db.Column(db.Text)

	def __init__(self,rankings,schoolId,school,hebSchoolId,hebSchool,DOB,DOBdd,BMdd,nonDates=[],accommodation=False, **kwargs):

		super(Student, self).__init__(**kwargs)
		self.ranking_main=rankings[0]['value']
		self.ranking_familyMinyan=rankings[1]['value']
		self.ranking_torahInTheRound=rankings[2]['value']

		self.dob=parse(DOB).date()

		self.birthdayDD = json.dumps(DOBdd)
		self.bmDD = json.dumps(BMdd)


		self.nonDates=[]
		# for nonDate in nonDates:
		# 	greg = nonDate['greg']
		# 	gdate = date(greg['year'],greg['month'],greg['day'])
		# 	nd = NonDate(greg=gdate)
		# 	nd.student_id = self.id
		# 	self.nonDates.append(nd)
		# 	nd.student=self
		# 	print("APPENDING non-DATE")
		# 	print(f"My id is: {self.id}")
		# 	db.session.add(nd)
		# gregs=[nonDate['greg'] for nonDate in nonDates]
		# self.nonDates=NonDate.cls_construct(gregs)
	def approx_bm_dd_str(self):
		BMdd=json.loads(self.bmDD)
		return parse(BMdd['hgregorian']).strftime('%m/%d/%Y') +  " (" + BMdd['hdate_str'] + "/" + BMdd['hdate_str_heb'] + ")"
	def birthday_dd_str(self):
		DOBdd=json.loads(self.birthdayDD)
		return self.dob.strftime('%m/%d/%Y') + " (" + DOBdd['hdate_str'] + "/" + DOBdd['hdate_str_heb'] + ")"
	def non_date_string(self):
		nds = [nd.greg.strftime('%m/%d/%Y') for nd in self.nonDates]
		return ", ".join(nds)

	def to_dict(self):
		nds=[{'hgregorian':nd.greg,'hdate_str':nd.hdate_str,'hdate_str_heb':nd.hdate_str_heb} for nd in self.nonDates]
		d = {'email': self.email,
		'childName':self.childName,
		'school':self.school.name,
		'schoolId':self.school.id,
		'hebSchool':self.hebSchool.name,
		'hebSchoolId':self.hebSchool.id,
		'DOB':self.dob,
		'DOBdd':json.loads(self.birthdayDD),
		'BMdd':json.loads(self.bmDD),
		'rankings':[{
		      'name': "Main Sanctuary",
		      'value': self.ranking_main
		    },
		    {
		      'name': "Family Minyan",
		      'value': self.ranking_familyMinyan
		    },
		    {
		      'name': "Torah In The Round",
		      'value': self.ranking_torahInTheRound
		    }],
		 'atVenue':self.atVenue,
		 'over200':self.over200,
		 'nonDates':nds,
		 'accommodation':self.accommodation_other != '',
		 'accommodation_other':self.accommodation_other,
		 'twin':self.twin,
		}
		return d

	def to_csv_row(self):
		a_row = [self.email, self.childName, self.birthday_dd_str(), self.school.name, self.hebSchool.name, self.atVenue, self.over200, self.twin, self.accommodation_other,]

		a_row.append(self.approx_bm_dd_str())
		a_row.append("Main: {}, Family Minyan: {}, Torah in the Round: {}".format(self.ranking_main,self.ranking_familyMinyan,self.ranking_torahInTheRound))
		a_row.append(self.non_date_string())
		return a_row
예제 #17
0
class Exam(db.Model):
    __tablename__ = "exams"

    id = db.Column(db.Integer, primary_key=True)

    description = db.Column(db.String(), nullable=False)

    photo_url = db.Column(db.String(), nullable=False)

    procedure_code = db.Column(db.String(), nullable=True)

    date_for_receipt = db.Column(db.Date())

    cut_off_date = db.Column(db.Date())

    fk_exam_types_id = db.Column(db.Integer,
                                 db.ForeignKey("exam_types.id"),
                                 nullable=False)
    exam_type = db.relationship("ExamType",
                                foreign_keys="Exam.fk_exam_types_id")

    fk_locations_id = db.Column(db.Integer,
                                db.ForeignKey("locations.id"),
                                nullable=False)
    location = db.relationship("Location", foreign_keys="Exam.fk_locations_id")

    fk_providers_id = db.Column(db.Integer,
                                db.ForeignKey("providers.id"),
                                nullable=False)
    provider = db.relationship("Provider", foreign_keys="Exam.fk_providers_id")

    fk_health_plans_id = db.Column(db.Integer,
                                   db.ForeignKey("health_plans.id"),
                                   nullable=False)
    health_plan = db.relationship("HealthPlan",
                                  foreign_keys="Exam.fk_health_plans_id")

    items = db.relationship("ExamItem", uselist=True)

    fk_users_id = db.Column(db.Integer,
                            db.ForeignKey("users.id"),
                            nullable=False)
    user = db.relationship("User", foreign_keys="Exam.fk_users_id")

    created_at = db.Column(db.DateTime())
    updated_at = db.Column(db.DateTime())

    def save(self):
        try:
            db.session.add(self)
            db.session.commit()
        except Exception as ex:
            db.session.rollback()
            print(ex)
            raise Exception("Ocorreu um erro ao inserir local de atendimento!")

    def delete(self):
        db.session.query(Exam.id == self.id).delete()
        db.session.commit()

    def json(self):
        return {"id": self.id}

    @classmethod
    def find_by_id(cls, id):
        return db.session.query(cls).filter(cls.id == id).first()

    # -----------------------------------------------------
    # GRAPHQL
    # -----------------------------------------------------
    @classmethod
    def resolve_exams(cls, authorizedUser, **kwargs):
        query = db.session.query(Exam)

        id, description, page_index, page_size = (
            kwargs.get("id"),
            kwargs.get("l_description"),
            kwargs.get("page_index", 0),
            kwargs.get("page_size", 10),
        )

        provider_id = kwargs.get("provider_id")
        location_id = kwargs.get("location_id")
        exam_type_id = kwargs.get("exam_type_id")

        begin = kwargs.get("begin")
        end = kwargs.get("end")

        query = query.filter(cls.fk_users_id == authorizedUser.id)

        if id is not None:
            query = query.filter(Exam.id == id)

        if provider_id is not None:
            query = query.filter(cls.fk_providers_id == provider_id)

        if location_id is not None:
            query = query.filter(cls.fk_locations_id == location_id)

        if exam_type_id is not None:
            query = query.filter(cls.fk_exam_types_id == exam_type_id)

        if begin is not None:
            query = query.filter(cls.created_at >= begin)

        if end is not None:
            query = query.filter(cls.created_at <= end)

        if description is not None:
            query = query.filter(Exam.description.like(f"%{description}%"))

        return query.offset(page_index * page_size).limit(page_size)

    @classmethod
    def resolve_exam(cls, authorizedUser, **kwargs):
        query = db.session.query(Exam)
        query = query.filter(cls.fk_users_id == authorizedUser.id)
        id = kwargs.get("id")
        return query.filter(Exam.id == id).first()

    @classmethod
    def resolve_pending_exams(cls, authorizedUser, **kwargs):

        page_index, page_size = (
            kwargs.get("page_index", 0),
            kwargs.get("page_size", 10),
        )

        query = db.session.query(cls) \
            .outerjoin(cls.items)

        query = query.filter(cls.fk_users_id == authorizedUser.id)

        # Exames sem data para recebimento, exames sem data de corte, exames com procedimentos sem custo definido
        query = query.filter(
            or_(cls.date_for_receipt == None, cls.cut_off_date == None,
                ExamItem.cost == None))

        return query.offset(page_index * page_size).limit(page_size)
예제 #18
0
class Organization(db.Model):

    __tablename__ = "organizations"

    id = db.Column(db.Integer, primary_key=True)
    cpf_cnpj = db.Column(db.String(256), index=True, unique=True)
    description = db.Column(db.String(256))

    created_at = db.Column(db.Date())
    updated_at = db.Column(db.Date())

    users = db.relationship("User", uselist=True)

    locations = db.relationship("Location", uselist=True)
    providers = db.relationship("Provider", uselist=True)
    exam_types = db.relationship("ExamType", uselist=True)

    def __init__(self, *args, **kwargs):
        self.id = None
        self.cpf_cnpj = kwargs.get("cpf_cnpj", None)
        self.description = kwargs.get("description", None)
        self.created_at = kwargs.get("created_at", datetime.now())
        self.updated_at = kwargs.get("updated_at", datetime.now())

        if self.cpf_cnpj is None:
            raise Exception("Informe o CPF ou CNPJ!")
        elif self.description is None:
            raise Exception("Informe a descrição!")

    def json(self):
        return {
            "id": self.id,
            "cpf_cnpj": self.cpf_cnpj,
            "description": self.description,
            "created_at": self.created_at,
            "updated_at": self.updated_at,
        }

    def save(self):
        print("Saving Organization")
        db.session.add(self)
        db.session.commit()

    @classmethod
    def find_by_id(cls, id):
        return db.session.query(cls).filter(cls.id == id).first()

    @classmethod
    def resolve_organizations(cls, **kwargs):
        query = db.session.query(Organization)
        id, page_index, page_size = (
            kwargs.get("id"),
            kwargs.get("page_index", 0),
            kwargs.get("page_size", 10),
        )
        if id is not None:
            query = query.filter(Organization.id == id)

        return query.offset(page_index * page_size).limit(page_size)

    @classmethod
    def resolve_organization(cls, **kwargs):
        query = db.session.query(Organization)
        id = kwargs.get("id")
        return query.filter(Organization.id == id).first()