payment/payment_backend/services/order.py

59 lines
2.2 KiB
Python
Raw Normal View History

2024-11-10 10:00:58 +00:00
import uuid
from custom_decorators import singleton
2024-11-13 07:55:17 +00:00
from models import User
2024-11-10 10:00:58 +00:00
from repositories.order import OrderRepository
2024-11-13 07:55:17 +00:00
from repositories.user import UserRepository
2024-11-11 07:32:36 +00:00
from services.payment import PaymentService
2024-11-10 10:00:58 +00:00
from utils.datetime import current, current_timestamp, is_time_difference_greater_than
@singleton
class OrderService:
2024-11-11 10:23:57 +00:00
def __init__(self, config):
2024-11-13 07:55:17 +00:00
self.config = config
2024-11-11 07:32:36 +00:00
self.payment_service = PaymentService()
2024-11-13 07:55:17 +00:00
self.order_repo = OrderRepository(config)
self.user_repo = UserRepository(config)
2024-11-10 10:00:58 +00:00
2024-11-13 07:55:17 +00:00
def get_user_addresses(self, phone=None, email=None, address=None, payment_method=None):
if address is None:
if phone or email:
users = self.user_repo.get_or_create(User(phone=phone, email=email))
addresses = set(user.address for user in users if address)
return list(addresses)
raise ValueError('A phone number, email, or address is required.')
return [address]
def create_order(self, address=None):
2024-11-10 10:00:58 +00:00
date_str = current().strftime('%Y%m%d%H%M%S')
unique_id = str(uuid.uuid4()).split('-')[0]
order_id = f"{date_str}-{unique_id}"
2024-11-13 07:55:17 +00:00
self.order_repo.create(order_id, address,
self.config['PaymentAddresses'])
2024-11-10 10:00:58 +00:00
return order_id
def finish_order(self, order_id):
# 判断支付时间是否超过订单存活时间
2024-11-11 10:23:57 +00:00
quant, from_address, to_address, create_timestamp = self.order_repo.get_order_info(order_id)
2024-11-11 07:32:36 +00:00
current = current_timestamp()
status = 0
2024-11-11 10:23:57 +00:00
if is_time_difference_greater_than(create_timestamp, current, minutes=15):
2024-11-11 07:32:36 +00:00
# 订单超时
status = 4
2024-11-10 10:00:58 +00:00
else:
2024-11-11 10:23:57 +00:00
correct_quant, confirmed = self.payment_service.check_payment(quant, from_address, to_address, create_timestamp, current)
2024-11-11 07:32:36 +00:00
if correct_quant and confirmed:
# 支付成功
status = 1
elif correct_quant < 0:
# 没有转账
status = 2
elif confirmed:
# 金额不对
status = 3
if status:
self.order_repo.update_status(order_id, status)
2024-11-10 10:00:58 +00:00
return status