2025-12-11 06:35:26 +00:00
|
|
|
import io
|
|
|
|
|
|
|
|
|
|
from flask import Response
|
2025-12-11 13:29:03 +00:00
|
|
|
from helpers import init_db_connection
|
2025-12-11 06:35:26 +00:00
|
|
|
from PIL import Image
|
2025-12-11 13:29:03 +00:00
|
|
|
import logging
|
2025-12-11 06:35:26 +00:00
|
|
|
|
2025-12-11 13:29:03 +00:00
|
|
|
# Giả sử bạn đã cấu hình logger
|
|
|
|
|
logging.basicConfig(level=logging.DEBUG)
|
|
|
|
|
logger = logging.getLogger(__name__)
|
2025-12-11 06:35:26 +00:00
|
|
|
|
2025-12-11 13:29:03 +00:00
|
|
|
|
|
|
|
|
def exists_address_for_post(user_id: str, address: str):
|
|
|
|
|
cursor = None # Khởi tạo cursor để đảm bảo không gặp lỗi khi vào finally
|
|
|
|
|
conn = None # Khởi tạo conn để đảm bảo không gặp lỗi khi vào finally
|
2025-12-11 06:35:26 +00:00
|
|
|
try:
|
2025-12-11 13:29:03 +00:00
|
|
|
conn = init_db_connection()
|
|
|
|
|
cursor = conn.cursor()
|
|
|
|
|
|
|
|
|
|
cursor.execute("""
|
|
|
|
|
SELECT 1
|
|
|
|
|
FROM ailbl_user_address
|
|
|
|
|
WHERE user_id = %s AND address = %s
|
|
|
|
|
""", (user_id, address))
|
2025-12-11 06:35:26 +00:00
|
|
|
|
2025-12-11 13:29:03 +00:00
|
|
|
row = cursor.fetchone() # Nếu có kết quả, trả về dữ liệu 1 dòng
|
|
|
|
|
return row is not None # Nếu tồn tại, trả về True
|
2025-12-11 06:35:26 +00:00
|
|
|
except Exception as e:
|
2025-12-11 13:29:03 +00:00
|
|
|
logger.error(f"Database error checking address existence: {e}")
|
|
|
|
|
raise
|
|
|
|
|
finally:
|
|
|
|
|
if cursor:
|
|
|
|
|
cursor.close()
|
|
|
|
|
if conn:
|
|
|
|
|
conn.close() # Đảm bảo đóng kết nối sau khi xong
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def create_address(user_id: str, data):
|
|
|
|
|
try:
|
|
|
|
|
conn = init_db_connection()
|
|
|
|
|
cursor = conn.cursor()
|
|
|
|
|
|
|
|
|
|
query = """
|
|
|
|
|
INSERT INTO ailbl_user_address (user_id, address, area_code, city_code, created, modified)
|
|
|
|
|
VALUES (%s, %s, %s, %s, NOW(), NOW())
|
|
|
|
|
"""
|
|
|
|
|
# Lay cac truong tu data
|
|
|
|
|
address = data.get("address")
|
|
|
|
|
area_code = data.get("area_code")
|
|
|
|
|
city_code = data.get("city_code")
|
|
|
|
|
|
|
|
|
|
# Thực thi câu truy vấn SQL để thêm địa chỉ
|
|
|
|
|
cursor.execute(query, (user_id, address, area_code, city_code))
|
|
|
|
|
conn.commit() # Lưu thay đổi vào cơ sở dữ liệu
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
"user_id": user_id,
|
|
|
|
|
"address": address,
|
|
|
|
|
"area_code": area_code,
|
|
|
|
|
"city_code": city_code,
|
|
|
|
|
"status": "added"
|
|
|
|
|
}, 200
|
|
|
|
|
except Exception as e:
|
|
|
|
|
logging.error(f"Error creating address: {e}")
|
2025-12-11 06:35:26 +00:00
|
|
|
return {"error": str(e)}, 500
|
2025-12-11 13:29:03 +00:00
|
|
|
finally:
|
|
|
|
|
if cursor:
|
|
|
|
|
cursor.close()
|
|
|
|
|
if conn:
|
|
|
|
|
conn.close()
|
2025-12-11 06:35:26 +00:00
|
|
|
|
|
|
|
|
|
2025-12-11 13:29:03 +00:00
|
|
|
def filter_address(user_id: str, paging):
|
|
|
|
|
conn = None # Khởi tạo conn với giá trị None
|
|
|
|
|
cursor = None
|
2025-12-11 06:35:26 +00:00
|
|
|
try:
|
2025-12-11 13:29:03 +00:00
|
|
|
conn = init_db_connection() # Kết nối cơ sở dữ liệu
|
|
|
|
|
cursor = conn.cursor()
|
|
|
|
|
|
|
|
|
|
# Xây dựng điều kiện lọc
|
|
|
|
|
conditions = ["user_id = %(user_id)s"]
|
|
|
|
|
values = {"user_id": user_id} # Điều kiện cơ bản cho user_id
|
|
|
|
|
|
|
|
|
|
# Lọc theo address
|
|
|
|
|
if paging.filter.address:
|
|
|
|
|
conditions.append("LOWER(Address) LIKE %(address)s")
|
|
|
|
|
values["address"] = f"%{paging.filter.address.lower()}%"
|
|
|
|
|
|
|
|
|
|
# Lọc theo area_code
|
|
|
|
|
if paging.filter.area_code:
|
|
|
|
|
conditions.append("AreaCode = %(area_code)s")
|
|
|
|
|
values["area_code"] = paging.filter.area_code
|
|
|
|
|
|
|
|
|
|
# Lọc theo city_code
|
|
|
|
|
if paging.filter.city_code:
|
|
|
|
|
conditions.append("CityCode = %(city_code)s")
|
|
|
|
|
values["city_code"] = paging.filter.city_code
|
|
|
|
|
|
|
|
|
|
# Lọc theo ngày tạo
|
|
|
|
|
if paging.filter.created_from:
|
|
|
|
|
conditions.append("Created >= %(created_from)s")
|
|
|
|
|
values["created_from"] = paging.filter.created_from
|
|
|
|
|
|
|
|
|
|
if paging.filter.created_to:
|
|
|
|
|
conditions.append("Created <= %(created_to)s")
|
|
|
|
|
values["created_to"] = paging.filter.created_to
|
|
|
|
|
|
|
|
|
|
# Lọc theo ngày sửa đổi
|
|
|
|
|
if paging.filter.modified_from:
|
|
|
|
|
conditions.append("Modified >= %(modified_from)s")
|
|
|
|
|
values["modified_from"] = paging.filter.modified_from
|
|
|
|
|
|
|
|
|
|
if paging.filter.modified_to:
|
|
|
|
|
conditions.append("Modified <= %(modified_to)s")
|
|
|
|
|
values["modified_to"] = paging.filter.modified_to
|
|
|
|
|
|
|
|
|
|
# Kết hợp điều kiện lọc
|
|
|
|
|
where_clause = " AND ".join(conditions)
|
|
|
|
|
if where_clause:
|
|
|
|
|
where_clause = "WHERE " + where_clause
|
|
|
|
|
|
|
|
|
|
# Sắp xếp kết quả nếu có:
|
|
|
|
|
order_clause = ""
|
|
|
|
|
if paging.sortby:
|
|
|
|
|
direction = "ASC" if paging.asc else "DESC"
|
|
|
|
|
order_clause = f"ORDER BY {paging.sortby} {direction}"
|
|
|
|
|
|
|
|
|
|
# Kết hợp truy vấn
|
|
|
|
|
sql = f"""
|
|
|
|
|
SELECT
|
|
|
|
|
id,
|
|
|
|
|
user_id,
|
|
|
|
|
address,
|
|
|
|
|
area_code,
|
|
|
|
|
city_code,
|
|
|
|
|
created,
|
|
|
|
|
modified,
|
|
|
|
|
COUNT(*) OVER() AS total
|
|
|
|
|
FROM ailbl_user_address
|
|
|
|
|
{where_clause}
|
|
|
|
|
{order_clause}
|
|
|
|
|
LIMIT %(limit)s OFFSET %(offset)s
|
|
|
|
|
"""
|
|
|
|
|
values["limit"] = paging.size
|
|
|
|
|
values["offset"] = paging.page * paging.size
|
|
|
|
|
|
|
|
|
|
print("SQL Query: ", sql) # In ra câu truy vấn SQL
|
|
|
|
|
print("Values: ", values) # In ra các tham số
|
|
|
|
|
|
|
|
|
|
cursor.execute(sql, values) # Thực thi câu truy vấn với các giá trị
|
|
|
|
|
|
|
|
|
|
# Lấy tất cả các kết quả
|
|
|
|
|
addresses = cursor.fetchall()
|
|
|
|
|
print("Fetched addresses: ", addresses) # In ra kết quả
|
|
|
|
|
|
|
|
|
|
# Nếu không có kết quả
|
|
|
|
|
if not addresses:
|
|
|
|
|
return {"message": "No addresses found"}, 404
|
|
|
|
|
|
|
|
|
|
address_list = []
|
|
|
|
|
for address in addresses:
|
|
|
|
|
address_dict = {
|
|
|
|
|
"id": address[0],
|
|
|
|
|
"user_id": address[1],
|
|
|
|
|
"address": address[2],
|
|
|
|
|
"area_code": address[3],
|
|
|
|
|
"city_code": address[4],
|
|
|
|
|
"created": address[5],
|
|
|
|
|
"modified": address[6]
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
# Kiểm tra xem có cột 'total' hay không
|
|
|
|
|
if len(address) > 7:
|
|
|
|
|
address_dict["total"] = address[7]
|
|
|
|
|
|
|
|
|
|
address_list.append(address_dict)
|
|
|
|
|
|
|
|
|
|
return address_list, 200
|
2025-12-11 06:35:26 +00:00
|
|
|
|
|
|
|
|
except Exception as e:
|
|
|
|
|
return {"error": str(e)}, 500
|
2025-12-11 13:29:03 +00:00
|
|
|
finally:
|
|
|
|
|
if conn:
|
|
|
|
|
conn.close()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def exists_address_for_delete(address_id: str, user_id: str):
|
|
|
|
|
try:
|
|
|
|
|
# Kiểm tra xem địa chỉ có tồn tại cho user_id này không
|
|
|
|
|
conn = init_db_connection()
|
|
|
|
|
with conn.cursor() as cursor:
|
|
|
|
|
cursor.execute("""
|
|
|
|
|
SELECT 1
|
|
|
|
|
FROM ailbl_user_address
|
|
|
|
|
WHERE id = %s AND user_id = %s
|
|
|
|
|
""", (address_id, user_id))
|
2025-12-11 06:35:26 +00:00
|
|
|
|
2025-12-11 13:29:03 +00:00
|
|
|
row = cursor.fetchone()
|
|
|
|
|
return row is not None # Nếu có kết quả, địa chỉ tồn tại
|
2025-12-11 06:35:26 +00:00
|
|
|
|
2025-12-11 13:29:03 +00:00
|
|
|
except Exception as e:
|
|
|
|
|
logger.error(f"Database error checking address existence: {e}")
|
|
|
|
|
raise
|
|
|
|
|
finally:
|
|
|
|
|
if conn:
|
|
|
|
|
conn.close() # Đảm bảo kết nối được đóng
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def delete_address(address_id: str, user_id: str):
|
2025-12-11 06:35:26 +00:00
|
|
|
try:
|
2025-12-11 13:29:03 +00:00
|
|
|
conn = init_db_connection()
|
|
|
|
|
cursor = conn.cursor()
|
|
|
|
|
|
|
|
|
|
# Xóa địa chỉ từ bảng ailbl_user_address
|
|
|
|
|
cursor.execute("""
|
|
|
|
|
DELETE FROM ailbl_user_address
|
|
|
|
|
WHERE id = %s AND user_id = %s
|
|
|
|
|
""", (address_id, user_id))
|
|
|
|
|
|
|
|
|
|
conn.commit() # Lưu thay đổi vào cơ sở dữ liệu
|
|
|
|
|
return {"message": "Address deleted successfully"}, 200
|
|
|
|
|
|
2025-12-11 06:35:26 +00:00
|
|
|
except Exception as e:
|
2025-12-11 13:29:03 +00:00
|
|
|
logger.error(f"Error deleting address: {e}")
|
2025-12-11 06:35:26 +00:00
|
|
|
return {"error": str(e)}, 500
|
2025-12-11 13:29:03 +00:00
|
|
|
finally:
|
|
|
|
|
if cursor:
|
|
|
|
|
cursor.close()
|
|
|
|
|
if conn:
|
|
|
|
|
conn.close()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def update_address(address_id, user_id, request_data):
|
|
|
|
|
try:
|
|
|
|
|
conn = init_db_connection()
|
|
|
|
|
cursor = conn.cursor()
|
|
|
|
|
|
|
|
|
|
# Xây dựng câu lệnh UPDATE
|
|
|
|
|
update_query = """
|
|
|
|
|
UPDATE ailbl_user_address
|
|
|
|
|
SET address = %s, area_code = %s, city_code = %s, modified = NOW()
|
|
|
|
|
WHERE id = %s AND user_id = %s
|
|
|
|
|
RETURNING id;
|
|
|
|
|
"""
|
|
|
|
|
cursor.execute(update_query, (
|
|
|
|
|
request_data.get("address"),
|
|
|
|
|
request_data.get("area_code"),
|
|
|
|
|
request_data.get("city_code"),
|
|
|
|
|
address_id,
|
|
|
|
|
user_id
|
|
|
|
|
))
|
|
|
|
|
|
|
|
|
|
# Lấy kết quả sau khi thực hiện UPDATE
|
|
|
|
|
result = cursor.fetchone()
|
|
|
|
|
if result:
|
|
|
|
|
conn.commit()
|
|
|
|
|
return {"id": result[0], "status": "updated"}, 200
|
|
|
|
|
else:
|
|
|
|
|
return {"error": "Address not found or not updated"}, 404
|
|
|
|
|
|
|
|
|
|
except Exception as e:
|
|
|
|
|
# conn.rollback()
|
|
|
|
|
# current_app.logger.error(f"[update_address] DB Error: {e}")
|
|
|
|
|
return {"error": "DATABASE_ERROR"}, 500
|
|
|
|
|
|
|
|
|
|
finally:
|
|
|
|
|
cursor.close()
|
|
|
|
|
conn.close()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
# def get_address_by_id(address_id: str): Update chưa xong
|
|
|
|
|
# conn = None
|
|
|
|
|
# cursor = None
|
|
|
|
|
# try:
|
|
|
|
|
# conn = init_db_connection()
|
|
|
|
|
# with conn.cursor() as cursor:
|
|
|
|
|
# cursor.execute("""
|
|
|
|
|
# SELECT address, area_code, city_code, created, modified
|
|
|
|
|
# FROM ailbl_user_address
|
|
|
|
|
# WHERE id = %s;
|
|
|
|
|
# """, (address_id,))
|
|
|
|
|
|
|
|
|
|
# row = cursor.fetchone()
|
|
|
|
|
# if row:
|
|
|
|
|
# return {
|
|
|
|
|
# "address": row[0],
|
|
|
|
|
# "area_code": row[1],
|
|
|
|
|
# "city_code": row[2],
|
|
|
|
|
# "created": row[3],
|
|
|
|
|
# "modified": row[4]
|
|
|
|
|
# }
|
|
|
|
|
# else:
|
|
|
|
|
# return None # Nếu không tìm thấy địa chỉ, trả về None
|
|
|
|
|
|
|
|
|
|
# except Exception as e:
|
|
|
|
|
# return {"error": "DATABASE_ERROR"}, 500
|
|
|
|
|
# finally:
|
|
|
|
|
# if cursor:
|
|
|
|
|
# cursor.close()
|
|
|
|
|
# if conn:
|
|
|
|
|
# conn.close()
|