wstkeys/app/routes.py

153 lines
4.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# from flask import Blueprint, request, jsonify
from flask import Blueprint, request, jsonify, send_from_directory
import os
import sqlite3
import json
# from services.rokky import ones
from API.rok import create_order
from API.TG import send_telegram
from services.orders import get_sku
from services.gg import get_product, create_messagea
from services.send_mai import send_html_flow
import logging
main = Blueprint("main", __name__)
DB_PATH = "./files/rokky.db"
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
IMAGE_FOLDER = os.path.join(BASE_DIR, 'images')
@main.route("/")
def index():
return "Hello wstkeys!!!"
@main.route("/images/<filename>")
def get_image(filename):
return send_from_directory(IMAGE_FOLDER, filename)
@main.route("/orders/api_payments", methods=["POST", "GET"])
def index1():
# Получаем все GET-параметры
params = request.args.to_dict()
logging.warn(f"newOrder: {params}")
# Просто выводим на экран (в ответ клиенту)
# парсим данные
id_d = params.get("id_d")
id_i = params.get("id_i")
email = params.get("email")
amount = params.get("amount")
currency = params.get("currency")
date = params.get("date")
# всё остальное сохраняем как JSON
content = json.dumps(params, ensure_ascii=False)
message = f"🔹Спасибо за покупку в WST Keys (West Store Trusted Keys)\n\n ⏳ Ваш заказ находится в процессе отгрузки."
create_messagea(id_i, message)
name_p, im = get_product(id_d)
sku_rokky, price_rokky = get_sku(id_d)
send_telegram(content)
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
try:
cursor.execute("""
INSERT INTO orders (id_i, id_d, email,name_p, im, amount, content, currency, date, sku_rokky, price_rokky)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?)
""", (id_i, id_d, email, name_p, im, amount, content, currency, date, sku_rokky, price_rokky))
conn.commit()
except Exception as e:
conn.close()
return jsonify({"error": str(e)}), 500
conn.close()
create_order(sku_rokky, price_rokky, id_i)
return jsonify({"success": True}), 200
# return "Hello GET"
@main.route("/newOrder", methods=["POST"])
def new_order():
if not request.is_json:
return jsonify({"error": "Invalid content type"}), 400
data = request.get_json()
print(data)
order_id = data.get("orderId")
if order_id is None:
return jsonify({"error": "orderId is required"}), 400
if not isinstance(order_id, int):
return jsonify({"error": "orderId must be int"}), 400
# TODO: обработка заказа
print(f"New order received: {order_id}")
send_telegram(data)
# logging.warn(get_order_content(order_id))
logging.warn(f"newOrder: {order_id}")
get_order_content(order_id)
send_html_flow(order_id)
return jsonify({"status": "ok"}), 200
@main.route("/skuChanged", methods=["POST"])
def sku():
if not request.is_json:
return jsonify({"error": "Invalid content type"}), 400
data = request.get_json()
print(data)
order_id = data.get("orderId")
if order_id is None:
return jsonify({"error": "orderId is required"}), 400
if not isinstance(order_id, int):
return jsonify({"error": "orderId must be int"}), 400
# TODO: обработка заказа
print(f"New order received: {order_id}")
send_telegram(data)
# logging.warn(get_order_content(order_id))
logging.warn(f"NEWsku: {order_id}")
return jsonify({"status": "ok"}), 200
@main.route("/product")
def product_update():
# получаем параметры
sku = request.args.get("rokky")
ggsale = request.args.get("ggsale")
if not sku or not ggsale:
return jsonify({"error": "Missing parameters"}), 400
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
# проверяем есть ли продукт с таким SKU
cursor.execute("SELECT id FROM products WHERE sku=?", (sku,))
row = cursor.fetchone()
if not row:
conn.close()
return jsonify({"error": "SKU not found"}), 404
# обновляем поле gg
cursor.execute("UPDATE products SET gg=? WHERE sku=?", (ggsale, sku))
conn.commit()
conn.close()
return jsonify({"success": True, "sku": sku, "ggsale": ggsale})