This commit is contained in:
tema 2022-06-05 15:02:41 +03:00
parent 64c6aeb002
commit 7abdf589aa
Signed by: tema
GPG Key ID: 21FDB6D162488F6F
43 changed files with 164 additions and 135 deletions

View File

@ -3,10 +3,10 @@
token = "123:adminadmin"
skip_update = False #
use_webhook = True #
skip_update = True #
use_webhook = False #
#telegram_api_server = "" #
#permission_file = ""
#permission_file = "" #
app_host = "127.0.0.1"
app_port = 2001

View File

@ -1,6 +1,8 @@
from load import dp
from .admin import IsAdmin
from .operator import IsOperator
dp.filters_factory.bind(IsAdmin)
dp.filters_factory.bind(IsOperator)

View File

@ -11,4 +11,4 @@ class IsAdmin(BoundFilter):
self.is_admin = is_admin
async def check(self, message: Message):
return message.from_user.id in get_admins()
return message.from_user.id in get_admins()

View File

@ -1,3 +1,4 @@
from . import user
from . import admin
from . import callback
from . import callback
from . import operator

View File

@ -1,15 +1,13 @@
import io
from aiogram import types
from aiogram.types import ContentType
from aiogram.dispatcher import FSMContext
from aiogram.types import ContentType
from load import bot, dp, messages
from utils.helper import download_file
from keyboard.default.admin.main_menu import base_menu, continue_btn, all_right
from keyboard.default.main_menu import back_to_main_menu
from load import bot, dp, messages
from state.post import Post
from utils.database.market import add_item
from utils.helper import download_file
@dp.message_handler(lambda x: x.text == messages.add_post, is_admin=True)
@ -37,7 +35,7 @@ async def admin_form_desk(message: types.Message, state: FSMContext):
@dp.message_handler(is_admin=True, state=Post.price)
async def admin_form_price(message: types.message, state: FSMContext):
if not message.text.replace('.','').replace(',', '').isdigit():
if not message.text.replace('.', '').replace(',', '').isdigit():
await Post.price.set()
await state.update_data(price=float(message.text.replace(",", ".")))
await bot.send_message(message.chat.id, "Отправьте фото товара")
@ -45,7 +43,7 @@ async def admin_form_price(message: types.message, state: FSMContext):
@dp.message_handler(is_admin=True, state=Post.image, content_types=[ContentType.PHOTO])
async def admin_form_image(message:types.Message, state: FSMContext):
async def admin_form_image(message: types.Message, state: FSMContext):
file_id = message.photo[-1].file_id
file_info = await bot.get_file(file_id)
photo = await download_file(file_info.file_path)
@ -55,10 +53,10 @@ async def admin_form_image(message:types.Message, state: FSMContext):
"Все данные для поста были заполнены",
reply_markup=continue_btn
)
await Post.finish.set()
await state.set_state("finish_post")
@dp.message_handler(lambda x:x.text == messages.continue_, state=Post.finish, is_admin=True)
@dp.message_handler(lambda x: x.text == messages.continue_, state="finish_post", is_admin=True)
async def finish(message: types.Message, state: FSMContext):
data = await state.get_data()
await bot.send_photo(
@ -73,7 +71,8 @@ async def finish(message: types.Message, state: FSMContext):
parse_mode='Markdown'
)
@dp.message_handler(lambda x: x.text == messages.all_right_message, is_admin=True, state=Post.finish)
@dp.message_handler(lambda x: x.text == messages.all_right_message, is_admin=True, state="finish_post")
async def write_on_db(message: types.Message, state: FSMContext):
data = await state.get_data()
add_item(**data)

View File

@ -7,4 +7,3 @@ from keyboard.default.admin.main_menu import main_menu
@dp.message_handler(lambda x: x.text == messages.admin_panel, is_admin=True)
async def cmd_menu(message: types.Message):
await bot.send_message(message.chat.id, "Admin panel", reply_markup=main_menu())

View File

@ -7,13 +7,12 @@ from keyboard.default.admin.main_menu import base_menu
from keyboard.default.main_menu import back_to_main_menu
@dp.message_handler(lambda x: x.text == messages.add_admin, is_admin=True)
async def add_admin(message: types.Message):
await bot.send_message(
message.chat.id,
("Отправьте user_id пользователя\n"
"Его можно узнать зайдя в информацию о пользователе"),
"Его можно узнать зайдя в информацию о пользователе"),
reply_markup=base_menu()
)
await AddUser.user_id.set()
@ -34,4 +33,3 @@ async def add_admin1(message: types.Message, state):
return
Register.register_admin(user)
await bot.send_message(message.chat.id, "Администратор добавлен!", reply_markup=back_to_main_menu)

View File

@ -4,7 +4,8 @@ from load import dp, bot, messages
from keyboard.inline.admin.user import item_list
from utils.database.base import get_full_admin
@dp.message_handler(lambda x: x.text==messages.del_admin, is_admin=True)
@dp.message_handler(lambda x: x.text == messages.del_admin, is_admin=True)
async def del_admin(message: types.Message):
admins = get_full_admin()
admin = admins[0]
@ -13,5 +14,5 @@ async def del_admin(message: types.Message):
message.chat.id,
result,
parse_mode="Markdown",
reply_markup=item_list(items=len(admins)-1)
reply_markup=item_list(items=len(admins) - 1)
)

View File

@ -1,4 +1,5 @@
from . import null
from . import catalog
from . import cart
from . import admin
from . import admin
from . import operator

View File

@ -1,4 +1,4 @@
import io
import io
from aiogram import types
@ -25,9 +25,10 @@ async def next_item_adm(callback: types.CallbackQuery):
),
parse_mode="Markdown",
),
reply_markup=item_list(count, len(items)-1, int(data[2]))
reply_markup=item_list(count, len(items) - 1, int(data[2]))
)
@dp.callback_query_handler(lambda c: c.data.split("|")[0] == 'delete_post', is_admin=True)
async def delete_post_adm(callback: types.CallbackQuery):
data = callback.data.split("|")
@ -47,7 +48,7 @@ async def delete_post_adm(callback: types.CallbackQuery):
),
parse_mode="Markdown",
),
reply_markup=item_list(items=len(items)-1)
reply_markup=item_list(items=len(items) - 1)
)
else:
await callback.message.delete()
@ -57,4 +58,4 @@ async def delete_post_adm(callback: types.CallbackQuery):
reply_markup=back_to_main_menu
)
await callback.answer("Товар удалён!")
await callback.answer()
await callback.answer()

View File

@ -1,4 +1,3 @@
from subprocess import call
from aiogram import types
from load import dp, messages
@ -20,6 +19,7 @@ async def next_item_adm(callback: types.CallbackQuery):
)
await callback.answer()
@dp.callback_query_handler(lambda x: x.data.split("|")[0] == "delete_admin")
async def delete_admin(callback: types.CallbackQuery):
data = callback.data.split("|")

View File

@ -1,6 +1,6 @@
import io
from aiogram import types
from aiogram import types
from load import dp, messages
from utils.database.cart import add_to_cart, get_user_cart, del_from_cart
@ -9,14 +9,15 @@ from keyboard.inline.cart import cart_list
from keyboard.default.main_menu import back_to_main_menu
@dp.callback_query_handler(lambda c: c.data.split("|")[0]=="add_to_cart")
@dp.callback_query_handler(lambda c: c.data.split("|")[0] == "add_to_cart")
async def add_cart(callback: types.CallbackQuery):
item_id = callback.data.split("|")[1]
item = int(callback.data.split("|")[1])
item_id = Catalog.get_catalog()[item]["id"]
add_to_cart(callback.from_user.id, item_id)
await callback.answer("Товар добавлен!")
@dp.callback_query_handler(lambda c: c.data.split("|")[0]=="del_from_cart")
@dp.callback_query_handler(lambda c: c.data.split("|")[0] == "del_from_cart")
async def del_cart(callback: types.CallbackQuery):
c = callback.data.split("|")[1]
item_id = get_user_cart(callback.from_user.id)[int(c)][0]
@ -26,7 +27,7 @@ async def del_cart(callback: types.CallbackQuery):
items = get_user_cart(callback.from_user.id)
if items:
index, count =items[0]
index, count = items[0]
item = Catalog.get_catalog(index)
await callback.message.edit_media(
media=types.InputMediaPhoto(
@ -35,11 +36,11 @@ async def del_cart(callback: types.CallbackQuery):
name=item["name"],
description=item["description"],
count=count,
price=item['price']*count
price=item['price'] * count
),
parse_mode="Markdown",
),
reply_markup=cart_list(items=len(items)-1)
reply_markup=cart_list(items=len(items) - 1)
)
else:
await callback.message.delete()
@ -66,9 +67,9 @@ async def next_item(callback: types.CallbackQuery):
name=item["name"],
description=item["description"],
count=count,
price=item['price']*count
price=item['price'] * count
),
parse_mode="Markdown",
),
reply_markup=cart_list(c, len(items)-1)
reply_markup=cart_list(c, len(items) - 1)
)

View File

@ -26,4 +26,3 @@ async def next_item(callback: types.CallbackQuery):
),
reply_markup=item_list(count, len(items)-1, int(data[2]))
)

View File

@ -2,6 +2,7 @@ from aiogram.types import CallbackQuery
from load import dp
@dp.callback_query_handler(lambda c: c.data == "null")
async def null(callback: CallbackQuery):
await callback.answer()

View File

@ -3,3 +3,4 @@ from . import catalog
from . import cart
from . import checkout
from . import ordering
from . import support

View File

@ -24,4 +24,4 @@ async def catalog(message: types.Message):
),
parse_mode="Markdown",
reply_markup=item_list(items=len(items))
)
)

View File

@ -9,7 +9,7 @@ from state.state import UserState
@dp.message_handler(lambda x: x.text == messages.checkout)
async def checkout(message:types.Message):
async def checkout(message: types.Message):
items = get_user_cart(message.from_user.id)
output: str = ""
cost = 0
@ -22,14 +22,14 @@ async def checkout(message:types.Message):
await UserState.confirm.set()
@dp.message_handler(lambda x: x.text == messages.all_right_message)
async def continue_user_form(message: types.Message):
@dp.message_handler(lambda x: x.text == messages.all_right_message, state="save_or_continue")
async def continue_user_form():
pass
@dp.message_handler(lambda x: x.text == messages.save_and_continue, state="*")
@dp.message_handler(lambda x: x.text == messages.save_and_continue, state="save_or_continue")
async def save_user_info(message: types.Message):
state = dp.current_state(chat=message.chat.id, user=message.from_user.id)
info = await state.get_data()
save_info(user_id=message.from_user.id, **info)
await continue_user_form(message)
await continue_user_form()

View File

