Skip to content

New QR code with more details#1402

Closed
tarunnjoshi wants to merge 1 commit intodevfrom
new-qr-code-with-details
Closed

New QR code with more details#1402
tarunnjoshi wants to merge 1 commit intodevfrom
new-qr-code-with-details

Conversation

@tarunnjoshi
Copy link
Copy Markdown
Member

@tarunnjoshi tarunnjoshi commented Aug 29, 2025

New QR code with more details

Summary by CodeRabbit

  • New Features
    • QR codes are now generated as branded images with a centered logo and caption for clearer recognition and a polished look.
    • Camp pages now auto-redirect: after a camp ends (with a short grace period), visitors are sent to the main site; active camps continue to open normally.
    • Improved reliability when generating and saving QR codes, with better handling of failures.

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Aug 29, 2025

Walkthrough

The QrCodeable trait’s generateQrCode now composes a new PNG by layering a resized external logo, the QR image, and caption text, then saves the composite. A new static method handleCampRedirect($id) determines redirect target based on camp end date (+3 days) and performs a redirect; imports for EckEntity were added.

Changes

Cohort / File(s) Summary
QrCodeable trait updates
wp-content/civi-extensions/goonjcustom/Civi/Traits/QrCodeable.php
- generateQrCode: decodes QR PNG, loads external logo, resizes (scale 0.4), composites logo+QR+caption on a new GD canvas, saves composite via saveQrCode; preserves try/catch and logging.
- Adds public static handleCampRedirect($id): loads Collection_Camp via EckEntity, reads End_Date from Collection_Camp_Intent_Details, if past End_Date+3 days redirect to https://goonj.org/, else redirect to standard camp URL; logs and redirects via CRM_Utils_System::redirect.
- Adds EckEntity import.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant Svc as Caller Service
  participant Q as QrCodeable::generateQrCode
  participant GD as GD Library
  participant IO as saveQrCode

  Svc->>Q: generateQrCode(data, saveOptions)
  Q->>GD: Decode QR PNG to image
  Q->>GD: Load external logo (URL)
  Q->>GD: Resize logo (scale ≈ 0.4 of QR)
  Q->>GD: Create canvas, compose logo+QR
  Q->>GD: Draw caption text
  Q->>IO: saveQrCode(finalImage, saveOptions)
  IO-->>Q: Success/Exception
  Q-->>Svc: TRUE on success / FALSE on error
  note over Q,GD: Errors logged via try/catch
Loading
sequenceDiagram
  autonumber
  participant UI as Request / Router
  participant Q as QrCodeable::handleCampRedirect(id)
  participant E as EckEntity
  participant SYS as CRM_Utils_System

  UI->>Q: handleCampRedirect(id)
  Q->>E: Fetch Collection_Camp by id
  E-->>Q: Camp + Intent_Details (End_Date)
  alt End_Date exists and today > End_Date+3
    Q->>SYS: redirect("https://goonj.org/")
  else
    Q->>SYS: redirect("{baseURL}/actions/collection-camp/{id}")
  end
  note over Q: Logs errors if exceptions occur
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested labels

status : ready for review

Suggested reviewers

  • pokhiii

Poem

A QR learns new tricks today,
Logo perched above in grand display.
A caption whispers where to go,
Camps now guide with date-bound flow.
If time has passed, to home we steer—
Pixels, paths, and purpose clear.

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch new-qr-code-with-details

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
🪧 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>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbit in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbit 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:
    • @coderabbit gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbit read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbit help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbit ignore or @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbit summary or @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbit or @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
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: 5

🧹 Nitpick comments (4)
wp-content/civi-extensions/goonjcustom/Civi/Traits/QrCodeable.php (4)

49-53: Magic number + emoji comment; make logo scale configurable and clamp.

Hard-coded 0.4 hurts reuse; clamp to sane bounds.

-      $scaleFactor = 0.4; // 👈 change this (0.5 = 50% width, 0.3 = 30% width, etc.)
+      $scaleFactor = (float)($saveOptions['logoScale'] ?? 0.4);
+      $scaleFactor = max(0.1, min($scaleFactor, 0.8));

69-75: Canvas alpha not preserved.

If logo has transparency, enable alpha for canvas.

-      $canvas = imagecreatetruecolor($qrWidth, $canvasHeight);
+      $canvas = imagecreatetruecolor($qrWidth, $canvasHeight);
+      imagealphablending($canvas, false);
+      imagesavealpha($canvas, true);

89-97: Compression level not specified; minor size win possible.

Set PNG compression (0–9). Default is 6; consider 9.

-      imagepng($canvas);
+      imagepng($canvas, null, 9);

116-150: Remove debug prints; use Civi logging only on errors.

error_log() lines are noisy and some are unreachable.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 5284f6c and b410158.

📒 Files selected for processing (1)
  • wp-content/civi-extensions/goonjcustom/Civi/Traits/QrCodeable.php (2 hunks)
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: belwalshubham
PR: ColoredCow/goonj#284
File: wp-content/civi-extensions/goonjcustom/Civi/CollectionCampService.php:520-520
Timestamp: 2024-10-11T09:53:14.458Z
Learning: In `wp-content/civi-extensions/goonjcustom/Civi/CollectionCampService.php`, it's acceptable that the `reGenerateCollectionCampQr` method calls `generateQrCode` with only the `$collectionCampId` parameter, as QR codes are generated when the Dropping Center is authorized. We'll implement changes if any issues arise in the future.
📚 Learning: 2024-10-11T09:53:14.458Z
Learnt from: belwalshubham
PR: ColoredCow/goonj#284
File: wp-content/civi-extensions/goonjcustom/Civi/CollectionCampService.php:520-520
Timestamp: 2024-10-11T09:53:14.458Z
Learning: In `wp-content/civi-extensions/goonjcustom/Civi/CollectionCampService.php`, it's acceptable that the `reGenerateCollectionCampQr` method calls `generateQrCode` with only the `$collectionCampId` parameter, as QR codes are generated when the Dropping Center is authorized. We'll implement changes if any issues arise in the future.

Applied to files:

  • wp-content/civi-extensions/goonjcustom/Civi/Traits/QrCodeable.php
🔇 Additional comments (4)
wp-content/civi-extensions/goonjcustom/Civi/Traits/QrCodeable.php (4)

76-81: Unconditional logo copy can warn when logo failed to load.

Guard copy when $logoImage/$resizedLogo exist; otherwise set $newLogoHeight=0 and skip.

Please ensure the code branches correctly when logo fetch fails after applying the earlier guard. I can supply a follow-up diff once you confirm desired fallback (QR-only vs. hard-fail).


22-29: QR config choices: low ECC and fixed version may harm scan robustness.

Consider ECC_M or ECC_Q and let version auto-size unless you have strict size constraints.

Would you like me to propose data-driven defaults (auto version, ECC_M, scale derived from target pixel size)?


31-38: QR binary is mishandled (base64 decode likely corrupts image).

QRCode::render(OUTPUT_IMAGE_PNG) already returns PNG bytes. Stripping a data URI and base64_decoding will break binary and can make imagecreatefromstring() fail.

Apply:

-      // Generate QR as PNG binary
-      $qrcode = (new QRCode($options))->render($data);
-      $qrcode = str_replace('data:image/png;base64,', '', $qrcode);
-      $qrcode = base64_decode($qrcode);
+      // Generate QR as PNG binary
+      $qrcodeBinary = (new QRCode($options))->render($data);

And below:

-      $qrImage = imagecreatefromstring($qrcode);
+      $qrImage = imagecreatefromstring($qrcodeBinary);
+      if ($qrImage === false) {
+        throw new \RuntimeException('Failed to create QR GD image');
+      }
⛔ Skipped due to learnings
Learnt from: belwalshubham
PR: ColoredCow/goonj#352
File: wp-content/civi-extensions/goonjcustom/Civi/QrCodeService.php:51-53
Timestamp: 2024-10-09T15:24:42.859Z
Learning: In `QrCodeService::generateQrCode`, when using `QRCode::OUTPUT_IMAGE_PNG`, the `render` method returns a data URI with base64-encoded image data. Therefore, it's necessary to remove the `data:image/png;base64,` prefix and base64-decode the data to obtain the raw binary image.

98-103: All generateQrCode callers include customGroupName and customFieldName in their $saveOptions; no action required.

Comment on lines +41 to +47
// --- Step 2: Load logo image (from URL) ---
$logoUrl = "https://goonj.org/wp-content/uploads/2020/06/Goonj-logo-10June20.png";
$logoData = file_get_contents($logoUrl);
$logoImage = imagecreatefromstring($logoData);

$logoWidth = imagesx($logoImage);
$logoHeight = imagesy($logoImage);
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Remote logo fetch without timeout/validation; hard external dependency.

Network I/O on hot path + no timeout/error handling. Prefer a bundled/local asset or make URL configurable; at minimum add a short timeout and validate GD resource creation.

-      $logoUrl = "https://goonj.org/wp-content/uploads/2020/06/Goonj-logo-10June20.png";
-      $logoData = file_get_contents($logoUrl);
-      $logoImage = imagecreatefromstring($logoData);
+      $logoUrl = $saveOptions['logoUrl'] ?? "https://goonj.org/wp-content/uploads/2020/06/Goonj-logo-10June20.png";
+      $ctx = stream_context_create([
+        'http' => ['timeout' => 4],
+        'ssl'  => ['verify_peer' => true, 'verify_peer_name' => true],
+      ]);
+      $logoData = @file_get_contents($logoUrl, false, $ctx);
+      if ($logoData === false) {
+        \CRM_Core_Error::debug_log_message('QR: logo fetch failed, proceeding without logo.');
+      }
+      $logoImage = $logoData ? @imagecreatefromstring($logoData) : false;
+      if ($logoImage === false) {
+        // proceed without logo
+        $logoWidth = $logoHeight = 0;
+      }

Note: If you keep logo optional, guard all subsequent logo math/copies accordingly.

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +65 to +71
// --- Step 3: Create new canvas (logo + QR + text space) ---
$text = "Hello here is the qr code";
$fontHeight = 30; // reserve space for text

$canvasHeight = $newLogoHeight + $qrHeight + $fontHeight + 20;
$canvas = imagecreatetruecolor($qrWidth, $canvasHeight);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Placeholder caption, no i18n, incorrect text metrics.

Use configurable caption, compute font metrics with imagefont* to center, and only reserve space when text is non-empty.

-      $text = "Hello here is the qr code";
-      $fontHeight = 30; // reserve space for text
+      $text = (string)($saveOptions['caption'] ?? '');
+      $font = 5; // GD built-in font index
+      $fontHeight = $text !== '' ? imagefontheight($font) : 0;
+      $textWidth  = $text !== '' ? imagefontwidth($font) * strlen($text) : 0;
@@
-      $canvasHeight = $newLogoHeight + $qrHeight + $fontHeight + 20;
+      $extra = $text !== '' ? ($fontHeight + 20) : 0;
+      $canvasHeight = $newLogoHeight + $qrHeight + $extra;
@@
-      $black = imagecolorallocate($canvas, 0, 0, 0);
-      $x = 10;
-      $y = $newLogoHeight + $qrHeight + 20;
-      imagestring($canvas, 5, $x, $y, $text, $black);
+      if ($text !== '') {
+        $black = imagecolorallocate($canvas, 0, 0, 0);
+        $x = max(0, (int)(($qrWidth - $textWidth) / 2));
+        $y = $newLogoHeight + $qrHeight + 10;
+        imagestring($canvas, $font, $x, $y, $text, $black);
+      }

Also consider translating caption via ts()/E::ts().

Also applies to: 82-87

Comment on lines 98 to +103
$baseFileName = "qr_code_{$entityId}.png";

$saveOptions['baseFileName'] = $baseFileName;
$saveOptions['entityId'] = $entityId;

self::saveQrCode($qrcode, $saveOptions);
}
catch (\Exception $e) {
self::saveQrCode($finalImage, $saveOptions);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Ignoring save result; generateQrCode returns TRUE even if save fails.

Propagate failure from saveQrCode.

-      self::saveQrCode($finalImage, $saveOptions);
+      $attachment = self::saveQrCode($finalImage, $saveOptions);
+      if ($attachment === FALSE) {
+        throw new \RuntimeException('Failed to save QR attachment');
+      }
📝 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. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
$baseFileName = "qr_code_{$entityId}.png";
$saveOptions['baseFileName'] = $baseFileName;
$saveOptions['entityId'] = $entityId;
self::saveQrCode($qrcode, $saveOptions);
}
catch (\Exception $e) {
self::saveQrCode($finalImage, $saveOptions);
$baseFileName = "qr_code_{$entityId}.png";
$saveOptions['baseFileName'] = $baseFileName;
$saveOptions['entityId'] = $entityId;
$attachment = self::saveQrCode($finalImage, $saveOptions);
if ($attachment === FALSE) {
throw new \RuntimeException('Failed to save QR attachment');
}
🤖 Prompt for AI Agents
In wp-content/civi-extensions/goonjcustom/Civi/Traits/QrCodeable.php around
lines 98 to 103, the code calls self::saveQrCode($finalImage, $saveOptions) but
ignores its return value so generateQrCode can return true even when saving
fails; capture the boolean result of saveQrCode, and if it returns false
propagate that failure by returning false (or throwing the existing error path)
from generateQrCode so callers receive the real outcome.

Comment on lines +104 to 107
} catch (\Exception $e) {
\CRM_Core_Error::debug_log_message('Error generating QR code: ' . $e->getMessage());
return FALSE;
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Catch broader throwables; log with context.

Catching only \Exception misses \Error. Use \Throwable and include entityId.

-    } catch (\Exception $e) {
-      \CRM_Core_Error::debug_log_message('Error generating QR code: ' . $e->getMessage());
+    } catch (\Throwable $e) {
+      \CRM_Core_Error::debug_log_message('Error generating QR code for entityId '
+        . ($saveOptions['entityId'] ?? 'unknown') . ': ' . $e->getMessage());
       return FALSE;
     }
📝 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. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
} catch (\Exception $e) {
\CRM_Core_Error::debug_log_message('Error generating QR code: ' . $e->getMessage());
return FALSE;
}
} catch (\Throwable $e) {
\CRM_Core_Error::debug_log_message('Error generating QR code for entityId '
. ($saveOptions['entityId'] ?? 'unknown') . ': ' . $e->getMessage());
return FALSE;
}
🤖 Prompt for AI Agents
In wp-content/civi-extensions/goonjcustom/Civi/Traits/QrCodeable.php around
lines 104 to 107, the catch currently only handles \Exception and logs the error
message without context; change the catch to handle \Throwable instead of
\Exception and update the debug log to include the relevant entityId (or other
identifying variable in scope) along with the throwable message (and optionally
trace) so the log reads something like "Error generating QR code for
entityId=<id>: <message>" to ensure Errors are captured and the log contains
entity context.

Comment on lines +116 to +150
public static function handleCampRedirect($id) {
$camp = EckEntity::get('Collection_Camp', TRUE)
->addSelect('Collection_Camp_Intent_Details.End_Date')
->addWhere('id', '=', $id)
->execute()
->first();

error_log("data: " . print_r($camp, TRUE));

$endRaw = $camp['Collection_Camp_Intent_Details.End_Date'] ?? NULL;
error_log("endRaw: " . print_r($endRaw, TRUE));

if ($endRaw) {
$endDate = new \DateTime($endRaw);
$endDate->modify('+3 days');
$today = new \DateTime();

if ($today > $endDate) {
error_log("working");

// Redirect to goonj.org after end+3 days.
\CRM_Utils_System::redirect('https://goonj.org/');
error_log("is redirect??: ");

return;

error_log("Checking ??: ");

}
}

// Otherwise normal camp page.
$baseUrl = \CRM_Core_Config::singleton()->userFrameworkBaseURL;
\CRM_Utils_System::redirect("{$baseUrl}actions/collection-camp/{$id}");
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Redirect logic does not belong in this trait; remove debug noise and fix date/time handling.

SRP violation (QR trait doing HTTP redirects), noisy error_log(), timezone-sensitive comparison, and missing null checks on $camp. Suggest moving to a controller/service; meanwhile, fix logic.

-  public static function handleCampRedirect($id) {
-    $camp = EckEntity::get('Collection_Camp', TRUE)
-      ->addSelect('Collection_Camp_Intent_Details.End_Date')
-      ->addWhere('id', '=', $id)
-      ->execute()
-      ->first();
-
-    error_log("data: " . print_r($camp, TRUE));
-
-    $endRaw = $camp['Collection_Camp_Intent_Details.End_Date'] ?? NULL;
-    error_log("endRaw: " . print_r($endRaw, TRUE));
-
-    if ($endRaw) {
-      $endDate = new \DateTime($endRaw);
-      $endDate->modify('+3 days');
-      $today = new \DateTime();
-
-      if ($today > $endDate) {
-    error_log("working");
-
-        // Redirect to goonj.org after end+3 days.
-        \CRM_Utils_System::redirect('https://goonj.org/');
-        error_log("is redirect??: ");
-
-        return;
-
-        error_log("Checking ??: ");
-
-      }
-    }
-
-    // Otherwise normal camp page.
-    $baseUrl = \CRM_Core_Config::singleton()->userFrameworkBaseURL;
-    \CRM_Utils_System::redirect("{$baseUrl}actions/collection-camp/{$id}");
-  }
+  public static function handleCampRedirect($id) {
+    $id = (int)$id;
+    $camp = EckEntity::get('Collection_Camp', true)
+      ->addSelect('Collection_Camp_Intent_Details.End_Date')
+      ->addWhere('id', '=', $id)
+      ->setLimit(1)
+      ->execute()
+      ->first();
+
+    $endRaw = is_array($camp) ? ($camp['Collection_Camp_Intent_Details.End_Date'] ?? null) : null;
+    $tz     = new \DateTimeZone('Asia/Kolkata'); // align with org TZ if different
+
+    if ($endRaw) {
+      $endDate   = new \DateTime($endRaw, $tz);
+      $threshold = (clone $endDate)->modify('+3 days')->setTime(23, 59, 59);
+      $today     = new \DateTime('now', $tz);
+
+      if ($today > $threshold) {
+        \CRM_Utils_System::redirect('https://goonj.org/');
+        return;
+      }
+    }
+
+    $baseUrl = rtrim(\CRM_Core_Config::singleton()->userFrameworkBaseURL, '/');
+    \CRM_Utils_System::redirect("{$baseUrl}/actions/collection-camp/{$id}");
+  }

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In wp-content/civi-extensions/goonjcustom/Civi/Traits/QrCodeable.php around
lines 116 to 150, the trait currently performs HTTP redirects and leaves noisy
error_log() calls and fragile date handling; change it to be SRP-compliant by
removing all redirects and debug logging, add a null-check for $camp before
accessing the end date, parse the end date into a DateTimeImmutable with an
explicit timezone (e.g. from config or UTC), add 3 days with add(new
DateInterval('P3D')) and compare using DateTimeImmutable instances, and return a
simple status (e.g. boolean or enum: 'redirect_to_goonj' / 'show_camp') so a
controller/service can perform the actual redirect; keep the method lightweight
and side-effect free and document the return values.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant