2025-01-27 17:55:35 +03:00

127 lines
4.1 KiB
TypeScript
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.

/* eslint-disable canonical/id-match */
/* eslint-disable consistent-return */
import { env as environment } from './config/env';
import { commandsList, KEYBOARD_REMOVE, KEYBOARD_SHARE_PHONE, MESSAGE_NOT_MASTER } from './message';
import { normalizePhoneNumber } from './utils/phone';
import {
createOrUpdateUser,
getCustomer,
updateCustomerMaster,
updateCustomerProfile,
} from '@repo/graphql/api';
import { Enum_Customer_Role } from '@repo/graphql/types';
import { Telegraf } from 'telegraf';
import { message } from 'telegraf/filters';
const bot = new Telegraf(environment.BOT_TOKEN);
bot.start(async (context) => {
const customer = await getCustomer({ telegramId: context.from.id });
if (customer) {
return context.reply(
`Приветствуем снова, ${customer.name} 👋.
Чтобы воспользоваться сервисом, откройте приложение.` + commandsList,
KEYBOARD_REMOVE,
);
}
return context.reply(
'Добро пожаловать! Пожалуйста, поделитесь своим номером телефона.',
KEYBOARD_SHARE_PHONE,
);
});
bot.command('addcontact', async (context) => {
const customer = await getCustomer({ telegramId: context.from.id });
if (!customer) {
return context.reply(
'Чтобы добавить контакт, сначала поделитесь своим номером телефона.',
KEYBOARD_SHARE_PHONE,
);
}
if (customer.role !== Enum_Customer_Role.Master) {
return context.reply(MESSAGE_NOT_MASTER);
}
return context.reply('Отправьте контакт клиента, которого вы хотите добавить');
});
bot.command('becomemaster', async (context) => {
const customer = await getCustomer({ telegramId: context.from.id });
if (!customer) {
return context.reply('Сначала поделитесь своим номером телефона.', KEYBOARD_SHARE_PHONE);
}
if (customer.role === Enum_Customer_Role.Master) {
return context.reply('Вы уже являетесь мастером.');
}
const response = await updateCustomerProfile({
data: { role: Enum_Customer_Role.Master },
documentId: customer.documentId,
}).catch((error) => {
context.reply('Произошла ошибка.\n' + error);
});
if (response) {
return context.reply('Вы стали мастером');
}
});
bot.on(message('contact'), async (context) => {
const customer = await getCustomer({ telegramId: context.from.id });
const isRegistration = !customer;
const { contact } = context.message;
const name = (contact.first_name || '') + ' ' + (contact.last_name || '').trim();
const phone = normalizePhoneNumber(contact.phone_number);
if (isRegistration) {
const response = await createOrUpdateUser({
name,
phone,
telegramId: context.from.id,
}).catch((error) => {
context.reply('Произошла ошибка.\n' + error);
});
if (response) {
return context.reply(
`Спасибо! Мы сохранили ваш номер телефона. Теперь можете открыть приложение или воспользоваться командами бота.` +
commandsList,
KEYBOARD_REMOVE,
);
}
} else {
if (customer.role !== Enum_Customer_Role.Master) {
return context.reply(MESSAGE_NOT_MASTER);
}
try {
await createOrUpdateUser({ name, phone });
await updateCustomerMaster({
masterId: customer.documentId,
operation: 'add',
phone,
});
return context.reply(
`Добавили контакт ${name}. Пригласите пользователя в приложение и тогда вы сможете добавлять записи с этим контактом.`,
);
} catch (error) {
context.reply('Произошла ошибка.\n' + error);
}
}
});
bot.launch();
// Enable graceful stop
process.once('SIGINT', () => bot.stop('SIGINT'));
process.once('SIGTERM', () => bot.stop('SIGTERM'));