@ -16,28 +16,27 @@ async def confirm(message: types.Message, state: FSMContext):
info = get_info(message.from_user.id)
await bot.send_message(
message.chat.id,
message.chat.id,
"Может у вас есть сохраненные данные?",
reply_markup=load_info(bool(info))
)
await Checkout.loaded.set()
await state.set_state(state="load_data")
@dp.message_handler(lambda x: x.text == messages.load_data, state=Checkout.loaded)
@dp.message_handler(lambda x: x.text == messages.load_data, state="load_data")
async def load_form(message: types.message, state: FSMContext):
info = get_info(message.from_user.id)
await state.update_data(
loaded=True,
first_name = info["first_name"],
last_name = info["last_name"],
phone_number = info["phone_number"],
address = info["address"]
first_name=info["first_name"],
last_name=info["last_name"],
phone_number=info["phone_number"],
address=info["address"]
)
await bot.send_message(message.chat.id, "Ваши данные загружены!", reply_markup=continue_btn)
await Checkout.finish.set()
await state.set_state("finish_send_form")
@dp.message_handler(lambda x: x.text == messages.rewrite_data, state=Checkout.loaded)
@dp.message_handler(lambda x: x.text == messages.rewrite_data, state="load_data")
async def new_form(message: types.Message, state: FSMContext = None):
await state.update_data(loaded=False)
await bot.send_message(
@ -65,7 +64,7 @@ async def form_first_name(message: types.Message, state: FSMContext):
await bot.send_message(
message.chat.id,
("Номер телефона\n\n"
"Можете написать номер телефона вручную"),
"Можете написать номер телефона вручную"),
reply_markup=get_phone_number
)
await Checkout.phone_number.set()
@ -73,36 +72,39 @@ async def form_first_name(message: types.Message, state: FSMContext):
@dp.message_handler(state=Checkout.phone_number, content_types=[types.ContentType.CONTACT, types.ContentType.TEXT])
async def form_phone(message: types.Message, state: FSMContext):
if message.contact is not None:
phone=message.contact.phone_number
else: phone=message.text
if len(phone) in [10,12,13]:
await state.update_data(phone_number=phone)
await bot.send_message(message.chat.id, "Отправте адрес доставки", reply_markup=cancel_btn)
await Checkout.address.set()
else:
if message.contact is not None:
phone = message.contact.phone_number
else:
phone = message.text
if len(phone) not in [10, 12, 13]:
await bot.send_message(message.chat.id, "Номер телефона не правильный!")
await Checkout.phone_number.set()
return
await state.update_data(phone_number=phone)
await bot.send_message(message.chat.id, "Отправте адрес доставки", reply_markup=cancel_btn)
await Checkout.address.set()
@dp.message_handler(state=Checkout.address)
async def form_address(message: types.Message, state: FSMContext):
await state.update_data(address=message.text)
await bot.send_message(message.chat.id, "Отлично заявка заполнена!", reply_markup=continue_btn)
await Checkout.finish.set()
await bot.send_message(message.chat.id, "Отлично, заявка заполнена!", reply_markup=continue_btn)
await state.set_state("finish_send_form")
@dp.message_handler(state=Checkout.finish)
@dp.message_handler(state="finish_send_form")
async def finish_form(message: types.Message, state: FSMContext):
data = await state.get_data()
text = (f"Имя: {data['first_name']}\n"
f"Фамилия: {data['last_name']}\n"
f"Номер телефона: {data['phone_number']}\n"
f"Адрес: {data['address']}\n"
)
f"Фамилия: {data['last_name']}\n"
f"Номер телефона: {data['phone_number']}\n"
f"Адрес: {data['address']}\n"
)
await bot.send_message(
message.chat.id,
message.chat.id,
text,
reply_markup=confirm_all_info()
)
await state.set_state("save_or_continue")

View File

@ -1,7 +1,7 @@
from aiogram import types
from aiogram.dispatcher.filters import CommandStart
from load import dp, bot, messages
from load import dp, bot, messages
from keyboard.default.main_menu import main_menu
from utils.database.base import get_admins, get_operator
from utils.database.user import Register
@ -18,6 +18,7 @@ async def start(message: types.Message):
reply_markup=main_menu(admin=is_bot_admin, operator=is_operator)
)
@dp.message_handler(lambda x: x.text == messages.back)
async def back_to_menu(message: types.Message):
is_bot_admin = message.from_user.id in get_admins()
@ -36,11 +37,11 @@ async def cancel(message: types.Message):
await back_to_menu(message)
@dp.message_handler(lambda x:x.text == messages.info)
@dp.message_handler(lambda x: x.text == messages.info)
async def userinfo(message: types.Message):
await bot.send_message(
message.chat.id,
("User_id: <code>{user_id}</code>").format(user_id=message.from_user.id),
message.chat.id,
"User_id: <code>{user_id}</code>".format(user_id=message.from_user.id),
parse_mode="HTML"
)

View File

@ -31,11 +31,11 @@ def base_menu(cancel=True, skip=False):
continue_btn = ReplyKeyboardMarkup(
[[KeyboardButton(messages.continue_),
KeyboardButton(messages.cancel_message)]],
KeyboardButton(messages.cancel_message)]],
resize_keyboard=True
)
all_right = ReplyKeyboardMarkup(
[[KeyboardButton(messages.all_right_message),
KeyboardButton(messages.cancel_message)]],
KeyboardButton(messages.cancel_message)]],
resize_keyboard=True
)

View File

@ -2,12 +2,14 @@ from aiogram.types.reply_keyboard import ReplyKeyboardMarkup, KeyboardButton
from load import messages
def checkout_btn() -> ReplyKeyboardMarkup:
return ReplyKeyboardMarkup([[
KeyboardButton(messages.all_right_message),
KeyboardButton(messages.cancel_message)
]], resize_keyboard=True)
def confirm_all_info():
markup = ReplyKeyboardMarkup(resize_keyboard=True)
markup.add(KeyboardButton(messages.all_right_message))

View File

@ -7,16 +7,17 @@ def main_menu(admin=False, operator=False):
markup = ReplyKeyboardMarkup(
[
[
KeyboardButton(messages.catalog), # Go to catalog
KeyboardButton(messages.cart) # Go to cart
KeyboardButton(messages.catalog), # Go to catalog
KeyboardButton(messages.cart) # Go to cart
]
],
resize_keyboard=True
).add(KeyboardButton(messages.info))
if admin == True:
if admin:
markup.add(KeyboardButton(messages.admin_panel))
if operator == True:
if operator:
markup.add(KeyboardButton(messages.operator_panel))
return markup
@ -30,7 +31,8 @@ def cart_btn(is_empty=True):
markup.add(KeyboardButton(messages.back))
return markup
back_to_main_menu = ReplyKeyboardMarkup(keyboard=[[KeyboardButton(messages.back)]],resize_keyboard=True)
back_to_main_menu = ReplyKeyboardMarkup(keyboard=[[KeyboardButton(messages.back)]], resize_keyboard=True)
cancel_btn = ReplyKeyboardMarkup([[KeyboardButton(messages.cancel_message)]], resize_keyboard=True)
get_phone_number = ReplyKeyboardMarkup(
keyboard=[

View File

@ -2,6 +2,7 @@ from aiogram.types.reply_keyboard import ReplyKeyboardMarkup, KeyboardButton
from load import messages
def load_info(data:bool = False):
markup = ReplyKeyboardMarkup(resize_keyboard=True)
if data:

View File

@ -3,22 +3,20 @@ from aiogram.types.inline_keyboard import InlineKeyboardMarkup, InlineKeyboardBu
from load import messages
def item_list(item=0, items:int=1, user_count:int=1) -> InlineKeyboardMarkup:
def item_list(item: int = 0, items: int = 1, user_count: int = 1) -> InlineKeyboardMarkup:
markup = InlineKeyboardMarkup()
default = [
InlineKeyboardButton(user_count, callback_data='null')
InlineKeyboardButton(str(user_count), callback_data='null')
]
back = ['⬅️', f"adm_prev|{item-1}|{user_count-1}"]
next = ['➡️', f"adm_next|{item+1}|{user_count+1}"]
if items < 1 or item >= items:
next = [" ", "null"]
if item == 0:
back = [" ", "null"]
default.append(InlineKeyboardButton(next[0], callback_data=next[1]))
markup.add(InlineKeyboardButton(back[0], callback_data=back[1]), *default)

View File

@ -1,24 +1,23 @@
from aiogram.types.inline_keyboard import InlineKeyboardButton, InlineKeyboardMarkup
from load import messages
def item_list(item=0, items:int=1, user_count:int=1) -> InlineKeyboardMarkup:
def item_list(item: int = 0, items: int = 1, user_count: int = 1) -> InlineKeyboardMarkup:
markup = InlineKeyboardMarkup()
default = [
InlineKeyboardButton(user_count, callback_data='null')
InlineKeyboardButton(str(user_count), callback_data='null')
]
back = ['⬅️', f"admin_prev|{item-1}|{user_count-1}"]
next = ['➡️', f"admin_next|{item+1}|{user_count+1}"]
if items < 1 or item >= items:
next = [" ", "null"]
if item == 0:
back = [" ", "null"]
default.append(InlineKeyboardButton(next[0], callback_data=next[1]))
markup.add(InlineKeyboardButton(back[0], callback_data=back[1]), *default)
markup.row(InlineKeyboardButton(messages.del_admin, callback_data=f"delete_admin|{item}"))
return markup
return markup

View File

@ -2,15 +2,15 @@ from aiogram.types.inline_keyboard import InlineKeyboardMarkup, InlineKeyboardBu
from load import messages
def cart_list(item=0, items:int=1) -> InlineKeyboardMarkup:
def cart_list(item:int = 0, items: int = 1) -> InlineKeyboardMarkup:
markup = InlineKeyboardMarkup()
default = [
InlineKeyboardButton(item+1, callback_data='null')
InlineKeyboardButton(str(item+1), callback_data='null')
]
back = ['⬅️', f"cart_prev|{item-1}"]
next = ['➡️', f"cart_next|{item+1}"]
if items < 1 or item >= items:
next = [" ", "null"]

View File

@ -3,15 +3,14 @@ from aiogram.types.inline_keyboard import InlineKeyboardMarkup, InlineKeyboardBu
from load import messages
def item_list(item=0, items:int=1, user_count:int=1) -> InlineKeyboardMarkup:
def item_list(item: int = 0, items: int = 1, user_count: int = 1) -> InlineKeyboardMarkup:
markup = InlineKeyboardMarkup()
default = [
InlineKeyboardButton(user_count, callback_data='null')
InlineKeyboardButton(str(user_count), callback_data='null')
]
back = ['⬅️', f"prev|{item-1}|{user_count-1}"]
next = ['➡️', f"next|{item+1}|{user_count+1}"]
if items < 1 or item >= items:
next = [" ", "null"]
@ -22,4 +21,4 @@ def item_list(item=0, items:int=1, user_count:int=1) -> InlineKeyboardMarkup:
markup.add(InlineKeyboardButton(back[0], callback_data=back[1]), *default)
markup.row(InlineKeyboardButton(messages.add_to_cart, callback_data=f"add_to_cart|{item}"))
return markup
return markup

View File

@ -1,15 +1,14 @@
from aiogram.types.inline_keyboard import InlineKeyboardMarkup, InlineKeyboardButton
def cart_list(item=0, items:int=1) -> InlineKeyboardMarkup:
def cart_list(item: int = 0, items: int = 1) -> InlineKeyboardMarkup:
markup = InlineKeyboardMarkup()
default = [
InlineKeyboardButton(item+1, callback_data='null')
InlineKeyboardButton(str(item+1), callback_data='null')
]
back = ['⬅️', f"cart_prev|{item-1}"]
next = ['➡️', f"cart_next|{item+1}"]
if items < 1 or item >= items:
next = [" ", "null"]

View File

@ -8,8 +8,7 @@ from peewee import SqliteDatabase
from playhouse.db_url import connect
import config
from utils import messages # used, do not delete!
from utils import messages # used, do not delete!
# Bot init
bot = Bot(
@ -24,6 +23,6 @@ dp = Dispatcher(
storage=storage
)
db:SqliteDatabase = connect(config.db_url)
db: SqliteDatabase = connect(config.db_url)
permissions = json.load(open(config.permission_file))

View File

@ -1,11 +1,8 @@
from aiogram.dispatcher.filters.state import StatesGroup, State
class Checkout(StatesGroup):
first_name = State()
last_name = State()
phone_number = State()
address = State()
loaded = State()
finish = State()

View File

@ -1,9 +1,8 @@
from aiogram.dispatcher.filters.state import StatesGroup, State
class Post(StatesGroup):
name = State()
description = State()
price = State()
image = State()
finish = State()

View File

@ -1,5 +1,6 @@
from aiogram.dispatcher.filters.state import StatesGroup, State
class UserState(StatesGroup):
confirm = State()

View File

@ -14,6 +14,7 @@ def get_operator():
users.append(i.user_id)
return users
def get_full_admin():
usr = []
for i in Admin.select():
@ -28,3 +29,10 @@ def get_full_admin():
def del_admin(user_id:int):
Admin.delete().where(Admin.user_id == user_id).execute()
def get_active_operator():
usr = []
for i in Operator.select().where(Operator.active==True):
usr.append(i.user_id)
return usr

View File

@ -16,6 +16,7 @@ def del_from_cart(user_id: int, item_id: int):
def clean_cart(user_id: int):
Cart.delete().where(Cart.user_id==user_id).execute()
def get_user_cart(user_id:int):
cart = []
for i in Cart.select().where(Cart.user_id == user_id):

View File

@ -1,10 +1,9 @@
from ast import Mod
import typing as t
from .model import Catalog as Model
class Catalog():
class Catalog:
@staticmethod
def __get_item(item_id: int) -> dict:
item = {}
@ -23,17 +22,16 @@ class Catalog():
return item
@classmethod
def get_catalog(self, item_id:int = None, get_count:bool = False) -> t.Union[list, dict]:
def get_catalog(cls, item_id:int = None, get_count:bool = False) -> t.Union[list, dict]:
if item_id:
if get_count:
return self.__get_item(item_id), Model.select().count()
return self.__get_item(item_id)
return cls.__get_item(item_id), Model.select().count()
return cls.__get_item(item_id)
items = []
for i in Model.select():
items.append(self.__get_item(i.id))
items.append(cls.__get_item(i.id))
return items
@staticmethod
def delete_post(item_id: int):

View File

@ -1,11 +1,11 @@
from peewee import (Model, BigIntegerField, TextField, BlobField,
IntegerField, CharField, FloatField, ForeignKeyField)
IntegerField, CharField, FloatField, BooleanField)
from load import db
class BaseModel(Model):
'''Base model. Abstract Class'''
"""Base model. Abstract Class"""
class Meta:
database = db
@ -22,7 +22,7 @@ class Admin(User):
class Operator(User):
pass
active = BooleanField(default=False)
class Catalog(BaseModel):
@ -45,4 +45,5 @@ class UserInfo(BaseModel):
phone_number = CharField(15)
address = TextField()
db.create_tables([Cart, Catalog, Operator, Admin, User, UserInfo])

View File

@ -10,6 +10,7 @@ def save_info(user_id: int, last_name:str, first_name:str, phone_number:str, add
address=address
).on_conflict_replace().execute()
def get_info(user_id: int):
output = None
if UserInfo.select().where(UserInfo.user_id == user_id).exists():

View File

@ -9,7 +9,7 @@ from utils import types
class Register:
@classmethod
def __register_user(self, model: Model, user: UserType):
def __register_user(cls, model: Model, user: UserType):
model.insert(
user_id=user.id,
first_name=user.first_name,
@ -18,16 +18,16 @@ class Register:
).on_conflict_replace().execute()
@classmethod
def register_user(self, user: UserType):
return self.__register_user(UserModel, user)
def register_user(cls, user: UserType):
return cls.__register_user(UserModel, user)
@classmethod
def register_admin(self, user: UserType):
return self.__register_user(Admin, user)
def register_admin(cls, user: UserType):
return cls.__register_user(Admin, user)
@classmethod
def register_operator(self, user: UserType):
return self.__register_user(Operator, user)
def register_operator(cls, user: UserType):
return cls.__register_user(Operator, user)
class User:
@ -43,3 +43,15 @@ class User:
last_name=data.last_name,
username=data.username
)
@staticmethod
def get_state(user_id:int):
if Operator.select().where(Operator.user_id == user_id).exists():
return Operator.get(Operator.user_id == user_id).active
return False
@staticmethod
def set_state(user_id:int, state:bool=False):
if Operator.select().where(Operator.user_id == user_id).exists():
Operator.update(active=state).where(Operator.user_id == user_id).execute()
return None

View File

@ -3,6 +3,7 @@ import typing as t
from load import bot, config
async def download_file(file_path, *args, **kw) -> t.Union[io.BytesIO, t.Any]:
if config.telegram_api_server == "https://api.telegram.org":
return await bot.download_file(file_path, *args, **kw)

View File

@ -2,4 +2,4 @@ from load import permissions as __permissions
from .model import Permission
permission = Permission(**__permissions)
permission = Permission(**__permissions)

View File

@ -1,5 +1,6 @@
from pydantic import BaseModel
class Permission(BaseModel):
can_admin_add_admins: bool
can_admin_del_admins: bool

View File

@ -19,6 +19,9 @@ continue_ = "Продолжить"
rewrite_data = "Ввести заново"
load_data = "Загрузить данные"
#Operator
on_work = "Активировать"
leave_work = "Выключить"
#Admins \ Moder
admin_panel = "Админ панель"

View File

@ -2,22 +2,22 @@ import typing as t
from abc import ABC
class BaseUserFileds(ABC):
class BaseUser(ABC):
id: int
first_name: str
last_name: t.Union[str, None] = None
username: t.Union[str, None] = None
class User(BaseUserFileds):
class User(BaseUser):
def __new__(self, **kw):
def __new__(cls, **kw):
if "user_id" in kw:
self.id = kw["user_id"]
cls.id = kw["user_id"]
if "first_name" in kw:
self.first_name = kw["first_name"]
cls.first_name = kw["first_name"]
if "last_name" in kw:
self.last_name = kw["last_name"]
cls.last_name = kw["last_name"]
if "username" in kw:
self.username = kw["username"]
return self
cls.username = kw["username"]
return cls