Skip to content

Conversation

@alvarezrrj
Copy link

@alvarezrrj alvarezrrj commented Mar 6, 2024

Description

Mejorado el flujo de carga de fichas para soportar el caso en el que el agente no tenga saldo suficiente.

Summary by CodeRabbit

  • New Features

    • Introduced a WhatsApp bot for enhanced user interaction in production.
    • Added web push notifications for real-time alerts.
    • Enhanced player, bank account, and transaction management capabilities.
    • Implemented authentication and authorization mechanisms for agents and users.
    • Added environment-specific configurations for improved security and customization.
  • Bug Fixes

    • Adjusted database schema to accommodate changes in bank account management and user properties.
  • Documentation

    • Updated project name and API documentation to reflect current functionalities.
  • Refactor

    • Improved modularization of routes for better maintainability.
    • Enhanced error handling for more descriptive feedback.
  • Chores

    • Updated .gitignore and .env.example files to align with current project needs.
    • Included new data models and migrations for evolving database requirements.
Alpha Dev and others added 30 commits February 19, 2024 15:25
Instantiate objects globally only when necessary, Move all http requests into httpService, Delete console.logs
Transcribir PlayersController.create
Validate index params, Move authorization logic into DAO
alvarezrrj and others added 27 commits February 26, 2024 09:57
…ransferResponse, Return deposit object from TransactionsController.deposit(), Avoid double payment verifications with dirty flag, Delay response in verifyPayment(), Merge /deposit and /deposit/:id/conifirm endpoints
Refactor FinanceServices deposit() and confirmDeposit()
Replace sender_balance and recipient_balance with player_balance on T…
Add JWT-based authentication with refresh token rotation
GET /players/id, Deposit, Cashout
Add endpoints to complete pending coin transfers
@coderabbitai
Copy link

coderabbitai bot commented Mar 6, 2024

Walkthrough

The project underwent significant updates, transitioning from "TEN stack" to "Timba Api" with enhancements across the board. Modifications include the introduction of new environment variables, updates to database schema through Prisma migrations, and expanded functionality in various components like authentication, bank accounts, and web push notifications. The codebase improvements also encompass error handling, agent operations, and a WhatsApp bot integration, aiming to refine the API's robustness and feature set.

Changes

File(s) Change Summary
.env.example, src/config/index.ts Added new environment variables for diverse functionalities including database, encryption, web push, and AWS.
.gitignore Updated to ignore .env.development, .env.production, mysql-data, and test.txt.
README.md Project renamed and API documentation updated.
ecosystem.config.js, prisma/..., seed.sql Database schema updates and app configuration adjustments.
src/.../controller.ts, src/.../services.ts, src/.../validators.ts, src/.../index.ts Enhanced functionality for agents, authentication, bank accounts, players, transactions, and web push notifications.
src/helpers/..., src/middlewares/..., src/routes/... Improved error handling, added middleware for role checking, and restructured routing for better modularity.
src/server.ts, src/index.ts Integrated WhatsApp bot and adjusted server startup processes.
src/utils/... Added cryptographic utilities and modified parsers for data handling.

🐇✨
In the land of code and wire,
Changes swift as rabbits aspire.
From TEN to Timba, we hop and leap,
Enhancing secrets we must keep.
With every push, and pull, and commit,
A better world we aim to knit.
🌟🐾

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-tests 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 tests 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 tests.
    • @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.
  • The JSON schema for the configuration file is available here.
  • 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/coderabbit-overrides.v2.json

CodeRabbit Discord Community

Join our Discord Community to get help, request features, and share feedback.

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.

Review Status

Actionable comments generated: 59

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between b5ec7a9 and 3c052bc.
Files ignored due to path filters (6)
  • bot.qr.png is excluded by: !**/*.png
  • docker-compose.yml is excluded by: !**/*.yml
  • package-lock.json is excluded by: !**/*.json
  • package.json is excluded by: !**/*.json
  • prisma/migrations/migration_lock.toml is excluded by: !**/*.toml
  • yarn.lock is excluded by: !**/*.lock
Files selected for processing (94)
  • .env.example (2 hunks)
  • .gitignore (2 hunks)
  • .vscode/settings.json (1 hunks)
  • README.md (2 hunks)
  • ecosystem.config.js (2 hunks)
  • prisma/migrations/20240220155527_initial_migration/migration.sql (1 hunks)
  • prisma/migrations/20240222132000_drop_bank_accounts/migration.sql (1 hunks)
  • prisma/migrations/20240222133838_drop_bank_account_indexes/migration.sql (1 hunks)
  • prisma/migrations/20240222133915_add_bank_accounts/migration.sql (1 hunks)
  • prisma/migrations/20240222140003_add_player_and_owner_to_bank_account/migration.sql (1 hunks)
  • prisma/migrations/20240222140931_make_bank_alias_nullable/migration.sql (1 hunks)
  • prisma/migrations/20240222203552_replace_panel_id_foreign_key_with_id/migration.sql (1 hunks)
  • prisma/migrations/20240223113516_make_user_root_id_int/migration.sql (1 hunks)
  • prisma/migrations/20240223184220_add_currency_to_deposits/migration.sql (1 hunks)
  • prisma/migrations/20240223185921_add_currency_to_payments/migration.sql (1 hunks)
  • prisma/migrations/20240226180926_add_dirty_flag_to_deposits/migration.sql (1 hunks)
  • prisma/migrations/20240227170435_add_bank_account_to_user_root/migration.sql (1 hunks)
  • prisma/migrations/20240228123536_add_tokens_table/migration.sql (1 hunks)
  • prisma/migrations/20240304132411_add_coins_transfered_to_deposits/migration.sql (1 hunks)
  • prisma/migrations/20240304210104_create_web_push_subscriptions_table/migration.sql (1 hunks)
  • prisma/migrations/20240304214515_stretch_endpoint_and_add_exp_time_to_push_subscriptions/migration.sql (1 hunks)
  • prisma/migrations/20240305132627_add_timestamps_to_token_and_pushsub/migration.sql (1 hunks)
  • prisma/schema.prisma (1 hunks)
  • seed.sql (1 hunks)
  • src/app.ts (2 hunks)
  • src/components/agent/controller.ts (1 hunks)
  • src/components/agent/index.ts (1 hunks)
  • src/components/agent/services.ts (1 hunks)
  • src/components/agent/validators.ts (1 hunks)
  • src/components/auth/controller.ts (1 hunks)
  • src/components/auth/services.ts (1 hunks)
  • src/components/bank-accounts/controller.ts (1 hunks)
  • src/components/bank-accounts/index.ts (1 hunks)
  • src/components/bank-accounts/services.ts (1 hunks)
  • src/components/bank-accounts/validators.ts (1 hunks)
  • src/components/players/controller.ts (1 hunks)
  • src/components/players/index.ts (1 hunks)
  • src/components/players/services.ts (1 hunks)
  • src/components/players/validators.ts (1 hunks)
  • src/components/transactions/controller.ts (1 hunks)
  • src/components/transactions/index.ts (1 hunks)
  • src/components/transactions/services.ts (1 hunks)
  • src/components/transactions/validators.ts (1 hunks)
  • src/components/web-push/controller.ts (1 hunks)
  • src/components/web-push/services.ts (1 hunks)
  • src/components/web-push/validators.ts (1 hunks)
  • src/config/index.ts (3 hunks)
  • src/db/agent.ts (1 hunks)
  • src/db/bank-accounts.ts (1 hunks)
  • src/db/deposits.ts (1 hunks)
  • src/db/payments.ts (1 hunks)
  • src/db/players.ts (1 hunks)
  • src/db/token.ts (1 hunks)
  • src/db/transactions.ts (1 hunks)
  • src/db/user-root.ts (1 hunks)
  • src/db/web-push.ts (1 hunks)
  • src/helpers/apiResponse.ts (1 hunks)
  • src/helpers/loggers.ts (3 hunks)
  • src/helpers/notification.ts (1 hunks)
  • src/index.ts (1 hunks)
  • src/middlewares/auth.ts (1 hunks)
  • src/middlewares/errorHandler.ts (2 hunks)
  • src/middlewares/requestErrorHandler.ts (1 hunks)
  • src/routes/agent.router.ts (1 hunks)
  • src/routes/auth.router.ts (1 hunks)
  • src/routes/bank-accounts.router.ts (1 hunks)
  • src/routes/home.router.ts (1 hunks)
  • src/routes/index.ts (1 hunks)
  • src/routes/players.router.ts (1 hunks)
  • src/routes/transactions.router.ts (1 hunks)
  • src/routes/web-push.ts (1 hunks)
  • src/server.ts (2 hunks)
  • src/services/http.service.ts (1 hunks)
  • src/services/jwt.service.ts (1 hunks)
  • src/services/token.service.ts (1 hunks)
  • src/types/bot/bot-whatsapp-database-baileys.d.ts (1 hunks)
  • src/types/bot/bot-whatsapp-provider-mock.d.ts (1 hunks)
  • src/types/bot/bot-whatsapp.d.ts (1 hunks)
  • src/types/global.d.ts (2 hunks)
  • src/types/request/bank-account.ts (1 hunks)
  • src/types/request/players.ts (1 hunks)
  • src/types/request/token.ts (1 hunks)
  • src/types/request/transfers.ts (1 hunks)
  • src/types/request/user-root.ts (1 hunks)
  • src/types/request/web-push.ts (1 hunks)
  • src/types/response/agent.ts (1 hunks)
  • src/types/response/bankAccount.ts (1 hunks)
  • src/types/response/jwt.ts (1 hunks)
  • src/types/response/players.ts (1 hunks)
  • src/types/response/transactions.ts (1 hunks)
  • src/types/response/transfers.ts (1 hunks)
  • src/utils/auth.ts (1 hunks)
  • src/utils/crypt.ts (2 hunks)
  • src/utils/parser.ts (1 hunks)
