Skip to content

Conversation

@alvarezrrj
Copy link
Collaborator

@alvarezrrj alvarezrrj commented Apr 8, 2024

Description

Algunos cambios para que el bot use distintos flujos dependiendo de si alguien está de guardia

Mejoras en seed.ts:

  • El script busca a los usuarios en la bbdd y solo pide los datos si no los encuentra.
  • Inserta los flujos del bot desde /src/chatbot/messages.ts
Base automatically changed from logging to develop April 9, 2024 15:26
@AlphaDev87 AlphaDev87 merged commit f74de64 into develop Apr 9, 2024
@AlphaDev87 AlphaDev87 deleted the bot branch April 9, 2024 17:11
AlphaDev87 added a commit that referenced this pull request Apr 9, 2024
* Bot (#20) * Add chatbot flows, Add bot.qr.png to .gitignore * Fetch bot menus and answers from DB * Auth fix (#22) * Fix double refresh hanging the server * 🧹 Clean up * Add console.error() to exitLog * Testing (#24) * Add role to player on PlayersDAO.upsert * Add tests * Alquimia (#25) * Add alquimia payment verification * Update seed.sql * Comment out services.old.ts * Remove Player from DepositDAO.create() * Remove Player from DepositDAO.create() * Alquimia (#26) * Fix deposit test * Look for deposits 24 hours into the past * Fix tests * Update deposit on /transactions/deposit/:id (#27) * Alquimia sync (#28) * Update deposit on /transactions/deposit/:id * Sync deposits from Alquimia DB to local on FinanceServices.verifyPayment() * Set deposit status to rejected if not found * Change integer incremental IDs to string UUIDs * Modify endpoints to use only GET and POST methods (#29) * Modify endpoints to use only GET and POST methods * Misc (#30) * Add endpoint to show Alquimia bank details, Configure cors for development, Update deposit instead of create when existing tracking key found in request * Add ALLOWED_ORIGIN to .env * origin source * lint --------- Co-authored-by: Alpha Dev <alphadev@MacBook-Pro-de-Gonzalo.local> --------- Co-authored-by: Alpha Dev <alphadev@MacBook-Pro-de-Gonzalo.local> --------- Co-authored-by: Alpha Dev <alphadev@MacBook-Pro-de-Gonzalo.local> * Deposit flow (#31) * Create CasinoCoinsService to handle coin transfers, Improve FinanceService.confirmDeposit error handling, Remove paid_at and coins_transfered from Deposit model, add casinoTokenService.login() call to seed.ts, Improve Notify error handling, Improve TransactionsDAO error handling, Turn Player.balance_currency into a required field, Swap Transaction.status with Transaction.ok * Update .gitignore * Fix bug in FinanceServices.alquimiaDepositLookup (#32) * Fix bug in FinanceServices.alquimiaDepositLookup * Improve bank-account request validator * Fix bank-account test * fix cashout validation * Add rate limiter to POST /transactions/deposit/:id? (#33) * Deposit (#34) * Improve DepositDAO.authorizeConfirmation, Give agent role permission to confirm deposit, Remove TransactionsController.deleteDeposit, Fixed finalizeDeposit logic to not send coins on confirmed deposits, Add optional id to GET /agent/depoists to retreive individual depoist, Rename /agent/deposits/complete to /agent/pending/depoists * Update README * Payment throttling (#35) * Update dependecies, Restrict withdrawals to 1 every 24 hours * Update CHANGELOG * update bankNumber validation * Logging (#36) * Add logtailLogger, Fix bug in AuthServices.refresh * Update CHANGELOG * Update CONFIG.LOG.CODES * Bot (#37) * Add logtailLogger, Fix bug in AuthServices.refresh * Update CHANGELOG * Update CONFIG.LOG.CODES * Update USER_ALREADY_EXISTS error description * Add on call bot flows, Add endpoint to set on call status on/off * Rename table BOT_MESSAGES to BOT_FLOWS * Update REAMDE, Update CHANGELOG * Improve seed.ts * Update CHANGELOG * Add GET /agent/on-call endpoint * Update README with on call endpoints * Add tests for on-call endpoints * Move test agent creds to .env --------- Co-authored-by: AlphaDev87 <155021991+AlphaDev87@users.noreply.github.com> --------- Co-authored-by: Rodrigo Alvarez <65652568+alvarezrrj@users.noreply.github.com> Co-authored-by: Alpha Dev <alphadev@MacBook-Pro-de-Gonzalo.local>
@alvarezrrj
Copy link
Collaborator Author

@coderabbitai review

@coderabbitai
Copy link

coderabbitai bot commented Apr 11, 2024

Walkthrough

The recent update introduces a new on-call feature for agents, allowing them to set and view their on-call status through newly added API endpoints. The database schema and related data access objects have been adjusted accordingly, including renaming tables and adding new columns. Tests ensure the functionality works as expected, and the frontend now includes routes for easy interaction with these new features.

Changes

File Group Change Summary
README.md, __tests__/agent.test.ts, src/routes/agent.router.ts Added functionality and endpoints for agent on-call status management.
prisma/..., src/db/..., src/components/agent/... Database schema updates, including renaming and adding columns, and updates in agent components to handle new on-call features.
src/chatbot/... Updated chatbot logic and messages to support on-call and regular flows.
src/config/errors.ts, src/db/seed.ts Improved error messages and updated seeding logic for database.

🐰✨
In the burrows of the code, deep and wide,
A rabbit worked with joy and pride.
New paths he carved, for agents bright,
To signal when they're in the night.
On-call they stand, so bold and grand,
In digital fields, hand in hand. 🌟🐇


Recent Review Details

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between 4730eb5 and ac52b65.
Files ignored due to path filters (1)
  • yarn.lock is excluded by !**/*.lock
Files selected for processing (14)
  • CHANGELOG.md (1 hunks)
  • README.md (4 hunks)
  • tests/agent.test.ts (2 hunks)
  • prisma/migrations/20240408200558_rename_bot_messages_to_bot_flows/migration.sql (1 hunks)
  • prisma/schema.prisma (1 hunks)
  • src/chatbot/flows.ts (4 hunks)
  • src/chatbot/messages.ts (2 hunks)
  • src/components/agent/controller.ts (1 hunks)
  • src/components/agent/services.ts (2 hunks)
  • src/components/agent/validators.ts (1 hunks)
  • src/config/errors.ts (1 hunks)
  • src/db/bot-flows.ts (1 hunks)
  • src/db/seed.ts (2 hunks)
  • src/routes/agent.router.ts (2 hunks)
Additional comments not posted (12)
prisma/migrations/20240408200558_rename_bot_messages_to_bot_flows/migration.sql (1)

8-19: Ensure data migration from BOT_MESSAGES to BOT_FLOWS is handled to prevent data loss.

src/components/agent/validators.ts (1)

77-84: Validation rules for on-call requests are correctly implemented.

src/routes/agent.router.ts (1)

61-68: Ensure thorough testing of the new on-call management routes to verify security and functionality.

Verification successful

The review comment suggested ensuring thorough testing of the new on-call management routes to verify security and functionality. The provided shell script output confirms that there are tests for both the POST and GET methods of the /agent/on-call route, as seen in the __tests__/agent.test.ts file.

Given this information, it appears that the necessary tests have been implemented to cover the new routes, aligning with the recommendation in the review comment to verify security and functionality through testing.

Based on this, I can conclude that the review comment has been verified successfully.

Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash # Check for tests covering the new on-call routes rg --type ts "describe.*(on-call)" 

Length of output: 169

src/config/errors.ts (1)

7-7: Updated error message for USER_ALREADY_EXISTS is clear and user-friendly.

src/db/seed.ts (1)

28-127: > 📝 NOTE

This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [6-122]

Consider adding more detailed logging in the seed script to improve traceability and debugging.

+ console.log("Starting to seed bot flows..."); + console.log("Bot flows seeded successfully.");
src/components/agent/services.ts (1)

17-17: Consider adding a comment above the BotFlowsDAO import to explain its usage in this file.

prisma/schema.prisma (1)

146-153: The changes to the BotFlow model are correctly implemented and align with the PR objectives.

README.md (2)

278-280: Ensure the description for the "Setear Guardia" endpoint is clear and actionable.

The current description "Indicar que alguien está al teléfono para que el bot muestre el menú 'contactanos'." could be more specific. Consider revising to clarify what action the endpoint performs, such as "Sets the agent's status to on-call, which triggers the bot to display the 'contact us' menu."


288-290: Clarify the description for the "Ver Guardia" endpoint to enhance understanding.

The description "Indicar que alguien está al teléfono para que el bot muestre el menú 'contactanos'." is repeated from the previous endpoint and might be confusing here. It should explicitly state that this endpoint retrieves the current on-call status of an agent, possibly affecting the bot's response.

__tests__/agent.test.ts (2)

47-48: Using environment variables for credentials enhances security by avoiding hardcoded sensitive information in the codebase.


402-475: The new tests for the on-call status endpoints are comprehensive, covering various scenarios including successful operations and different error cases (400, 401, 403). This ensures robustness and reliability of the on-call functionality.

src/chatbot/messages.ts (1)

290-578: > 📝 NOTE

This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [246-577]

The updates to botMessages and the addition of botMessagesOnCall and botMenusOnCall enhance the chatbot's functionality by providing tailored interactions for on-call scenarios. This aligns with the PR's objective to make the bot responsive to the operational status of agents.


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 7

Comment on lines +114 to +116
static async setOnCallBotFlow(active: boolean): Promise<void> {
await BotFlowsDAO.setOnCall(active);
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ensure robustness by adding error handling for the setOnCallBotFlow method.

 static async setOnCallBotFlow(active: boolean): Promise<void> { + try { await BotFlowsDAO.setOnCall(active); + } catch (error) { + console.error("Failed to set on-call status:", error); + throw new CustomError({ code: "database_error", description: "Failed to update on-call status" }); + } }

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
static async setOnCallBotFlow(active: boolean): Promise<void> {
await BotFlowsDAO.setOnCall(active);
}
static async setOnCallBotFlow(active: boolean): Promise<void> {
try {
await BotFlowsDAO.setOnCall(active);
} catch (error) {
console.error("Failed to set on-call status:", error);
throw new CustomError({ code: "database_error", description: "Failed to update on-call status" });
}
}
Comment on lines +118 to +122
static async getOnCallStatus(): Promise<boolean> {
const botFlow = await BotFlowsDAO.findOnCallFlow();

return !!botFlow;
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add error handling to the getOnCallStatus method to improve reliability.

 static async getOnCallStatus(): Promise<boolean> { + try { const botFlow = await BotFlowsDAO.findOnCallFlow(); + return !!botFlow; + } catch (error) { + console.error("Failed to retrieve on-call status:", error); + throw new CustomError({ code: "database_error", description: "Failed to retrieve on-call status" }); + } }

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
static async getOnCallStatus(): Promise<boolean> {
const botFlow = await BotFlowsDAO.findOnCallFlow();
return !!botFlow;
}
static async getOnCallStatus(): Promise<boolean> {
try {
const botFlow = await BotFlowsDAO.findOnCallFlow();
return !!botFlow;
} catch (error) {
console.error("Failed to retrieve on-call status:", error);
throw new CustomError({ code: "database_error", description: "Failed to retrieve on-call status" });
}
}
Comment on lines +61 to +70
for (let i = 1; i < (regularFlow.menus as string[][]).length; i++) {
// @ts-ignore
const flow = createSubMenu(regularFlow.menus[i], regularFlow.messages[i]);
submenus.push(flow);
}
for (let i = 1; i < (onCallFlow.menus as string[][][]).length; i++) {
// @ts-ignore
const flow = createSubMenu(onCallFlow.menus[i], onCallFlow.messages[i]);
onCallSubmenus.push(flow);
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider removing @ts-ignore and properly typing the variables to avoid potential runtime errors.

Comment on lines +90 to +112
.addAction(async (_ctx, { flowDynamic }) => {
const weAreOnCall = await BotFlowsDAO.findOnCallFlow();
// @ts-ignore
const mainMenu = weAreOnCall ? onCallFlow.menus[0] : regularFlow.menus[0];
await flowDynamic(mainMenu.join("\n"));
})
.addAction(
{ capture: true },
async (ctx, { gotoFlow, fallBack, state }) => {
const mainMenuOptions = botMenus[0].filter((option) =>
const weAreOnCall = await BotFlowsDAO.findOnCallFlow();
// @ts-ignore
const menus = (
weAreOnCall ? onCallFlow.menus : regularFlow.menus
) as string[][];
const mainMenuOptions = menus[0].filter((option) =>
/\*\d+/.test(option),
);
const subflows = weAreOnCall ? onCallSubmenus : submenus;

const choice = Math.round(Number(ctx.body.trim()));

if (choice > 0 && choice <= mainMenuOptions.length) {
await gotoFlow(submenus[choice - 1]);
await gotoFlow(subflows[choice - 1]);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add error handling to asynchronous operations in the main menu logic to prevent unhandled promise rejections.

 .addAction(async (_ctx, { flowDynamic }) => { + try { const weAreOnCall = await BotFlowsDAO.findOnCallFlow(); const mainMenu = weAreOnCall ? onCallFlow.menus[0] : regularFlow.menus[0]; await flowDynamic(mainMenu.join("\n")); + } catch (error) { + console.error("Failed to fetch or process main menu:", error); + throw new CustomError({ code: "flow_error", description: "Failed to process main menu" }); + } })

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
.addAction(async (_ctx, { flowDynamic }) => {
const weAreOnCall = await BotFlowsDAO.findOnCallFlow();
// @ts-ignore
const mainMenu = weAreOnCall ? onCallFlow.menus[0] : regularFlow.menus[0];
await flowDynamic(mainMenu.join("\n"));
})
.addAction(
{ capture: true },
async (ctx, { gotoFlow, fallBack, state }) => {
const mainMenuOptions = botMenus[0].filter((option) =>
const weAreOnCall = await BotFlowsDAO.findOnCallFlow();
// @ts-ignore
const menus = (
weAreOnCall ? onCallFlow.menus : regularFlow.menus
) as string[][];
const mainMenuOptions = menus[0].filter((option) =>
/\*\d+/.test(option),
);
const subflows = weAreOnCall ? onCallSubmenus : submenus;
const choice = Math.round(Number(ctx.body.trim()));
if (choice > 0 && choice <= mainMenuOptions.length) {
await gotoFlow(submenus[choice - 1]);
await gotoFlow(subflows[choice - 1]);
.addAction(async (_ctx, { flowDynamic }) => {
try {
const weAreOnCall = await BotFlowsDAO.findOnCallFlow();
// @ts-ignore
const mainMenu = weAreOnCall ? onCallFlow.menus[0] : regularFlow.menus[0];
await flowDynamic(mainMenu.join("\n"));
} catch (error) {
console.error("Failed to fetch or process main menu:", error);
throw new CustomError({ code: "flow_error", description: "Failed to process main menu" });
}
})
.addAction(
{ capture: true },
async (ctx, { gotoFlow, fallBack, state }) => {
const weAreOnCall = await BotFlowsDAO.findOnCallFlow();
// @ts-ignore
const menus = (
weAreOnCall ? onCallFlow.menus : regularFlow.menus
) as string[][];
const mainMenuOptions = menus[0].filter((option) =>
/\*\d+/.test(option),
);
const subflows = weAreOnCall ? onCallSubmenus : submenus;
const choice = Math.round(Number(ctx.body.trim()));
if (choice > 0 && choice <= mainMenuOptions.length) {
await gotoFlow(subflows[choice - 1]);
Comment on lines +5 to +28
export class BotFlowsDAO {
static async findOnCallFlow(): Promise<BotFlow | null> {
try {
return await prisma.botFlow.findFirst({
where: { on_call: true, active: true },
});
} catch (e) {
throw e;
} finally {
prisma.$disconnect();
}
}
static async setOnCall(active: boolean): Promise<void> {
try {
await prisma.botFlow.updateMany({
where: { on_call: true },
data: { active },
});
} catch (e) {
throw e;
} finally {
prisma.$disconnect();
}
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider using context management for Prisma connections to ensure cleaner and safer handling of database connections.

- prisma.$disconnect(); + // Use Prisma middleware or context techniques for connection management

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
export class BotFlowsDAO {
static async findOnCallFlow(): Promise<BotFlow | null> {
try {
return await prisma.botFlow.findFirst({
where: { on_call: true, active: true },
});
} catch (e) {
throw e;
} finally {
prisma.$disconnect();
}
}
static async setOnCall(active: boolean): Promise<void> {
try {
await prisma.botFlow.updateMany({
where: { on_call: true },
data: { active },
});
} catch (e) {
throw e;
} finally {
prisma.$disconnect();
}
}
export class BotFlowsDAO {
static async findOnCallFlow(): Promise<BotFlow | null> {
try {
return await prisma.botFlow.findFirst({
where: { on_call: true, active: true },
});
} catch (e) {
throw e;
} finally {
// Use Prisma middleware or context techniques for connection management
}
}
static async setOnCall(active: boolean): Promise<void> {
try {
await prisma.botFlow.updateMany({
where: { on_call: true },
data: { active },
});
} catch (e) {
throw e;
} finally {
// Use Prisma middleware or context techniques for connection management
}
}
Comment on lines +15 to +16
- `seed.ts` now tries to find users on db before requesting details.
- `seed.ts` now inserts bot flows into db.
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Start sentences with an uppercase letter in the changelog for consistency and professionalism.

- `seed.ts` now tries to find users on db before requesting details. + `Seed.ts` now tries to find users on db before requesting details. - `seed.ts` now inserts bot flows into db. + `Seed.ts` now inserts bot flows into db.

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
- `seed.ts` now tries to find users on db before requesting details.
- `seed.ts` now inserts bot flows into db.
- `Seed.ts` now tries to find users on db before requesting details.
- `Seed.ts` now inserts bot flows into db.
Comment on lines +110 to +130
static async setOnCallBotFlow(req: Req, res: Res, next: NextFn) {
try {
const { active } = req.body;

await AgentServices.setOnCallBotFlow(active);

res.status(OK).send();
} catch (error) {
next(error);
}
}

static async getOnCallStatus(_req: Req, res: Res, next: NextFn) {
try {
const onCall: boolean = await AgentServices.getOnCallStatus();

res.status(OK).json(apiResponse(onCall));
} catch (error) {
next(error);
}
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add API documentation comments to the new methods for better clarity and maintainability.

+ /** + * Sets the on-call bot flow based on the active status. + * @param req The request object. + * @param res The response object. + * @param next The next middleware function. + */ + /** + * Retrieves the current on-call status. + * @param req The request object. + * @param res The response object. + * @param next The next middleware function. + */

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
static async setOnCallBotFlow(req: Req, res: Res, next: NextFn) {
try {
const { active } = req.body;
await AgentServices.setOnCallBotFlow(active);
res.status(OK).send();
} catch (error) {
next(error);
}
}
static async getOnCallStatus(_req: Req, res: Res, next: NextFn) {
try {
const onCall: boolean = await AgentServices.getOnCallStatus();
res.status(OK).json(apiResponse(onCall));
} catch (error) {
next(error);
}
}
/**
* Sets the on-call bot flow based on the active status.
* @param req The request object.
* @param res The response object.
* @param next The next middleware function.
*/
static async setOnCallBotFlow(req: Req, res: Res, next: NextFn) {
try {
const { active } = req.body;
await AgentServices.setOnCallBotFlow(active);
res.status(OK).send();
} catch (error) {
next(error);
}
}
/**
* Retrieves the current on-call status.
* @param req The request object.
* @param res The response object.
* @param next The next middleware function.
*/
static async getOnCallStatus(_req: Req, res: Res, next: NextFn) {
try {
const onCall: boolean = await AgentServices.getOnCallStatus();
res.status(OK).json(apiResponse(onCall));
} catch (error) {
next(error);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

3 participants