Skip to content

KNA-3366/feat: Basic tests and general order logic improvements#23

Open
SalmanTwo wants to merge 18 commits intostagingfrom
shabib/kna-3366-plugin-tests-for-presta-shop-and-improvements
Open

KNA-3366/feat: Basic tests and general order logic improvements#23
SalmanTwo wants to merge 18 commits intostagingfrom
shabib/kna-3366-plugin-tests-for-presta-shop-and-improvements

Conversation

@SalmanTwo
Copy link
Contributor

No description provided.

@gemini-code-assist
Copy link

Summary of Changes

Hello @SalmanTwo, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly refactors the payment module's order processing to adopt a provider-first checkout flow, enhancing robustness and preventing issues like phantom orders. It introduces a new mechanism to track checkout attempts, ensuring idempotency and consistency by validating cart snapshots and using unique keys for order creation. The changes also include substantial improvements to tax calculation accuracy, error handling, and the addition of a dedicated test suite to ensure the reliability of critical payment logic.

Highlights

  • Provider-First Checkout Flow: The module now creates the external payment provider's order before creating the local PrestaShop order, preventing phantom orders and improving checkout robustness.
  • Checkout Attempt Persistence: A new twopayment_attempt database table tracks checkout attempts, storing metadata like cart snapshots and idempotency keys for reliable callback handling and retries.
  • Enhanced Tax Calculation Accuracy: Tax rates are now serialized with higher precision, and product tax rate selection prioritizes applied PrestaShop amounts for greater accuracy.
  • Comprehensive Test Suite: A new test harness with PHPUnit and a custom offline runner has been added to validate critical order building, tax logic, and callback authorization.
Changelog
  • CHANGELOG.md
    • Updated the changelog to include version 2.4.0, detailing new features, changes, and technical improvements.
  • README.md
    • Updated the module's feature list and clarified the order confirmation flow to reflect the provider-first approach.
  • composer.json
    • Added a new Composer configuration file for development dependencies, specifically PHPUnit.
  • config.xml
    • Updated the module version to 2.4.0.
  • controllers/front/cancel.php
    • Refactored the cancellation logic to support attempt_token for provider-first flow, including authorization checks and Two order cancellation, while retaining legacy id_order handling.
  • controllers/front/confirmation.php
    • Refactored the confirmation logic to support attempt_token for provider-first flow, including cart snapshot validation, local order creation after Two verification, and merchant_order_id alignment, while retaining legacy id_order handling.
  • controllers/front/orderintent.php
    • Modified rate limiting to use cookies instead of session for better compatibility and added country validation for session company data.
  • controllers/front/payment.php
    • Implemented the provider-first checkout flow, creating a Two order first and persisting attempt data, then redirecting for verification or handling immediate errors without creating a local PrestaShop order. Also added cleanup for stale attempts.
  • override/classes/form/CustomerAddressFormatter.php
    • Changed the type of the address2 field from 'number' to 'text' in address formatting.
  • package-release.sh
    • Added a new shell script for automating the module release packaging process, including version extraction and file exclusion.
  • phpunit.xml.dist
    • Added a new PHPUnit configuration file for running tests.
  • tests/OrderBuilderTest.php
    • Added new PHPUnit tests for order builder logic, tax calculations, snapshot hashing, and callback authorization.
  • tests/README.md
    • Added a README file for the test suite, explaining its coverage and how to run tests.
  • tests/bootstrap.php
    • Added a new bootstrap file for the test environment, including stub classes for PrestaShop components.
  • tests/run.php
    • Added a new script for running offline deterministic tests without PHPUnit.
  • twopayment.php
    • Added new constants for tax rate precision, variance tolerance, and checkout attempt retention/cleanup.
    • Updated module version to 2.4.0.
    • Modified createTwoTables to include twopayment_attempt table.
    • Updated logging for API responses to use a redacted summary.
    • Conditionalized jQuery CDN fallback for legacy PrestaShop versions.
    • Added strict line-item formula validation before building order payloads.
    • Refactored getTwoNewOrderData to accept merchant_order_id and merchant_urls for provider-first flow, and calculate order-level tax rate.
    • Refined getTwoProductItems to prioritize applied tax rates and serialize tax rates with higher precision, and handle empty barcodes.
    • Introduced getTwoValidatedSessionCompanyData to validate session company data against the current country.
    • Added formatTwoTaxRate and calculateTwoOrderTaxRate for precise tax handling.
    • Enhanced getTwoErrorMessage to better parse nested error messages and treat HTTP >= 400 as errors.
    • Added functions for generateTwoCheckoutAttemptToken, isTwoAttemptCallbackAuthorized, buildTwoMerchantOrderId, buildTwoOrderCreateIdempotencyKey, calculateTwoCheckoutSnapshotHash, buildTwoCheckoutSnapshot, normalizeSnapshotAmount, normalizeSnapshotRate, maybeCleanupStaleTwoCheckoutAttempts, setTwoCheckoutAttempt, getTwoCheckoutAttempt, updateTwoCheckoutAttemptStatus, linkTwoCheckoutAttemptToOrder, setTwoCheckoutAttemptMerchantOrderId, and getTwoOrderIdByCart to support the new provider-first flow and attempt persistence.
  • upgrade/upgrade-2.4.0.php
    • Added a new upgrade script to create and update the twopayment_attempt table and its columns/indexes.
  • views/js/modules/TwoCheckoutManager.js
    • Adjusted the reinitialization timeout and improved mutation observer handling to prevent multiple initializations.
  • views/js/twopayment.js
    • Added cleanup calls for TwoCheckoutManager_Instance on reinitialization and before page unload, and removed the redundant mutation observer.
Ignored Files
  • Ignored by pattern: .github/workflows/** (1)
    • .github/workflows/tests.yml
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request introduces significant improvements to the Two payment module, focusing on checkout flow robustness, security, and tax calculation accuracy. The major change is the move to a 'provider-first' checkout flow, where the PrestaShop order is created only after successful verification from the Two API. This eliminates issues with phantom orders on payment failure.

Key enhancements include:

  • A new twopayment_attempt table to track checkout attempts, enabling better idempotency and recovery.
  • Cart snapshot validation to prevent order creation if the cart changes after payment initiation.
  • Use of an X-Idempotency-Key header for order creation to prevent duplicate orders on retries.
  • Hardened tax calculation logic to ensure accuracy and API compliance.
  • More robust error message parsing from the Two API.
  • Improved session handling to prevent using stale company data across different countries.
  • A comprehensive test suite has been added using PHPUnit and a standalone runner, which is a fantastic addition for maintainability.

The code is well-structured and the changes significantly improve the module's quality. I have one suggestion regarding the termination of non-AJAX requests in a controller for improved clarity and safety.

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.

2 participants