Files not reviewed due to errors (6)
  • (no review received)
  • (no review received)
  • (no review received)
  • (no review received)
  • (no review received)
  • (no review received)
Files skipped from review due to trivial changes (7)
  • src/components/agent/index.ts
  • src/components/bank-accounts/index.ts
  • src/components/players/index.ts
  • src/components/transactions/index.ts
  • src/types/bot/bot-whatsapp-provider-mock.d.ts
  • src/types/request/token.ts
  • src/types/response/transactions.ts
Additional comments: 104
src/types/bot/bot-whatsapp-database-baileys.d.ts (1)
  • 1-1: Declaring the module @bot-whatsapp/provider/baileys is a good practice for ensuring type safety and enhancing developer experience with IntelliSense. Ensure that these type definitions are kept up-to-date with the actual implementation of the package.
prisma/migrations/20240226180926_add_dirty_flag_to_deposits/migration.sql (1)
  • 1-2: Adding a dirty BOOLEAN column to the DEPOSITS table with a default value of true is a good practice for tracking records that require further processing or verification. Ensure that the default value aligns with the intended workflow, where new deposit records are considered "dirty" until processed.
prisma/migrations/20240223184220_add_currency_to_deposits/migration.sql (1)
  • 1-2: Adding a currency column to the DEPOSITS table with a default value of 'MXN' is a crucial update for handling financial transactions in multiple currencies. Ensure that the default currency aligns with the primary currency of the application's user base or the most common transaction currency.
prisma/migrations/20240223185921_add_currency_to_payments/migration.sql (1)
  • 1-2: Adding a currency column to the PAYMENTS table with a default value of 'MXN' mirrors the update made to the DEPOSITS table, ensuring consistency in handling financial transactions across the application. This consistency is crucial for a coherent financial management system.
src/types/response/transfers.ts (1)
  • 1-5: The TransferResult type is well-structured for representing the outcomes of transfer operations, including success, incomplete status, and potential errors. Ensure that error handling is comprehensive and consider documenting possible values for the error field to aid in debugging and consumer understanding.
prisma/migrations/20240304214515_stretch_endpoint_and_add_exp_time_to_push_subscriptions/migration.sql (1)
  • 1-3: Modifying the WEB_PUSH_SUBSCRIPTIONS table to add an expirationTime column and extend the endpoint column size to VARCHAR(512) are sensible updates for managing the lifecycle of web push subscriptions and accommodating longer endpoint URLs. Ensure that the application logic properly handles the expiration of subscriptions.
src/routes/auth.router.ts (1)
  • 1-8: Setting up the authentication router with a POST route for token refreshing is a good practice for maintaining secure user sessions. Ensure that the token refresh mechanism is secure, well-documented, and tested to prevent potential security vulnerabilities.
src/middlewares/requestErrorHandler.ts (1)
  • 1-8: The throwIfBadRequest middleware function is correctly implemented for handling request validation errors. However, the parameters Req, Res, and NextFn are used without being explicitly imported or defined. Ensure that these types are correctly imported from Express or defined elsewhere in the codebase to avoid potential type errors.
Verification successful

The verification process has confirmed that the types Req, Res, and NextFn are indeed defined in the codebase within src/types/global.d.ts, where they are aliased to Request, Response, and NextFunction from the express package, respectively. This directly addresses the concern raised in the review comment about ensuring these types are correctly imported or defined to avoid potential type errors. Therefore, the original comment's concern has been addressed by the presence of these type definitions.

Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash # Verify if Req, Res, and NextFn types are defined or imported rg --type ts "import .* from 'express'" 

Length of output: 47



Script:

#!/bin/bash # Broaden the search for Req, Res, and NextFn types across the codebase rg --type ts "type Req |type Res |type NextFn" 

Length of output: 189


Script:

#!/bin/bash # Additionally, search for any import or export statements that might include these types rg --type ts "import .*\(Req|Res|NextFn\).*" 

Length of output: 11744

prisma/migrations/20240228123536_add_tokens_table/migration.sql (1)
  • 1-12: The migration script correctly creates the TOKENS table with appropriate fields and establishes a foreign key relationship with the PLAYERS table. Ensure that the player_id column in the PLAYERS table is of type INTEGER and that there are appropriate indexes on the player_id column for performance optimization, especially if the PLAYERS table is expected to grow significantly.
