Skip to content

[Bug]: Payment type stored as translated string breaks reports #3790

Open

Description

@objecttothis

Our current implementation of this column in the database is not stored as an enum but rather the localized text string of the sale type in the language that the sale payment was made in. In monolingual installs where each user uses the same language and the translation for that word never changes it's not that big of a deal, but the current implementation makes it near impossible to programmatically determine the type of payment without using string comparison functions or regex.

For example, if we want to do a report of each payment type showing the amount paid for each type, We are going to get a different amount for "кредитная карта" and "credit card" even though they are the same payment type, but one employee uses the Russian language interface and another the en-US. In my case I'm running into this because I have to send (via RESTful API calls) the payment amounts of each type which requires me to programmatically loop through each payment, determine the payment type and add it to the appropriate value to include in the JSON. Not only does the code for that look horrendous because of the string compares but all it will take is a translation to change or someone to use a new language and the integration is broken until I add that string.

I think the solution for this would be to use constants in the code and where the view needs to display the payment type, to run it through the CI translation engine based on the constant like we do everything else. Normally we would also need to change the column to a tiny int but to do that we would need to convert all existing sales_payments to their appropriate enum value... I'm not sure how to do this programmatically.

This brings up another problem. When the payment type is a Giftcard, a colon, space and the card number is appended to the payment_type field. While that information is helpful to store, the giftcard number should have its own column. Programatically, that conversion can be done fairly easily by any payment type that has a colon replacing it with the enum for giftcard and taking the number to the right of the colon and sticking it in the newly created giftcard_number column. Debit, Credit and Cash payment types would be more difficult though.

@jekkos do you have any thoughts on this?

Activity

  1. self-assigned this
    on Aug 4, 2023
  2. jekkos commented on Aug 5, 2023

    @jekkos
    Member

    Thanks for raising this @objecttothis . As you say it's indeed not good practice to store the payment types using their translated string as

    • the translation can change
    • the language in use might change.

    Changing this to an int column is indeed the solution here, but migrating the old data might be a bit of a challenge. What we should try then is map all database values with payment types to their correct int representation. In a first step it can be done by iterating over the key values in the $lang[] array for payment types, then do the value match, get the key from the match and map that to the int constant.

    But there is indeed a chance that the migration will not work if in the past translations for payment types were updated. We could go through git history programmatically to retrieve all strings a payment type was mapped to and use these as valid match occurrences. I think this can be scripted easily (iterate over revisions of a language file and extract the value from a key of that file version, and add it to a list in the migration script). If we have this then I think it will go fine 99% of the time. Sounds like a fun challenge.

    the giftcard number id suffix feels a bit like a hack to me. I think that we should model it explicitly indeed. Some logic on top of SQL in the migration script might be required to do this. Or perhaps an SQL case match might do the job here. In that case you can fill a column based on a match in another one, eg
    UPDATE ospos_payment_type SET giftcard_number (CASE WHEN Type LIKE '%:%' THEN SUBSTRING_INDEX(type, ':', -1); )

  3. objecttothis commented on Aug 5, 2023

    @objecttothis
    MemberAuthor

    @jekkos I think we can probably separate the work into two or three separate modules.

    • Parse out giftcard numbers into its own column in that table and rework the business logic to look there to assemble that string when needed rather than just display the payment_type field.
    • As you put it to find/replace all known strings with the enum value of their proper payment type. At the end of the replacement, I think it would be helpful to log any values that could not be determined and then we need to figure out some way of correcting those. If we are thorough, this should only happen when people manually modified a translation of a phrase that never got put into the repo or used a payment type not in the repo. Once the column has been converted to the enum values, we can retype the column to tinyint, but we need a rock-solid means of resolving conflicts. My vote is to fail that particular migration and log the rows that could not be translated to an enum then ask the user to correct their database since unsupported translations or payment types were used.

    In addition to the database changes via migration, we need to update the business logic to store the payment_type correctly, conduct any business logic related to it and to display it correctly.

    @jekkos as long as we can come up with an agreed upon solution, I don't mind taking this on. For now, in my 3.3.2 based production build I'm integrating API calls to the local government cash register and I'll just do a hack based on our database to determine the payment type. Then once we release 3.4.0 I will build a proper migration and rework the business logic in the CI4 framework.

  4. stale commented on Sep 17, 2023

    @stale

    This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

  5. added this to the 3.4.0 milestone on Sep 17, 2023
  6. modified the milestones: 3.4.0, 3.5.0 on Dec 12, 2023
  7. changed the title [-]ospos_sales_payments.payment_type stored as a translated string representing the sale type[/-] [+][Bug]: Payment type stored as translated string breaks reports[/+] on Apr 1, 2026
  8. objecttothis commented on Sep 1, 2026

    @objecttothis
    MemberAuthor

    Proposed implementation path

    1. Replace localized strings with constants/enum IDs
    Store payment_type as a constant (e.g. PAYMENT_TYPE_CASH, PAYMENT_TYPE_GIFTCARD, PAYMENT_TYPE_REWARDS, PAYMENT_TYPE_CHECK, PAYMENT_TYPE_CREDIT, PAYMENT_TYPE_DEBIT, etc.) instead of the translated string. Only translate at display time via lang(), same pattern used elsewhere in the codebase.

    2. Add a dedicated giftcard_number column
    sales_payments.payment_type currently gets giftcard:<number> appended via string concatenation (see Sales::postAddPayment() and Sale::save_value(), which does explode(':', $payment['payment_type'], 2)). Add a giftcard_number column instead, and stop overloading payment_type with the colon-separated value. Simplifies both the split logic and the DB schema.

    3. Migration for existing data
    Existing sales_payments rows have payment_type stored as whatever locale string was active when the payment was made. Migration needs to reverse-map known localized strings (across all shipped locale files in app/Language/*/Sales.php) back to the new constants. Any row that doesn't match a known translation (e.g. from a since-changed translation, or a locale no longer shipped) should be flagged for manual review rather than silently coerced.

    4. Downstream benefit: enables a real allow-list in the payment controller
    Currently Sales::postAddPayment() (around line 411) guards against spoofed giftcard/rewards payment types using str_contains($paymentType, lang('Sales.giftcard')) against the translated string — fragile across locales/case and not a true allow-list (it can't be, since payment type is free-form localized text and other valid types like cash/check/credit must still pass through untouched). Once payment types are IDs, this becomes a straightforward in_array($paymentTypeId, VALID_PAYMENT_TYPE_IDS) check with no locale dependency, closing that fragility.

  9. objecttothis commented on Nov 4, 2026

    @objecttothis
    MemberAuthor

    Claude Issue Checker Agent (cc @objecttothis)

    Investigated against current master.

    Status: Still present (fix not implemented), though a related mitigation exists.

    sales_payments.payment_type is still stored as a free-text/localized string rather than a foreign key or enum/constant — Sale::save_value() still does explode(':', $payment['payment_type'], 2) to split out an embedded gift-card number, and Sale::get_payments_summary()/report filters still match against lang('Sales.*')-translated strings rather than stable IDs, exactly as described. @objecttothis's September 2026 comment on this thread lays out a concrete migration plan (constants/enum IDs, a dedicated giftcard_number column, and a reverse-mapping migration for historical locale strings), but none of it has been implemented yet — no PAYMENT_TYPE_* constants or giftcard_number column exist in app/Models/Sale.php or the schema. This is the same underlying issue flagged again in #4548 (payment types for Bank Transfer/Wallet), which also remains open. The one related mitigation that has landed is a dedicated get_reference_code_payment_types() allow-list helper (see #4093/#4548 threads) for the reference-code UI concern — but the core payment-type-as-translated-string storage problem this issue is about is unresolved.

  10. dispeakble commented on Nov 28, 2026

    @dispeakble

    Data point from a translation PR (#4846, Romanian catalog) — this is the case where the hazard fires without anyone switching languages: the ro pack already shipped due = Datorat, check = Bon/cec, credit = Card Credit, debit = Card Debit, and it also shipped bank_transfer / wallet / upi / refund as the English fallback. Completing the catalog renames all of them, so on an existing Romanian install every historical row keeps the old string and stops matching Sale::search() (LIKE lang('Sales.due')), Cashups (trans_type == lang('Sales.cash')), the receipt/invoice views and Expense::search() / get_payments_summary() (which filter with Expenses.* while the expense form stores Sales.* labels — a cross-catalog mismatch that silently returns nothing; I hit exactly that while auditing).

    For whoever implements the int/enum column, the data side of the migration for these values is mechanical — this is what I ran against throwaway tables cloned from the real schema, and it round-trips the : suffix that gift card / reward rows carry (Card Cadou:1234, Reward Points:5):

    UPDATE ospos_sales_payments
    SET payment_type = CONCAT(
            CASE SUBSTRING_INDEX(payment_type, ':', 1)
                WHEN 'Cash' THEN 'Numerar'          WHEN 'Check' THEN 'Cec'
                WHEN 'Credit Card' THEN 'credit'    WHEN 'Debit Card' THEN 'debit'
                WHEN 'Due' THEN 'due'               WHEN 'Gift Card' THEN 'giftcard'
                WHEN 'Reward Points' THEN 'rewards' -- …one arm per stored label
                ELSE SUBSTRING_INDEX(payment_type, ':', 1)
            END,
            IF(LOCATE(':', payment_type) > 0,
               CONCAT(':', SUBSTRING(payment_type, LOCATE(':', payment_type) + 1)), '')
        );

    Two notes that matter for the design:

    • the mapping has to be per-locale: the same constant has as many stored spellings as languages the install has been used in (plus the English fallback used by incomplete packs, which is how Cash/Due end up in a ro database);
    • gift card numbers currently live inside the label, so the column split you described in the first comment (number → own column) has to land before or with the enum, otherwise the prefix parse is duplicated across Sale::save_value(), Sale_lib::addPayment() and Sales::postAddPayment().

    Happy to test a branch of this against a live 3.4.3 instance with real Romanian data if it is useful.

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

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions