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))
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 api_internal_yandex_get_auth_url(discodes_id): log = logging.getLogger('payment') result = {'error': 1} if not PaymentWallet.get_valid_by_discodes_id(discodes_id): return make_response(jsonify(result)) url = None if 'url' in request.args: url = request.args['url'] if not url: return make_response(jsonify(result)) try: auth_url = Wallet.build_obtain_token_url( YandexMoneyConfig.CLIENT_ID, url, YandexMoneyConfig.WALLET_SCOPE) except Exception as e: log.error(e) return make_response(jsonify(result)) else: result['error'] = 0 result['url'] = auth_url return make_response(jsonify(result))
def get_ym_token(discodes_id, code, url): log = logging.getLogger('payment') wallet = PaymentWallet.get_valid_by_discodes_id(discodes_id) if not wallet: return False try: info = Wallet.get_access_token( client_id=YandexMoneyConfig.CLIENT_ID, code=code, redirect_uri=url, client_secret=YandexMoneyConfig.OAUTH_KEY) except Exception as e: log.error(e) return False else: if 'error' in info: log.error(info) return False try: PaymentCard.set_archiv(wallet.id) card = PaymentCard.add_ym_wallet(wallet, info['access_token']) card.save() except Exception as e: log.error(e) return False else: wallet.blacklist = PaymentWallet.ACTIVE_ON wallet.save() return True
def test_func_add_history(self): history = PaymentHistory() data_wallet = dict( id=1, payment_id=self.PAYMENT_ID, hard_id=self.HARD_ID, name=self.TEST_STRING, user_id=self.USER_ID, discodes_id=self.DISCODES_ID, card_pan=self.CARD_PAN ) wallet = PaymentWallet() wallet.__dict__.update(data_wallet) data_report = dict( term_id=self.TERM_ID, event_id=self.EVENT_ID, person_id=self.PERSON_ID, payment_id=self.FIRM_ID, firm_id=self.FIRM_ID, creation_date=date_helper.get_current_date(), ) report = Report() report.__dict__.update(data_report) assert history.add_history(wallet, report) history.delete()
def background_old_payment(report_id): """Платеж с кошелька uniteller""" log = logging.getLogger('payment') report = Report.query.get(report_id) if not report: message = 'Payment: Not found report with id %s' % report_id log.error(message) return message wallet = PaymentWallet.get_by_payment_id(report.payment_id) if not wallet: message = 'Payment: Not found wallet with pid %s' % report.payment_id log.error(message) return message history = PaymentHistory.query.filter_by(report_id=report.id).first() if history: return False history = PaymentHistory().from_report(report, wallet) if not history: message = 'Payment: Fail in history add, report_id=%s' % report_id log.error(message) return message term = Term.query.get(report.term_id) if not term: log.error('Payment: Not found term %s' % report.term_id) new_balance = wallet.balance - report.amount if new_balance < 0: history.amount = wallet.balance wallet.balance = 0 report.copy_new_from_old(new_balance) else: wallet.balance = new_balance if not wallet.save(): return False history.request_id = 'old' history.status = PaymentHistory.STATUS_COMPLETE if not history.save(): return False report.status = Report.STATUS_COMPLETE if not report.save(): return False return True
def import_wallet(self): with open('tmp/import.csv', 'rb') as csvfile: spamreader = csv.reader(csvfile, delimiter=';', quotechar='"') for row in spamreader: spot = Spot.query.filter(Spot.code == row[2]).first() if not spot: continue wallet = PaymentWallet().filter( PaymentWallet.discodes_id == spot.discodes_id).first() if wallet: continue wallet = PaymentWallet() wallet.hard_id = row[0] wallet.payment_id = row[1] wallet.discodes_id = spot.discodes_id wallet.save()
def api_internal_yandex_get_token(discodes_id, code): result = {'error': 1} if not PaymentWallet.get_valid_by_discodes_id(discodes_id): return make_response(jsonify(result)) url = None if 'url' in request.args: url = request.args['url'] if not url: return make_response(jsonify(result)) PaymentTask.get_ym_token.delay(discodes_id, code, url) result['error'] = 0 return make_response(jsonify(result))
def api_internal_yandex_linking(discodes_id): result = {'error': 1} if not PaymentWallet.get_valid_by_discodes_id(discodes_id): return make_response(jsonify(result)) url = None if 'url' in request.args: url = request.args['url'] params = PaymentCard().linking_init(discodes_id, url) if params: result = params result['error'] = 0 return make_response(jsonify(result))
def blacklist_alert(report_id): payment = PaymentFail.query.get(report_id) if payment.count != Config.BLACKLIST_ALARM_LIMIT: return False report = Report.query.get(report_id) wallet = PaymentWallet.get_by_payment_id(report.payment_id) spot = Spot.query.filter_by( discodes_id=wallet.discodes_id).first() card = PaymentCard.get_payment_card(wallet.id) user = User.query.get(wallet.user_id) if not spot or not user or not card: return False all_fails = PaymentFail.query.filter_by( payment_id=payment.payment_id).all() amount = 0 for fail in all_fails: report = Report.query.get(fail.report_id) amount += report.amount user_profile = UserProfile.query.filter_by( user_id=user.id).first() username = u'Dear user' if user_profile and user_profile.name: username = user_profile.name elif user.lang == 'ru': username = u'Уважаемый пользователь' mail.send.delay( BlacklistAlarmMessage, to=user.email, lang=user.lang, spotname=spot.name, username=username, amount="%02d.%02d" % (amount / 100, amount % 100), card_pan=u'%s %s' % (card.type, card.pan) ) return True
def blacklist_alert(report_id): payment = PaymentFail.query.get(report_id) if payment.count != Config.BLACKLIST_ALARM_LIMIT: return False report = Report.query.get(report_id) wallet = PaymentWallet.get_by_payment_id(report.payment_id) spot = Spot.query.filter_by(discodes_id=wallet.discodes_id).first() card = PaymentCard.get_payment_card(wallet.id) user = User.query.get(wallet.user_id) if not spot or not user or not card: return False all_fails = PaymentFail.query.filter_by( payment_id=payment.payment_id).all() amount = 0 for fail in all_fails: report = Report.query.get(fail.report_id) amount += report.amount user_profile = UserProfile.query.filter_by(user_id=user.id).first() username = u'Dear user' if user_profile and user_profile.name: username = user_profile.name elif user.lang == 'ru': username = u'Уважаемый пользователь' mail.send.delay(BlacklistAlarmMessage, to=user.email, lang=user.lang, spotname=spot.name, username=username, amount="%02d.%02d" % (amount / 100, amount % 100), card_pan=u'%s %s' % (card.type, card.pan)) return True
def new_payment_manager(): history = PaymentHistory.get_new_payment() for key in history: PaymentTask.check_status.delay(key.id) reports = Report.get_new_payment() if not reports: return False for report in reports: history = PaymentHistory.query.filter_by( report_id=report.id).first() if history: continue # Start: Костыль на время перехода от кошельков с балансом wallet = PaymentWallet.get_valid_by_payment_id(report.payment_id) if wallet and int(wallet.balance) > 0: PaymentTask.background_old_payment.delay(report.id) continue # End PaymentTask.background_payment.delay(report.id) return True
def api_admin_linking_spot(): """Добавляем спот и связанный с ним кошелёк""" base._api_access(request) add_success = 0 hid = request.form['hid'] pids = request.form['pids'] ean = request.form['ean'] hard_type = Spot.DEFAULT_HARD_TYPE if 'hard_type' in request.form: hard_type = int(request.form['hard_type']) if not SpotHardType.query.get(hard_type): abort(400) status = 1 if 'status' in request.form: status = int(request.form['status']) if not hid or not ean or not pids: abort(400) if not len(str(ean)) == 13: abort(400) try: hid = int(hid) pids = int(pids) except Exception: abort(405) spot = Spot.query.filter_by( barcode=ean).first() if not spot: abort(404) spot.hard_type = hard_type troika_info = troika_api.release_card(hid) if troika_info: spot.user_id = troika_info['user_id'] spot_troika = SpotTroika() spot_troika.discodes_id = spot.discodes_id spot_troika.save() wallet = PaymentWallet.query.filter( (PaymentWallet.hard_id == hid) | (PaymentWallet.discodes_id == spot.discodes_id)).first() if not wallet: wallet = PaymentWallet() wallet.payment_id = wallet.get_pid(pids) wallet.hard_id = hid wallet.discodes_id = spot.discodes_id if status == 0: wallet.type = PaymentWallet.TYPE_DEMO spot.spot_type_id = Spot.TYPE_DEMO if troika_info: wallet.user_id = troika_info['user_id'] wallet.status = PaymentWallet.STATUS_ACTIVE if wallet.save(): spot.status = Spot.STATUS_ACTIVATED if troika_info: spot.status = Spot.STATUS_REGISTERED if not spot.save(): abort(400) add_success = 1 if wallet.discodes_id != spot.discodes_id: abort(400) add_xml = render_template( 'api/admin/add_info.xml', spot=spot, wallet=wallet, add_success=add_success, ).encode('cp1251') response = make_response(add_xml) return response
def background_payment(report_id): """Проводим фоновый платеж""" log = logging.getLogger('payment') report = Report.query.get(report_id) if not report: message = 'Payment: Not found report with id %s' % report_id log.error(message) return message if report.is_payment_busy(): return False wallet = PaymentWallet.get_by_payment_id(report.payment_id) if not wallet: message = 'Payment: Not found wallet with pid %s' % report.payment_id log.error(message) return message PaymentHistory.remove_braked(report.id) history = PaymentHistory.query.filter_by(report_id=report.id).first() if history: return False history = PaymentHistory().from_report(report, wallet) if not history: message = 'Payment: Fail in history add, report_id=%s' % report_id log.error(message) return message card = PaymentCard.get_payment_card(wallet.id) if not card: PaymentTask.set_fail(report_id, wallet) history.delete() message = 'Payment: Not found card, for wallet_id=%s' % wallet.id log.error(message) return False term = Term.query.get(report.term_id) if not term: log.error('Payment: Not found term %s' % report.term_id) firm = Firm.query.get(report.term_firm_id) if not firm: log.error( 'Payment: Not found firm, with term %s' % report.term_id) request_options = { "pattern_id": firm.pattern_id, "sum": float(report.amount) / int(Term.DEFAULT_FACTOR), "customerNumber": history.id, } try: if card.system == PaymentCard.SYSTEM_MPS: history.system = PaymentHistory.SYSTEM_MPS ym = ExternalPayment(YandexMoneyConfig.INSTANCE_ID) payment = ym.request(request_options) elif card.system == PaymentCard.SYSTEM_YANDEX: history.system = PaymentHistory.SYSTEM_YANDEX ym = Wallet(card.token) payment = ym.request_payment(request_options) else: return False except Exception as e: log.error(e) return False else: if not payment or 'request_id' not in payment: PaymentTask.set_fail(report_id, wallet) message = 'Payment: Fail in request payment, report_id %s, request %s' % ( report_id, payment) log.error(message) history.delete() return message history.request_id = payment['request_id'] history.save() return True
def test_func_get_pid(self): wallet = PaymentWallet() wallet.get_pid(self.PIDS)
def api_admin_linking_spot(): """Добавляем спот и связанный с ним кошелёк""" base._api_access(request) add_success = 0 hid = request.form['hid'] pids = request.form['pids'] ean = request.form['ean'] hard_type = Spot.DEFAULT_HARD_TYPE if 'hard_type' in request.form: hard_type = int(request.form['hard_type']) if not SpotHardType.query.get(hard_type): abort(400) status = 1 if 'status' in request.form: status = int(request.form['status']) if not hid or not ean or not pids: abort(400) if not len(str(ean)) == 13: abort(400) try: hid = int(hid) pids = int(pids) except Exception: abort(405) spot = Spot.query.filter_by(barcode=ean).first() if not spot: abort(404) spot.hard_type = hard_type troika_info = troika_api.release_card(hid) if troika_info: spot.user_id = troika_info['user_id'] spot_troika = SpotTroika() spot_troika.discodes_id = spot.discodes_id spot_troika.save() wallet = PaymentWallet.query.filter((PaymentWallet.hard_id == hid) | ( PaymentWallet.discodes_id == spot.discodes_id)).first() if not wallet: wallet = PaymentWallet() wallet.payment_id = wallet.get_pid(pids) wallet.hard_id = hid wallet.discodes_id = spot.discodes_id if status == 0: wallet.type = PaymentWallet.TYPE_DEMO spot.spot_type_id = Spot.TYPE_DEMO if troika_info: wallet.user_id = troika_info['user_id'] wallet.status = PaymentWallet.STATUS_ACTIVE if wallet.save(): spot.status = Spot.STATUS_ACTIVATED if troika_info: spot.status = Spot.STATUS_REGISTERED if not spot.save(): abort(400) add_success = 1 if wallet.discodes_id != spot.discodes_id: abort(400) add_xml = render_template( 'api/admin/add_info.xml', spot=spot, wallet=wallet, add_success=add_success, ).encode('cp1251') response = make_response(add_xml) return response