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 Comment(db.Model): __tablename__ = 'Comment' id = db.Column(db.Integer, primary_key=True, autoincrement=True) text = db.Column(db.Text()) video_id = db.Column(db.Text(), db.ForeignKey('Video.id'), nullable=False) user_id = db.Column(db.Integer, db.ForeignKey('User.id'), nullable=False) def __init__(self, text, video_id, user_id): self.text = text self.user_id = user_id self.video_id = video_id def save(self): db.session.add(self) db.session.commit()
class Articles(db.Model): __tablename__ = 'articles' id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(255), nullable=False) body = db.Column(db.Text(), nullable=False) summary = db.Column(db.String(150),nullable=False) img_url = db.Column(db.String(255),nullable=False) insert_date = db.Column(db.DateTime, nullable=False) insert_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False) update_date = db.Column(db.DateTime, nullable=True) update_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=True) delete_flg = db .Column(db.Boolean, nullable=False, default=False) version = db.Column(db.Integer, nullable=True) __mapper_args__ = {'version_id_col': version} def __init__(self,title,body,summary,img_url,insert_date,insert_id,version=0,update_date=None,update_id=None): self.title = title self.body = body self.summary = summary self.img_url = img_url self.insert_date = insert_date self.insert_id = insert_id self.version = version self.update_date = update_date self.update_id = update_id
class SpotContent(db.Model, BaseModel): __bind_key__ = 'mobispot' __tablename__ = 'spot_content' id = db.Column(db.Integer, primary_key=True) discodes_id = db.Column(db.Integer) user_id = db.Column(db.Integer) lang = db.Column(db.String(10)) spot_type_id = db.Column(db.Integer) content = db.Column(db.Text())
class PaymentLoyaltySharing(db.Model, BaseModel): __bind_key__ = 'payment' __tablename__ = 'loyalty_sharing' id = db.Column(db.Integer, primary_key=True) loyalty_id = db.Column(db.Integer) sharing_type = db.Column(db.Integer) desc = db.Column(db.Text()) data = db.Column(db.Text()) link = db.Column(db.Text()) control_value = db.Column(db.String(256)) @staticmethod def get_action_link(sharing_id): link = False sharing = PaymentLoyaltySharing.query.filter_by(id=sharing_id).first() if sharing and sharing.link: link = sharing.link return link
class WalletLoyalty(db.Model, BaseModel): __bind_key__ = 'payment' __tablename__ = 'wallet_loyalty' STATUS_OFF = 0 STATUS_CONNECTING = 1 STATUS_ERROR = 2 STATUS_ON = 3 id = db.Column(db.Integer, primary_key=True) wallet_id = db.Column(db.Integer) loyalty_id = db.Column(db.Integer) summ = db.Column(db.String(50)) count = db.Column(db.Integer) part_count = db.Column(db.Integer) bonus_count = db.Column(db.Integer) bonus_limit = db.Column(db.Integer) checked = db.Column(db.Text()) status = db.Column(db.Integer) errors = db.Column(db.Text()) def __init__(self): self.status = self.STATUS_OFF self.count = 0 self.part_count = 0 self.bonus_count = 0 @staticmethod def get_by_wallet_list(wallet_list, loyalty_id=False): query = WalletLoyalty.query query = query.filter(WalletLoyalty.wallet_id.in_(wallet_list)) if loyalty_id: query = query.filter_by(loyalty_id=loyalty_id) return query.all()
class Tag(db.Model): __tablename__ = 'Tag' id = db.Column(db.Integer, primary_key=True, autoincrement=True) text = db.Column(db.Text(), unique=True) def save(self): db.session.add(self) db.session.commit() @staticmethod def create_unique(text): tag = Tag.query.filter_by(text=text).first() if tag is None: tag = Tag(text=text) return tag
class PaymentLoyalty(db.Model, BaseModel): __bind_key__ = 'payment' __tablename__ = 'loyalty' RULE_FIXED = 0 RULE_RATE = 1 RULE_DISCOUNT = 2 RULE_PRESENT = 3 STATUS_NOT_ACTUAL = 0 STATUS_ACTUAL = 1 STATUS_ALL = 2 STATUS_MY = 100 FACEBOOK_LIKE = 1 FACEBOOK_SHARE = 2 TWITTER_SHARE = 3 TWITTER_RETWIT = 4 TWITTER_READING = 5 TWITTER_HASHTAG = 6 FOURSQUARE_CHECKIN = 7 FOURSQUARE_MAYOR = 8 FOURSQUARE_BADGE = 9 INSTAGRAM_LIKE = 10 INSTAGRAM_FOLLOWING = 11 GOOGLE_CIRCLE = 12 GOOGLE_PLUS_ONE = 13 YOUTUBE_FOLLOWING = 14 YOUTUBE_VIEWS = 15 VK_SUBS = 18 VK_LIKE = 19 DEFAULT_COUNT = 20 MAX_COUNT = 100 id = db.Column(db.Integer, primary_key=True) terms_id = db.Column(db.Integer) event_id = db.Column(db.Integer, db.ForeignKey('person_event.id')) firm_id = db.Column(db.Integer) rules = db.Column(db.Integer) interval = db.Column(db.Integer) amount = db.Column(db.String(32)) threshold = db.Column(db.String(32)) desc = db.Column(db.Text()) name = db.Column(db.String(128)) creation_date = db.Column(db.DateTime) start_date = db.Column(db.DateTime) stop_date = db.Column(db.DateTime) sharing_type = db.Column(db.Integer) data = db.Column(db.Text()) coupon_class = db.Column(db.String(64)) limit = db.Column(db.Integer) timeout = db.Column(db.Integer) bonus_limit = db.Column(db.Integer) control_value = db.Column(db.String(256)) def __init__(self): self.rules = self.RULE_FIXED self.creation_date = date_helper.get_current_date() def get_rules_dict(self): return { self.RULE_FIXED: 'RULE_FIXED', self.RULE_RATE: 'RULE_RATE', self.RULE_DISCOUNT: 'RULE_DISCOUNT', self.RULE_RATE: 'RULE_PRESENT', } def rules_const(self): rules_dict = PaymentLoyalty().get_rules_dict() rules = '-1' if self.rules in rules_dict: rules = rules_dict[self.rules] return rules @staticmethod def get_action_link(action_id): link = '' actionTag = "<a ng-click=\"checkLike(" + str(action_id) + ")\">" userAction = PaymentLoyalty.query.filter_by(id=action_id).first() if userAction and actionTag in userAction.desc: link = userAction.desc[userAction.desc.find(actionTag) + len(actionTag):] if "</a>" in link: link = link[0:link.find("</a>")] return link
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