commit
b866f0e7cc
7 changed files with 177 additions and 128 deletions
@ -0,0 +1,16 @@ |
|||||||
|
from django.core.management.base import BaseCommand |
||||||
|
|
||||||
|
|
||||||
|
class Command(BaseCommand): |
||||||
|
help = 'Команда для тестов' |
||||||
|
|
||||||
|
def handle(self, *args, **options): |
||||||
|
from finance.loggers import FinanceLogger |
||||||
|
logger = FinanceLogger() |
||||||
|
try: |
||||||
|
10 / 0 |
||||||
|
except Exception as exc: |
||||||
|
logger.exception('FinanceLogger test log record', extra={'asdf': 3246523}, |
||||||
|
invoice_id=42, exc={'a': 1, 'b': 3, 'привет': 'медвед'} |
||||||
|
) |
||||||
|
|
||||||
@ -0,0 +1,56 @@ |
|||||||
|
# -*- coding: utf-8 -*- |
||||||
|
|
||||||
|
import logging |
||||||
|
|
||||||
|
_logger = logging.getLogger('finance_data') |
||||||
|
|
||||||
|
|
||||||
|
class FinanceLogger: |
||||||
|
""" |
||||||
|
Все kwargs попадют в %(finance_data)s и логируются |
||||||
|
'format': '%(asctime)s - %(levelname)s - %(message)s - %(finance_data)s' |
||||||
|
""" |
||||||
|
|
||||||
|
def __init__(self, prefix=None): |
||||||
|
self.prefix = prefix |
||||||
|
|
||||||
|
def log(self, level, msg, *args, **kwargs): |
||||||
|
_logger.log(level=level, msg=self._get_msg(msg), *args, **self._make_kwargs(kwargs)) |
||||||
|
|
||||||
|
def _get_msg(self, msg): |
||||||
|
if self.prefix: |
||||||
|
msg = '{}: {}'.format(self.prefix, msg) |
||||||
|
return msg |
||||||
|
|
||||||
|
def _make_kwargs(self, kwargs): |
||||||
|
new_kwargs = {} |
||||||
|
for inspected_kwarg in ('exc_info', 'stack_info', 'extra'): |
||||||
|
try: |
||||||
|
new_kwargs[inspected_kwarg] = kwargs.pop(inspected_kwarg) |
||||||
|
except KeyError: |
||||||
|
pass |
||||||
|
if 'extra' in new_kwargs: |
||||||
|
new_kwargs['extra']['finance_data'] = kwargs |
||||||
|
else: |
||||||
|
new_kwargs['extra'] = dict(finance_data=kwargs) |
||||||
|
return new_kwargs |
||||||
|
|
||||||
|
def debug(self, msg, *args, **kwargs): |
||||||
|
self.log(level=logging.DEBUG, msg=msg, *args, **kwargs) |
||||||
|
|
||||||
|
def info(self, msg, *args, **kwargs): |
||||||
|
self.log(level=logging.INFO, msg=msg, *args, **kwargs) |
||||||
|
|
||||||
|
def warning(self, msg, *args, **kwargs): |
||||||
|
self.log(level=logging.WARNING, msg=msg, *args, **kwargs) |
||||||
|
|
||||||
|
# TODO отделить логирование ошибок в другой лог |
||||||
|
def error(self, msg, *args, **kwargs): |
||||||
|
self.log(level=logging.ERROR, msg=msg, *args, **kwargs) |
||||||
|
|
||||||
|
def critical(self, msg, *args, **kwargs): |
||||||
|
self.log(level=logging.CRITICAL, msg=msg, *args, **kwargs) |
||||||
|
|
||||||
|
def exception(self, msg, *args, **kwargs): |
||||||
|
kwargs['stack_info'] = True |
||||||
|
_logger.exception(self._get_msg(msg), *args, **self._make_kwargs(kwargs)) |
||||||
@ -1,15 +1,14 @@ |
|||||||
import logging |
|
||||||
|
|
||||||
from django.core.management.base import BaseCommand |
from django.core.management.base import BaseCommand |
||||||
|
|
||||||
|
from finance.loggers import FinanceLogger |
||||||
from finance.tasks import periodic_billing |
from finance.tasks import periodic_billing |
||||||
|
|
||||||
logger_yandex = logging.getLogger('yandex_money') |
finance_logger = FinanceLogger() # prefix='YandexMoney' |
||||||
|
|
||||||
|
|
||||||
class Command(BaseCommand): |
class Command(BaseCommand): |
||||||
|
|
||||||
def handle(self, *args, **options): |
def handle(self, *args, **options): |
||||||
logger_yandex.info("start console repeat payment command") |
finance_logger.info("start console repeat payment command") |
||||||
print('Started') |
print('Started') |
||||||
periodic_billing() |
periodic_billing() |
||||||
|
|||||||
@ -1,61 +1,60 @@ |
|||||||
import logging |
import logging |
||||||
|
|
||||||
import os |
import os |
||||||
|
|
||||||
import requests |
import requests |
||||||
from dateutil.relativedelta import relativedelta |
from django.conf import settings |
||||||
|
from django.db import transaction |
||||||
|
from django.utils import timezone |
||||||
from yandex_money.models import Payment |
from yandex_money.models import Payment |
||||||
|
|
||||||
|
from finance.loggers import FinanceLogger |
||||||
from finance.models import InvoiceRebilling |
from finance.models import InvoiceRebilling |
||||||
from lms import celery_app |
from lms import celery_app |
||||||
from django.conf import settings |
|
||||||
from django.utils import timezone |
|
||||||
|
|
||||||
logger_yandex = logging.getLogger('yandex_money') |
|
||||||
|
|
||||||
|
finance_logger = FinanceLogger() |
||||||
|
|
||||||
@celery_app.task |
@celery_app.task |
||||||
def periodic_billing(): |
def periodic_billing(): |
||||||
try: |
finance_logger.info("start periodic billing task") |
||||||
logger_yandex.info("start periodic billing task") |
|
||||||
invoices = InvoiceRebilling.objects.filter(method='Y').exclude(status='F') |
invoices = InvoiceRebilling.objects.filter(method='Y').exclude(status='F') |
||||||
|
for invoice in invoices.filter(expected_date__lt=timezone.now()): |
||||||
for invoice in invoices.filter( |
# выбираем все необработанные из прошлого |
||||||
expected_date__gt=timezone.now(), expected_date__lt=timezone.now() + relativedelta(days=1)): |
with transaction.atomic(): |
||||||
# TODO выбирать все, даже прошлые неотработанные - что бы не потерять |
try: |
||||||
|
_yandex_repeat_card_payment(invoice) |
||||||
user = invoice.bill.user |
except Exception as exc: |
||||||
yandex_pay = Payment.objects.create( |
finance_logger.exception('YandexMoney repeatCardPayment Exception', invoice_id=invoice.id) |
||||||
order_amount=invoice.price, |
invoice.comment = 'Ошибка при попытке повторного платежа, свяжитесь с клиентской службой' |
||||||
customer_number=user.id, |
invoice.save() |
||||||
user=user, |
|
||||||
cps_email=user.email, |
|
||||||
shop_id=settings.YANDEX_MONEY_REBILLING_SHOP_ID, |
def _yandex_repeat_card_payment(invoice): |
||||||
scid=settings.YANDEX_MONEY_REBILLING_SCID |
user = invoice.bill.user |
||||||
) |
yandex_pay = Payment.objects.create( |
||||||
invoice.yandex_pay = yandex_pay |
order_amount=invoice.price, |
||||||
invoice.save() |
customer_number=user.id, |
||||||
|
user=user, |
||||||
repeat_card_payment(invoice) |
cps_email=user.email, |
||||||
except Exception as exc: |
shop_id=settings.YANDEX_MONEY_REBILLING_SHOP_ID, |
||||||
logger_yandex.error('periodic billing Exception', exc_info=True, extra={ |
scid=settings.YANDEX_MONEY_REBILLING_SCID |
||||||
'exc': exc |
) |
||||||
}) |
invoice.yandex_pay = yandex_pay |
||||||
# TODO записывать в invoice.comments ошибку яндекса |
|
||||||
|
finance_logger.info('YandexMoney repeatCardPayment start', invoice_id=invoice.id) |
||||||
|
resp = requests.post( |
||||||
def repeat_card_payment(invoice): |
url=settings.YANDEX_MONEY_MWS_URL + 'repeatCardPayment', |
||||||
resp = requests.post(settings.YANDEX_MONEY_MWS_URL + 'repeatCardPayment', |
data={ |
||||||
data={ |
'clientOrderId': invoice.id, # уникальное возрастающее целое число |
||||||
'clientOrderId': invoice.id, # уникальное возрастающее целое число |
'invoiceId': invoice.key, |
||||||
'invoiceId': invoice.key, |
'amount': invoice.price, |
||||||
'amount': invoice.price, |
'orderNumber': invoice.yandex_pay.order_number |
||||||
'orderNumber': invoice.yandex_pay.order_number |
}, |
||||||
}, |
cert=( |
||||||
cert=( |
os.path.join(settings.SSL_ROOT, 'skillbox.cer'), |
||||||
os.path.join(settings.SSL_ROOT, 'skillbox.cer'), |
os.path.join(settings.SSL_ROOT, 'skillbox.key') |
||||||
os.path.join(settings.SSL_ROOT, 'skillbox.key') |
), |
||||||
), |
verify=os.path.join(settings.SSL_ROOT, 'yamoney_chain.cer') |
||||||
verify=os.path.join(settings.SSL_ROOT, 'yamoney_chain.cer')) |
) |
||||||
logger_yandex.info('periodic billing finish', exc_info=True, extra={ |
# TODO тут проверять нет ли ошибки яндекса (даже при 200 ответе) |
||||||
'response': resp.text, 'code': resp.status_code, |
finance_logger.info('YandexMoney repeatCardPayment ended', |
||||||
}) |
invoice_id=invoice.id, response=resp.text, code=resp.status_code, ) |
||||||
|
|||||||
Loading…
Reference in new issue