class Role(db.Model, RoleMixin): __tablename__ = "web_roles" id = db.Column(db.Integer(), primary_key=True) name = db.Column(db.String(80), unique=True) description = db.Column(db.String(255)) def __repr__(self): return "%s - %s" % (self.name, self.description)
class PersonWallet(SurrogatePK, Model): __tablename__ = 'corp_wallet' person_id = ReferenceCol('person', nullable=False) person = relationship('Person', backref='corp_wallet') creation_date = db.Column(db.DateTime, nullable=False) balance = db.Column(db.Integer, nullable=False) limit = db.Column(db.Integer, nullable=False) interval = db.Column(db.Integer, nullable=False, index=True) status = db.Column(db.Integer, nullable=False, index=True)
class Person(SurrogatePK, Model): __tablename__ = 'person' PER_PAGE = 50 STATUS_VALID = 1 STATUS_BANNED = 0 TYPE_TIMEOUT = 0 TYPE_WALLET = 1 SEARCH_KEY = ('name', 'tabel_id', 'card', 'hard_id') MANDATORY_PARAMETERS = ('name', 'tabel_id', 'hard_id') OPTIONAL_PARAMETERS = ('payment_id', 'card') name = db.Column(db.Text, nullable=False) tabel_id = db.Column(db.String(150)) birthday = db.Column(db.Date()) firm_id = ReferenceCol('firm', nullable=False) firm = relationship('Firm', backref='person') card = db.Column(db.String(8)) payment_id = db.Column(db.String(20), nullable=False, index=True) hard_id = db.Column(db.String(128), nullable=False) creation_date = db.Column(db.DateTime, nullable=False) status = db.Column(db.Integer, nullable=False, index=True) wallet_status = db.Column(db.Integer, nullable=False, index=True) type = db.Column(db.Integer, nullable=False, index=True) def __init__(self): self.status = self.STATUS_VALID self.wallet_status = self.STATUS_VALID self.type = self.TYPE_TIMEOUT self.creation_date = date_helper.get_current_date() self.name = u'Пользователь' @staticmethod def delete(person): try: db.session.query(PersonEvent).\ filter(PersonEvent.person_id == person.id).delete() db.session.query(PersonWallet).\ filter(PersonWallet.person_id == person.id).delete() db.session.delete(person) db.session.commit() except Exception, e: db.session.rollback() logger.error(e) return False return True
class Term(SurrogatePK, Model): __tablename__ = 'term' id = db.Column(db.Integer, primary_key=True) hard_id = db.Column(db.Integer, unique=True) type = db.Column(db.Integer, nullable=False) name = db.Column(db.String(300), nullable=False) tz = db.Column(db.String(300), nullable=False) blacklist = db.Column(db.Integer) auth = db.Column(db.String(16)) settings_id = db.Column(db.Integer, nullable=False) status = db.Column(db.Integer, index=True)
class PersonEvent(SurrogatePK, Model): __tablename__ = 'person_event' STATUS_ACTIVE = 1 STATUS_BANNED = 0 person_id = ReferenceCol('person', nullable=False) person = relationship('Person', backref='person_event') term_id = ReferenceCol('term', nullable=False) term = relationship('Term', backref='person_event') event_id = ReferenceCol('event', nullable=False) event = relationship('Event', backref='person_event') firm_id = ReferenceCol('firm', nullable=False) firm = relationship('Firm', backref='person_event') timeout = db.Column(db.Integer, nullable=False) status = db.Column(db.Integer, nullable=False)
class User(SurrogatePK, Model): __tablename__ = 'api_user' STATUS_ACTIVE = 1 STATUS_BANNED = 0 SCHEME_EGGER = 'egger' SCHEME_BCK = 'bck' email = db.Column(db.String(128), nullable=False, index=True) key = db.Column(db.String(150)) secret = db.Column(db.String(150)) app = db.Column(db.Text, nullable=False) firm = db.Column(db.Text, nullable=False) scheme = db.Column(db.String(64), nullable=False) status = db.Column(db.Integer, index=True)
class Login(UserMixin, Model): __tablename__ = 'logins' login_id = Column(db.Integer, primary_key=True, autoincrement=True, nullable=False) user_id = Column(db.Integer, db.ForeignKey('users.id'), unique=True, nullable=False) username = Column(db.String(50), unique=True, nullable=False) password_hash = db.Column(db.String(128)) updated_at = Column( TIMESTAMP, nullable=False, server_default=text('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP')) created_at = Column(TIMESTAMP, server_default=func.now()) # Methods def __repr__(self): return f'<Login login_id={self.login_id} user_id={self.user_id} updated_at={self.updated_at}>' @property def password(self): raise AttributeError('Password is not a readable attribute.') @password.setter def set_password(self, password): self.password_hash = generate_password_hash(password) def check_password(self, password): is_correct_password = check_password_hash(self.password_hash, password) if not is_correct_password: raise ValueError('Incorrect Password') return is_correct_password
class Order(db.Model): account_number = db.Column(db.String(32)) invoice_number = db.Column(db.String(32), primary_key=True) invoice_term_name = db.Column(db.String(32)) invoice_date = db.Column(db.String(32)) supplier = db.Column(db.String(32)) customer_account_number = db.Column(db.String(32)) vendor = db.Column(db.String(32)) order_items = db.Column(db.String(32)) raw_sold_to_info = db.Column(db.String(32)) invoice_subtotal = db.Column(db.String(32)) def __init__(self, supplier_organization_number, account_number): self._Page = None self._Form_dict = None self.organization_number = supplier_organization_number self.account_number = account_number def __repr__(self): return '<Order {0}>'.format(self.invoice_number) @property def Page(self): return self._Page @Page.setter def Page(self, page_obj): self._Page = page_obj self._Form_dict = convert_form_to_dict(page_obj.form) @property def Form_dict(self): return self._Form_dict def add_order_items(self, order_item): self.order_items.append(order_item) def set_order_template(self, template_name): """ Function to set the order template """ # Fetch the required template type template_data = fetch_json(template_name) # Fetch the order and date template self.order_template = template_data.get('mapper').get('order') self.date_format = template_data.get('date_format') def extract_keys_using_template(self): """ Extract keys from Page object's Form Fields, search template for matches, and return matches with their corresponding indices """ order_template = self.order_template # For each extracted key, search for relevant keys from the json template matched_keys_raw = { prefix_dictionary_search(field_key, order_template): self.Form_dict[field_key] for field_key, val in self.Form_dict.items() if val is not None } # Remove all empty keys del matched_keys_raw[''] return { **matched_keys_raw, **failover(matched_keys_raw, order_template, self._Page) } def format_date(self): """ Textract may read dates as "YYY MM DD". Reformat to "YYYY-MM-DD" for DB insertion. If our template provides a date format then use it for conversion. """ try: if self.date_format: _date = dt.strptime(self.invoice_date, self.date_format) self.invoice_date = dt.strftime(_date, DB_DATE_FORMAT) else: # In case there is no date_format, then simply replace the characters. self.invoice_date = self.invoice_date.replace(" ", "-") except: current_app.logger.warning("Invoice date was not picked.") def set_order_values(self, page_obj, template_name='sysco.json'): # Set the order template to the class self.set_order_template(template_name) # Set Page object self.Page = page_obj # Get Page's Form searched_form_dict = self.extract_keys_using_template() # Set attributes using extracted keys self.set_attributes(searched_form_dict) # Format Date self.format_date() # Perform validation self.validate() for k, v in self.__dict__.items(): if k not in ['_Page', '_Form_dict']: print(k, ':', v) def set_attributes(self, data): for key, val in data.items(): if hasattr(self, key): setattr(self, key, val) def validate(self): """ Function to perform validation """ assert self.invoice_number not in (None, 'None', '') def convert_to_tsv(self): """ Used to export Header values as a tsv file. Returns both raw string format and buf """ # TO DO: refactor - consider using avro in the future vals = [] for key in ORDER_HEADER_COLUMN_ORDER: vals.append(self.__dict__.get(key)) tsv_buf = StringIO() pd.DataFrame([vals], columns=ORDER_HEADER_COLUMN_ORDER).to_csv( path_or_buf=tsv_buf, sep='\t', header=True, index=False) raw_tsv = pd.DataFrame( [vals], columns=ORDER_HEADER_COLUMN_ORDER).to_csv(path_or_buf=None, sep='\t', header=True, index=False) return tsv_buf, raw_tsv
class Firm(SurrogatePK, Model): __tablename__ = 'firm' name = db.Column(db.String(300), nullable=False)
class Event(SurrogatePK, Model): __tablename__ = 'event' name = db.Column(db.String(150), nullable=False) key = db.Column(db.String(150), nullable=False)
class User(db.Model, UserMixin): __tablename__ = "web_users" id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(255), unique=True) password = db.Column(db.String(255)) last_login_at = db.Column(db.DateTime()) current_login_at = db.Column(db.DateTime()) last_login_ip = db.Column(db.String(100)) current_login_ip = db.Column(db.String(100)) login_count = db.Column(db.Integer) active = db.Column(db.Boolean()) confirmed_at = db.Column(db.DateTime()) timezone = db.Column(db.String(25)) steamid = db.Column(db.String(17), unique=True) roles = db.relationship("Role", secondary=roles_users, backref=db.backref("users", lazy="dynamic")) def __repr__(self): return "%s - %s" % (self.code, self.name)
from flask_security import RoleMixin, UserMixin from web.database import db roles_users = db.Table( "roles_users", db.Column("user_id", db.Integer(), db.ForeignKey("web_users.id")), db.Column("role_id", db.Integer(), db.ForeignKey("web_roles.id")), ) class Role(db.Model, RoleMixin): __tablename__ = "web_roles" id = db.Column(db.Integer(), primary_key=True) name = db.Column(db.String(80), unique=True) description = db.Column(db.String(255)) def __repr__(self): return "%s - %s" % (self.name, self.description) class User(db.Model, UserMixin): __tablename__ = "web_users" id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(255), unique=True) password = db.Column(db.String(255)) last_login_at = db.Column(db.DateTime()) current_login_at = db.Column(db.DateTime()) last_login_ip = db.Column(db.String(100)) current_login_ip = db.Column(db.String(100)) login_count = db.Column(db.Integer)
class OrderItem(db.Model): """ Used to store item-level information """ order_item_id = db.Column(db.String(32), primary_key=True) item_number = db.Column(db.String(32)) order_quantity = db.Column(db.String(32)) shipped_quantity = db.Column(db.String(32)) unit = db.Column(db.String(32)) size = db.Column(db.String(32)) brand = db.Column(db.String(32)) description = db.Column(db.String(32)) weight = db.Column(db.String(32)) price = db.Column(db.String(32)) total_price = db.Column(db.String(32)) def __repr__(self): return f'''{[ self.item_number, self.order_quantity, self.shipped_quantity, self.unit, self.size, self.brand, self.description, self.weight, self.price, self.total_price ]}''' def set_attributes(self, data): for key, val in data.items(): if hasattr(self, key): setattr(self, f'{key}', val)
class User(db.Model): __tablename__ = 'users' id = db.Column(db.Integer, db.Sequence('id', start=1001, increment=1), primary_key=True) first_name = db.Column(db.String(100)) last_name = db.Column(db.String(100)) username = db.Column(db.String(80), unique=True) password = db.Column(db.String(255)) email = db.Column(db.String(120)) role = db.Column(db.String(10)) phone = db.Column(db.String(16)) email_alert = db.Column(db.String(3)) sms_alert = db.Column(db.String(3)) last_login = db.Column(db.DateTime) login_attempts = db.Column(db.String(2)) def __init__(self, first_name, last_name, username, password, email, role='user', phone=None): self.first_name = first_name self.last_name = last_name self.username = username self.password = password self.email = email self.role = role self.phone = phone def verify_password(self, password): if current_app.config['LDAP'] is True: flash('LDAP backend not implemented') else: return check_password_hash(self.password, password) # Flask-Login integration def is_authenticated(self): return True def is_active(self): return True def is_anonymous(self): return False def get_id(self): return self.id