Skip to content

Collection camp code bug#1594

Open
tarunnjoshi wants to merge 1 commit intodevfrom
collection-camp-code-bug
Open

Collection camp code bug#1594
tarunnjoshi wants to merge 1 commit intodevfrom
collection-camp-code-bug

Conversation

@tarunnjoshi
Copy link
Copy Markdown
Member

@tarunnjoshi tarunnjoshi commented Mar 13, 2026

Collection camp code bug

Summary by CodeRabbit

Release Notes

  • Refactor
    • Improved event code derivation logic with enhanced validation guards.
    • Enhanced logging and error handling for collection data processing.
    • Updated title generation format to incorporate year, state code, event code, and source ID.
    • Title updates are now logged for tracking purposes but no longer persisted.

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Mar 13, 2026

Walkthrough

This PR refactors the CollectionSource trait's event code derivation logic to shift from title-based lookups to sourceTypeName/subtypeId-based approaches, removes title persistence to the database, and enhances observability through CiviCRM logger calls.

Changes

Cohort / File(s) Summary
CollectionSource Event Code Refactoring
wp-content/civi-extensions/goonjcustom/Civi/Traits/CollectionSource.php
Restructures event code derivation from title-based to subtypeId-based approach; removes EckEntity database update call; replaces legacy logging with CiviCRM logger (debug/info levels); adds guard logging for abort paths (missing stateId, stateProvince, stateAbbreviation); builds newTitle as year/stateCode/eventCode/sourceId pattern.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested labels

status : ready for review

Suggested reviewers

  • pokhiii

Poem

🔄 From titles to subtypes, the logic takes flight,
Event codes now fresher, the path burning bright,
Logs dance through CiviCRM, no DB persist,
Clean derivation logic—a refactor you'll miss! 📝✨

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Title check ❓ Inconclusive The title 'Collection camp code bug' is vague and does not clearly describe the specific changes made, such as logger migration, event code derivation logic rework, or title construction changes. Use a more specific title that describes the main change, such as 'Refactor collection camp code generation with logger migration' or 'Fix collection camp code derivation logic'.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch collection-camp-code-bug
📝 Coding Plan
  • Generate coding plan for human review comments

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Tip

CodeRabbit can scan for known vulnerabilities in your dependencies using OSV Scanner.

OSV Scanner will automatically detect and report security vulnerabilities in your project's dependencies. No additional configuration is required.

@claude
Copy link
Copy Markdown

claude bot commented Mar 13, 2026

Code Review Summary

Critical Issues

[CollectionSource.php:162] The code no longer saves the generated camp code to the database. The previous implementation had:

EckEntity::update('Collection_Camp')
  ->addWhere('id', '=', $sourceId)
  ->addValue('title', $newTitle)
  ->execute();

This has been removed. While $objectRef['title'] = $newTitle modifies the reference, this may not persist to the database depending on how CiviCRM's hook system handles object references. This could result in camp codes being generated but not saved.

Suggestions

[CollectionSource.php:156] The logic change from using $sourceTitle (the current camp title) to $sourceTypeName (derived from subtype) for event code lookup may cause issues if existing camps rely on the title-based matching. Consider verifying that:

  • All existing camp titles match their subtype names (with underscores replaced by spaces)
  • The event_codes config array has entries that match the transformed subtype names

[CollectionSource.php:158] The debug log includes all intermediate variables ($sourceTypeName, $sourceTypeTitle, $eventCode). While this improves debugging, consider if this level of detail is necessary in production or if it should be behind a more verbose logging level.

What Looks Good

  • ✅ Excellent improvement replacing error_log() with structured \Civi::log() calls
  • ✅ Better structured context arrays in log messages make debugging much easier
  • ✅ Added helpful abort messages when data is missing (lines 134, 143, 149)
  • ✅ Removed unnecessary comments that just restated the code
  • ✅ Cleaner variable naming with $collectionSourceCreatedDate logging as createdDate
  • ✅ Good use of log levels (debug for flow, info for significant events)
  • ✅ Using [CodeGen] prefix consistently for easy log filtering

Required Action

