修复bug

This commit is contained in:
wystan_rin 2024-11-21 17:28:14 +08:00
parent 5da63e23cc
commit 04679ac6c8
9 changed files with 57 additions and 44 deletions

View File

@ -2,14 +2,15 @@ import os
import subprocess import subprocess
import sys import sys
from flask import Flask, request, jsonify, make_response from flask import Flask, request, jsonify
from flask_cors import CORS from flask_cors import CORS
from loguru import logger
from config import get_config from config import get_config
from loguru import logger
from services.order import OrderService from services.order import OrderService
from services.user import UserService from services.user import UserService
from utils.datetime import parse_time_string, to_milliseconds from utils.datetime import parse_time_string, to_milliseconds
from utils.proj import filter_empty
app = Flask('app') app = Flask('app')
CORS(app, resources={r"/*": {"origins": "http://localhost:8080"}}) CORS(app, resources={r"/*": {"origins": "http://localhost:8080"}})
@ -31,11 +32,11 @@ def add_cors_headers(response):
@app.route('/createOrder', methods=['POST']) @app.route('/createOrder', methods=['POST'])
def create_order(): def create_order():
data = request.get_json() data = request.get_json()
name = data.get('name', None) name = filter_empty(data.get('name', None))
phone = data.get('phone', None) phone = filter_empty(data.get('phone', None))
email = data.get('email', None) email = filter_empty(data.get('email', None))
payment_method = data.get('paymentMethod', None) payment_method = filter_empty(data.get('paymentMethod', None))
if payment_method not in config['PaymentAddresses']: if payment_method is None or payment_method not in config['PaymentAddresses']:
return jsonify({ return jsonify({
"message": "wrong payment method" "message": "wrong payment method"
}), 400 }), 400
@ -45,15 +46,17 @@ def create_order():
"message": "Amount below minimum limit." "message": "Amount below minimum limit."
}), 400 }), 400
wallet_address = data.get('wallet_address', None) wallet_address = filter_empty(data.get('wallet_address', None))
if wallet_address is None: if wallet_address is None:
logger.debug('wallet address not provided')
wallet_addresses = user_service.get_wallet_addresses(name, phone, email, payment_method) wallet_addresses = user_service.get_wallet_addresses(name, phone, email, payment_method)
if not wallet_addresses: if not wallet_addresses:
logger.debug('wallet address are not found')
return jsonify({ return jsonify({
"message": "empty wallet address" "message": "empty wallet address"
}), 400 }), 400
if len(wallet_addresses) > 1: if len(wallet_addresses) > 1:
logger.debug('multiple wallet addresses')
return jsonify({ return jsonify({
"message": "Please select an address to place your order.", "message": "Please select an address to place your order.",
"wallet_addresses": wallet_addresses "wallet_addresses": wallet_addresses
@ -62,7 +65,7 @@ def create_order():
wallet_address = wallet_addresses[0] wallet_address = wallet_addresses[0]
else: else:
user_service.update_or_create(name, phone, email, wallet_address, payment_method) user_service.update_or_create(name, phone, email, wallet_address, payment_method)
logger.debug(f'wallet address: {wallet_address}')
order_id, create_timestamp = order_service.create_order(name=name, phone=phone, email=email, order_id, create_timestamp = order_service.create_order(name=name, phone=phone, email=email,
quant=quant, payment_method=payment_method, quant=quant, payment_method=payment_method,
wallet_address=wallet_address) wallet_address=wallet_address)
@ -76,10 +79,10 @@ def create_order():
@app.route('/queryOrder', methods=['POST']) @app.route('/queryOrder', methods=['POST'])
def query_order(): def query_order():
data = request.get_json() data = request.get_json()
name = data.get('name', None) name = filter_empty(data.get('name', None))
phone = data.get('phone', None) phone = filter_empty(data.get('phone', None))
email = data.get('email', None) email = filter_empty(data.get('email', None))
wallet_address = data.get('wallet_address', None) wallet_address = filter_empty(data.get('wallet_address', None))
page = data.get('page', 1) # 获取页码,默认为第 1 页 page = data.get('page', 1) # 获取页码,默认为第 1 页
page_size = data.get('page_size', 10) page_size = data.get('page_size', 10)

View File

@ -121,6 +121,8 @@ class Setting:
yield k, v yield k, v
def __contains__(self, item): def __contains__(self, item):
if item is None:
raise ValueError('None is not a valid key')
return item.lower() in self.__dict__ return item.lower() in self.__dict__
def __str__(self): def __str__(self):

View File

@ -17,12 +17,14 @@ class User:
payment_method=self.payment_method) payment_method=self.payment_method)
return f"INSERT INTO users ({params_sql}) VALUES ({','.join('%s' for _ in params)})", params return f"INSERT INTO users ({params_sql}) VALUES ({','.join('%s' for _ in params)})", params
def select_sql(self, condition="AND", params_format="list"): def select_sql(self, query_columns=None, condition="AND", params_format="list"):
if query_columns is None:
query_columns = ["id", "name", "phone", "email", "wallet_address", "payment_method"]
params_sql, params = pack_params(params_format=params_format, param_sql="{param}=%s", join_str=f" {condition} ", params_sql, params = pack_params(params_format=params_format, param_sql="{param}=%s", join_str=f" {condition} ",
name=self.name, phone=self.phone, email=self.email, name=self.name, phone=self.phone, email=self.email,
wallet_address=self.wallet_address, wallet_address=self.wallet_address,
payment_method=self.payment_method) payment_method=self.payment_method)
return f"SELECT id, name, phone, email, wallet_address, payment_method FROM users WHERE {params_sql}", params return f'SELECT {",".join(query_columns)} FROM users WHERE {params_sql}', params
def exists_sql(self, condition="AND", params_format="list"): def exists_sql(self, condition="AND", params_format="list"):
params_sql, params = pack_params(params_format=params_format, param_sql="{param}=%s", join_str=f" {condition} ", params_sql, params = pack_params(params_format=params_format, param_sql="{param}=%s", join_str=f" {condition} ",

View File

@ -1,5 +1,3 @@
import loguru
from custom_decorators import singleton from custom_decorators import singleton
from database import Database from database import Database
from loguru import logger from loguru import logger

View File

@ -12,7 +12,10 @@ class UserRepository:
def get_and_update(self, user): def get_and_update(self, user):
users = [] users = []
cursor = self.db.execute_query(*user.select_sql(condition="OR")) cursor = self.db.execute_query(
*user.select_sql(query_columns=["id", "name", "phone", "email", "wallet_address", "payment_method"],
condition="OR")
)
same_users = cursor.fetchall() same_users = cursor.fetchall()
new_user = not len(same_users) new_user = not len(same_users)
# 对用户已存在的属性判断是否有新属性 # 对用户已存在的属性判断是否有新属性
@ -22,6 +25,7 @@ class UserRepository:
delete_params = [] delete_params = []
exist_conflicting_attr = False exist_conflicting_attr = False
for same_user in same_users: for same_user in same_users:
same_user = User(*same_user)
exist_conflicting_attr = False exist_conflicting_attr = False
different_attrs = user.get_difference(same_user) different_attrs = user.get_difference(same_user)
# 用于判断是否有新属性 # 用于判断是否有新属性
@ -33,7 +37,7 @@ class UserRepository:
setattr(same_user, k, new_attr) setattr(same_user, k, new_attr)
update_sql_params.append(f"{k}=%s") update_sql_params.append(f"{k}=%s")
update_params.append(new_attr) update_params.append(new_attr)
else: elif new_attr is not None:
# 出现冲突的属性,考虑新增一行记录 # 出现冲突的属性,考虑新增一行记录
exist_conflicting_attr = True exist_conflicting_attr = True
break break
@ -45,14 +49,14 @@ class UserRepository:
exist_new_attr = bool(update_params) exist_new_attr = bool(update_params)
if exist_new_attr: if exist_new_attr:
update_user.add(same_user) update_user.add(same_user)
update_sqls.append(f'UPDATE user SET {",".join(update_sql_params)} WHERE id=%s;') update_sqls.append(f'UPDATE users SET {",".join(update_sql_params)} WHERE id=%s;')
update_params.append(same_user.id) update_params.append(same_user.id)
update_params_list.append(update_params) update_params_list.append(update_params)
sql_flag = False sql_flag = False
try: try:
if delete_params: if delete_params:
sql_flag = True sql_flag = True
self.db.get_connection().cursor().executemany("DELETE FROM user WHERE id=%s", delete_params) self.db.get_connection().cursor().executemany("DELETE FROM users WHERE id=%s", delete_params)
if update_user: if update_user:
sql_flag = True sql_flag = True
self.db.get_connection().cursor().execute("".join(update_sqls), self.db.get_connection().cursor().execute("".join(update_sqls),

View File

@ -67,10 +67,10 @@ class OrderService:
# 订单超时 # 订单超时
status = 0 status = 0
else: else:
correct_quant, confirmed = self.payment_service.check_payment(quant, correct_quant, confirmed = self.payment_service.check_payment(int(quant),
from_address, to_address, from_address, to_address,
# 减去十秒, 避免网络延迟导致的订单创建时间太晚 # 减去十秒, 避免网络延迟导致的订单创建时间太晚
create_timestamp - 10, now) create_timestamp - 10000, now)
if correct_quant and confirmed: if correct_quant and confirmed:
# 支付成功 # 支付成功
status = 1 status = 1

View File

@ -1,3 +1,5 @@
from loguru import logger
from custom_decorators import singleton from custom_decorators import singleton
from models import User from models import User
from repositories.user import UserRepository from repositories.user import UserRepository
@ -11,9 +13,10 @@ class UserService:
def get_wallet_addresses(self, name=None, phone=None, email=None, payment_method=None): def get_wallet_addresses(self, name=None, phone=None, email=None, payment_method=None):
if phone or email: if phone or email:
logger.debug(f'query wallet addresses by phone {phone} or email {email}')
users = self.user_repo.get_and_update(User(name=name, phone=phone, email=email, users = self.user_repo.get_and_update(User(name=name, phone=phone, email=email,
payment_method=payment_method)) payment_method=payment_method))
addresses = set(user.address for user in users if user.address) addresses = set(user.address for user in users if user.wallet_address)
return list(addresses) return list(addresses)
return [] return []

View File

@ -0,0 +1,5 @@
def filter_empty(param):
if param is not None:
if isinstance(param, str):
param = param.strip() or None
return param

View File

@ -115,16 +115,18 @@ function closeAddressModal() {
addressList.innerHTML = ''; addressList.innerHTML = '';
} }
function openAlertModal() {
document.getElementById('alertModal').style.display = 'flex';
}
function closeAlertModal() { function closeAlertModal() {
document.getElementById('alertModal').style.display = 'none'; document.getElementById('alertModal').style.display = 'none';
const alertElement = document.getElementById("alertMessage") const alertElement = document.getElementById("alertMessage")
alertElement.innerText = ""; alertElement.innerText = "";
} }
function openAlertModal(message) {
document.getElementById("alertMessage").innerText = message;
document.getElementById('alertModal').style.display = 'flex';
setTimeout(closeAlertModal, 5000);
}
function closeModalOnClickOutside(event) { function closeModalOnClickOutside(event) {
const modals = document.querySelectorAll('.modal'); const modals = document.querySelectorAll('.modal');
modals.forEach(modal => { modals.forEach(modal => {
@ -139,14 +141,11 @@ function promptUserForPaymentMethod() {
handleError('Unsupported payment method. Currently, only USDT payments are supported.'); handleError('Unsupported payment method. Currently, only USDT payments are supported.');
} }
function handleError(message) {
alert(message)
}
function promptUserForAddress() { function promptUserForAddress() {
const address = prompt('No payment address associated with this phone number was found. Please enter a payment address or provide additional information.'); const address = prompt('No payment address associated with this phone number was found. Please enter a payment address or provide additional information.');
if (address && address.trim() !== "") { if (address && address.trim() !== "") {
createOrder(null, null, address.trim()); document.getElementById('wallet').value = address.trim();
handleSubmit();
} else { } else {
handleError('No payment address associated with you was found. Please provide a payment address.'); handleError('No payment address associated with you was found. Please provide a payment address.');
} }
@ -194,10 +193,6 @@ function handleSubmit() {
const email = document.getElementById('email').value.trim(); const email = document.getElementById('email').value.trim();
const payment_address = document.getElementById('wallet').value.trim(); const payment_address = document.getElementById('wallet').value.trim();
// 清除之前的消息
// document.getElementById('message').classList.add('hidden');
// 调用createOrder函数
createOrder(amount, name, phone, email, payment_address, "USDT"); createOrder(amount, name, phone, email, payment_address, "USDT");
} }
@ -226,16 +221,12 @@ function finishOrder() {
.then(data => { .then(data => {
if (data.status === 0) { if (data.status === 0) {
// 订单超时, 联系客服 // 订单超时, 联系客服
const alertElement = document.getElementById("alertMessage") openAlertModal("<h2>The order has timed out. Please contact customer support if you have any questions.</h2>");
alertElement.innerText = "<h2>The order has timed out. Please contact customer support if you have any questions.</h2>";
openAlertModal();
} else if (data.status === 1) { } else if (data.status === 1) {
const createOrderElement = document.getElementById('createOrder'); const createOrderElement = document.getElementById('createOrder');
createOrderElement.textContent = 'Gain More Points!!!'; createOrderElement.textContent = 'Gain More Points!!!';
} else if (data.status === 3) { } else if (data.status === 3) {
const alertElement = document.getElementById("alertMessage") openAlertModal("<h2>The payment amount is abnormal. Please contact customer support if you have any questions.</h2>");
alertElement.innerText = "<h2>The payment amount is abnormal. Please contact customer support if you have any questions.</h2>";
openAlertModal();
} }
return data; return data;
}) })
@ -257,3 +248,8 @@ function handleQuery() {
// 调用createOrder函数 // 调用createOrder函数
queryOrder(name, phone, email, payment_address); queryOrder(name, phone, email, payment_address);
} }
function handleError(message) {
openAlertModal(message)
}