OfflineHQ / marketplace

https://offline.live/
GNU General Public License v3.0
0 stars 0 forks source link

Event features + Cometh Connect + Unlock #302

Closed sebpalluel closed 6 months ago

sebpalluel commented 6 months ago

Type

enhancement, tests


Description


Changes walkthrough

Relevant files
Enhancement
index.ts
Refactor GraphQL Types for Account and Order Management   

libs/gql/admin/types/src/generated/index.ts
  • Simplified the AccountFieldsFragment by removing optional fields like
    scwAddress, email, and phone.
  • Updated mutation and query types to use 'uuid' and 'String' input
    types for better type safety.
  • Removed unused queries related to fetching accounts by email.
  • Added new types for handling orders with claim information.
  • +429/-98
    insight-server.d.ts
    Add Posthog Class for Feature Flag Management                       

    libs/insight/server/src/lib/insight-server.d.ts
  • Introduced a new class 'Posthog' with methods to handle feature flags
    and payloads.
  • Added complex type definitions for handling nested data structures in
    feature flag payloads.
  • +1123/-0
    PassList.stories.tsx
    Cleanup Unused Imports in PassList Stories                             

    libs/features/organizer/event/src/lib/organisms/PassList/PassList.stories.tsx
  • Removed unused import of PassListBoundaryMaxExample from the PassList
    stories setup.
  • +1/-20   
    index.ts
    Export initKyc Function in KYC Actions Module                       

    libs/features/kyc-actions/src/index.ts - Added export for initKyc function to the module's public API.
    +1/-0     
    Tests
    loyalty-card-cron.integration.test.ts
    Implement Integration Tests for Loyalty Card Cron               

    libs/features/loyalty-card-cron/src/lib/loyalty-card-cron.integration.test.ts
  • Implemented integration tests for the loyalty card cron functionality.
  • Mocked necessary dependencies and tested various scenarios including
    single and multiple NFT claims.
  • +528/-0 

    PR-Agent usage: Comment /help on the PR to get a list of all available PR-Agent tools and their descriptions

    vercel[bot] commented 6 months ago

    The latest updates on your projects. Learn more about Vercel for Git ↗︎

    Name Status Preview Updated (UTC)
    back-office ✅ Ready (Inspect) Visit Preview May 2, 2024 8:00am
    marketplace ✅ Ready (Inspect) Visit Preview May 2, 2024 8:00am
    unlock ✅ Ready (Inspect) Visit Preview May 2, 2024 8:00am
    codiumai-pr-agent-free[bot] commented 6 months ago

    PR Description updated to latest commit (https://github.com/OfflineHQ/marketplace/commit/f278445d1547bff9be122222c344997d25296734)

    codiumai-pr-agent-free[bot] commented 6 months ago

    PR Review

    ⏱️ Estimated effort to review [1-5] 4, because the PR includes a significant amount of changes across multiple files and systems, involving complex features like GraphQL type refactoring, integration tests, and feature flag management. The complexity and breadth of changes require thorough testing and understanding of multiple domains.
    🧪 Relevant tests Yes
    🔍 Possible issues Possible Bug: The `Posthog` class in `libs/insight/server/src/lib/insight-server.d.ts` has a very complex method `getFeatureFlagPayload` which could be prone to errors due to its deeply nested structures and multiple types. Simplifying this method could reduce potential bugs and improve maintainability.
    Performance Concern: The `loyalty-card-cron.integration.test.ts` file includes multiple test cases that mock external API calls. If these mocks are not accurately representing the API's behavior, it could lead to false positives in testing, where tests pass but the actual integration might fail under real conditions.
    🔒 Security concerns No

    ✨ Review tool usage guide:
    **Overview:** The `review` tool scans the PR code changes, and generates a PR review which includes several types of feedbacks, such as possible PR issues, security threats and relevant test in the PR. More feedbacks can be [added](https://pr-agent-docs.codium.ai/tools/review/#general-configurations) by configuring the tool. The tool can be triggered [automatically](https://pr-agent-docs.codium.ai/usage-guide/automations_and_usage/#github-app-automatic-tools-when-a-new-pr-is-opened) every time a new PR is opened, or can be invoked manually by commenting on any PR. - When commenting, to edit [configurations](https://github.com/Codium-ai/pr-agent/blob/main/pr_agent/settings/configuration.toml#L23) related to the review tool (`pr_reviewer` section), use the following template: ``` /review --pr_reviewer.some_config1=... --pr_reviewer.some_config2=... ``` - With a [configuration file](https://pr-agent-docs.codium.ai/usage-guide/configuration_options/), use the following template: ``` [pr_reviewer] some_config1=... some_config2=... ``` See the review [usage page](https://pr-agent-docs.codium.ai/tools/review/) for a comprehensive guide on using this tool.
    codiumai-pr-agent-free[bot] commented 6 months ago

    PR Code Suggestions

    CategorySuggestions                                                                                                                                                       
    Enhancement
    Add error handling for the Headers constructor to improve robustness. ___ **Consider adding error handling for the new Headers constructor to catch potential
    exceptions that might be thrown if the input is invalid.** [libs/integrations/external-api-handlers/src/lib/shopify/index.spec.ts [34-36]](https://github.com/OfflineHQ/marketplace/pull/302/files#diff-df93842e018141cf209891b7f7fa3c10fbc063d5eed17ace2701d2d12a234844R34-R36) ```diff -new Headers({ - 'x-shopify-client-id': 'validApiKey', -}) +try { + new Headers({ + 'x-shopify-client-id': 'validApiKey', + }) +} catch (error) { + console.error('Failed to create headers:', error); +} ```
    Enhance the test coverage for verifySignature to include more edge cases. ___ **To ensure that the verifySignature method handles various edge cases, add more
    comprehensive tests that include scenarios with malformed signatures, missing fields, and
    unexpected data types.** [libs/integrations/external-api-handlers/src/lib/shopify/index.spec.ts [102-107]](https://github.com/OfflineHQ/marketplace/pull/302/files#diff-df93842e018141cf209891b7f7fa3c10fbc063d5eed17ace2701d2d12a234844R102-R107) ```diff -expect(verifySignatureMock).toHaveBeenCalledWith({ - body: expect.any(String), - integritySecret: expect.any(String), - signature: 'validSignature', +// Additional test cases for verifySignature +it('should handle malformed signatures', async () => { + verifySignatureMock.mockReturnValue(false); + const malformedSignatureRequest = createMockRequest(new URLSearchParams({ + signature: 'malformedSignature', + })); + await expect( + handler.extractAndVerifyShopifyRequest(malformedSignatureRequest), + ).rejects.toThrow('Invalid signature'); }); ```
    Add error handling and retry mechanism to the sign-in process. ___ **The loginSiwe function should handle the case where signIn fails due to network issues or
    server errors. Currently, it only logs the error but does not retry or provide a fallback
    mechanism. Implementing a retry mechanism or a fallback strategy can improve the
    robustness of the sign-in process.** [libs/next/auth/src/lib/safeAuthSetup.tsx [73-80]](https://github.com/OfflineHQ/marketplace/pull/302/files#diff-62c2e484cf5b18e47c237cc9a40b19276134b027875bfbf22bb37acb63d1194eR73-R80) ```diff const signInRes = await signIn('credentials', { message, redirect: false, signature, address, }); if (signInRes?.error) { console.error('Error signing in with SIWE:', signInRes?.error); + // Implement retry logic or fallback strategy here } ```
    Add error handling to the account creation process. ___ **The createAccount function currently does not handle exceptions that might be thrown by
    connectWithSiwe or loginSiwe. It is recommended to add error handling to manage these
    exceptions gracefully.** [libs/next/auth/src/lib/safeAuthSetup.tsx [179-181]](https://github.com/OfflineHQ/marketplace/pull/302/files#diff-62c2e484cf5b18e47c237cc9a40b19276134b027875bfbf22bb37acb63d1194eR179-R181) ```diff const createAccount = useCallback(async () => { - await connectWithSiwe(loginSiwe, undefined, true); + try { + await connectWithSiwe(loginSiwe, undefined, true); + } catch (error) { + console.error('Failed to create account:', error); + // Handle error appropriately + } }, [connectWithSiwe, loginSiwe]); ```
    Ensure complete logout process before resetting user tracking. ___ **The logout function should verify if the disconnect and logoutSiwe operations are
    successful before calling logoutUserPostHog. This ensures that the user is fully logged
    out from all systems before resetting the tracking information.** [libs/next/auth/src/lib/safeAuthSetup.tsx [170-176]](https://github.com/OfflineHQ/marketplace/pull/302/files#diff-62c2e484cf5b18e47c237cc9a40b19276134b027875bfbf22bb37acb63d1194eR170-R176) ```diff const logout = useCallback( async ({ refresh }: { refresh?: boolean }) => { - await disconnect(); - await logoutSiwe({ refresh }); - logoutUserPostHog(); + try { + await disconnect(); + await logoutSiwe({ refresh }); + logoutUserPostHog(); + } catch (error) { + console.error('Failed to fully logout:', error); + // Handle incomplete logout scenario + } }, [disconnect, logoutSiwe, logoutUserPostHog], ); ```
    Improve the reliability of the connectivity check by handling potential errors. ___ **The isConnected function is used to check if the user is connected, but it is not clear
    how it handles different states of connectivity. It would be beneficial to add explicit
    handling for different connectivity states or errors that might occur during the
    connectivity check.** [libs/next/auth/src/lib/safeAuthSetup.tsx [190]](https://github.com/OfflineHQ/marketplace/pull/302/files#diff-62c2e484cf5b18e47c237cc9a40b19276134b027875bfbf22bb37acb63d1194eR190-R190) ```diff -const isNextAuthConnected = isConnected ? await isConnected() : false; +let isNextAuthConnected = false; +try { + isNextAuthConnected = isConnected ? await isConnected() : false; +} catch (error) { + console.error('Failed to check connectivity:', error); + // Handle connectivity check error +} ```
    Add error handling to the auto-login process to enhance stability. ___ **The loginAuto function attempts to log in automatically but does not handle the case where
    the connectWithSiwe or loginSiwe might fail. Adding error handling here would prevent
    unhandled promise rejections and improve the stability of the auto-login feature.** [libs/next/auth/src/lib/safeAuthSetup.tsx [152-162]](https://github.com/OfflineHQ/marketplace/pull/302/files#diff-62c2e484cf5b18e47c237cc9a40b19276134b027875bfbf22bb37acb63d1194eR152-R162) ```diff const loginAuto = useCallback( async (address: string) => { - if (!!session?.user && session?.user?.address !== address) { - await logoutSiwe({ refresh: false }); + try { + if (!!session?.user && session?.user?.address !== address) { + await logoutSiwe({ refresh: false }); + } + console.log('Auto login with SIWE...', address); + const instance = await connectWithSiwe(loginSiwe, address, true); + if (!instance) throw new Error('Error connecting with SIWE'); + else await loginSiwe(instance); + } catch (error) { + console.error('Failed to auto-login with SIWE:', error); + // Handle error during auto-login } - console.log('Auto login with SIWE...', address); - const instance = await connectWithSiwe(loginSiwe, address, true); - if (!instance) throw new Error('Error connecting with SIWE'); - else await loginSiwe(instance); }, [connectWithSiwe, loginSiwe, logoutSiwe, session], ); ```
    Use more specific matchers in test assertions for improved test accuracy. ___ **Use a more specific matcher than expect.anything() in your test assertions to ensure that
    the function is called with the expected type of arguments, enhancing the test's accuracy
    and reliability.** [libs/features/loyalty-card-cron/src/lib/loyalty-card-cron.integration.test.ts [102]](https://github.com/OfflineHQ/marketplace/pull/302/files#diff-4f7b7cdfce4314f6e816b30477dcf2dae3f97994cdbcecdffc18863f89aaa74dR102-R102) ```diff -expect.anything(), +expect.any(Object), // or a more specific type if applicable ```
    Maintainability
    Centralize the creation of mock requests to reduce redundancy and improve code maintainability. ___ **Refactor the repeated creation of NextRequest objects in tests by centralizing the
    creation logic into a single function or utilizing a setup function to reduce redundancy
    and improve maintainability.** [libs/integrations/external-api-handlers/src/lib/shopify/index.spec.ts [172-179]](https://github.com/OfflineHQ/marketplace/pull/302/files#diff-df93842e018141cf209891b7f7fa3c10fbc063d5eed17ace2701d2d12a234844R172-R179) ```diff -const mockRequest = createMockRequest( - new URLSearchParams({ - password: 'test-password', - ownerAddress: 'test-address', - shop: 'example.myshopify.com', - timestamp: Date.now().toString(), - signature: 'validSignature', - }), -); +function createStandardMockRequest() { + return createMockRequest( + new URLSearchParams({ + password: 'test-password', + ownerAddress: 'test-address', + shop: 'example.myshopify.com', + timestamp: Date.now().toString(), + signature: 'validSignature', + }), + ); +} +const mockRequest = createStandardMockRequest(); ```
    Refactor repeated mock setup into a utility function to reduce duplication. ___ **Refactor the repeated mock setup for adminSdk.GetLoyaltyCardByContractAddressForProcess
    into a separate utility function to reduce code duplication and improve maintainability.** [libs/features/loyalty-card-cron/src/lib/loyalty-card-cron.integration.test.ts [69]](https://github.com/OfflineHQ/marketplace/pull/302/files#diff-4f7b7cdfce4314f6e816b30477dcf2dae3f97994cdbcecdffc18863f89aaa74dR69-R69) ```diff -adminSdk.GetLoyaltyCardByContractAddressForProcess as jest.Mock +setupMockGetLoyaltyCardByContractAddressForProcess(); ```
    Remove redundant test assertions or replace them with more specific checks. ___ **Replace the redundant calls to
    expect(adminSdk.GetLoyaltyCardByContractAddressForProcess).toHaveBeenCalled(); with a
    single call or use different assertions to validate different aspects of the mock's usage
    if needed.** [libs/features/loyalty-card-cron/src/lib/loyalty-card-cron.integration.test.ts [95-99]](https://github.com/OfflineHQ/marketplace/pull/302/files#diff-4f7b7cdfce4314f6e816b30477dcf2dae3f97994cdbcecdffc18863f89aaa74dR95-R99) ```diff expect( adminSdk.GetLoyaltyCardByContractAddressForProcess, -).toHaveBeenCalled(); +).toHaveBeenCalledTimes(1); ```
    Best practice
    Use a fixed or mocked timestamp in tests to ensure determinism. ___ **Replace the direct usage of Date.now() in tests with a mock or a fixed timestamp to make
    the tests deterministic and not dependent on the actual current time.** [libs/integrations/external-api-handlers/src/lib/shopify/index.spec.ts [123]](https://github.com/OfflineHQ/marketplace/pull/302/files#diff-df93842e018141cf209891b7f7fa3c10fbc063d5eed17ace2701d2d12a234844R123-R123) ```diff -timestamp: Date.now().toString(), +timestamp: 'fixed-timestamp', ```
    Use specific error types for better context and debugging. ___ **Use a more specific error type than Error for better error handling and to provide more
    context in the error messages, improving the debugging process.** [libs/integrations/external-api-handlers/src/lib/shopify/index.spec.ts [402]](https://github.com/OfflineHQ/marketplace/pull/302/files#diff-df93842e018141cf209891b7f7fa3c10fbc063d5eed17ace2701d2d12a234844R402-R402) ```diff -.mockRejectedValue(new Error('Unexpected error')), +.mockRejectedValue(new InternalServerError('Unexpected error')), ```
    Make test data generation deterministic to ensure test reliability and reproducibility. ___ **Replace the direct use of Math.random() in the generateNFTs function with a deterministic
    approach for generating test data. This change will make the tests more predictable and
    reproducible, which is crucial for debugging and reliability in automated testing
    environments.** [libs/features/loyalty-card-cron/src/lib/loyalty-card-cron.integration.test.ts [495]](https://github.com/OfflineHQ/marketplace/pull/302/files#diff-4f7b7cdfce4314f6e816b30477dcf2dae3f97994cdbcecdffc18863f89aaa74dR495-R495) ```diff -const numNFTs = Math.floor(Math.random() * 10) + 1; +const numNFTs = 5; // Fixed number for predictability in tests ```
    Add error handling for asynchronous operations in test setup and teardown. ___ **Consider adding error handling for the asynchronous operations within the beforeAll,
    afterAll, and beforeEach blocks to catch and handle any potential errors that might occur
    during database setup and teardown. This will improve the robustness of your test suite.** [libs/features/loyalty-card-cron/src/lib/loyalty-card-cron.integration.test.ts [35]](https://github.com/OfflineHQ/marketplace/pull/302/files#diff-4f7b7cdfce4314f6e816b30477dcf2dae3f97994cdbcecdffc18863f89aaa74dR35-R35) ```diff -await deleteAllTables(client); +try { + await deleteAllTables(client); +} catch (error) { + console.error('Error during table deletion:', error); +} ```
    Improve type safety by specifying a more precise type than any. ___ **Consider using a more specific type instead of any for the id field in the
    AccountFieldsFragment type to ensure type safety and better integration with TypeScript's
    static type checking.** [libs/gql/user/types/src/generated/index.ts [3]](https://github.com/OfflineHQ/marketplace/pull/302/files#diff-8fa05dfd812ca9d26127460143dc7172fefcdb8ccd3df70a434915a9691c0628R3-R3) ```diff -export type AccountFieldsFragment = { __typename?: 'account', id: any, address: string }; +export type AccountFieldsFragment = { __typename?: 'account', id: string, address: string }; ```
    Enhance type safety by using specific types instead of any. ___ **Replace the any type with a more specific type for the id fields in the
    GetPendingOrderForEventPassQuery to enhance type safety.** [libs/gql/user/types/src/generated/index.ts [107]](https://github.com/OfflineHQ/marketplace/pull/302/files#diff-8fa05dfd812ca9d26127460143dc7172fefcdb8ccd3df70a434915a9691c0628R107-R107) ```diff -export type GetPendingOrderForEventPassQuery = { __typename?: 'query_root', pendingOrder: Array<{ __typename?: 'pendingOrder', id: any, eventPassId?: string | null, quantity: number, created_at: any }> }; +export type GetPendingOrderForEventPassQuery = { __typename?: 'query_root', pendingOrder: Array<{ __typename?: 'pendingOrder', id: string, eventPassId?: string | null, quantity: number, created_at: any }> }; ```
    Improve type safety by specifying a more precise type for tokenId. ___ **Use a specific type for the tokenId field in the EventPassNftFieldsFragment instead of any
    to improve type safety and maintain consistency.** [libs/gql/user/types/src/generated/index.ts [150]](https://github.com/OfflineHQ/marketplace/pull/302/files#diff-8fa05dfd812ca9d26127460143dc7172fefcdb8ccd3df70a434915a9691c0628R150-R150) ```diff -export type EventPassNftFieldsFragment = { __typename?: 'eventPassNft', tokenId?: any | null, eventId: string, eventPassId: string, organizerId: string, isRevealed: boolean, currentOwnerAddress?: string | null }; +export type EventPassNftFieldsFragment = { __typename?: 'eventPassNft', tokenId?: string | null, eventId: string, eventPassId: string, organizerId: string, isRevealed: boolean, currentOwnerAddress?: string | null }; ```
    Use a more specific type for the created_at field to improve clarity and type safety. ___ **Specify a more precise type for the created_at field in the
    GetPendingOrderForEventPassQuery to enhance type safety and clarity.** [libs/gql/user/types/src/generated/index.ts [107]](https://github.com/OfflineHQ/marketplace/pull/302/files#diff-8fa05dfd812ca9d26127460143dc7172fefcdb8ccd3df70a434915a9691c0628R107-R107) ```diff -export type GetPendingOrderForEventPassQuery = { __typename?: 'query_root', pendingOrder: Array<{ __typename?: 'pendingOrder', id: any, eventPassId?: string | null, quantity: number, created_at: any }> }; +export type GetPendingOrderForEventPassQuery = { __typename?: 'query_root', pendingOrder: Array<{ __typename?: 'pendingOrder', id: any, eventPassId?: string | null, quantity: number, created_at: Date }> }; ```

    ✨ Improve tool usage guide:
    **Overview:** The `improve` tool scans the PR code changes, and automatically generates suggestions for improving the PR code. The tool can be triggered [automatically](https://pr-agent-docs.codium.ai/usage-guide/automations_and_usage/#github-app-automatic-tools-when-a-new-pr-is-opened) every time a new PR is opened, or can be invoked manually by commenting on a PR. - When commenting, to edit [configurations](https://github.com/Codium-ai/pr-agent/blob/main/pr_agent/settings/configuration.toml#L78) related to the improve tool (`pr_code_suggestions` section), use the following template: ``` /improve --pr_code_suggestions.some_config1=... --pr_code_suggestions.some_config2=... ``` - With a [configuration file](https://pr-agent-docs.codium.ai/usage-guide/configuration_options/), use the following template: ``` [pr_code_suggestions] some_config1=... some_config2=... ``` See the improve [usage page](https://pr-agent-docs.codium.ai/tools/improve/) for a comprehensive guide on using this tool.