prisma/migrations/20240223113516_make_user_root_id_int/migration.sql (1)
  • 1-11: The migration script for altering the USERS_ROOT table's primary key from VarChar(191) to INTEGER and setting it to auto-increment is correctly implemented. However, the warnings about potential data loss and the removal of the primary key constraint during the operation are significant. Ensure that this migration is thoroughly tested in a staging environment and that there's a backup of the USERS_ROOT table before applying this change in production.
prisma/migrations/20240222132000_drop_bank_accounts/migration.sql (1)
  • 1-17: The migration script for dropping the BANK_ACCOUNTS table and its related foreign keys is correctly structured. Dropping a table is a significant operation, especially if it contains data. Ensure that the decision to remove the BANK_ACCOUNTS table is well-justified and that any necessary data migrations or backups have been performed prior to executing this script.
src/types/request/user-root.ts (1)
  • 1-22: The interfaces RootUpdatableProps and RootRequest are well-defined, covering various properties that can be updated or required in a request. However, it's important to ensure that sensitive information such as password is handled securely throughout the application, especially when updating or transmitting such data. Consider implementing additional security measures, such as hashing passwords before storing them in the database.
src/components/auth/controller.ts (1)
  • 6-17: The refresh method in the AuthController class is correctly implemented to handle token refreshing. It uses the AuthService to refresh the token and sends the response using the apiResponse helper function. Ensure that error handling is robust, especially for cases where the token might be invalid or expired. The current implementation correctly forwards errors to the next middleware, which is good practice.
prisma/migrations/20240222133838_drop_bank_account_indexes/migration.sql (1)
  • 1-18: The migration script for dropping indexes and columns related to bank accounts in the DEPOSITS and PAYMENTS tables is correctly structured. This change appears to be part of a larger restructuring of how financial transactions are handled in the application. Ensure that the removal of these columns and indexes does not adversely affect the application's functionality or data integrity. It's also important to verify that any necessary data migrations have been performed prior to executing this script.
src/types/global.d.ts (1)
  • 12-25: > 📝 NOTE

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

The changes to global type definitions, including the introduction of AuthedReq and the extension of the Express.User interface, are well-implemented and align with the objectives of enhancing authentication and user management within the application.

prisma/migrations/20240305132627_add_timestamps_to_token_and_pushsub/migration.sql (1)
  • 8-14: The addition of created_at and updated_at columns to the TOKENS and WEB_PUSH_SUBSCRIPTIONS tables is correctly implemented, with appropriate default values for created_at. Ensure that the application logic appropriately manages the updated_at column to reflect the last modification time accurately.
src/routes/index.ts (1)
  • 2-20: The refactoring of the main router to use separate routers for different endpoints is a significant improvement, enhancing modularity and organization within the application's routing system.
prisma/migrations/20240222203552_replace_panel_id_foreign_key_with_id/migration.sql (1)
  • 1-20: The migration script correctly handles the replacement of foreign key constraints and the management of indexes for BANK_ACCOUNTS, DEPOSITS, and PAYMENTS tables. These changes are necessary for maintaining referential integrity and align with the database schema evolution.
.vscode/settings.json (1)
  • 2-22: The adjustments to VSCode settings, including sticky scroll and color customizations for various UI elements, are correctly implemented and enhance the visual aspects of the development environment. These changes are subjective and do not impact the application's functionality or code quality.
src/routes/web-push.ts (4)
  • 14-16: Ensure that the JWT authentication middleware is correctly configured for your application's security requirements. The session: false and failWithError: true options are typically used for stateless API authentication, which is appropriate for most REST APIs.
  • 17-17: The use of requireAgentRole middleware after JWT authentication ensures that only users with the agent role can access the web push routes. This is a good practice for role-based access control (RBAC).
  • 19-25: The POST route for /subscription correctly chains middleware for validation (validatePushSubscriptionRequest()), exact check (checkExact()), error handling (throwIfBadRequest), and finally calls the controller method (WebPushController.create). This is a well-structured approach to handling requests and validating input data.
  • 26-26: The DELETE route for subscriptions does not specify a resource identifier in the URL, which means it operates on a collection rather than a specific resource. Ensure that the implementation of WebPushController.delete and validateDeleteRequest() correctly handles this scenario, possibly by using request body or query parameters to identify the subscription to delete.
src/components/agent/validators.ts (1)
  • 28-47: The validateBankAccountUpdate middleware uses a well-structured approach to define optional string validation rules for various bank account fields. This approach promotes code reuse and readability. Ensure that all fields that can be updated are included and correctly validated.
ecosystem.config.js (2)
  • 4-4: Changing the application name to timba-api in the PM2 configuration aligns with the project's rebranding efforts. This is a straightforward change that helps maintain consistency across the project.
  • 22-22: Dynamically setting the port using process.env.PORT in the env_production configuration is a best practice for cloud deployments, as it allows the port to be configured through the environment rather than being hardcoded. This change enhances the flexibility and portability of the application deployment.
src/routes/transactions.router.ts (3)
  • 11-13: The use of JWT authentication middleware with session: false and failWithError: true options is correctly applied for stateless API authentication. This ensures that only authenticated users can access the transaction routes.
  • 14-14: Applying requireUserRole middleware after JWT authentication ensures that only users with specific roles can access the transaction routes. This is a good practice for implementing role-based access control (RBAC) in the application.
  • 15-21: The POST route for /deposit/:id? correctly chains middleware for validation (validateTransferRequest()), exact check (checkExact()), error handling (throwIfBadRequest), and finally calls the controller method (TransactionsController.deposit). This structured approach is commendable for handling requests and validating input data.
src/routes/players.router.ts (3)
  • 14-21: The POST route for creating players correctly chains middleware for validation (validatePlayerRequest()), exact check (checkExact()), error handling (throwIfBadRequest), and finally calls the controller method (PlayersController.create). This is a well-structured approach to handling requests and validating input data.
  • 23-29: The POST route for player login correctly uses validateCredentials() middleware for input validation, followed by checkExact(), throwIfBadRequest, and the controller method (PlayersController.login). This ensures that login requests are properly validated and handled.
  • 30-32: The use of JWT authentication middleware for routes that require user authentication is correctly configured. This ensures that only authenticated players can access certain player routes.
src/components/web-push/controller.ts (1)
  • 6-44: The WebPushController class methods (index, create, delete) are well-implemented, with clear separation of concerns and appropriate error handling. Each method uses a try-catch block to handle exceptions and passes them to the next middleware for centralized error handling. This is a good practice for maintaining clean and maintainable code.
src/app.ts (4)
  • 6-6: The import of passport is correctly added to support authentication strategies.
  • 9-9: The import and instantiation of AuthService are correctly added to set up authentication services.
  • 16-18: The CORS setup based on the environment is a good practice for security, ensuring that only allowed origins can access the API in production.
  • 45-46: The setup of the passport strategy using AuthService is correctly implemented. Ensure that the jwtStrategy method in AuthService is properly defined and returns a valid passport strategy.
Verification successful


The AuthService class and its jwtStrategy method have been successfully located within the codebase, specifically in src/components/auth/services.ts. The method jwtStrategy is implemented to configure and return a new instance of passport-jwt.Strategy, which is a valid passport strategy. This confirms that the setup of the passport strategy using AuthService is correctly implemented, as the jwtStrategy method is properly defined and returns a valid passport strategy.

Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash # Search for the jwtStrategy method definition in AuthService to ensure it returns a valid passport strategy. ast-grep --lang javascript --pattern $'class AuthService {  $$$  jwtStrategy($_) {  $$$  }  $$$  }' 

Length of output: 108



Script:

#!/bin/bash # Search for the AuthService class definition to verify its existence and list its methods. ast-grep --lang javascript --pattern $'class AuthService {  $$$ }' 

Length of output: 68



Script:

#!/bin/bash # Use ripgrep to search for references to AuthService across all JavaScript or TypeScript files. rg "AuthService" --type js rg "AuthService" --type ts 

Length of output: 726



Script:

#!/bin/bash # Extract the jwtStrategy method's implementation from AuthService in src/components/auth/services.ts rg "jwtStrategy" src/components/auth/services.ts 

Length of output: 378

src/components/transactions/validators.ts (3)
  • 3-3: The emptyBody custom validator correctly checks if the request body is empty. This is a useful validation for ensuring that requests contain necessary data.
  • 6-35: The validateTransferRequest function correctly sets up validation rules for transfer requests. It ensures that the id is provided in the URL parameters only if the body is empty, and validates amount, currency, and bank_account fields in the body. The use of custom validators and error messages enhances the clarity and robustness of request validation.
  • 38-44: The validateDepositId function correctly sets up validation for the id parameter in deposit-related requests. It ensures that the id is an integer and not empty, which is crucial for identifying specific deposits.
.env.example (1)
  • 15-31: > 📝 NOTE

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

The addition of new environment variables for database connection details, encryption settings, web push keys, AWS credentials, Cognito client ID, 3rd-party API keys, and agent-related information is comprehensive and well-organized. Ensure that sensitive information such as passwords, keys, and credentials are never hardcoded in the codebase and are always securely managed through environment variables or secure secrets management tools.

src/routes/bank-accounts.router.ts (2)
  • 15-18: The use of passport.authenticate middleware for JWT authentication on all bank account routes is correctly implemented, ensuring that these routes are protected and accessible only by authenticated users.
  • 19-45: The setup of CRUD operations for bank accounts with appropriate validation and error handling middleware is well-structured and follows best practices for REST API design. The use of validateBankAccount, validateAccountUpdate, and validateBankAccountIndex validators along with checkExact and throwIfBadRequest middleware ensures robust input validation and error handling.
src/server.ts (2)
  • 3-5: The imports for the WhatsApp bot functionality (BotWhatsapp, MockAdapter, and ProviderWS) are correctly added. Ensure that these modules are properly installed and configured in the project.
  • 30-42: The startWhatsappBot function correctly sets up and starts the WhatsApp bot with a mock database adapter, a provider, and a predefined flow. Ensure that the bot's functionality is thoroughly tested, especially the integration with the ProviderWS and the handling of keywords and responses.
src/routes/agent.router.ts (1)
  • 15-43: The setup of agent-related routes with appropriate validation and error handling middleware is well-structured. The use of passport.authenticate and requireAgentRole middleware ensures that these routes are protected and accessible only by agents with the correct role. The validators such as validateCredentials and validateBankAccountUpdate are correctly applied to relevant routes, enhancing the robustness of request validation.
src/components/web-push/services.ts (1)
  • 8-53: The WebPushServices class methods for managing web push subscriptions and sending notifications are correctly implemented. The use of WebPushDAO for database operations and the web-push library for sending notifications is appropriate. Ensure that the VAPID details (publicKey, privateKey, and subject) are correctly configured in the environment and that the parseSubscription utility function accurately processes subscription data.
.gitignore (3)
  • 74-75: Adding .env.development and .env.production to the .gitignore file is a good practice to ensure that environment-specific configurations, which might contain sensitive information, are not accidentally committed to the version control system.
  • 112-112: Including mysql-data in the .gitignore file is appropriate if you're using a local MySQL database for development purposes. This prevents the database files from being tracked by Git, which is important for security and to avoid unnecessary clutter in your repository.
  • 114-114: Adding test.txt to the .gitignore file seems to be a specific case. If this file is used for temporary testing or contains sensitive information, ignoring it is justified. However, if test.txt was added by mistake or is not relevant to the project, consider removing this entry to avoid confusion.
src/db/bank-accounts.ts (1)
  • 82-91: The authorization methods (authorizeUpdate, authorizeDelete, and authorizeView) do not explicitly disconnect the Prisma client, which is consistent with the recommended practice of managing connections at a higher level or leveraging Prisma's connection pooling. However, ensure that the overall connection management strategy is optimized to avoid performance issues.
src/utils/crypt.ts (4)
  • 18-23: The hash function has been modified to use SHA256 hashing instead of bcrypt. Ensure that this change aligns with the application's security requirements and that all places using the hash function are updated accordingly to handle the new hash format.
  • 44-68: The encrypt function introduces AES192 encryption. Verify that the encryption key length and algorithm meet the application's security requirements. Additionally, ensure that the initialization vector (IV) is securely generated and that the serialized IV and ciphertext are handled securely.
  • 75-88: The decrypt function is responsible for decrypting data encrypted with AES192. Ensure that the decryption process securely handles the initialization vector and ciphertext, and that the decrypted data is properly sanitized before use in the application.
  • 90-106: The getConfig function generates the encryption key for AES192 encryption. Verify that the password used for key generation is securely stored and that the scryptSync function's parameters (e.g., salt) are appropriately configured for security.
src/components/agent/controller.ts (7)
  • 10-20: The login method correctly handles the login process and returns a token. Ensure that error handling is comprehensive and that sensitive information is not leaked in error messages or logs.
  • 22-30: The showPayments method retrieves and returns payment information. Verify that the data returned does not include sensitive information and that access control checks are in place to ensure that agents can only access their own payment information.
  • 32-42: The markAsPaid method updates the payment status. Ensure that proper validation and access control checks are performed to prevent unauthorized updates to payment statuses.
  • 44-52: The showDeposits method retrieves and returns deposit information. Similar to showPayments, verify that sensitive information is not included in the response and that access control is enforced.
  • 54-64: The qr method serves a QR code image from the filesystem. Ensure that the file path is securely handled to prevent directory traversal attacks and that access to the QR code is appropriately restricted.
  • 66-76: The getBankAccount and updateBankAccount methods manage bank account information. Verify that these methods include robust validation and access control to prevent unauthorized access or modifications to bank account data.
  • 88-96: The getBalance and completePendingDeposits methods handle sensitive financial operations. Ensure that these methods implement strict access control and validation to safeguard against unauthorized access and manipulation.
src/services/http.service.ts (6)
  • 13-21: The agentAxiosInstance getter creates a new axios instance with authorization headers. Ensure that the token is securely handled and that the instance is reused when possible to avoid unnecessary overhead.
  • 26-32: The authedAgentApi property exposes methods for authenticated requests. Verify that these methods are used appropriately and that sensitive operations are protected by adequate security checks.
  • 38-43: The plainAgentApi getter creates an axios instance for non-authenticated requests. Ensure that this instance is used only for operations that do not require authentication and that security implications are considered.
  • 48-53: The playerApi getter creates an axios instance for player requests. Verify that this instance is used in a secure manner and that player-related operations enforce proper authentication and authorization.
  • 71-91: The send method handles the actual sending of requests and includes logic for token expiration handling. Ensure that the token refresh logic is secure and that retries are managed appropriately to prevent potential denial-of-service scenarios.
  • 93-106: The handleTokenExpiration method attempts to refresh the token upon expiration. Verify that the token refresh process is secure and that it properly invalidates the old token to prevent reuse.
src/components/auth/services.ts (4)
  • 12-22: The cypherPass getter ensures that the encryption password is present in the environment variables. Verify that the environment variable is securely managed and that error handling is appropriate for missing configuration.
  • 29-35: The tokens method generates access and refresh token pairs. Ensure that the token generation process is secure and that tokens are properly linked to database objects for tracking and invalidation.
  • 40-63: The refresh method handles token refresh operations. Verify that the refresh token validation is secure, that tokens are properly invalidated upon use, and that potential token reuse is mitigated.
  • 69-94: The jwtStrategy method configures the JWT strategy for passport authentication. Ensure that the strategy properly validates tokens, checks for token invalidation, and securely deserializes user information.
src/types/bot/bot-whatsapp.d.ts (1)
  • 1-134: The type definitions for the WhatsApp bot module appear to be comprehensive and correctly defined. Ensure that these types accurately represent the bot's functionality and that they are used consistently throughout the application to facilitate type safety and code readability.
src/components/players/services.ts (3)
  • 24-29: The getPlayerById method retrieves player information by ID and uses hidePassword to remove sensitive information. Verify that this method correctly handles non-existent players and that access control is enforced.
  • 34-70: The create method handles player creation, including interactions with external services. Ensure that the player creation process is secure, that input validation is performed, and that error handling is comprehensive to prevent information leakage or unintended behavior.
  • 75-100: The login method manages player login, including validation against local and external databases. Verify that password comparison is secure, that external API interactions are handled securely, and that tokens are generated and returned in a secure manner.
src/components/agent/services.ts (9)
  • 18-27: The method username retrieves the encrypted username from the environment variables, decrypts it, and returns the decrypted username. It throws a CustomError if the username is not found in the environment variables.

This is a secure way to handle sensitive information. However, ensure that the decryption key is securely managed and not exposed in the code or version control.

  • 30-45: The login method performs authentication by comparing the provided credentials with the expected ones. It uses hashing for password comparison and throws a CustomError if the credentials are invalid.

The use of hashing for password comparison is a good security practice. However, consider implementing rate limiting or account lockout mechanisms to prevent brute-force attacks.

  • 48-50: The showPayments method retrieves all payments from the database.

This method is straightforward and correctly retrieves the payments. Ensure that appropriate permissions checks are in place to prevent unauthorized access to payment information.

  • 56-60: The markAsPaid method updates a payment's status to paid by setting the paid field to the current date and time.

Correctly marks a payment as paid. Ensure that this operation is idempotent to prevent any unintended consequences if called multiple times for the same payment.

  • 63-65: The showDeposits method retrieves all deposits from the database.

This method is straightforward and correctly retrieves the deposits. Similar to the showPayments method, ensure that appropriate permissions checks are in place.

  • 68-70: The getBankAccount method retrieves the bank account information for the agent.

Correctly retrieves the bank account information. Ensure that sensitive information such as account numbers is handled securely.

  • 73-80: The updateBankAccount method updates the bank account information for the agent.

Correctly updates the bank account information. Ensure that validation checks are in place to prevent invalid data from being saved.

  • 83-96: The getBalance method retrieves the balance information for the agent by making an authenticated API call.

Correctly retrieves balance information. Ensure that error handling is robust and that the external API's availability and response times are considered to prevent service degradation.

  • 99-115: The completePendingDeposits method processes pending deposits by transferring coins and marking the transfer date.

This method correctly processes pending deposits. However, consider adding transactional integrity checks to ensure that all steps of the process complete successfully or are rolled back in case of failure.

src/db/deposits.ts (9)
  • 15-22: The create method creates a new deposit entry in the database and includes the associated player in the response.

Correctly creates a deposit entry. Ensure that input validation is performed to prevent invalid data from being inserted into the database.

  • 25-35: The index method retrieves all deposits or only unconfirmed deposits based on the all parameter.

This method provides flexibility in retrieving deposits. Ensure that appropriate permissions checks are in place to prevent unauthorized access to deposit information.

  • 43-52: The getById method retrieves a specific deposit by its ID.

Correctly retrieves a deposit by ID. Ensure that appropriate permissions checks are in place to prevent unauthorized access to deposit information.

  • 56-63: The getPending method retrieves all pending deposits for a specific player.

Correctly retrieves pending deposits for a player. Ensure that appropriate permissions checks are in place to prevent unauthorized access to deposit information.

  • 66-75: The getPendingCoinTransfers method retrieves all deposits with pending coin transfers.

Correctly retrieves deposits with pending coin transfers. Ensure that appropriate permissions checks are in place to prevent unauthorized access to deposit information.

  • 79-85: The update method updates a deposit's information based on the provided data.

Correctly updates a deposit's information. Ensure that input validation is performed to prevent invalid data from being updated in the database.

  • 89-95: The delete method deletes a deposit by its ID.

Correctly deletes a deposit by ID. Ensure that appropriate permissions checks are in place to prevent unauthorized deletion of deposit information.

  • 103-115: The authorizeTransaction method ensures a deposit exists and belongs to a specific player.

Correctly authorizes a transaction. Ensure that this method is used consistently to prevent unauthorized access or manipulation of deposit information.

  • 128-147: The authorizeConfirmation method ensures a deposit exists, belongs to a specific player, is not already confirmed, and is not being confirmed.

Correctly authorizes a confirmation. Ensure that this method is used consistently to prevent unauthorized access or manipulation of deposit information.

prisma/migrations/20240220155527_initial_migration/migration.sql (1)
  • 95-107: When adding foreign keys, it's important to consider the ON DELETE and ON UPDATE actions. The current setup uses RESTRICT for ON DELETE, which is generally safe. However, ensure that this behavior aligns with the application's data management strategy, especially for entities like PAYMENTS and DEPOSITS that are closely related to PLAYERS and BANK_ACCOUNTS.

Consider if CASCADE or SET NULL might be more appropriate for your use case, depending on how you want to handle deletions of related entities.

prisma/schema.prisma (1)
  • 97-112: The Deposit model includes a dirty field with a default value of true. This design choice should be carefully considered, as it implies new deposits are initially marked as "dirty" by default. Ensure this aligns with the intended business logic and handling of deposit records.

Confirm the business logic behind the default true value for the dirty field in the Deposit model.

src/services/token.service.ts (1)
  • 127-140: The login method sets the agent's dirty flag to true before attempting login and resets it to false afterward. Ensure that this flag is correctly managed in all scenarios, including when exceptions occur, to avoid leaving the agent in an incorrect state.

Verify that the dirty flag is correctly managed in all scenarios to avoid leaving the agent in an incorrect state.

src/middlewares/errorHandler.ts (1)
  • 44-50: The handling of Prisma errors in the genericErrorHandler middleware is a good practice. However, ensure that all possible Prisma error types are covered and that the error handling logic is comprehensive enough to provide meaningful feedback for all error scenarios.

Verify that the Prisma error handling covers all necessary cases and provides meaningful feedback.

seed.sql (5)
  • 2-5: The configuration settings, including disabling foreign key checks, are noted. Ensure that data integrity is maintained when using SET foreign_key_checks = 0, especially in a production environment.
  • 9-13: Insert statements for the BANK_ACCOUNTS table use fictional characters, indicating this is seed data for testing or development. Ensure the purpose of this seed data is clearly documented to avoid confusion.
  • 15-20: The DEPOSITS table insert statements include a mix of NULL and non-NULL confirmed column values, indicating a design where deposits can be pending confirmation. This pattern is appropriate for financial applications.
  • 22-29: The PAYMENTS table insert statements also include a mix of NULL and non-NULL paid column values, indicating a consistent design choice with the DEPOSITS table where transactions can be pending.
  • 31-42: The insert statements for the PLAYERS and TRANSACTIONS tables demonstrate good security practices with hashed passwords and a system capable of tracking transaction states. This is essential for financial applications.
README.md (1)
  • 1-1: The project name "Timba Api" might be mistaken for a spelling error. Consider confirming the project name's spelling to ensure clarity and avoid confusion.

**TEN stack** is a `Typescript` + `Express` + `Node` starter kit to develop `REST API` server apps.
**Timba Api** is a `Typescript` + `Express` + `Node` starter kit to develop `REST API` server apps.
Nothing new under the sun, just a straight forward combo to make server development a little bit faster. And of course, this make my freelancing days more enjoyable 😎
Copy link

Choose a reason for hiding this comment

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

The phrase "just a straight forward combo" should be corrected to "just a straightforward combo" for proper grammar.
Additionally, "this make my freelancing days more enjoyable" should be corrected to "this makes my freelancing days more enjoyable" to ensure subject-verb agreement.

- just a straight forward combo to make server development a little bit faster. And of course, this make my freelancing days more enjoyable + just a straightforward combo to make server development a little bit faster. And of course, this makes my freelancing days more enjoyable

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
Nothing new under the sun, just a straight forward combo to make server development a little bit faster. And of course, this make my freelancing days more enjoyable 😎
Nothing new under the sun, just a straightforward combo to make server development a little bit faster. And of course, this makes my freelancing days more enjoyable 😎
Comment on lines +1 to 4
**Timba Api** is a `Typescript` + `Express` + `Node` starter kit to develop `REST API` server apps.
Nothing new under the sun, just a straight forward combo to make server development a little bit faster. And of course, this make my freelancing days more enjoyable 😎
Comes with:

Copy link

Choose a reason for hiding this comment

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

📝 NOTE
This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [13-13]

The word "proccess" should be corrected to "process" to fix the typo.

- Manage production app proccess with [PM2](https://pm2.keymetrics.io/) + Manage production app process with [PM2](https://pm2.keymetrics.io/)
Comment on lines +19 to +279
# Docs

## Prerequisites
## Contenidos

- [Node.js](https://nodejs.org) (`>= 16.0.0`)
- [Yarn](https://yarnpkg.com/en/docs/install) or [NPM](https://docs.npmjs.com/getting-started/installing-node)
### Endpoints Jugadores
+ [Ver Jugador](#ver-jugador)
+ [Crear Jugador](#crear-jugador)
+ [Login de Jugador](#login-jugador)

## Install
### Endpoints Cuentas Bancarias
+ [Ver Cuentas Bancarias](#ver-cuentas-bancarias)
+ [Crear Cuenta Bancaria](#crear-cuenta-bancaria)
+ [Actualizar Cuenta Bancaria](#actualizar-cuenta-bancaria)
+ [Eliminar Cuenta Bancaria](#eliminar-cuenta-bancaria)

- Fork or Use [this](https://github.com/filoscoder/tenstack-starter/generate) template repository.
- [Clone](https://github.com/git-guides/git-clone) the forked repository.
- Install the dependencies with [yarn](https://yarnpkg.com/getting-started/usage) or [npm](https://docs.npmjs.com/cli/v7/commands/npm-install).
### Endpoints Transferencias
+ [Cargar Fichas](#cargar-fichas)
+ [Retirar Premios](#retirar-premios)
+ [Ver Depósitos Pendientes](#ver-depósitos-pendientes)
+ [Confirmar Depósito Pendiente](#confirmar-depósito-pendiente)
+ [Eliminar Depósito Pendiente](#eliminar-depósito-pendiente)

> Make sure you already have [`node.js`](https://github.com/filoscoder/tenstack-starter#prerequisites) and [`npm`](https://github.com/filoscoder/tenstack-starter#prerequisites) or [`yarn`](https://github.com/filoscoder/tenstack-starter#prerequisites) installed in your system.
### [Interfaces](#interfaces)

- Set your `git remote add origin` path
### Ver Jugador

```bash
git remote add origin ${forked-and-cloned-path}
```
|Endpoint:| `/players/:id`|
---|---|
Método | `GET`
Devuelve | [`Player & { bank_accounts: BankAccount[] }`](#player)

> [Update the url](https://docs.github.com/en/get-started/getting-started-with-git/managing-remote-repositories#changing-a-remote-repositorys-url) if you already have an `origin`
### Crear Jugador

<br>
<br>
|Endpoint:| `/players`|
---|---|
Método | `POST`
Body (json) | [`PlayerRequest`](#playerrequest)
Devuelve | [`Player`](#Player)

## Config
### Login Jugador

- Copy `.env.example` a file at the root of the application.
- Add or modify specific variables and update it according to your need.
|Endpoint| `/players/login`|
---|---|
Método |`POST`
Body (json) | [`Credenciales`](#credenciales)
Devuelve | [`Player`](#player)

```bash
cp .env.example .env
```
### Ver Cuentas Bancarias

> Check the `config` folder to customize your settings (`/src/config`)

<br>
<br>
|Endpoint| `/bank-account/:id?`|
---|---|
Método |`GET`
Devuelve | [`BankAccount[]`](#bankaccount)

## Alias @
> **Nota:** Siempre devuleve un array
To make paths clean and ease to access `@` is setup up for `/src` path
> **Nota:** Omitir el parámetro `id` para ver todas las cuentas bancarias del usuario
```javascript
// BEFORE
import config from './config';
import routes from './routes';
### Crear Cuenta Bancaria

// NOW
import config from '@/config';
import routes from '@/routes';
```

> You can customize this setup:
> `/tsconfig.json` > compilerOptions.paths
> `/eslintrc.yml` > rules.settings.alias.map
|Endpoint| `/bank-account`|
---|---|
Método |`POST`
Body (json) | [`BankAccountRequest`](#bankaccountrequest)
Devuelve | [`BankAccount`](#bankaccount)

<br>
<br>
### Actualizar Cuenta Bancaria

## Local Development
|Endpoint| `/bank-account`|
---|---|
Método |`PUT`
Body (json) | [`BankAccountRequest`](#bankaccountrequest)
Devuelve | [`BankAccount`](#bankaccount)

Run the server locally. It will be run with Nodemon and ready to serve on port `8080` (unless you specify it on your `.env`)
> **Nota:** Los campos son opcionales. Incluir los que se quiera modificar
```bash
yarn start # or npm start
```
### Eliminar Cuenta Bancaria

|Endpoint| `/bank-account`|
---|---|
Método |`DELETE`
Devuelve | 200 OK

### Cargar Fichas
Incluir el id en la URL y omitir el body para confirmar un depósito pendiente
Omitir el id en la URL e incluir los datos en el body para crear un depósito nuevo

|Endpoint| `/transactions/deposit/:id?`|
---|---|
Método |`POST`
Body (json) |[`TransferRequest`](#transferrequest)
Devuelve |[`TransferResult & { deposit: Deposit }`](#transferresult)

> Check [`package.json`](https://github.com/filoscoder/tenstack-starter/blob/master/package.json) to see more "scripts"
### Retirar Premios

<br>
<br>
|Endpoint| `/transactions/cashout`|
---|---|
Método |`POST`
Body (json) |[`TransferRequest`](#transferrequest)
Devuelve |[`TransferResult`](#transferresult)

## Production
### Ver Depósitos Pendientes

First, build the application.
|Endpoint| `/transactions/deposit/pending`|
---|---|
Método |`GET`
Devuelve |[`Deposit[]`](#deposit)

```bash
yarn build # or npm run build
> **Nota:** siempre devuelve un array
### Confirmar Depósito Pendiente

|Endpoint| `/transactions/deposit/:id/confirm`|
---|---|
Método |`PUT`
Devuelve |[`TransferResult`](#transferresult)

### Eliminar Depósito Pendiente
|Endpoint| `/transactions/deposit/:id`|
---|---|
Método |`DELETE`
Devuelve | 200 OK

## Interfaces

### Player
```typescript
{
id: number;
panel_id: number;
username: string;
email?: string;
first_name?: string;
last_name?: string;
date_of_birth?: string;
movile_number?: string;
country?: string;
balance_currency: string;
status: string;
created_at: string; // 2024-01-29T18:14:41.534Z
}
```

### PlayerRequest
```typescript
{
username: string,
password: string,
email: string,
first_name?: string,
last_name?: string,
date_of_birth?: DateTime,
movile_number?: string,
country?: string
}
```

### BankAccountRequest
```typescript
{
owner: string // Nombre del beneficiario
owner_id: number // DNI
bankName: string // Nombre del banco
bankNumber: string // CBU
bankAlias: string?
}
```
Then, use [`pm2`](https://github.com/Unitech/pm2) to start the application as a service.
### BankAccount
```typescript
{
id: number
owner: string // Nombre del beneficiario
owner_id: number // DNI
player_id: number // ID de Player
bankName: string // Nombre del banco
bankNumber: string // CBU
bankAlias: string?
created_at: // 2024-01-29T18:14:41.534Z
updated_at: // 2024-01-29T18:14:41.534Z
}
```
```bash
yarn service:start # or npm run service:start
### Credenciales
```typescript
{
username: string
password: string
}
```
<br>
<br>
### TransferRequest
```typescript
{
amount: number
currency: string
bank_account: number // ID de cuenta bancaria
}
```
# Contribution
### TransferResult
```typescript
{
status: "COMPLETED" | "INCOMPLETE"
player_balance?: number // undefined en caso de deposito incompleto
error?: string // En caso de error, el motivo
deposit: Deposit
}
```
This repository will be managed as an `open-source`. <br>
Please feel free to open an `issue` or a `pull request` to suggest changes or additions.
### Deposit
```typescript
{
id: number
player_id: number
amount: number
confirmed?: datetime // 2024-02-23T12:35:51.017Z
bank_account: number
currency: string
dirty: boolean
created_at: datetime // 2024-02-23T12:35:51.017Z
updated_at: datetime // 2024-02-23T12:35:51.017Z
}
```
# Support & Contact
### RootBankAccount
```typescript
{
name: string
dni: string
bankName: string
accountNumber: string
clabe: string
alias: string
}
```
If you have any question or suggestion, don't hesitate to contact me:
## TODO
✉️ [filoscoder.io@gmail.com](mailto:filoscoder.io@gmail.com)
- Instanciar servicios en lugar de usar metodos estaticos
- Cambiar contraseña (no funciona en el casino, vamos por este lado)
- Endpoint https://agent.casinomex.vip/api/users/5941/change-password/
- Body: `{ new_password:string }`
- Recibir clave de rastreo en endpoints de cashIn y confirmarDeposito
- Hacer email opcional en player request validator
- Documentar endpoints agente
- Inhabilitar tokens anteriores al loguear un usuario (borrarlos de la bbdd, seleccionando por player_id)
- **Que pasa cuando un pago se verifica pero el agente no tiene fichas suficientes? o algo sale mal en el servidor del casino?**
+ Si el agente no tiene fichas, mandar push al panel de agente con total pendiente
+ Botón liberar fichas
+ Chequear que total pendiente sea menor a nuevo stock
+ Liberar transferencias
- Encriptar JWT
# Author & Credits
## Optimizaciones
<a src="https://github.com/filoscoder">
<img width="60px" style="border-radius: 50%;" src="https://avatars.githubusercontent.com/filoscoder">
</a>
- Invalidar tokens en conjunto con una sola petición SQL
Copy link

Choose a reason for hiding this comment

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

The documentation of endpoints and interfaces is comprehensive and well-structured. However, there are several instances of possible spelling mistakes and grammatical errors throughout the document. It's recommended to go through the document and correct these errors for clarity and professionalism. For example, "devuleve" should be "devuelve" in the context of returning an array, and "metodos estaticos" should be "métodos estáticos" to maintain consistency with Spanish language accents and spelling.

Consider using a spell checker or a grammar correction tool to identify and correct these errors throughout the document.

Comment on lines +260 to +279
- Instanciar servicios en lugar de usar metodos estaticos
- Cambiar contraseña (no funciona en el casino, vamos por este lado)
- Endpoint https://agent.casinomex.vip/api/users/5941/change-password/
- Body: `{ new_password:string }`
- Recibir clave de rastreo en endpoints de cashIn y confirmarDeposito
- Hacer email opcional en player request validator
- Documentar endpoints agente
- Inhabilitar tokens anteriores al loguear un usuario (borrarlos de la bbdd, seleccionando por player_id)
- **Que pasa cuando un pago se verifica pero el agente no tiene fichas suficientes? o algo sale mal en el servidor del casino?**
+ Si el agente no tiene fichas, mandar push al panel de agente con total pendiente
+ Botón liberar fichas
+ Chequear que total pendiente sea menor a nuevo stock
+ Liberar transferencias
- Encriptar JWT
# Author & Credits
## Optimizaciones
<a src="https://github.com/filoscoder">
<img width="60px" style="border-radius: 50%;" src="https://avatars.githubusercontent.com/filoscoder">
</a>
- Invalidar tokens en conjunto con una sola petición SQL
Copy link

Choose a reason for hiding this comment

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

The TODO and Optimizations sections contain valuable insights into future improvements and optimizations. It's crucial to track these tasks in a project management tool or issue tracker to ensure they are addressed in a timely manner. Additionally, consider translating these sections into English if the project aims for a broader international audience.

Would you like assistance in creating GitHub issues for these tasks or translating these sections?

Comment on lines +44 to +45
INSERT INTO `USERS_ROOT` (`id`, `username`, `password`, `panel_id`, `access`, `refresh`, `json_response`, `dirty`, `created_at`, `updated_at`) VALUES
(3, 'luquin', '{\"ivArray\":[\"98\",\"178\",\"232\",\"94\",\"155\",\"6\",\"15\",\"40\",\"39\",\"234\",\"143\",\"28\",\"44\",\"43\",\"56\",\"92\"],\"ciphertext\":\"a2b3df852669cf01f9983953dc67cf43\"}', 414, 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNzA4Njk1MTIwLCJqdGkiOiJlN2IzNTcyZTEzNTA0ZDcyYWQyNDA0YzdmOWQzYTNlNSIsInVzZXJfaWQiOjQxNCwicmVmcmVzaF9zaGlmdCI6MTIwLCJ1dWlkIjoiOGE2OGM0ZTgwNGY4NDc2Zjk1OGM0NTJiZjE0YzcxN2YifQ.gOf5JEObwX24EEloDfDzawJX0pavbLssb_xL2vUkccI', 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTcwODY5ODEyMCwianRpIjoiODVjNDI1Mjg2M2IxNDRkNTlmZGY3MWFiNmE5ZDQwNTUiLCJ1c2VyX2lkIjo0MTQsInJlZnJlc2hfc2hpZnQiOjEyMCwidXVpZCI6IjhhNjhjNGU4MDRmODQ3NmY5NThjNDUyYmYxNGM3MTdmIn0.g2TDjCxGLBFot0LE1h1WYVCAoXSKKHNAaeHg9wVedmk', '{\"id\":414,\"jackpots_won\":[],\"is_email_verified\":true,\"info\":{\"first_name\":\"lucas\",\"last_name\":\"lucas\",\"date_of_birth\":null,\"mobile_number\":\"\",\"country\":\"\",\"city\":\"\",\"street_address\":\"\",\"postal_code\":\"\",\"state\":null},\"bonus_balance\":\"0.00\",\"balance\":\"9.27\",\"role\":\"PA\",\"email\":\"luquin@gmail.com\",\"is_withdraw_allowed\":true,\"is_banned\":false,\"access\":\"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNzA4Njk1MTIwLCJqdGkiOiJlN2IzNTcyZTEzNTA0ZDcyYWQyNDA0YzdmOWQzYTNlNSIsInVzZXJfaWQiOjQxNCwicmVmcmVzaF9zaGlmdCI6MTIwLCJ1dWlkIjoiOGE2OGM0ZTgwNGY4NDc2Zjk1OGM0NTJiZjE0YzcxN2YifQ.gOf5JEObwX24EEloDfDzawJX0pavbLssb_xL2vUkccI\",\"refresh\":\"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTcwODY5ODEyMCwianRpIjoiODVjNDI1Mjg2M2IxNDRkNTlmZGY3MWFiNmE5ZDQwNTUiLCJ1c2VyX2lkIjo0MTQsInJlZnJlc2hfc2hpZnQiOjEyMCwidXVpZCI6IjhhNjhjNGU4MDRmODQ3NmY5NThjNDUyYmYxNGM3MTdmIn0.g2TDjCxGLBFot0LE1h1WYVCAoXSKKHNAaeHg9wVedmk\",\"last_login\":\"2024-02-23T13:22:00.225711Z\",\"username\":\"luquin\",\"first_name\":\"\",\"last_name\":\"\",\"date_joined\":\"2023-11-15T16:52:59.768862Z\",\"balance_currency\":\"MXN\",\"bonus_balance_currency\":\"MXN\",\"is_self_registered\":false,\"language\":\"en-US\",\"needs_document_approve\":true,\"affise_data\":null,\"pap_data\":null,\"cpf_document\":null,\"parent\":3}', 0, '2024-02-23 13:22:00.401', '2024-02-23 13:22:00.401');
Copy link

Choose a reason for hiding this comment

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

Storing JWT tokens in the database, as seen in the USERS_ROOT table insert, raises security concerns. Ensure these tokens are placeholders and not valid tokens. Additionally, consider whether storing large JSON responses in the database is necessary, as it might indicate a need for normalization or a different storage strategy.

Comment on lines +8 to +19
static async index(player_id: number) {
try {
const accounts = await prisma.bankAccount.findMany({
where: { player_id },
});
return accounts;
} catch (error: any) {
// Prisma errors handled by prismaErrorHandler()
throw error;
} 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.

The index method disconnects the Prisma client after fetching bank accounts. This could lead to unnecessary disconnections and reconnections, affecting performance. Consider optimizing the connection management strategy.

Comment on lines +22 to +34
static async show(account_id: number, player_id: number) {
try {
await this.authorizeView(account_id, player_id);

const account = await prisma.bankAccount.findUnique({
where: { id: account_id },
});
return account;
} catch (error: any) {
throw error;
} 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.

The show method follows the same pattern of disconnecting the Prisma client after each operation. This is not recommended for performance reasons. Evaluate the connection management approach to ensure efficient resource use.

Comment on lines +37 to +48
static async create(player_id: number, request: BankAccountRequest) {
try {
const account = await prisma.bankAccount.create({
data: { player_id, ...request },
});
return account;
} catch (error: any) {
throw error;
} 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.

Similar to previous methods, the create method disconnects the Prisma client in a finally block. This practice can lead to performance issues. Reconsider the connection management strategy for better performance.

Comment on lines +50 to +68
static async update(
account_id: number,
player_id: number,
request: BankAccountRequest,
) {
try {
await this.authorizeUpdate(account_id, player_id);

const updated = await prisma.bankAccount.update({
where: { id: account_id, player_id },
data: request,
});
return updated;
} catch (error: any) {
throw error;
} 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.

The update method also disconnects the Prisma client after each operation. This could negatively impact performance due to frequent disconnections and reconnections. Optimize connection management to enhance efficiency.

Comment on lines +70 to +80
static async delete(account_id: number, player_id: number) {
try {
await this.authorizeDelete(account_id, player_id);

await prisma.bankAccount.delete({ where: { id: account_id } });
} catch (error: any) {
throw error;
} 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.

The delete method exhibits the same issue with disconnecting the Prisma client after each operation. This is not optimal for performance. Reevaluate the connection management approach to improve application efficiency.

@alvarezrrj alvarezrrj closed this Mar 6, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

2 participants