Please restore the database save operation or confirm that $objectRef modifications persist automatically in this CiviCRM hook context.

Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@wp-content/civi-extensions/goonjcustom/Civi/Traits/CollectionSource.php`:
- Around line 160-164: The generated title stored into $objectRef['title'] in
the CollectionSource trait is only an in-memory change for the after-write hook
and is not persisted; update the DB explicitly after generating $newTitle (use
the record id from $objectRef['id']) so Collection_Camp.title is saved (e.g.,
call the appropriate API/DAO update for the Collection_Camp entity rather than
just mutating $objectRef), ensure you check the id exists and log/report any
update errors alongside the existing \Civi::log() calls.
- Around line 155-158: The mapping lookup for event codes can return 'UNKNOWN'
and the code continues, which can corrupt downstream identifiers; in the block
using getSourceTypeName($subtypeId) and $config['event_codes'], validate that
$config['event_codes'][$sourceTypeTitle] exists and is not empty before
proceeding—if missing, abort generation by throwing an exception or returning an
error (do not silently set $eventCode = 'UNKNOWN'), and log a clear error
including $sourceTypeName/$sourceTypeTitle to help debugging.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 2eff2d9d-ee7a-4fa2-81ac-5a60c99adc09

📥 Commits

Reviewing files that changed from the base of the PR and between 5cf8d5c and 24def2a.

📒 Files selected for processing (1)
  • wp-content/civi-extensions/goonjcustom/Civi/Traits/CollectionSource.php

Comment on lines +155 to +158
$sourceTypeName = self::getSourceTypeName($subtypeId);
$sourceTypeTitle = str_replace('_', ' ', $sourceTypeName);
$eventCode = $config['event_codes'][$sourceTypeTitle] ?? 'UNKNOWN';
\Civi::log()->debug('[CodeGen] eventCode', ['sourceTypeName' => $sourceTypeName, 'sourceTypeTitle' => $sourceTypeTitle, 'eventCode' => $eventCode]);
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Avoid silently generating event codes with UNKNOWN.

If subtype-to-event mapping fails, the code still proceeds and produces a title with UNKNOWN, which can corrupt identifier semantics downstream. Abort generation when mapping is missing.

Suggested hardening
-        $sourceTypeName = self::getSourceTypeName($subtypeId);
-        $sourceTypeTitle = str_replace('_', ' ', $sourceTypeName);
-        $eventCode = $config['event_codes'][$sourceTypeTitle] ?? 'UNKNOWN';
-        \Civi::log()->debug('[CodeGen] eventCode', ['sourceTypeName' => $sourceTypeName, 'sourceTypeTitle' => $sourceTypeTitle, 'eventCode' => $eventCode]);
+        $sourceTypeName = self::getSourceTypeName((string) $subtypeId);
+        if (!$sourceTypeName) {
+          \Civi::log()->debug('[CodeGen] Aborting: sourceTypeName missing', ['subtypeId' => $subtypeId]);
+          return;
+        }
+        $sourceTypeTitle = str_replace('_', ' ', $sourceTypeName);
+        $eventCode = $config['event_codes'][$sourceTypeTitle] ?? NULL;
+        if (!$eventCode) {
+          \Civi::log()->debug('[CodeGen] Aborting: eventCode mapping missing', ['sourceTypeTitle' => $sourceTypeTitle]);
+          return;
+        }
+        \Civi::log()->debug('[CodeGen] eventCode', ['sourceTypeName' => $sourceTypeName, 'sourceTypeTitle' => $sourceTypeTitle, 'eventCode' => $eventCode]);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@wp-content/civi-extensions/goonjcustom/Civi/Traits/CollectionSource.php`
around lines 155 - 158, The mapping lookup for event codes can return 'UNKNOWN'
and the code continues, which can corrupt downstream identifiers; in the block
using getSourceTypeName($subtypeId) and $config['event_codes'], validate that
$config['event_codes'][$sourceTypeTitle] exists and is not empty before
proceeding—if missing, abort generation by throwing an exception or returning an
error (do not silently set $eventCode = 'UNKNOWN'), and log a clear error
including $sourceTypeName/$sourceTypeTitle to help debugging.

Comment on lines 160 to +164
$newTitle = $year . '/' . $stateCode . '/' . $eventCode . '/' . $sourceId;
error_log('newTitle:' . print_r($newTitle, TRUE));
\Civi::log()->info('[CodeGen] newTitle', ['newTitle' => $newTitle]);
$objectRef['title'] = $newTitle;

// Save the updated title back to the Collection Camp entity.
EckEntity::update('Collection_Camp')
->addWhere('id', '=', $sourceId)
->addValue('title', $newTitle)
->execute();
\Civi::log()->info('[CodeGen] Camp code generated', ['sourceId' => $sourceId, 'newTitle' => $newTitle]);
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

Generated title is not persisted in an after-write hook.

Line 162 only mutates $objectRef['title']. Since this hook runs after DB write, the generated code is unlikely to be saved to Collection_Camp.title unless explicitly updated.

Suggested persistence fix
         $newTitle = $year . '/' . $stateCode . '/' . $eventCode . '/' . $sourceId;
         \Civi::log()->info('[CodeGen] newTitle', ['newTitle' => $newTitle]);
         $objectRef['title'] = $newTitle;
+        if (($sourceTitle ?? NULL) !== $newTitle) {
+          EckEntity::update('Collection_Camp', FALSE)
+            ->addValue('title', $newTitle)
+            ->addWhere('id', '=', $sourceId)
+            ->execute();
+        }
 
         \Civi::log()->info('[CodeGen] Camp code generated', ['sourceId' => $sourceId, 'newTitle' => $newTitle]);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@wp-content/civi-extensions/goonjcustom/Civi/Traits/CollectionSource.php`
around lines 160 - 164, The generated title stored into $objectRef['title'] in
the CollectionSource trait is only an in-memory change for the after-write hook
and is not persisted; update the DB explicitly after generating $newTitle (use
the record id from $objectRef['id']) so Collection_Camp.title is saved (e.g.,
call the appropriate API/DAO update for the Collection_Camp entity rather than
just mutating $objectRef), ensure you check the id exists and log/report any
update errors alongside the existing \Civi::log() calls.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant