class UserRoles(db.Model): __tablename__ = 'user_roles' id = db.Column(db.Integer(), primary_key=True) user_id = db.Column(db.Integer(), db.ForeignKey('user.id', ondelete='CASCADE')) user = db.relationship('User') role_id = db.Column(db.Integer(), db.ForeignKey('role.id', ondelete='CASCADE')) user = db.relationship('Role')
class Firm(db.Model, BaseModel): __bind_key__ = 'term' __tablename__ = 'firm' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(300), nullable=False) inn = db.Column(db.String(50)) sub_domain = db.Column(db.Text(), nullable=False, index=True) pattern_id = db.Column(db.String(200), nullable=False) logo = db.Column(db.Text()) address = db.Column(db.Text()) account_email = db.Column(db.Text()) transaction_percent = db.Column(db.Integer()) # до сотых долей процента, 1% = 100 transaction_comission = db.Column(db.Integer()) legal_entity = db.Column(db.String(256)) general_manager = db.Column(db.String(128)) chief_accountant = db.Column(db.String(128)) gprs_rate = db.Column(db.Integer()) contract = db.Column(db.String(256)) @staticmethod def get_by_sub_domain(sub_domain): return Firm.query.filter_by(sub_domain=sub_domain).first() @staticmethod @cache.cached(timeout=3600, key_prefix='all_firms_type_dict') def select_name_dict(): firms = Firm.query.all() result = {} for firm in firms: result[firm.id] = firm.name return result
class Home(JsonSerializer, db.Model): __json_hidden__ = ["deploys", "users"] id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(64)) ssh_host = db.Column(db.String(32)) ssh_port = db.Column(db.Integer) ssh_method = db.Column(db.Integer()) ssh_user = db.Column(db.String(64)) ssh_pass = db.Column(db.String(100)) created_at = db.Column(db.DateTime, default=db.func.now()) updated_at = db.Column(db.DateTime, default=db.func.now(), onupdate=db.func.now())
class Hosts(JsonSerializer, db.Model): __json_hidden__ = ["deploys", "users"] id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(64)) ssh_host = db.Column(db.String(32)) ssh_port = db.Column(db.Integer) ssh_user = db.Column(db.String(64)) ssh_method = db.Column(db.Integer()) ssh_pass = db.Column(db.String(100)) created_at = db.Column(db.DateTime, default=db.func.now()) updated_at = db.Column(db.DateTime, default=db.func.now(), onupdate=db.func.now()) users = db.relationship("Users", secondary=rel_user_host, backref=db.backref("hosts", lazy="dynamic"))
class site_vars(db.Model): var = db.Column(db.String(), primary_key=True) val = db.Column(db.Integer()) def __repr__(self): return '<%r: %r>' % (self.var, self.val)
class TermBlacklist(db.Model, BaseModel): __bind_key__ = 'term' __tablename__ = 'blacklist' STATUS_PAYMENT = 0 STATUS_BLACK = 1 payment_id = db.Column(db.String(), primary_key=True) timestamp = db.Column(db.Integer(), nullable=False) status = db.Column(db.Integer(), nullable=False, index=True) def __init__(self): self.status = self.STATUS_BLACK def __repr__(self): return '<payment_id %r>' % (self.payment_id) @staticmethod def get_max_timestamp(): return db.session.query( db.func.max(TermBlacklist.timestamp)).scalar() @staticmethod def generate_blacklist(): wallets = PaymentWallet.get_full() if not wallets: return False valid = set() blacklist = set() for wallet in wallets: if int(wallet.blacklist) == PaymentWallet.ACTIVE_OFF: blacklist.add(str(wallet.payment_id)) elif int(wallet.status) != PaymentWallet.STATUS_ACTIVE: blacklist.add(str(wallet.payment_id)) else: valid.add(str(wallet.payment_id)) # Start: Костыль на время перехода от кошельков с балансом wallets_not_empty = PaymentWallet.get_not_empty() for wallet in wallets_not_empty: blacklist.discard(wallet.payment_id) wallets_empty = PaymentWallet.get_empty() for wallet in wallets_empty: if wallet.payment_id not in valid: blacklist.add(wallet.payment_id) # End persons = Person.query.group_by(Person.payment_id).all() for person in persons: if not person.payment_id: continue if person.payment_id not in valid: blacklist.add(person.payment_id) return set(list(blacklist)) @staticmethod def get_all_list(): all_cards = TermBlacklist.query.all() return set([str(row.payment_id) for row in all_cards]) @staticmethod def get_all_black_list(): all_cards = TermBlacklist.query.filter_by( status=TermBlacklist.STATUS_BLACK).all() return set([str(row.payment_id) for row in all_cards]) def save(self): self.timestamp = date_helper.get_current_utc() return BaseModel.save(self)
class UserRoles(db.Model): id = db.Column(db.Integer(), primary_key=True) user_id = db.Column(db.Integer(), db.ForeignKey('user.id', ondelete='CASCADE')) role_id = db.Column(db.Integer(), db.ForeignKey('role.id', ondelete='CASCADE'))
class Role(db.Model): id = db.Column(db.Integer(), primary_key=True) name = db.Column(db.String(50), unique=True)
class PaymentWallet(db.Model, BaseModel): __bind_key__ = 'payment' __tablename__ = 'wallet' STATUS_NOACTIVE = 0 STATUS_ACTIVE = 1 STATUS_BANNED = -1 ACTIVE_ON = 1 ACTIVE_OFF = 0 TYPE_DEMO = 0 TYPE_FULL = 1 BALANCE_MIN = 0 id = db.Column(db.Integer, primary_key=True) payment_id = db.Column(db.String(20)) hard_id = db.Column(db.String(128)) name = db.Column(db.String(150), nullable=False) user_id = db.Column(db.Integer, db.ForeignKey('user.id')) user = db.relationship('User') discodes_id = db.Column(db.Integer(), index=True) creation_date = db.Column(db.DateTime, nullable=False) status = db.Column(db.Integer, nullable=False) blacklist = db.Column(db.Integer, nullable=False) balance = db.Column(db.Integer) type = db.Column(db.Integer(), index=True) def __init__(self): self.discodes_id = 0 self.name = 'My spot' self.type = self.TYPE_FULL self.blacklist = self.ACTIVE_OFF self.balance = 0 self.user_id = 0 self.creation_date = date_helper.get_current_date() self.status = self.STATUS_NOACTIVE def add_to_blacklist(self): self.blacklist = PaymentWallet.ACTIVE_OFF if self.save(): return self return False def remove_from_blacklist(self): self.blacklist = PaymentWallet.ACTIVE_ON if self.save(): return self return False def get_pid(self, pids): pid = "%s%s" % (pids, random.randint(100000000, 999999999)) pid = "%s%s" % (pid, hash_helper.get_isin_checksum(pid)) pid = str(pid).rjust(20, '0')[-20:] wallet = self.query.filter_by(payment_id=pid).first() if wallet: self.get_pid(self, pids) else: return pid @staticmethod def get_by_payment_id(payment_id): return PaymentWallet.query.filter_by(payment_id=payment_id).first() @staticmethod def get_full(): query = PaymentWallet.query.filter( PaymentWallet.type == PaymentWallet.TYPE_FULL) return query.group_by(PaymentWallet.payment_id).all() @staticmethod def get_empty(): query = PaymentWallet.query query = query.filter( PaymentWallet.balance <= PaymentWallet.BALANCE_MIN) return query.group_by(PaymentWallet.payment_id).all() @staticmethod def get_not_empty(): query = PaymentWallet.query query = query.filter(PaymentWallet.balance > PaymentWallet.BALANCE_MIN) return query.group_by(PaymentWallet.payment_id).all() @staticmethod def get_valid_by_payment_id(payment_id): return PaymentWallet.query.filter( PaymentWallet.payment_id == payment_id).filter( PaymentWallet.status == PaymentWallet.STATUS_ACTIVE).filter( PaymentWallet.user_id != 0).first() @staticmethod def get_valid_by_discodes_id(discodes_id): return PaymentWallet.query.filter( PaymentWallet.discodes_id == discodes_id).filter( PaymentWallet.user_id != 0).first() def save(self): self.payment_id = str(self.payment_id).rjust(20, '0') return BaseModel.save(self)
class PaymentCard(db.Model, BaseModel): __bind_key__ = 'payment' __tablename__ = 'payment_card' STATUS_PAYMENT = 1 STATUS_ARCHIV = 0 LINKING_AMOUNT = 1 TYPE_YM = 'Yandex' TYPE_MC = 'MasterCard' TYPE_VISA = 'VISA' PAYMENT_BY_CARD = 'AC' PAYMENT_BY_YM = 'PC' SYSTEM_MPS = 0 SYSTEM_YANDEX = 1 MAX_LINKING_CARD_TIMEOUT = 60 * 60 log = logging.getLogger('payment') id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey('user.id'), index=True) user = db.relationship('User') wallet_id = db.Column(db.Integer, db.ForeignKey('wallet.id'), index=True) wallet = db.relationship('PaymentWallet') pan = db.Column(db.String(128), nullable=True) token = db.Column(db.Text(), nullable=False) type = db.Column(db.String(128), nullable=False, index=True) system = db.Column(db.Integer(), nullable=False, index=True) status = db.Column(db.Integer(), nullable=False, index=True) def __init__(self): self.system = self.SYSTEM_MPS self.status = self.STATUS_ARCHIV @staticmethod def get_payment_card(wallet_id): return PaymentCard.query.filter_by( wallet_id=wallet_id, status=PaymentCard.STATUS_PAYMENT).first() def get_ym_params(self, amount, pattern, order_id, success_uri, fail_uri, type=PAYMENT_BY_CARD): """Запрос параметров от ym""" request_options = { "pattern_id": pattern, "sum": amount, "customerNumber": order_id, } if type == PaymentCard.PAYMENT_BY_CARD: ym = ExternalPayment(YandexMoneyConfig.INSTANCE_ID) payment = ym.request(request_options) elif type == PaymentCard.PAYMENT_BY_YM: return False else: return False if payment['status'] == "success": request_id = payment['request_id'] else: return False process_options = { "request_id": request_id, 'ext_auth_success_uri': success_uri, 'ext_auth_fail_uri': fail_uri } result = ym.process(process_options) return dict(url=result['acs_uri'], params=result['acs_params']) def get_linking_params(self, order_id=0, url=None): """Запрос параметров для привязки карты""" ym = YaMoneyApi(YandexMoneyConfig) return self.get_ym_params(self.LINKING_AMOUNT, ym.const.CARD_PATTERN_ID, order_id, url, url, self.PAYMENT_BY_CARD) def linking_init(self, discodes_id, url=None): """Инициализируем привязку карты""" wallet = PaymentWallet.get_valid_by_discodes_id(discodes_id) if not wallet: return False history = PaymentHistory() history.add_linking_record(wallet.user_id, wallet.id) if not history.save(): return False status = self.get_linking_params(history.id, url) if not status: history.delete() self.log.error('Linking card: Fail in getting parameters') return False history.request_id = status['params']['cps_context_id'] if not history.save(): return False fail_history = PaymentHistory.get_fail_linking_record( history.id, history.wallet_id) for row in fail_history: db.session.delete(row) db.session.commit() return status def linking_card(self, history_id): """Привязываем карту, получаем платежный токен""" from web.tasks.payment import PaymentTask history = PaymentHistory.query.get(history_id) if not history: return False if history.status == PaymentHistory.STATUS_COMPLETE: return False wallet = PaymentWallet.query.get(history.wallet_id) if not wallet: return False ym = YaMoneyApi(YandexMoneyConfig) result = ym.get_process_external_payment(history.request_id) if not result or not 'status' in result: message = 'Linking card: Not found status field, request_id=%s' % history.request_id self.log.error(message) return message if result['status'] == 'in_progress': history.status = PaymentHistory.STATUS_IN_PROGRESS if not history.save(): return False return result elif result['status'] == 'refused': history.status = PaymentHistory.STATUS_FAILURE if not history.save(): return False return result if result['status'] != 'success': return result PaymentCard.set_archiv(history.wallet_id) card = self.add_payment(history, result) if not card: return False history.invoice_id = result['invoice_id'] history.status = PaymentHistory.STATUS_COMPLETE if not history.save(): return False if not card.save(): return False PaymentTask.restart_fail_algorithm.delay(history.wallet_id) wallet.blacklist = PaymentWallet.ACTIVE_ON wallet.save() return result @staticmethod def set_archiv(wallet_id): """Переводим все карты привязанные к кошельку в архивное состояние""" old_cards = PaymentCard.query.filter_by( wallet_id=wallet_id, status=PaymentCard.STATUS_PAYMENT).all() for row in old_cards: row.status = PaymentCard.STATUS_ARCHIV db.session.add(row) db.session.commit() return True def add_payment(self, history, status): """ Добавляем платежную карту""" card = PaymentCard() card.user_id = history.user_id card.wallet_id = history.wallet_id if not 'money_source' in status: self.log.error('Linking card: Not found card parameters') return False if not 'pan_fragment' in status[ 'money_source'] or not 'payment_card_type' in status[ 'money_source']: self.log.error('Linking card: Not found card parameters') return False card.token = status['money_source']['money_source_token'] card.pan = status['money_source']['pan_fragment'] card.type = status['money_source']['payment_card_type'] card.status = PaymentCard.STATUS_PAYMENT return card @staticmethod def add_ym_wallet(wallet, token): """ Добавляем кошелек яндекс""" card = PaymentCard() card.user_id = wallet.user_id card.wallet_id = wallet.id card.token = token card.type = PaymentCard.TYPE_YM card.system = PaymentCard.SYSTEM_YANDEX card.status = PaymentCard.STATUS_PAYMENT return card
class PaymentHistory(db.Model, BaseModel): __bind_key__ = 'payment' __tablename__ = 'history' STATUS_NEW = 0 STATUS_IN_PROGRESS = 1 STATUS_COMPLETE = 2 STATUS_FAILURE = -1 TYPE_SYSTEM = 1 TYPE_PAYMENT = 2 SYSTEM_PAYMENT = 100 SYSTEM_MPS = 0 SYSTEM_YANDEX = 1 id = db.Column(db.Integer, primary_key=True) report_id = db.Column(db.Integer(), nullable=False) user_id = db.Column(db.Integer, db.ForeignKey('user.id'), index=True) user = db.relationship('User') wallet_id = db.Column(db.Integer, db.ForeignKey('wallet.id'), index=True) wallet = db.relationship('PaymentWallet') term_id = db.Column(db.Integer, db.ForeignKey('term.id')) term = db.relationship('Term') amount = db.Column(db.String(50), nullable=False) creation_date = db.Column(db.DateTime, nullable=False) request_id = db.Column(db.Text(), nullable=False) invoice_id = db.Column(db.Text()) type = db.Column(db.Integer(), nullable=False, index=True) system = db.Column(db.Integer(), nullable=False, index=True) status = db.Column(db.Integer(), nullable=False, index=True) def __init__(self): self.term_id = 0 self.status = self.STATUS_NEW self.system = self.SYSTEM_MPS self.type = self.TYPE_PAYMENT self.request_id = 0 self.report_id = 0 self.invoice_id = 0 self.creation_date = date_helper.get_current_date() def from_report(self, report, wallet): history = PaymentHistory() history.type = PaymentHistory.TYPE_PAYMENT history.amount = report.amount history.user_id = wallet.user_id history.report_id = report.id history.wallet_id = wallet.id history.term_id = report.term_id history.report_id = report.id if not history.save(): return False return history @staticmethod def get_fail_linking_record(history_id, wallet_id): return PaymentHistory.query.filter( PaymentHistory.id != history_id ).filter(PaymentHistory.wallet_id == wallet_id).filter( PaymentHistory.type == PaymentHistory.TYPE_SYSTEM).filter( PaymentHistory.status == PaymentHistory.STATUS_NEW).all() def add_linking_record(self, user_id, wallet_id): self.type = PaymentHistory.TYPE_SYSTEM self.amount = PaymentHistory.SYSTEM_PAYMENT self.user_id = user_id self.wallet_id = wallet_id return self def add_history(self, wallet, report): self.user_id = wallet.user_id self.wallet_id = wallet.id self.term_id = report.term.id self.amount = report.amount self.type = PaymentHistory.TYPE_PAYMENT self.status = PaymentHistory.STATUS_COMPLETE return self.save() @staticmethod def get_new_by_wallet_id(wallet_id): return PaymentHistory.query.filter_by(status=PaymentHistory.STATUS_NEW, wallet_id=wallet_id).first() @staticmethod def get_new_payment(): query = PaymentHistory.query.filter(PaymentHistory.report_id != 0) query = query.filter( (PaymentHistory.status == PaymentHistory.STATUS_NEW) | (PaymentHistory.status == PaymentHistory.STATUS_IN_PROGRESS)) return query.filter(PaymentHistory.request_id != 0).all() @staticmethod def remove_braked(report_id): query = PaymentHistory.query.filter( PaymentHistory.report_id == report_id) query = query.filter( PaymentHistory.status == PaymentHistory.STATUS_NEW) query = query.filter( PaymentHistory.creation_date < date_helper.get_delta_date( -app.config['HISTORY_BRAKED_TIME'])) history_braked = query.first() if not history_braked: return False history_braked.delete() return True
class Role(db.Model): __tablename__ = 'role' id = db.Column(db.Integer(), primary_key=True) name = db.Column(db.String(50), unique=True)