Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[PLA-1872] Beam packs #92

Merged
merged 29 commits into from
Nov 6, 2024
Merged

Conversation

enjinabner
Copy link
Contributor

@enjinabner enjinabner commented Aug 5, 2024

PR Type

Enhancement, Tests, Documentation


Description

  • Added support for creating, updating, and managing beam packs.
  • Implemented new models, migrations, and GraphQL types for beam packs.
  • Enhanced existing mutations and queries to handle beam packs.
  • Added extensive tests for beam pack scenarios.
  • Introduced new validation rules for beam pack operations.

Changes walkthrough 📝

Relevant files
Tests
4 files
CreateBeamTest.php
Add tests and validation for beam pack creation                   

tests/Feature/GraphQL/Mutations/CreateBeamTest.php

  • Added tests for creating beam packs.
  • Enhanced existing tests to include beam pack scenarios.
  • Added validation for beam pack creation.
  • +198/-19
    UpdateBeamTest.php
    Add tests for updating beam packs                                               

    tests/Feature/GraphQL/Mutations/UpdateBeamTest.php

  • Added tests for updating beam packs.
  • Enhanced existing tests to include beam pack scenarios.
  • +119/-51
    AddTokensTest.php
    Add tests for adding tokens to beam packs                               

    tests/Feature/GraphQL/Mutations/AddTokensTest.php

  • Added tests for adding tokens to beam packs.
  • Enhanced existing tests to include beam pack scenarios.
  • +122/-19
    RemoveTokensTest.php
    Add tests for removing tokens from beam packs                       

    tests/Feature/GraphQL/Mutations/RemoveTokensTest.php

  • Added tests for removing tokens from beam packs.
  • Enhanced existing tests to include beam pack scenarios.
  • +66/-3   
    Enhancement
    11 files
    BeamService.php
    Add support for creating and managing beam packs                 

    src/Services/BeamService.php

  • Added support for creating and managing beam packs.
  • Modified existing methods to handle beam packs.
  • Implemented new methods for beam pack claims.
  • +210/-59
    HasTokenInputRules.php
    Add token input rules for beam packs                                         

    src/GraphQL/Traits/HasTokenInputRules.php

  • Added new trait for token input rules.
  • Implemented validation rules for beam packs.
  • +159/-0 
    AddTokensMutation.php
    Support adding tokens to beam packs in mutation                   

    src/GraphQL/Mutations/AddTokensMutation.php

  • Modified mutation to support adding tokens to beam packs.
  • Implemented validation for beam pack tokens.
  • +19/-69 
    ClaimBeam.php
    Handle beam pack claims in job                                                     

    src/Jobs/ClaimBeam.php

  • Modified job to handle beam pack claims.
  • Added logic for updating beam pack claim status.
  • +32/-11 
    CreateBeamMutation.php
    Support creating beam packs in mutation                                   

    src/GraphQL/Mutations/CreateBeamMutation.php

  • Modified mutation to support creating beam packs.
  • Implemented validation for beam pack creation.
  • +13/-67 
    UpdateBeamMutation.php
    Support updating beam packs in mutation                                   

    src/GraphQL/Mutations/UpdateBeamMutation.php

  • Modified mutation to support updating beam packs.
  • Implemented validation for beam pack updates.
  • +11/-67 
    RemoveTokensMutation.php
    Support removing tokens from beam packs in mutation           

    src/GraphQL/Mutations/RemoveTokensMutation.php

  • Modified mutation to support removing tokens from beam packs.
  • Implemented validation for beam pack token removal.
  • +64/-2   
    BeamPackType.php
    Add new GraphQL type for beam packs                                           

    src/GraphQL/Types/BeamPackType.php

  • Added new GraphQL type for beam packs.
  • Defined fields and relationships for beam packs.
  • +74/-0   
    BeamPack.php
    Add new model for beam packs                                                         

    src/Models/Laravel/BeamPack.php

  • Added new model for beam packs.
  • Defined relationships and scopes for beam packs.
  • +136/-0 
    2024_08_01_041409_beam_packs.php
    Add migration for beam packs                                                         

    database/migrations/2024_08_01_041409_beam_packs.php

  • Added migration for beam packs.
  • Updated beams and beam claims tables to support beam packs.
  • +48/-0   
    GetSingleUseCodesQuery.php
    Support fetching single-use codes for beam packs                 

    src/GraphQL/Queries/GetSingleUseCodesQuery.php

  • Modified query to support fetching single-use codes for beam packs.
  • Implemented logic to differentiate between beam claims and beam packs.

  • +8/-2     
    Additional files (token-limit)
    13 files
    BeamPackInputType.php
    ...                                                                                                           

    src/GraphQL/Types/Input/BeamPackInputType.php

    ...

    +36/-0   
    input_type.php
    ...                                                                                                           

    lang/en/input_type.php

    ...

    +2/-0     
    BeamPackFactory.php
    ...                                                                                                           

    database/factories/BeamPackFactory.php

    ...

    +30/-0   
    GetSingleUseCodesTest.php
    ...                                                                                                           

    tests/Feature/GraphQL/Queries/GetSingleUseCodesTest.php

    ...

    +10/-0   
    Beam.php
    ...                                                                                                           

    src/Models/Laravel/Beam.php

    ...

    +9/-0     
    BeamType.php
    ...                                                                                                           

    src/GraphQL/Types/BeamType.php

    ...

    +6/-0     
    validation.php
    ...                                                                                                           

    lang/en/validation.php

    ...

    +2/-0     
    BeamServiceProvider.php
    ...                                                                                                           

    src/BeamServiceProvider.php

    ...

    +1/-0     
    CreateBeam.graphql
    ...                                                                                                           

    tests/Feature/GraphQL/Resources/CreateBeam.graphql

    ...

    +3/-1     
    UpdateBeam.graphql
    ...                                                                                                           

    tests/Feature/GraphQL/Resources/UpdateBeam.graphql

    ...

    +2/-0     
    GetSingleUseCodes.graphql
    ...                                                                                                           

    tests/Feature/GraphQL/Resources/GetSingleUseCodes.graphql

    ...

    +14/-4   
    RemoveTokens.graphql
    ...                                                                                                           

    tests/Feature/GraphQL/Resources/RemoveTokens.graphql

    ...

    +6/-2     
    AddTokens.graphql
    ...                                                                                                           

    tests/Feature/GraphQL/Resources/AddTokens.graphql

    ...

    +3/-5     

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

    @enjinabner enjinabner added the enhancement New feature or request label Aug 5, 2024
    @enjinabner enjinabner self-assigned this Aug 5, 2024
    @github-actions github-actions bot added documentation Improvements or additions to documentation tests Review effort [1-5]: 4 labels Aug 5, 2024
    Copy link

    github-actions bot commented Aug 5, 2024

    PR Reviewer Guide 🔍

    ⏱️ Estimated effort to review: 4 🔵🔵🔵🔵⚪
    🧪 PR contains tests
    🔒 No security concerns identified
    ⚡ Key issues to review

    Possible Bug
    The method createPackClaims in BeamService might not handle cases where the packs array is empty correctly, leading to unnecessary database transactions. Consider adding a check at the beginning of the method to return early if packs is empty.

    Code Clarity
    The method create in BeamService has complex conditional logic inside the transaction which might be simplified or broken down into smaller methods for better readability and maintainability.

    Validation Rules
    Ensure that the validation rules for tokens and packs in AddTokensMutation are comprehensive and correctly handle all edge cases, especially considering the new beam pack features.

    Data Handling
    The resolve method in CreateBeamMutation should ensure that all necessary attributes for beam creation, including those related to beam packs, are correctly handled and validated before passing to the service layer.

    Update Logic
    The resolve method in UpdateBeamMutation should include logic to handle updates specific to beam packs, ensuring that changes to packs are correctly applied and persisted.

    Copy link

    github-actions bot commented Aug 5, 2024

    PR Code Suggestions ✨

    CategorySuggestion                                                                                                                                    Score
    Possible bug
    Add missing validation for token existence in collection

    Add missing validation for TokensExistInCollection in the tokens.*.tokenIds rule to
    ensure that tokens exist in the collection when the beam type is TRANSFER_TOKEN.

    src/GraphQL/Traits/HasTokenInputRules.php [48-58]

     'tokens.*.tokenIds' => Rule::forEach(function ($value, $attribute) use ($args, $collectionId) {
         return [
             'bail',
             'required_without:tokens.*.tokenIdDataUpload',
             'prohibits:tokens.*.tokenIdDataUpload',
             'distinct',
             BeamType::getEnumCase(Arr::get($args, str_replace('tokenIds', 'type', $attribute))) == BeamType::TRANSFER_TOKEN
                 ? new TokensExistInCollection($collectionId)
    -            : '',
    +            : new TokensDoNotExistInCollection($collectionId),
             new TokensDoNotExistInBeam(),
         ];
     }),
     
    Suggestion importance[1-10]: 10

    Why: This suggestion addresses a potential bug by ensuring proper validation, which is critical for the correct functioning of the application.

    10
    Handle potential exceptions by checking the result of first() before proceeding

    Consider handling the potential exception that might be thrown by the first() method
    when no BeamPack is found, to avoid unhandled exceptions.

    src/Jobs/ClaimBeam.php [117-122]

    -if (!($pack = BeamPack::where('is_claimed', false)
    +$pack = BeamPack::where('is_claimed', false)
         ->where('beam_id', $data['beam']['id'])
         ->when($data['code'], fn ($subquery) => $subquery->where('code', $data['code']))
         ->inRandomOrder()
    -    ->first())) {
    +    ->first();
    +if (!$pack) {
         throw new BeamException('No available packs to claim.');
     }
     
    Suggestion importance[1-10]: 8

    Why: This suggestion improves error handling by explicitly checking the result of first(), which can prevent unhandled exceptions.

    8
    Enhancement
    Add a unique constraint to the 'code' column in the 'beam_packs' table

    Consider adding a unique constraint to the 'code' column in the 'beam_packs' table
    to ensure that each code is unique across the system. This will prevent potential
    issues with duplicate codes, which could lead to data integrity problems.

    database/migrations/2024_08_01_041409_beam_packs.php [20]

    -$table->string('code')->index()->nullable();
    +$table->string('code')->unique()->nullable();
     
    Suggestion importance[1-10]: 9

    Why: Adding a unique constraint to the 'code' column is a significant improvement that ensures data integrity by preventing duplicate codes, which could lead to potential issues in the system.

    9
    Add validation rules to the 'packs' array in the GraphQL type definition

    Ensure that the packs array in the GraphQL type definition includes validation rules
    similar to those for tokens, such as checking for distinct IDs or other necessary
    validations, to maintain data integrity and prevent issues.

    src/GraphQL/Mutations/UpdateBeamMutation.php [63-65]

     'packs' => [
         'type' => GraphQL::type('[BeamPackInput!]'),
         'description' => __('enjin-platform-beam::input_type.beam_pack.description'),
    +    'rules' => ['required', 'distinct', new ValidBeamPack()],
     ],
     
    Suggestion importance[1-10]: 8

    Why: Adding validation rules to the 'packs' array enhances data integrity and consistency, which is crucial for maintaining the reliability of the application.

    8
    Improve code readability and performance by using the null coalescing operator

    Replace the direct use of Arr::get with null coalescing operator ?? for better
    readability and performance.

    src/Jobs/ClaimBeam.php [48]

    -for ($i = 0; $i < Arr::get($token, 'claimQuantity', 1); $i++) {
    +for ($i = 0; $i < ($token['claimQuantity'] ?? 1); $i++) {
     
    Suggestion importance[1-10]: 7

    Why: The suggestion improves readability and performance by using the null coalescing operator, which is more concise and faster than Arr::get.

    7
    Possible issue
    Improve null handling in conditional checks

    Replace the use of the null-safe operator (?->) with explicit null checks to prevent
    potential issues when $beam is null. This will make the code more robust by
    explicitly handling cases where $beam might not be set.

    src/GraphQL/Mutations/UpdateBeamMutation.php [110-111]

    -!$beam?->is_pack => $this->tokenRules($args, $beam?->collection_chain_id),
    +!$beam || !$beam->is_pack => $this->tokenRules($args, $beam ? $beam->collection_chain_id : null),
     
    Suggestion importance[1-10]: 9

    Why: This suggestion improves the robustness of the code by explicitly handling null cases, which can prevent potential runtime errors.

    9
    Ensure 'tokenIds' or 'packs' is provided in the 'RemoveTokensMutation'

    To enhance data integrity, consider adding a check to ensure that the 'tokenIds' and
    'packs' arrays are not both empty. This prevents the mutation from running without
    meaningful data, which could lead to unintended effects.

    src/GraphQL/Mutations/RemoveTokensMutation.php [104-110]

     'tokenIds' => [
         'bail',
    -    'required',
    +    'required_without:packs',
         'prohibits:packs',
         'array',
         'min:1',
         'max:1000',
     ],
     
    Suggestion importance[1-10]: 8

    Why: Adding a check to ensure that either 'tokenIds' or 'packs' is provided prevents the mutation from running without meaningful data, enhancing data integrity and preventing unintended effects.

    8
    Add validation rules for the 'packs' input in the 'AddTokensMutation'

    Ensure that the 'packs' array is validated for required fields and structure to
    prevent runtime errors or malformed data entries. This can be done by adding
    detailed validation rules for the 'packs' input in the mutation.

    src/GraphQL/Mutations/AddTokensMutation.php [55-57]

     'packs' => [
         'type' => GraphQL::type('[BeamPackInput!]'),
         'description' => __('enjin-platform-beam::input_type.beam_pack.description'),
    +    'rules' => ['required', 'array'],
     ],
     
    Suggestion importance[1-10]: 7

    Why: Adding validation rules for the 'packs' input helps prevent runtime errors and ensures data integrity by validating the structure and required fields of the 'packs' array.

    7
    Maintainability
    Refactor the method to use early returns for better readability and reduced complexity

    Refactor the nested if statements to reduce complexity and improve readability by
    using early returns or consolidating conditions.

    src/Jobs/ClaimBeam.php [52-70]

    -if (count($claims)) {
    -    $wallet->firstOrStore(['public_key' => $data['wallet_public_key']]);
    -    $isPackUpdated = false;
    -    DB::beginTransaction();
    -    foreach ($claims as $claim) {
    -        $claim->forceFill($this->buildBeamClaimAttributes($batch, $claim))->save();
    -        Log::info('ClaimBeamJob: Claim assigned.', $claim->toArray());
    -        if ($claim->beamPack && Arr::get($this->data, 'is_pack') && ! $isPackUpdated) {
    -            $claim->beamPack->update(['is_claimed' => true]);
    -            $isPackUpdated = true;
    -        }
    -    }
    -    BeamScan::firstWhere(['wallet_public_key' => $data['wallet_public_key'], 'beam_id' => $data['beam']['id']])?->delete();
    -    DB::commit();
    -} else {
    +if (!count($claims)) {
         Cache::put(BeamService::key(Arr::get($data, 'beam.code')), 0);
         Log::info('ClaimBeamJob: No claim available, setting remaining count to 0', $data);
    +    return;
     }
    +$wallet->firstOrStore(['public_key' => $data['wallet_public_key']]);
    +$isPackUpdated = false;
    +DB::beginTransaction();
    +foreach ($claims as $claim) {
    +    $claim->forceFill($this->buildBeamClaimAttributes(batch, $claim))->save();
    +    Log::info('ClaimBeamJob: Claim assigned.', $claim->toArray());
    +    if ($claim->beamPack && Arr::get($this->data, 'is_pack') && ! $isPackUpdated) {
    +        $claim->beamPack->update(['is_claimed' => true]);
    +        $isPackUpdated = true;
    +    }
    +}
    +BeamScan::firstWhere(['wallet_public_key' => $data['wallet_public_key'], 'beam_id' => $data['beam']['id']])?->delete();
    +DB::commit();
     
    Suggestion importance[1-10]: 9

    Why: This refactoring reduces the complexity of the nested if statements and improves readability by using early returns.

    9
    Refactor ternary operation to if-else structure for better readability

    Refactor the ternary operation to a more readable format using an if-else structure
    to enhance code readability and maintainability.

    src/GraphQL/Queries/GetSingleUseCodesQuery.php [67-73]

    -return ($beam->is_pack ? new BeamPack() : new BeamClaim())
    +if ($beam->is_pack) {
    +    $model = new BeamPack();
    +} else {
    +    $model = new BeamClaim();
    +}
    +return $model
         ->loadSelectFields($resolveInfo, $this->name)
         ->hasCode($args['code'])
         ->where('nonce', 1)
         ->with('beam')
         ->claimable()
         ->cursorPaginateWithTotalDesc('id', $args['first']);
     
    Suggestion importance[1-10]: 7

    Why: The refactoring improves code readability and maintainability, making it easier for future developers to understand and modify the code.

    7
    Best practice
    Set a default value for the 'nonce' column in the 'beam_packs' table

    It's recommended to set a default value for the 'nonce' column in the 'beam_packs'
    table to ensure that it always has a valid integer value, even if not explicitly set
    during the creation of a record.

    database/migrations/2024_08_01_041409_beam_packs.php [21]

    -$table->unsignedInteger('nonce')->nullable();
    +$table->unsignedInteger('nonce')->default(0)->nullable();
     
    Suggestion importance[1-10]: 8

    Why: Setting a default value for the 'nonce' column ensures that it always has a valid integer value, which is a good practice to prevent potential issues with null values.

    8
    Use or create a more specific exception type for clarity and better error handling

    Use a more specific exception type or create a custom exception class for better
    error handling and to provide more context about the error.

    src/Jobs/ClaimBeam.php [122]

    -throw new BeamException('No available packs to claim.');
    +throw new NoAvailablePacksException('No available packs to claim.');
     
    Suggestion importance[1-10]: 6

    Why: Using a more specific exception type can improve error handling and provide more context, but it requires the creation of a new exception class.

    6

    src/Services/BeamService.php Outdated Show resolved Hide resolved
    src/GraphQL/Unions/ClaimUnion.php Outdated Show resolved Hide resolved
    src/GraphQL/Types/BeamPackType.php Outdated Show resolved Hide resolved
    src/GraphQL/Traits/HasTokenInputRules.php Outdated Show resolved Hide resolved
    src/GraphQL/Types/Input/BeamPackInputType.php Outdated Show resolved Hide resolved
    @leonardocustodio
    Copy link
    Contributor

    Should this one go in this release?

    @enjinabner
    Copy link
    Contributor Author

    Should this one go in this release?

    I think this can wait

    @enjinabner enjinabner merged commit 1f52d52 into master Nov 6, 2024
    7 checks passed
    @enjinabner enjinabner deleted the feature/pla-1872/beam-pack-feature branch November 6, 2024 00:45
    Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
    Labels
    documentation Improvements or additions to documentation enhancement New feature or request Review effort [1-5]: 4 tests
    Development

    Successfully merging this pull request may close these issues.

    3 participants