Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Improved Gift Card APIs [main] (#19488)
Lukasz Ostrowski2972ddd82bcc
diff --git a/AGENTS.md b/AGENTS.mdindex 9d77f6cfea..c323030f8f 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -10,6 +10,14 @@### GraphQL permissions- Use PermissionsField to describe field restrictions+# Architecture++- Do not use Django signals (e.g. `post_save`, `pre_delete`, `@receiver`). Call the relevant logic explicitly from the code that triggers it instead of wiring it through signal handlers. (The one exception is the `post_migrate` signal used to trigger data-migration tasks — see Data Migrations below.)++# Code style++- Use global import statements. Place all imports at the top of the file rather than inside functions, methods, or other local scopes.+# Testing## Running in a git worktree@@ -285,6 +293,20 @@ def foo():"""Doc string"""```+## Agent skills++### Issue tracker++Issue tracking is opted out — skills must not create issues, PRDs, or triage records anywhere, and should treat "publish to the issue tracker" steps as not applicable. See `docs/agents/issue-tracker.md`.++### Triage labels++Not applicable — there is no issue queue, so the triage state machine and label vocabulary are unused. See `docs/agents/issue-tracker.md`.++### Domain docs++Single-context: one `CONTEXT.md` + `docs/adr/` at the repo root. See `docs/agents/domain.md`.+# Performance- Avoid unnecessarely broad `Model.save()` calls and unnecessarely broad `Model.refresh_from_db()`.diff --git a/docs/adr/0001-gift-cards-remain-bearer-instruments.md b/docs/adr/0001-gift-cards-remain-bearer-instruments.mdnew file mode 100644index 0000000000..f1377dfed1--- /dev/null+++ b/docs/adr/0001-gift-cards-remain-bearer-instruments.md@@ -0,0 +1,20 @@+# Gift cards remain bearer instruments; customer assignment is a separate opt-in restriction++**Tags:** gift card, security, checkout++A gift card is a **bearer instrument** — whoever holds the code can spend it, including in guest checkout. This is the intended default: it was established when we deprecated `used_by` as a redemption lock in PR #13019 ("Allow to add a gift card to a checkout without email"), which removed the old rule that bound a card to the first customer who used it because it caused checkout friction. A card with no assignment behaves exactly as before.++Customer assignment is therefore an **opt-in restriction layered on top** of the bearer default, not a change to it. Enforcement only exists once staff explicitly restrict a card to a customer.++## Assignment is a new concept, separate from `used_by`++Assignment and "who used the card" are two different things, and keeping them apart is deliberate:++- **Assignment** is *forward-looking*: "this customer is **allowed** to spend this card." It is a restriction staff set on purpose.+- **`used_by`** is *historical*: "this is the last customer who **spent** the card." It is an audit record, updated on every use, and it is deprecated (since PR #13019).++Reusing `used_by` for assignment would conflate a restriction with an audit trail — two things that change at different times, for different reasons. So assignment gets its own dedicated field and is never derived from `used_by`.++## Enforcement must not leak who a card belongs to++Because a restriction ties a card to a specific account, enforcement must not become an **email/account enumeration oracle**: when a restricted card is rejected at checkout, the failure must be generic and must never reveal that the card is assigned, or to whom. Leaking that signal would let an attacker probe which emails a card is bound to. Restricted cards also cannot be used in guest checkout, since there is no account to match against.diff --git a/docs/adr/0002-assignment-survives-user-deletion.md b/docs/adr/0002-assignment-survives-user-deletion.mdnew file mode 100644index 0000000000..f595ddc8c1--- /dev/null+++ b/docs/adr/0002-assignment-survives-user-deletion.md@@ -0,0 +1,7 @@+# A restricted card stays restricted after its customer is deleted++**Tags:** gift card, security++When the customer a card is assigned to is deleted, the card must **not** silently become free for anyone to use again. We keep a trace of the assignment so the card stays restricted — effectively locked until staff explicitly reassign it to another customer.++The alternative (dropping the restriction on customer deletion) would quietly turn a deliberately-restricted card back into a bearer card, which is a security regression: a card meant for one account would become spendable by anyone. Retaining the trace makes "delete the customer" a safe operation that never widens who can spend the card.diff --git a/docs/adr/0003-manual-assignment-only-no-auto-assign.md b/docs/adr/0003-manual-assignment-only-no-auto-assign.mdnew file mode 100644index 0000000000..6f7ae4f39b--- /dev/null+++ b/docs/adr/0003-manual-assignment-only-no-auto-assign.md@@ -0,0 +1,7 @@+# Assignment is manual-only; no auto-assign-on-use++**Tags:** gift card++Cards are assigned **only** by explicit staff action. We considered, then cut, an "automatically assign the card to whoever pays with it" lifecycle (auto-assign on payment, make it permanent when the order completes, revert if the checkout is abandoned).++It was cut because it is the same auto-locking behavior Saleor already built and deliberately removed in PR #13019 — binding a card to the customer who used it caused enough checkout friction to be torn out. A narrower, reversible version would reintroduce that same class of behavior plus significant complexity (distinguishing automatic from manual assignment so cleanup never clobbers a staff decision, promotion on order completion, reversal on abandonment) for benefit that did not justify it. Keeping assignment manual leaves one concept, one rule, and no hidden lifecycle.diff --git a/docs/adr/0004-race-safe-balance-adjustments.md b/docs/adr/0004-race-safe-balance-adjustments.mdnew file mode 100644index 0000000000..e9fe28280f--- /dev/null+++ b/docs/adr/0004-race-safe-balance-adjustments.md@@ -0,0 +1,7 @@+# Balance adjustments must be race-safe and free of TOCTOU issues++**Tags:** gift card, concurrency++Changing a gift card's balance is money movement that can happen concurrently — a staff adjustment and a checkout charge can hit the same card at the same time. Any balance operation must therefore be **atomic** and free of time-of-check-to-time-of-use (TOCTOU) races: never read a balance, decide, and write it back as separate steps, because a concurrent operation can invalidate the decision in between and silently lose an update or overspend the card.++Practically, this means balance changes are expressed as a single atomic operation (an adjustment applied directly at the database level, self-clamping so a card can never go negative) rather than a read-modify-write in application code. Because this cannot be done safely through the ordinary "load, edit fields, save" update path, balance adjustment is a dedicated operation rather than another editable field on the general gift-card update. This rule applies to any future balance-changing operation, not just the current one.diff --git a/docs/adr/0005-email-identifier-visible-without-manage-users.md b/docs/adr/0005-email-identifier-visible-without-manage-users.mdnew file mode 100644index 0000000000..09c340bbcc--- /dev/null+++ b/docs/adr/0005-email-identifier-visible-without-manage-users.md@@ -0,0 +1,9 @@+# Denormalized email identifiers are visible without MANAGE_USERS++**Tags:** gift card, security, permissions++Staff who can manage gift cards (`MANAGE_GIFT_CARD`) can read the **denormalized email** of the user a card is assigned to (as well as the created-by / used-by emails), even if they do **not** hold `MANAGE_USERS`. Access to the full **`User` object** is stricter: it requires `MANAGE_USERS` (via `resolve_assigned_to`).++The reasoning is that the email is a low-sensitivity identifier that lets an operator reason about who is performing operations or who a card belongs to — needed to do the gift-card job at all. The full user entity exposes much more (profile, addresses, order history, metadata) and is genuinely account-management scope, so it stays behind `MANAGE_USERS`. `MANAGE_GIFT_CARD` on the email resolvers still ensures that someone who cannot manage gift cards sees nothing at all (unauthorized requestors get the obfuscated email). This mirrors the decision made for refund reasons.++This is a deliberate choice, not accidental broken access control. It is documented both here and inline at the resolver so future readers do not "fix" the email resolver to require `MANAGE_USERS` and break the intended workflow.diff --git a/docs/agents/domain.md b/docs/agents/domain.mdnew file mode 100644index 0000000000..041bd7ea4f--- /dev/null+++ b/docs/agents/domain.md@@ -0,0 +1,45 @@+# Domain Docs++How the engineering skills should consume this repo's domain documentation when exploring the codebase.++This is a **single-context** repo — one `CONTEXT.md` and one `docs/adr/` at the repo root.++## Before exploring, read these++- **`CONTEXT.md`** at the repo root — the project's glossary / ubiquitous language.+- **`docs/adr/`** — read the ADRs that touch the area you're about to work in.++If any of these files don't exist yet, **proceed silently**. Don't flag their absence; don't suggest creating them upfront. The `/domain-modeling` skill (reached via `/grill-with-docs` and `/improve-codebase-architecture`) creates them lazily when terms or decisions actually get resolved.++## File structure++```+/+├── CONTEXT.md+├── docs/adr/+│ ├── 0001-<decision>.md+│ └── 0002-<decision>.md+└── saleor/ ← application code+```++## ADR tags++Every ADR carries a `**Tags:**` line directly under its title — a short, comma-separated list of the areas it relates to (e.g. `gift card`, `security`, `concurrency`, `checkout`). Tags are for discovery: use them to find the ADRs that touch the area you're about to work in, rather than reading every file.++- When you add a new ADR, give it tags.+- Reuse existing tag names where one fits; only coin a new tag when nothing existing applies.+- Prefer stable, area-level tags (a domain like `gift card`, or a cross-cutting concern like `security`) over narrow, one-off labels.++ADRs describe **business / high-level decisions and their rationale** — why a choice was made and what the alternative would have cost. Keep implementation detail out; it goes stale and lives in the code. Include a code reference only when it is essential to understand the decision.++## Use the glossary's vocabulary++When your output names a domain concept (in a refactor proposal, a hypothesis, a test name), use the term as defined in `CONTEXT.md`. Don't drift to synonyms the glossary explicitly avoids.++If the concept you need isn't in the glossary yet, that's a signal — either you're inventing language the project doesn't use (reconsider) or there's a real gap (note it for `/domain-modeling`).++## Flag ADR conflicts++If your output contradicts an existing ADR, surface it explicitly rather than silently overriding:++> _Contradicts ADR-0007 (…) — but worth reopening because…_diff --git a/docs/agents/issue-tracker.md b/docs/agents/issue-tracker.mdnew file mode 100644index 0000000000..ca2fbd4f74--- /dev/null+++ b/docs/agents/issue-tracker.md@@ -0,0 +1,13 @@+# Issue tracker: none (opted out)++This repo does **not** use an agent-driven issue tracker. The maintainer has opted out of issue tracking for the engineering skills.++## What this means for skills++- Skills that would normally read from or write to an issue tracker (`to-issues`, `triage`, `to-prd`, `qa`, etc.) must **not** create issues, PRDs, or triage records anywhere — not on GitHub, not under `.scratch/`, not in any external tool.+- When a skill's workflow says "publish to the issue tracker" or "fetch the relevant ticket", treat that step as **not applicable**. Do the underlying work (e.g. produce the analysis, the plan, the fix) and return it directly in the conversation instead of persisting it as an issue.+- Do not prompt the user to set up an issue tracker. If issue tracking is wanted later, re-run `/setup-matt-pocock-skills`.++## Triage++Because there is no issue queue, the triage state machine and its label vocabulary do not apply. There is no `docs/agents/triage-labels.md`.diff --git a/pyproject.toml b/pyproject.tomlindex ccfb5984c7..81466b90f0 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -94,6 +94,9 @@ dev = ["coverage~=7.14","deptry>=0.23.0,<0.24","django-extensions~=4.1",+ # TODO: once on django-stubs >= 6.0.2, revert the PublishedQuerySet TypeVar+ # workaround in saleor/core/models.py back to bound="PublishableModel".+ # The fix landed in https://github.com/typeddjango/django-stubs/commit/461fb9ba8d26667cb43cfb55827acdc6d4ed42ed"django-stubs[compatible-mypy]>=5.1.3,<6","fakeredis~=2.26","freezegun>=1,<2",diff --git a/saleor/checkout/checkout_cleaner.py b/saleor/checkout/checkout_cleaner.pyindex df3b9fc1ee..6ad52da857 100644--- a/saleor/checkout/checkout_cleaner.py+++ b/saleor/checkout/checkout_cleaner.py@@ -121,6 +121,27 @@ def _validate_gift_cards(checkout: Checkout):msg = "Gift card has expired. Order placement cancelled."raise GiftCardNotApplicable(msg)+ # Re-check restricted gift cards at completion time: a card may have been+ # assigned to another customer after it was added to the checkout.+ # This also acts as a defense-in-depth safeguard in case an actor+ # may successfully add a giftcard that they are not authorized+ # to use into their checkout (shouldn't happen)+ # defense-in-depth safeguard, not a redundant check — do not remove it.+ #+ # We deliberately do not acquire a row lock here. A gift card changing hands+ # mid-checkoutComplete() is outside the threat model, and locking would have+ # a real performance/reliability cost for an unrealistic security risk.+ restricted = GiftCard.objects.filter(+ checkouts=checkout.token, assigned_to_email__isnull=False+ )+ if checkout.user_id:+ restricted = restricted.exclude(assigned_to_id=checkout.user_id)+ if restricted.exists():+ # Generic message — do not reveal the assignee.+ raise GiftCardNotApplicable(+ "Gift card cannot be used. Order placement cancelled."+ )+def validate_checkout(checkout_info: "CheckoutInfo",diff --git a/saleor/checkout/tests/test_checkout_cleaner.py b/saleor/checkout/tests/test_checkout_cleaner.pynew file mode 100644index 0000000000..7da7adcaa0--- /dev/null+++ b/saleor/checkout/tests/test_checkout_cleaner.py@@ -0,0 +1,37 @@+import pytest++from ...core.exceptions import GiftCardNotApplicable+from ..checkout_cleaner import _validate_gift_cards+++def test_validate_gift_cards_rejects_mismatched_assignment(+ checkout_with_gift_card, customer_user, staff_user+):+ # given+ checkout = checkout_with_gift_card+ checkout.user = staff_user+ checkout.save(update_fields=["user"])+ gift_card = checkout.gift_cards.first()+ gift_card.assigned_to = customer_user+ gift_card.assigned_to_email = customer_user.email+ gift_card.save(update_fields=["assigned_to", "assigned_to_email"])++ # when / then+ with pytest.raises(GiftCardNotApplicable):+ _validate_gift_cards(checkout)+++def test_validate_gift_cards_allows_matching_assignment(+ checkout_with_gift_card, customer_user+):+ # given+ checkout = checkout_with_gift_card+ checkout.user = customer_user+ checkout.save(update_fields=["user"])+ gift_card = checkout.gift_cards.first()+ gift_card.assigned_to = customer_user+ gift_card.assigned_to_email = customer_user.email+ gift_card.save(update_fields=["assigned_to", "assigned_to_email"])++ # when / then (no raise)+ _validate_gift_cards(checkout)diff --git a/saleor/core/models.py b/saleor/core/models.pyindex 9e00687a68..310e110492 100644--- a/saleor/core/models.py+++ b/saleor/core/models.py@@ -45,7 +45,13 @@ class SortableModel(models.Model):super().delete(*args, **kwargs)-T = TypeVar("T", bound="PublishableModel")+# Bound to models.Model instead of the more precise "PublishableModel":+# a forward-referenced bound on a TypeVar used in QuerySet[T] crashes mypy's+# semantic analyzer ("Must not defer during final iteration", mypy <= 1.20)+# when mypy is invoked on a small subset of files, as happens when pre-commit+# splits the file list into batches in CI.+# See https://github.com/typeddjango/django-stubs/issues/2479+T = TypeVar("T", bound=models.Model)class PublishedQuerySet(models.QuerySet[T]):diff --git a/saleor/giftcard/__init__.py b/saleor/giftcard/__init__.pyindex b91c3592e5..e0f939f271 100644--- a/saleor/giftcard/__init__.py+++ b/saleor/giftcard/__init__.py@@ -22,6 +22,9 @@ class GiftCardEvents:NOTE_ADDED = "note_added"USED_IN_ORDER = "used_in_order"REFUNDED_IN_ORDER = "refunded_in_order"+ BALANCE_ADJUSTED = "balance_adjusted"+ ASSIGNED_TO_USER = "assigned_to_user"+ UNASSIGNED_FROM_USER = "unassigned_from_user"CHOICES = [(ISSUED, "The gift card was created be staff user or app."),@@ -37,6 +40,9 @@ class GiftCardEvents:(NOTE_ADDED, "A note was added to the gift card."),(USED_IN_ORDER, "The gift card was used in order."),(REFUNDED_IN_ORDER, "The gift card was refunded in order."),+ (BALANCE_ADJUSTED, "The gift card balance was adjusted by a delta."),+ (ASSIGNED_TO_USER, "The gift card was assigned to a customer."),+ (UNASSIGNED_FROM_USER, "The gift card was unassigned from a customer."),]diff --git a/saleor/giftcard/error_codes.py b/saleor/giftcard/error_codes.pyindex c4294a3083..d7b950b867 100644--- a/saleor/giftcard/error_codes.py+++ b/saleor/giftcard/error_codes.py@@ -10,3 +10,4 @@ class GiftCardErrorCode(Enum):UNIQUE = "unique"EXPIRED_GIFT_CARD = "expired_gift_card"DUPLICATED_INPUT_ITEM = "duplicated_input_item"+ CANNOT_ASSIGN = "cannot_assign"diff --git a/saleor/giftcard/events.py b/saleor/giftcard/events.pyindex e22bd47c44..747be3aab4 100644--- a/saleor/giftcard/events.py+++ b/saleor/giftcard/events.py@@ -30,6 +30,70 @@ def gift_card_issued_event()+def gift_card_balance_adjusted_event(+ gift_card: GiftCard,+ old_current_balance: Decimal,+ old_initial_balance: Decimal,+ user: User | None,+ app: App | None,+) -> GiftCardEvent:+ return GiftCardEvent.objects.create(+ gift_card=gift_card,+ user=user,+ app=app,+ type=GiftCardEvents.BALANCE_ADJUSTED,+ parameters={+ "balance": {+ "currency": gift_card.currency,+ "current_balance": gift_card.current_balance_amount,+ "initial_balance": gift_card.initial_balance_amount,+ "old_current_balance": old_current_balance,+ "old_initial_balance": old_initial_balance,+ }+ },+ )+++def gift_card_assigned_event(+ gift_card: GiftCard,+ previous_user_id: int | None,+ previous_email: str | None,+ user: User | None,+ app: App | None,+) -> GiftCardEvent:+ return GiftCardEvent.objects.create(+ gift_card=gift_card,+ user=user,+ app=app,+ type=GiftCardEvents.ASSIGNED_TO_USER,+ parameters={+ "previous_assigned_to_id": previous_user_id,+ "previous_assigned_to_email": previous_email,+ "assigned_to_id": gift_card.assigned_to_id,+ "assigned_to_email": gift_card.assigned_to_email,+ },+ )+++def gift_card_unassigned_event(+ gift_card: GiftCard,+ previous_user_id: int | None,+ previous_email: str | None,+ user: User | None,+ app: App | None,+) -> GiftCardEvent:+ return GiftCardEvent.objects.create(+ gift_card=gift_card,+ user=user,+ app=app,+ type=GiftCardEvents.UNASSIGNED_FROM_USER,+ parameters={+ "previous_assigned_to_id": previous_user_id,+ "previous_assigned_to_email": previous_email,+ },+ )++def gift_cards_issued_event(gift_cards: Iterable[GiftCard],user: User | None,diff --git a/saleor/giftcard/lock_objects.py b/saleor/giftcard/lock_objects.pynew file mode 100644index 0000000000..5c060c20c7--- /dev/null+++ b/saleor/giftcard/lock_objects.py@@ -0,0 +1,11 @@+from django.db.models import QuerySet++from .models import GiftCard+++def gift_card_qs_select_for_update() -> QuerySet[GiftCard]:+ # order_by("pk") is intentional, not redundant: acquiring row locks in a+ # consistent primary-key order prevents deadlocks between concurrent+ # transactions that lock several rows. This mirrors every other+ # lock_objects module (see e.g. saleor/payment/lock_objects.py).+ return GiftCard.objects.order_by("pk").select_for_update(of=["self"])diff --git a/saleor/giftcard/migrations/0025_giftcard_customer_assignment.py b/saleor/giftcard/migrations/0025_giftcard_customer_assignment.pynew file mode 100644index 0000000000..538808bf83--- /dev/null+++ b/saleor/giftcard/migrations/0025_giftcard_customer_assignment.py@@ -0,0 +1,82 @@+# Generated by Django 5.2.15 on 2026-07-09 10:48++import django.contrib.postgres.indexes+import django.db.models.deletion+from django.contrib.postgres.operations import AddIndexConcurrently+from django.db import migrations, models+++class Migration(migrations.Migration):+ # AddIndexConcurrently cannot run inside a transaction.+ atomic = False++ dependencies = [+ ("account", "0099_remove_digitalcontent_customerevent_type"),+ ("app", "0038_merge_20260213_1154"),+ ("giftcard", "0024_alter_giftcardevent_type"),+ ("order", "0226_grantedrefundline_reason_ref_idx"),+ ("product", "0205_merge_20260615_1308"),+ ]++ operations = [+ migrations.AddField(+ model_name="giftcard",+ name="assigned_to",+ field=models.ForeignKey(+ blank=True,+ null=True,+ on_delete=django.db.models.deletion.PROTECT,+ related_name="assigned_gift_cards",+ to="account.user",+ ),+ ),+ migrations.AddField(+ model_name="giftcard",+ name="assigned_to_email",+ field=models.EmailField(blank=True, max_length=254, null=True),+ ),+ migrations.AlterField(+ model_name="giftcardevent",+ name="type",+ field=models.CharField(+ choices=[+ ("issued", "The gift card was created be staff user or app."),+ ("bought", "The gift card was bought by customer."),+ ("updated", "The gift card was updated."),+ ("activated", "The gift card was activated."),+ ("deactivated", "The gift card was deactivated."),+ ("balance_reset", "The gift card balance was reset."),+ ("expiry_date_updated", "The gift card expiry date was updated."),+ ("tags_updated", "The gift card tags were updated."),+ ("sent_to_customer", "The gift card was sent to the customer."),+ ("resent", "The gift card was resent to the customer."),+ ("note_added", "A note was added to the gift card."),+ ("used_in_order", "The gift card was used in order."),+ ("refunded_in_order", "The gift card was refunded in order."),+ (+ "balance_adjusted",+ "The gift card balance was adjusted by a delta.",+ ),+ ("assigned_to_user", "The gift card was assigned to a customer."),+ (+ "unassigned_from_user",+ "The gift card was unassigned from a customer.",+ ),+ ],+ max_length=255,+ ),+ ),+ AddIndexConcurrently(+ model_name="giftcard",+ index=django.contrib.postgres.indexes.BTreeIndex(+ fields=["assigned_to"], name="giftcard_assigned_to_idx"+ ),+ ),+ migrations.AddConstraint(+ model_name="giftcard",+ constraint=models.CheckConstraint(+ condition=models.Q(("current_balance_amount__gte", 0)),+ name="giftcard_current_balance_non_negative",+ ),+ ),+ ]diff --git a/saleor/giftcard/models.py b/saleor/giftcard/models.pyindex eacb9bc48a..819000fd18 100644--- a/saleor/giftcard/models.py+++ b/saleor/giftcard/models.py@@ -1,7 +1,7 @@import osfrom django.conf import settings-from django.contrib.postgres.indexes import GinIndex+from django.contrib.postgres.indexes import BTreeIndex, GinIndexfrom django.contrib.postgres.search import SearchVectorFieldfrom django.core.validators import MinLengthValidatorfrom django.db import models@@ -63,6 +63,18 @@ class GiftCard(ModelWithMetadata):)created_by_email = models.EmailField(null=True, blank=True)used_by_email = models.EmailField(null=True, blank=True)+ assigned_to = models.ForeignKey(+ settings.AUTH_USER_MODEL,+ blank=True,+ null=True,+ # PROTECT (not SET_NULL): deleting an assignee must go through+ # deactivate_assigned_gift_cards() so the card is detached AND+ # deactivated together. A raw delete is refused rather than silently+ # leaving an active card restricted to a ghost user.+ on_delete=models.PROTECT,+ related_name="assigned_gift_cards",+ )+ assigned_to_email = models.EmailField(null=True, blank=True)app = models.ForeignKey(App,blank=True,@@ -121,8 +133,19 @@ class GiftCard(ModelWithMetadata):permissions = ((GiftcardPermissions.MANAGE_GIFT_CARD.codename, "Manage gift cards."),)- indexes = [GinIndex(name="giftcard_tsearch", fields=["search_vector"])]+ indexes = [+ GinIndex(name="giftcard_tsearch", fields=["search_vector"]),+ BTreeIndex(fields=["assigned_to"], name="giftcard_assigned_to_idx"),+ ]indexes.extend(ModelWithMetadata.Meta.indexes)+ constraints = [+ # Defense-in-depth backstop: no code path should ever persist a+ # negative balance (writers clamp to zero), but the DB enforces it.+ models.CheckConstraint(+ condition=Q(current_balance_amount__gte=0),+ name="giftcard_current_balance_non_negative",+ ),+ ]@propertydef display_code(self):diff --git a/saleor/giftcard/tests/test_events.py b/saleor/giftcard/tests/test_events.pynew file mode 100644index 0000000000..b34be064d6--- /dev/null+++ b/saleor/giftcard/tests/test_events.py@@ -0,0 +1,58 @@+from decimal import Decimal++from .. import GiftCardEvents+from ..events import (+ gift_card_assigned_event,+ gift_card_balance_adjusted_event,+ gift_card_unassigned_event,+)+++def test_gift_card_balance_adjusted_event(gift_card, staff_user):+ # given+ old_current = Decimal("50.00")+ old_initial = Decimal("100.00")++ # when+ event = gift_card_balance_adjusted_event(+ gift_card, old_current, old_initial, staff_user, None+ )++ # then+ assert event.type == GiftCardEvents.BALANCE_ADJUSTED+ balance = event.parameters["balance"]+ assert balance["old_current_balance"] == old_current+ assert balance["old_initial_balance"] == old_initial+ assert balance["current_balance"] == gift_card.current_balance_amount+ assert balance["initial_balance"] == gift_card.initial_balance_amount+ assert balance["currency"] == gift_card.currency+++def test_gift_card_assigned_event_records_prev_and_new(+ gift_card, customer_user, staff_user+):+ # given+ gift_card.assigned_to = customer_user+ gift_card.assigned_to_email = customer_user.email++ # when+ event = gift_card_assigned_event(gift_card, None, None, staff_user, None)++ # then+ assert event.type == GiftCardEvents.ASSIGNED_TO_USER+ assert event.parameters["previous_assigned_to_id"] is None+ assert event.parameters["previous_assigned_to_email"] is None+ assert event.parameters["assigned_to_id"] == customer_user.id+ assert event.parameters["assigned_to_email"] == customer_user.email+++def test_gift_card_unassigned_event_records_prev(gift_card, customer_user, staff_user):+ # when+ event = gift_card_unassigned_event(+ gift_card, customer_user.id, customer_user.email, staff_user, None+ )++ # then+ assert event.type == GiftCardEvents.UNASSIGNED_FROM_USER+ assert event.parameters["previous_assigned_to_id"] == customer_user.id+ assert event.parameters["previous_assigned_to_email"] == customer_user.emaildiff --git a/saleor/giftcard/tests/test_lock_objects.py b/saleor/giftcard/tests/test_lock_objects.pynew file mode 100644index 0000000000..115cf2276d--- /dev/null+++ b/saleor/giftcard/tests/test_lock_objects.py@@ -0,0 +1,11 @@+from ..lock_objects import gift_card_qs_select_for_update+from ..models import GiftCard+++def test_gift_card_qs_select_for_update_returns_giftcard_queryset(gift_card):+ # when+ qs = gift_card_qs_select_for_update()++ # then+ assert qs.model is GiftCard+ assert qs.query.select_for_update is Truediff --git a/saleor/giftcard/tests/test_models.py b/saleor/giftcard/tests/test_models.pynew file mode 100644index 0000000000..0ad2f53310--- /dev/null+++ b/saleor/giftcard/tests/test_models.py@@ -0,0 +1,43 @@+from decimal import Decimal++import pytest+from django.db import IntegrityError, transaction+from django.db.models import ProtectedError++from ..models import GiftCard+++def test_gift_card_can_be_assigned_to_customer(gift_card, customer_user):+ # when+ gift_card.assigned_to = customer_user+ gift_card.assigned_to_email = customer_user.email+ gift_card.save(update_fields=["assigned_to", "assigned_to_email"])++ # then+ gift_card.refresh_from_db()+ assert gift_card.assigned_to == customer_user+ assert gift_card.assigned_to_email == customer_user.email+ assert gift_card in GiftCard.objects.filter(assigned_to=customer_user)+ assert customer_user.assigned_gift_cards.filter(pk=gift_card.pk).exists()+++def test_deleting_assigned_customer_is_protected(gift_card, customer_user):+ # given a card restricted to the customer+ gift_card.assigned_to = customer_user+ gift_card.assigned_to_email = customer_user.email+ gift_card.save(update_fields=["assigned_to", "assigned_to_email"])++ # when / then: assigned_to is on_delete=PROTECT, so a raw delete is refused.+ # Deletion must go through deactivate_assigned_gift_cards() first (used by+ # the user-deletion mutations).+ with pytest.raises(ProtectedError):+ customer_user.delete()+++def test_current_balance_cannot_be_negative(gift_card):+ # given+ gift_card.current_balance_amount = Decimal(-1)++ # when / then: the DB check constraint rejects a negative current balance+ with pytest.raises(IntegrityError), transaction.atomic():+ gift_card.save(update_fields=["current_balance_amount"])diff --git a/saleor/giftcard/tests/test_utils.py b/saleor/giftcard/tests/test_utils.pyindex 2a4e68c70a..c7f5893c49 100644--- a/saleor/giftcard/tests/test_utils.py+++ b/saleor/giftcard/tests/test_utils.py@@ -6,6 +6,7 @@ import grapheneimport pytestfrom dateutil.relativedelta import relativedeltafrom django.core.exceptions import ValidationError+from django.db.models import QuerySetfrom django.utils import timezonefrom freezegun import freeze_time@@ -23,9 +24,12 @@ from ...webhook.payloads import generate_meta, generate_requestorfrom .. import GiftCardEvents, GiftCardLineData, eventsfrom ..models import GiftCard, GiftCardEventfrom ..utils import (+ GiftCardCannotAssign,add_gift_card_code_to_checkout,+ assign_gift_card_to_user,assign_user_gift_cards,calculate_expiry_date,+ deactivate_assigned_gift_cards,deactivate_order_gift_cards,fulfill_gift_card_lines,fulfill_non_shippable_gift_cards,@@ -863,3 +867,298 @@ def test_is_gift_card_expired_false(expiry_date, gift_card):# thenassert result is False+++def test_assign_sets_user_and_email(gift_card, customer_user):+ # given+ assert gift_card.assigned_to is None+ assert gift_card.assigned_to_email is None++ # when+ assign_gift_card_to_user(gift_card, customer_user)++ # then+ gift_card.refresh_from_db()+ assert gift_card.assigned_to == customer_user+ assert gift_card.assigned_to_email == customer_user.email+++def test_assign_blocked_when_used_in_order(gift_card, customer_user):+ # given+ gift_card.last_used_on = timezone.now()+ gift_card.save(update_fields=["last_used_on"])++ # when / then+ with pytest.raises(GiftCardCannotAssign):+ assign_gift_card_to_user(gift_card, customer_user)+++def test_assign_detaches_clean_checkout(gift_card, customer_user, checkout):+ # given+ assert gift_card.assigned_to is None+ checkout_qs = checkout.gift_cards.filter(pk=gift_card.pk)+ checkout.gift_cards.add(gift_card)+ assert checkout_qs.exists() is True++ # when+ assign_gift_card_to_user(gift_card, customer_user)++ # then+ assert checkout_qs.exists() is False+ gift_card.refresh_from_db()+ assert gift_card.assigned_to == customer_user+++def test_assign_bumps_last_change_of_detached_checkout(+ gift_card, customer_user, checkout+):+ # given+ checkout.gift_cards.add(gift_card)+ checkout.refresh_from_db()+ last_change_before_assignment = checkout.last_change+ assignment_time = last_change_before_assignment + datetime.timedelta(days=1)+ assert last_change_before_assignment < assignment_time++ # when+ with freeze_time(assignment_time):+ assign_gift_card_to_user(gift_card, customer_user)++ # then+ checkout.refresh_from_db()+ assert checkout.last_change == assignment_time+++def test_assign_blocked_when_checkout_has_transaction(+ gift_card, customer_user, checkout, transaction_item_generator+):+ # given+ checkout.gift_cards.add(gift_card)+ transaction_item_generator(checkout_id=checkout.pk)++ # when / then+ with pytest.raises(GiftCardCannotAssign):+ assign_gift_card_to_user(gift_card, customer_user)+ assert checkout.gift_cards.filter(pk=gift_card.pk).exists()+++def test_deactivate_assigned_gift_cards_detaches_and_deactivates(+ gift_card, customer_user+):+ # given an active card restricted to the customer+ assigned_email = customer_user.email+ gift_card.assigned_to = customer_user+ gift_card.assigned_to_email = assigned_email+ gift_card.is_active = True+ gift_card.save(update_fields=["assigned_to", "assigned_to_email", "is_active"])++ # when+ deactivate_assigned_gift_cards([customer_user])++ # then the FK is nulled and the card deactivated, but the email is kept+ gift_card.refresh_from_db()+ assert gift_card.assigned_to_id is None+ assert gift_card.is_active is False+ assert gift_card.assigned_to_email == assigned_email+ assert GiftCardEvent.objects.filter(+ gift_card=gift_card, type=GiftCardEvents.DEACTIVATED+ ).exists()+++def test_deactivate_assigned_gift_cards_ignores_other_users(+ gift_card, customer_user, staff_user+):+ # given a card assigned to a different user than the one being removed+ gift_card.assigned_to = staff_user+ gift_card.assigned_to_email = staff_user.email+ gift_card.is_active = True+ gift_card.save(update_fields=["assigned_to", "assigned_to_email", "is_active"])++ # when+ deactivate_assigned_gift_cards([customer_user])++ # then the untouched card stays active and assigned+ gift_card.refresh_from_db()+ assert gift_card.assigned_to == staff_user+ assert gift_card.is_active is True+ assert not GiftCardEvent.objects.filter(+ gift_card=gift_card, type=GiftCardEvents.DEACTIVATED+ ).exists()+++def test_deactivate_assigned_gift_cards_no_event_for_already_inactive(+ gift_card, customer_user+):+ # given an already inactive card restricted to the customer+ gift_card.assigned_to = customer_user+ gift_card.assigned_to_email = customer_user.email+ gift_card.is_active = False+ gift_card.save(update_fields=["assigned_to", "assigned_to_email", "is_active"])++ # when+ deactivate_assigned_gift_cards([customer_user])++ # then the FK is still cleared (so the user can be deleted) but no event fires+ gift_card.refresh_from_db()+ assert gift_card.assigned_to_id is None+ assert gift_card.is_active is False+ assert not GiftCardEvent.objects.filter(+ gift_card=gift_card, type=GiftCardEvents.DEACTIVATED+ ).exists()+++def test_deactivate_assigned_gift_cards_deactivates_card_activated_before_detach(+ gift_card, customer_user+):+ # given an inactive card restricted to the customer+ assigned_email = customer_user.email+ gift_card.assigned_to = customer_user+ gift_card.assigned_to_email = assigned_email+ gift_card.is_active = False+ gift_card.save(update_fields=["assigned_to", "assigned_to_email", "is_active"])+ original_update = QuerySet.update+ activation_was_simulated = False++ def activate_before_detach(queryset, **kwargs):+ nonlocal activation_was_simulated+ if (+ not activation_was_simulated+ and queryset.model is GiftCard+ and "assigned_to" in kwargs+ ):+ activation_was_simulated = True+ original_update(GiftCard.objects.filter(pk=gift_card.pk), is_active=True)+ return original_update(queryset, **kwargs)++ # when another writer activates the card immediately before it is detached+ with patch.object(QuerySet, "update", activate_before_detach):+ deactivate_assigned_gift_cards([customer_user])++ # then detaching still guarantees that the card is inactive+ gift_card.refresh_from_db()+ assert activation_was_simulated is True+ assert gift_card.assigned_to_id is None+ assert gift_card.assigned_to_email == assigned_email+ assert gift_card.is_active is False+++def test_add_restricted_card_allows_matching_user(+ checkout_with_item, gift_card, customer_user+):+ # given+ checkout = checkout_with_item+ checkout.user = customer_user+ checkout.save(update_fields=["user"])+ gift_card.assigned_to = customer_user+ gift_card.assigned_to_email = customer_user.email+ gift_card.currency = checkout.currency+ gift_card.save(update_fields=["assigned_to", "assigned_to_email", "currency"])++ # when+ add_gift_card_code_to_checkout(+ checkout, customer_user.email, gift_card.code, checkout.currency+ )++ # then+ assert checkout.gift_cards.filter(pk=gift_card.pk).exists()+++def test_add_restricted_card_rejects_other_user(+ checkout_with_item, gift_card, customer_user, staff_user+):+ # given+ checkout = checkout_with_item+ checkout.user = staff_user+ checkout.save(update_fields=["user"])+ gift_card.assigned_to = customer_user+ gift_card.assigned_to_email = customer_user.email+ gift_card.currency = checkout.currency+ gift_card.save(update_fields=["assigned_to", "assigned_to_email", "currency"])++ # when / then+ with pytest.raises(InvalidPromoCode):+ add_gift_card_code_to_checkout(+ checkout, staff_user.email, gift_card.code, checkout.currency+ )+++def test_add_restricted_card_rejects_guest(+ checkout_with_item, gift_card, customer_user+):+ # given+ checkout = checkout_with_item+ checkout.user = None+ checkout.save(update_fields=["user"])+ gift_card.assigned_to = customer_user+ gift_card.assigned_to_email = customer_user.email+ gift_card.currency = checkout.currency+ gift_card.save(update_fields=["assigned_to", "assigned_to_email", "currency"])++ # when / then+ with pytest.raises(InvalidPromoCode):+ add_gift_card_code_to_checkout(+ checkout, "[email protected]", gift_card.code, checkout.currency+ )+++def test_add_restricted_card_rejects_guest_with_assignee_email(+ checkout_with_item, gift_card, customer_user+):+ # given+ checkout = checkout_with_item+ checkout.user = None+ checkout.save(update_fields=["user"])+ gift_card.assigned_to = customer_user+ gift_card.assigned_to_email = customer_user.email+ gift_card.currency = checkout.currency+ gift_card.save(update_fields=["assigned_to", "assigned_to_email", "currency"])++ # when / then+ # A guest whose email matches the assignee still cannot use the card until+ # authenticated — the restriction is keyed on the user, not the email.+ with pytest.raises(InvalidPromoCode):+ add_gift_card_code_to_checkout(+ checkout, customer_user.email, gift_card.code, checkout.currency+ )+++def test_add_restricted_card_rejects_when_assignee_deleted(+ checkout_with_item, gift_card, customer_user+):+ # given a card restricted to a now-deleted user: assigned_to was nulled by+ # SET_NULL while assigned_to_email was retained+ checkout = checkout_with_item+ checkout.user = customer_user+ checkout.save(update_fields=["user"])+ gift_card.assigned_to = None+ gift_card.assigned_to_email = customer_user.email+ gift_card.currency = checkout.currency+ gift_card.save(update_fields=["assigned_to", "assigned_to_email", "currency"])++ # when / then+ # Even a logged-in user matching assigned_to_email cannot use it — with no+ # assignee it can no longer be validated against an owner.+ with pytest.raises(InvalidPromoCode):+ add_gift_card_code_to_checkout(+ checkout, customer_user.email, gift_card.code, checkout.currency+ )+++def test_add_restricted_card_with_deleted_assignee_rejects_guest(+ checkout_with_item, gift_card, customer_user+):+ # given a guest checkout and a card whose assignee was deleted+ checkout = checkout_with_item+ checkout.user = None+ checkout.save(update_fields=["user"])+ gift_card.assigned_to = None+ gift_card.assigned_to_email = customer_user.email+ gift_card.currency = checkout.currency+ gift_card.save(update_fields=["assigned_to", "assigned_to_email", "currency"])++ # when / then+ # Regression: the previous single guard let this through because+ # `None != checkout.user_id` (None) was False for a guest.+ with pytest.raises(InvalidPromoCode):+ add_gift_card_code_to_checkout(+ checkout, customer_user.email, gift_card.code, checkout.currency+ )diff --git a/saleor/giftcard/utils.py b/saleor/giftcard/utils.pyindex 5b8be2ce13..a45b55eab0 100644--- a/saleor/giftcard/utils.py+++ b/saleor/giftcard/utils.py@@ -1,4 +1,5 @@import datetime+import loggingfrom collections import defaultdictfrom collections.abc import Iterablefrom typing import TYPE_CHECKING, Optional@@ -18,8 +19,10 @@ from ..core.utils.events import call_eventfrom ..core.utils.promo_code import InvalidPromoCode, generate_promo_codefrom ..order.actions import OrderFulfillmentLineInfo, create_fulfillmentsfrom ..order.models import OrderLine+from ..payment.models import Payment, TransactionItemfrom ..site import GiftCardSettingsExpiryTypefrom . import GiftCardEvents, GiftCardLineData, events+from .lock_objects import gift_card_qs_select_for_updatefrom .models import GiftCard, GiftCardEventfrom .notifications import send_gift_card_notification@@ -33,8 +36,11 @@ if TYPE_CHECKING:from ..site.models import SiteSettings+logger = logging.getLogger(__name__)++def add_gift_card_code_to_checkout(- checkout: Checkout, email: str, promo_code: str, currency: str+ checkout: Checkout, email: str | None, promo_code: str, currency: str):"""Add gift card data to checkout by code.@@ -51,6 +57,29 @@ def add_gift_card_code_to_checkout(except GiftCard.DoesNotExist as e:raise InvalidPromoCode() from e+ if gift_card.assigned_to_email and not gift_card.assigned_to_id:+ # The card is restricted but its assignee no longer exists (the user was+ # deleted and assigned_to was nulled). It cannot be validated against an+ # owner, so it must not be usable by anyone — including a guest whose+ # email happens to match assigned_to_email.+ logger.info(+ "Rejected use of gift card %s restricted to a deleted customer "+ "in checkout %s.",+ gift_card.pk,+ checkout.pk,+ )+ raise InvalidPromoCode()+ if gift_card.assigned_to_id and gift_card.assigned_to_id != checkout.user_id:+ # Restricted gift cards can only be used by the assigned customer.+ logger.info(+ "Rejected use of gift card %s restricted to another customer "+ "in checkout %s.",+ gift_card.pk,+ checkout.pk,+ )+ # Generic error — do not reveal the assignee.+ raise InvalidPromoCode()+checkout.gift_cards.add(gift_card)checkout.save(update_fields=["last_change"])@@ -70,6 +99,89 @@ def remove_gift_card_code_from_checkout_or_error()+class GiftCardCannotAssign(Exception):+ """Raised when a gift card cannot be (re)assigned to a customer."""+++def assign_gift_card_to_user(gift_card: "GiftCard", user: "User") -> None:+ """Restrict a gift card to a customer under a row lock.++ Raise GiftCardCannotAssign when the card was already used in an order or is+ attached to a checkout that has payments. Clean attached checkouts are+ detached (the same invalidation checkoutRemovePromoCode performs).+ """+ with traced_atomic_transaction():+ locked = gift_card_qs_select_for_update().get(pk=gift_card.pk)++ if locked.last_used_on is not None:+ raise GiftCardCannotAssign(+ "Cannot assign a gift card that was already used in an order."+ )++ attached_checkouts = locked.checkouts.all()+ has_payments = attached_checkouts.filter(+ Exists(Payment.objects.filter(checkout_id=OuterRef("pk"), is_active=True))+ | Exists(TransactionItem.objects.filter(checkout_id=OuterRef("pk")))+ ).exists()+ if has_payments:+ raise GiftCardCannotAssign(+ "Cannot assign a gift card attached to a checkout with payments."+ )++ # Detach clean checkouts in bulk (same invalidation that+ # checkoutRemovePromoCode performs). Batched to keep the row lock short.+ # Invalidate before clearing because the relation-backed queryset no longer+ # matches any checkouts after ``clear()``.+ if attached_checkouts.update(last_change=timezone.now()):+ locked.checkouts.clear()++ locked.assigned_to = user+ locked.assigned_to_email = user.email+ locked.save(update_fields=["assigned_to", "assigned_to_email"])++ gift_card.assigned_to = user+ gift_card.assigned_to_email = user.email+++def deactivate_assigned_gift_cards(users) -> None:+ """Detach and deactivate gift cards restricted to users being deleted.++ ``GiftCard.assigned_to`` uses ``on_delete=PROTECT``, so the assignee+ reference must be cleared before the user is deleted or the deletion is+ refused. Call this inside the deletion transaction, before deleting the+ users, from every mutation that removes users.++ The ``assigned_to`` FK is nulled on every referencing card (otherwise+ PROTECT would still block the delete), while ``assigned_to_email`` is kept+ so the now-inactive card retains who it belonged to. Cards are deactivated+ because they can no longer be validated against their owner. A deactivation+ event is recorded only for cards that were actually active.++ ``users`` may be any iterable or queryset of users.+ """+ # Lock and snapshot every assigned card, including inactive ones. Restricting the+ # snapshot to active cards would allow a concurrent activation to leave a card+ # detached but active.+ assigned_cards = list(+ gift_card_qs_select_for_update()+ .filter(assigned_to__in=users)+ .values_list("pk", "is_active")+ )+ assigned_ids = []+ deactivated_ids = []+ for gift_card_id, is_active in assigned_cards:+ assigned_ids.append(gift_card_id)+ if is_active:+ deactivated_ids.append(gift_card_id)+ # Clear the protected FK and unconditionally deactivate the exact locked set in+ # one update. Already-inactive cards do not receive a duplicate event.+ GiftCard.objects.filter(pk__in=assigned_ids).update(+ assigned_to=None, is_active=False+ )+ if deactivated_ids:+ events.gift_cards_deactivated_event(deactivated_ids, user=None, app=None)++def deactivate_gift_card(gift_card: GiftCard):"""Set gift card status as inactive."""if gift_card.is_active:diff --git a/saleor/graphql/account/bulk_mutations/customer_bulk_delete.py b/saleor/graphql/account/bulk_mutations/customer_bulk_delete.pyindex e756039fa8..52a2f4da85 100644--- a/saleor/graphql/account/bulk_mutations/customer_bulk_delete.py+++ b/saleor/graphql/account/bulk_mutations/customer_bulk_delete.py@@ -2,6 +2,8 @@ import graphenefrom django.conf import settingsfrom ....account import models+from ....core.tracing import traced_atomic_transaction+from ....giftcard.utils import deactivate_assigned_gift_cardsfrom ....permission.enums import AccountPermissionsfrom ....webhook.event_types import WebhookEventAsyncTypefrom ....webhook.utils import get_webhooks_for_event@@ -56,7 +58,12 @@ class CustomerBulkDelete(CustomerDeleteMixin, UserBulkDelete):@classmethoddef bulk_action(cls, info: ResolveInfo, queryset, /):instances = list(queryset)- queryset.delete()+ with traced_atomic_transaction():+ # Required before deleting the users: GiftCard.assigned_to is+ # on_delete=PROTECT, so restricted cards must be detached and+ # deactivated first, atomically with the deletion.+ deactivate_assigned_gift_cards(queryset)+ queryset.delete()webhooks = get_webhooks_for_event(WebhookEventAsyncType.CUSTOMER_DELETED)manager = get_plugin_manager_promise(info.context).get()for instance in instances:diff --git a/saleor/graphql/account/bulk_mutations/staff_bulk_delete.py b/saleor/graphql/account/bulk_mutations/staff_bulk_delete.pyindex a3f0af9467..e11343344b 100644--- a/saleor/graphql/account/bulk_mutations/staff_bulk_delete.py+++ b/saleor/graphql/account/bulk_mutations/staff_bulk_delete.py@@ -4,6 +4,8 @@ from django.conf import settingsfrom django.core.exceptions import ValidationErrorfrom ....account import models+from ....core.tracing import traced_atomic_transaction+from ....giftcard.utils import deactivate_assigned_gift_cardsfrom ....permission.enums import AccountPermissionsfrom ....webhook.event_types import WebhookEventAsyncTypefrom ....webhook.utils import get_webhooks_for_event@@ -69,7 +71,12 @@ class StaffBulkDelete(StaffDeleteMixin, UserBulkDelete):@classmethoddef bulk_action(cls, info: ResolveInfo, queryset, /):instances = list(queryset)- queryset.delete()+ with traced_atomic_transaction():+ # Required before deleting the users: GiftCard.assigned_to is+ # on_delete=PROTECT, so restricted cards must be detached and+ # deactivated first, atomically with the deletion.+ deactivate_assigned_gift_cards(queryset)+ queryset.delete()manager = get_plugin_manager_promise(info.context).get()webhooks = get_webhooks_for_event(WebhookEventAsyncType.STAFF_DELETED)for instance in instances:diff --git a/saleor/graphql/account/mutations/account/account_delete.py b/saleor/graphql/account/mutations/account/account_delete.pyindex bd332fc6b8..f269cf9da6 100644--- a/saleor/graphql/account/mutations/account/account_delete.py+++ b/saleor/graphql/account/mutations/account/account_delete.py@@ -10,6 +10,8 @@ from .....core.tokens import (legacy_account_delete_token_generator,try_generators,)+from .....core.tracing import traced_atomic_transaction+from .....giftcard.utils import deactivate_assigned_gift_cardsfrom .....permission.auth_filters import AuthorizationFiltersfrom .....webhook.event_types import WebhookEventAsyncTypefrom ....core import ResolveInfo@@ -82,7 +84,12 @@ class AccountDelete(ModelDeleteMutation):db_id = user.id- user.delete()+ with traced_atomic_transaction():+ # Required before deleting the user: GiftCard.assigned_to is+ # on_delete=PROTECT, so restricted cards must be detached and+ # deactivated first, atomically with the deletion.+ deactivate_assigned_gift_cards([user])+ user.delete()# After the instance is deleted, set its ID to the original database's# ID so that the success response contains ID of the deleted object.user.id = db_iddiff --git a/saleor/graphql/account/mutations/staff/customer_delete.py b/saleor/graphql/account/mutations/staff/customer_delete.pyindex 5ee5b35dd3..ab3ca4acbd 100644--- a/saleor/graphql/account/mutations/staff/customer_delete.py+++ b/saleor/graphql/account/mutations/staff/customer_delete.py@@ -1,6 +1,8 @@import graphenefrom .....account import models+from .....core.tracing import traced_atomic_transaction+from .....giftcard.utils import deactivate_assigned_gift_cardsfrom .....permission.enums import AccountPermissionsfrom .....webhook.event_types import WebhookEventAsyncTypefrom ....account.types import User@@ -38,10 +40,18 @@ class CustomerDelete(CustomerDeleteMixin, UserDelete):@classmethoddef perform_mutation(cls, root, info: ResolveInfo, /, **data):- results = super().perform_mutation(root, info, **data)+ with traced_atomic_transaction():+ results = super().perform_mutation(root, info, **data)cls.post_process(info)return results+ @classmethod+ def clean_instance(cls, info: ResolveInfo, instance) -> None:+ super().clean_instance(info, instance)+ # Runs inside the deletion transaction, right before the user is+ # removed. Required because GiftCard.assigned_to is on_delete=PROTECT.+ deactivate_assigned_gift_cards([instance])+@classmethoddef post_save_action(cls, info: ResolveInfo, instance, cleaned_input):manager = get_plugin_manager_promise(info.context).get()diff --git a/saleor/graphql/account/mutations/staff/staff_delete.py b/saleor/graphql/account/mutations/staff/staff_delete.pyindex f61f8ba6a8..2c5f1ec92c 100644--- a/saleor/graphql/account/mutations/staff/staff_delete.py+++ b/saleor/graphql/account/mutations/staff/staff_delete.py@@ -1,6 +1,8 @@import graphenefrom .....account import models+from .....core.tracing import traced_atomic_transaction+from .....giftcard.utils import deactivate_assigned_gift_cardsfrom .....permission.enums import AccountPermissionsfrom .....webhook.event_types import WebhookEventAsyncTypefrom ....account.types import User@@ -42,7 +44,12 @@ class StaffDelete(StaffDeleteMixin, UserDelete):cls.clean_instance(info, instance)db_id = instance.id- instance.delete()+ with traced_atomic_transaction():+ # Required before deleting the user: GiftCard.assigned_to is+ # on_delete=PROTECT, so restricted cards must be detached and+ # deactivated first, atomically with the deletion.+ deactivate_assigned_gift_cards([instance])+ instance.delete()# After the instance is deleted, set its ID to the original database's# ID so that the success response contains ID of the deleted object.instance.id = db_iddiff --git a/saleor/graphql/giftcard/dataloaders.py b/saleor/graphql/giftcard/dataloaders.pyindex 2e49a05062..295b4acd18 100644--- a/saleor/graphql/giftcard/dataloaders.py+++ b/saleor/graphql/giftcard/dataloaders.py@@ -1,6 +1,8 @@from collections import defaultdictfrom uuid import UUID+from django.db.models import Q+from ...checkout.models import Checkoutfrom ...giftcard.models import GiftCard, GiftCardEvent, GiftCardTagfrom ...order.models import Order@@ -12,11 +14,16 @@ class GiftCardsByUserLoader(DataLoader[int, list[GiftCard]]):def batch_load(self, keys):gift_cards = GiftCard.objects.using(self.database_connection_name).filter(- used_by_id__in=keys+ Q(used_by_id__in=keys) | Q(assigned_to_id__in=keys))+ key_set = set(keys)gift_cards_by_user_map = defaultdict(list)for gift_card in gift_cards:- gift_cards_by_user_map[gift_card.used_by_id].append(gift_card)+ seen = set()+ for uid in (gift_card.used_by_id, gift_card.assigned_to_id):+ if uid in key_set and uid not in seen:+ gift_cards_by_user_map[uid].append(gift_card)+ seen.add(uid)return [gift_cards_by_user_map.get(user_id, []) for user_id in keys]diff --git a/saleor/graphql/giftcard/filters.py b/saleor/graphql/giftcard/filters.pyindex 201f7529a2..befc7b8bef 100644--- a/saleor/graphql/giftcard/filters.py+++ b/saleor/graphql/giftcard/filters.py@@ -9,6 +9,7 @@ from ...account import models as account_modelsfrom ...giftcard import modelsfrom ...order import models as order_modelsfrom ...product import models as product_models+from ..core.descriptions import ADDED_IN_323, DEPRECATED_IN_3X_INPUTfrom ..core.doc_category import DOC_CATEGORY_GIFT_CARDSfrom ..core.filters import (FilterInputObjectType,@@ -50,6 +51,20 @@ def filter_gift_cards_by_used_by_user(qs, user_pks):return qs.filter(Exists(users.filter(pk=OuterRef("used_by_id"))))+# Intentionally not gated behind MANAGE_USERS (unlike resolving the assignedTo+# User object). Reaching this filter already requires MANAGE_GIFT_CARD, which+# exposes the assignee via the assignedToEmail field, so filtering by a+# caller-supplied user id reveals no additional information. It also only+# narrows gift cards; it never returns a User entity (the only thing gated+# behind MANAGE_USERS). This mirrors the used_by filter. See ADR 0005.+def filter_assigned_to(qs, _, value):+ if value:+ _, user_pks = resolve_global_ids_to_primary_keys(value, "User")+ users = account_models.User.objects.using(qs.db).filter(pk__in=user_pks)+ qs = qs.filter(Exists(users.filter(pk=OuterRef("assigned_to_id"))))+ return qs++def filter_tags_list(qs, _, value):if not value:return qs@@ -93,7 +108,19 @@ def filter_created_by_email(qs, _, value):class GiftCardFilter(MetadataFilterBase):tags = ListObjectTypeFilter(input_class=graphene.String, method=filter_tags_list)products = GlobalIDMultipleChoiceFilter(method=filter_products)- used_by = GlobalIDMultipleChoiceFilter(method=filter_used_by)+ used_by = GlobalIDMultipleChoiceFilter(+ method=filter_used_by,+ help_text=(+ "Filter by the customer who used a gift card." + DEPRECATED_IN_3X_INPUT+ ),+ )+ assigned_to = GlobalIDMultipleChoiceFilter(+ method=filter_assigned_to,+ help_text=(+ "Filter by the customer the gift card usage is restricted to."+ + ADDED_IN_323+ ),+ )used = django_filters.BooleanFilter(method=filter_gift_card_used)currency = django_filters.CharFilter(method=filter_currency)current_balance = ObjectTypeFilter(diff --git a/saleor/graphql/giftcard/mutations/__init__.py b/saleor/graphql/giftcard/mutations/__init__.pyindex 1b13812ff2..c702bad14c 100644--- a/saleor/graphql/giftcard/mutations/__init__.py+++ b/saleor/graphql/giftcard/mutations/__init__.py@@ -1,17 +1,23 @@from .gift_card_activate import GiftCardActivatefrom .gift_card_add_note import GiftCardAddNote+from .gift_card_assign_user import GiftCardAssignUser+from .gift_card_balance_adjust import GiftCardBalanceAdjustfrom .gift_card_create import GiftCardCreatefrom .gift_card_deactivate import GiftCardDeactivatefrom .gift_card_delete import GiftCardDeletefrom .gift_card_resend import GiftCardResend+from .gift_card_unassign_user import GiftCardUnassignUserfrom .gift_card_update import GiftCardUpdate__all__ = ["GiftCardActivate","GiftCardAddNote",+ "GiftCardAssignUser",+ "GiftCardBalanceAdjust","GiftCardCreate","GiftCardDeactivate","GiftCardDelete","GiftCardResend",+ "GiftCardUnassignUser","GiftCardUpdate",]diff --git a/saleor/graphql/giftcard/mutations/gift_card_assign_user.py b/saleor/graphql/giftcard/mutations/gift_card_assign_user.pynew file mode 100644index 0000000000..9e4b2faf29--- /dev/null+++ b/saleor/graphql/giftcard/mutations/gift_card_assign_user.py@@ -0,0 +1,104 @@+import graphene+from django.core.exceptions import ValidationError++from ....account.models import User as UserModel+from ....core.tracing import traced_atomic_transaction+from ....core.utils.events import call_event+from ....giftcard import events+from ....giftcard.error_codes import GiftCardErrorCode+from ....giftcard.utils import GiftCardCannotAssign, assign_gift_card_to_user+from ....permission.enums import GiftcardPermissions+from ....webhook.event_types import WebhookEventAsyncType+from ...account.types import User+from ...app.dataloaders import get_app_promise+from ...core import ResolveInfo+from ...core.descriptions import ADDED_IN_323+from ...core.doc_category import DOC_CATEGORY_GIFT_CARDS+from ...core.mutations import BaseMutation+from ...core.types import GiftCardError+from ...core.utils import WebhookEventInfo+from ...plugins.dataloaders import get_plugin_manager_promise+from ..types import GiftCard+++class GiftCardAssignUser(BaseMutation):+ gift_card = graphene.Field(GiftCard, description="The assigned gift card.")++ class Arguments:+ id = graphene.ID(required=True, description="ID of the gift card.")+ user_id = graphene.ID(+ required=True,+ description="ID of the customer to restrict the card to.",+ )++ class Meta:+ description = (+ "Restrict a gift card so only the given customer can use it. "+ + ADDED_IN_323+ )+ doc_category = DOC_CATEGORY_GIFT_CARDS+ permissions = (GiftcardPermissions.MANAGE_GIFT_CARD,)+ error_type_class = GiftCardError+ error_type_field = "gift_card_errors"+ webhook_events_info = [+ WebhookEventInfo(+ type=WebhookEventAsyncType.GIFT_CARD_UPDATED,+ description="A gift card was updated.",+ )+ ]++ @classmethod+ def perform_mutation( # type: ignore[override]+ cls, _root, info: ResolveInfo, /, *, id, user_id+ ):+ gift_card = cls.get_node_or_error(info, id, only_type=GiftCard, field="id")+ if gift_card is None:+ raise ValidationError(+ {+ "id": ValidationError(+ "Couldn't resolve to a gift card.",+ code=GiftCardErrorCode.NOT_FOUND.value,+ )+ }+ )+ user = cls.get_node_or_error(+ info,+ user_id,+ only_type=User,+ field="user_id",+ qs=UserModel.objects.filter(is_active=True),+ )+ if user is None:+ raise ValidationError(+ {+ "user_id": ValidationError(+ "Couldn't resolve to a user.",+ code=GiftCardErrorCode.NOT_FOUND.value,+ )+ }+ )++ previous_user_id = gift_card.assigned_to_id+ previous_email = gift_card.assigned_to_email++ staff = info.context.user+ app = get_app_promise(info.context).get()++ try:+ with traced_atomic_transaction():+ assign_gift_card_to_user(gift_card, user)+ events.gift_card_assigned_event(+ gift_card, previous_user_id, previous_email, staff, app+ )+ except GiftCardCannotAssign as e:+ raise ValidationError(+ {+ "id": ValidationError(+ str(e), code=GiftCardErrorCode.CANNOT_ASSIGN.value+ )+ }+ ) from e++ manager = get_plugin_manager_promise(info.context).get()+ call_event(manager.gift_card_updated, gift_card)+ return cls(gift_card=gift_card, errors=[])diff --git a/saleor/graphql/giftcard/mutations/gift_card_balance_adjust.py b/saleor/graphql/giftcard/mutations/gift_card_balance_adjust.pynew file mode 100644index 0000000000..ccf3f834d7--- /dev/null+++ b/saleor/graphql/giftcard/mutations/gift_card_balance_adjust.py@@ -0,0 +1,109 @@+from decimal import Decimal++import graphene+from django.core.exceptions import ValidationError++from ....core.tracing import traced_atomic_transaction+from ....core.utils.events import call_event+from ....giftcard import events+from ....giftcard.error_codes import GiftCardErrorCode+from ....giftcard.lock_objects import gift_card_qs_select_for_update+from ....permission.enums import GiftcardPermissions+from ....webhook.event_types import WebhookEventAsyncType+from ...app.dataloaders import get_app_promise+from ...core import ResolveInfo+from ...core.descriptions import ADDED_IN_323+from ...core.doc_category import DOC_CATEGORY_GIFT_CARDS+from ...core.mutations import BaseMutation+from ...core.scalars import Decimal as DecimalScalar+from ...core.types import GiftCardError+from ...core.utils import WebhookEventInfo+from ...core.validators import validate_price_precision+from ...plugins.dataloaders import get_plugin_manager_promise+from ..types import GiftCard+++class GiftCardBalanceAdjust(BaseMutation):+ gift_card = graphene.Field(GiftCard, description="The adjusted gift card.")++ class Arguments:+ id = graphene.ID(required=True, description="ID of the gift card to adjust.")+ amount = DecimalScalar(+ required=True,+ description=(+ "Signed amount to adjust the current balance by. Positive tops up, "+ "negative deducts. A deduction below zero clamps the balance to zero. "+ "A top-up above the initial balance raises the initial balance to the "+ "new current balance. " + ADDED_IN_323+ ),+ )++ class Meta:+ description = "Adjust a gift card's balance by a delta. " + ADDED_IN_323+ doc_category = DOC_CATEGORY_GIFT_CARDS+ permissions = (GiftcardPermissions.MANAGE_GIFT_CARD,)+ error_type_class = GiftCardError+ error_type_field = "gift_card_errors"+ webhook_events_info = [+ WebhookEventInfo(+ type=WebhookEventAsyncType.GIFT_CARD_UPDATED,+ description="A gift card was updated.",+ )+ ]++ @classmethod+ def perform_mutation( # type: ignore[override]+ cls, _root, info: ResolveInfo, /, *, id, amount+ ):+ gift_card = cls.get_node_or_error(info, id, only_type=GiftCard, field="id")+ if gift_card is None:+ raise ValidationError(+ {+ "id": ValidationError(+ "Couldn't resolve to a gift card.",+ code=GiftCardErrorCode.NOT_FOUND.value,+ )+ }+ )++ if amount == Decimal(0):+ raise ValidationError(+ {+ "amount": ValidationError(+ "Adjustment amount cannot be zero.",+ code=GiftCardErrorCode.INVALID.value,+ )+ }+ )+ try:+ validate_price_precision(abs(amount), gift_card.currency)+ except ValidationError as e:+ e.code = GiftCardErrorCode.INVALID.value+ raise ValidationError({"amount": e}) from e++ user = info.context.user+ app = get_app_promise(info.context).get()++ with traced_atomic_transaction():+ locked = gift_card_qs_select_for_update().get(pk=gift_card.pk)+ old_current = locked.current_balance_amount+ old_initial = locked.initial_balance_amount++ new_current = old_current + amount+ if new_current < Decimal(0):+ new_current = Decimal(0)+ locked.current_balance_amount = new_current+ update_fields = ["current_balance_amount"]+ if new_current > old_initial:+ locked.initial_balance_amount = new_current+ update_fields.append("initial_balance_amount")+ locked.save(update_fields=update_fields)++ events.gift_card_balance_adjusted_event(+ locked, old_current, old_initial, user, app+ )++ manager = get_plugin_manager_promise(info.context).get()+ call_event(manager.gift_card_updated, locked)++ return cls(gift_card=locked, errors=[])diff --git a/saleor/graphql/giftcard/mutations/gift_card_create.py b/saleor/graphql/giftcard/mutations/gift_card_create.pyindex 6d386ed24b..7151d2c8c7 100644--- a/saleor/graphql/giftcard/mutations/gift_card_create.py+++ b/saleor/graphql/giftcard/mutations/gift_card_create.py@@ -1,4 +1,5 @@from collections.abc import Iterable+from typing import castimport graphenefrom django.core.exceptions import ValidationError@@ -15,7 +16,7 @@ from ....permission.enums import GiftcardPermissionsfrom ....webhook.event_types import WebhookEventAsyncTypefrom ...app.dataloaders import get_app_promisefrom ...core import ResolveInfo-from ...core.descriptions import DEPRECATED_IN_3X_INPUT+from ...core.descriptions import ADDED_IN_323, DEPRECATED_IN_3X_INPUTfrom ...core.doc_category import DOC_CATEGORY_GIFT_CARDSfrom ...core.mutations import DeprecatedModelMutationfrom ...core.scalars import Date@@ -89,6 +90,12 @@ class GiftCardCreateInput(GiftCardInput):),)note = graphene.String(description="The gift card note from the staff member.")+ assigned_to = graphene.ID(+ required=False,+ description=(+ "ID of the customer the gift card is restricted to. " + ADDED_IN_323+ ),+ )class Meta:doc_category = DOC_CATEGORY_GIFT_CARDS@@ -167,6 +174,17 @@ class GiftCardCreate(DeprecatedModelMutation):)cleaned_input["customer_user"] = User.objects.filter(email=email).first()+ if assigned_to_id := data.get("assigned_to"):+ assigned_user = cast(+ User | None,+ cls.get_node_or_error(+ info, assigned_to_id, only_type="User", field="assigned_to"+ ),+ )+ if assigned_user:+ cleaned_input["assigned_to"] = assigned_user+ cleaned_input["assigned_to_email"] = assigned_user.email+return cleaned_input@staticmethod@@ -233,6 +251,14 @@ class GiftCardCreate(DeprecatedModelMutation):user=user,app=app,)+ if instance.assigned_to_id:+ events.gift_card_assigned_event(+ gift_card=instance,+ previous_user_id=None,+ previous_email=None,+ user=user,+ app=app,+ )manager = get_plugin_manager_promise(info.context).get()if note := cleaned_input.get("note"):events.gift_card_note_added_event(diff --git a/saleor/graphql/giftcard/mutations/gift_card_unassign_user.py b/saleor/graphql/giftcard/mutations/gift_card_unassign_user.pynew file mode 100644index 0000000000..a166422831--- /dev/null+++ b/saleor/graphql/giftcard/mutations/gift_card_unassign_user.py@@ -0,0 +1,70 @@+import graphene+from django.core.exceptions import ValidationError++from ....core.tracing import traced_atomic_transaction+from ....core.utils.events import call_event+from ....giftcard import events+from ....giftcard.error_codes import GiftCardErrorCode+from ....permission.enums import GiftcardPermissions+from ....webhook.event_types import WebhookEventAsyncType+from ...app.dataloaders import get_app_promise+from ...core import ResolveInfo+from ...core.descriptions import ADDED_IN_323+from ...core.doc_category import DOC_CATEGORY_GIFT_CARDS+from ...core.mutations import BaseMutation+from ...core.types import GiftCardError+from ...core.utils import WebhookEventInfo+from ...plugins.dataloaders import get_plugin_manager_promise+from ..types import GiftCard+++class GiftCardUnassignUser(BaseMutation):+ gift_card = graphene.Field(GiftCard, description="The unassigned gift card.")++ class Arguments:+ id = graphene.ID(required=True, description="ID of the gift card.")++ class Meta:+ description = "Remove a customer restriction from a gift card. " + ADDED_IN_323+ doc_category = DOC_CATEGORY_GIFT_CARDS+ permissions = (GiftcardPermissions.MANAGE_GIFT_CARD,)+ error_type_class = GiftCardError+ error_type_field = "gift_card_errors"+ webhook_events_info = [+ WebhookEventInfo(+ type=WebhookEventAsyncType.GIFT_CARD_UPDATED,+ description="A gift card was updated.",+ )+ ]++ @classmethod+ def perform_mutation( # type: ignore[override]+ cls, _root, info: ResolveInfo, /, *, id+ ):+ gift_card = cls.get_node_or_error(info, id, only_type=GiftCard, field="id")+ if gift_card is None:+ raise ValidationError(+ {+ "id": ValidationError(+ "Couldn't resolve to a gift card.",+ code=GiftCardErrorCode.NOT_FOUND.value,+ )+ }+ )+ previous_user_id = gift_card.assigned_to_id+ previous_email = gift_card.assigned_to_email++ staff = info.context.user+ app = get_app_promise(info.context).get()++ with traced_atomic_transaction():+ gift_card.assigned_to = None+ gift_card.assigned_to_email = None+ gift_card.save(update_fields=["assigned_to", "assigned_to_email"])+ events.gift_card_unassigned_event(+ gift_card, previous_user_id, previous_email, staff, app+ )++ manager = get_plugin_manager_promise(info.context).get()+ call_event(manager.gift_card_updated, gift_card)+ return cls(gift_card=gift_card, errors=[])diff --git a/saleor/graphql/giftcard/schema.py b/saleor/graphql/giftcard/schema.pyindex f3a402867b..3fdfe5a5d7 100644--- a/saleor/graphql/giftcard/schema.py+++ b/saleor/graphql/giftcard/schema.py@@ -24,10 +24,13 @@ from .filters import GiftCardFilterInput, GiftCardTagFilterInputfrom .mutations import (GiftCardActivate,GiftCardAddNote,+ GiftCardAssignUser,+ GiftCardBalanceAdjust,GiftCardCreate,GiftCardDeactivate,GiftCardDelete,GiftCardResend,+ GiftCardUnassignUser,GiftCardUpdate,)from .resolvers import resolve_gift_card, resolve_gift_card_tags, resolve_gift_cards@@ -136,6 +139,9 @@ class GiftCardQueries(graphene.ObjectType):class GiftCardMutations(graphene.ObjectType):gift_card_activate = GiftCardActivate.Field()+ gift_card_assign_user = GiftCardAssignUser.Field()+ gift_card_unassign_user = GiftCardUnassignUser.Field()+ gift_card_balance_adjust = GiftCardBalanceAdjust.Field()gift_card_create = GiftCardCreate.Field()gift_card_delete = GiftCardDelete.Field()gift_card_deactivate = GiftCardDeactivate.Field()diff --git a/saleor/graphql/giftcard/tests/mutations/test_gift_card_assign_user.py b/saleor/graphql/giftcard/tests/mutations/test_gift_card_assign_user.pynew file mode 100644index 0000000000..ae5ec67b98--- /dev/null+++ b/saleor/graphql/giftcard/tests/mutations/test_gift_card_assign_user.py@@ -0,0 +1,211 @@+import graphene+from django.utils import timezone++from .....giftcard import GiftCardEvents+from .....giftcard.error_codes import GiftCardErrorCode+from .....giftcard.utils import assign_gift_card_to_user+from ....tests.utils import assert_no_permission, get_graphql_content++MUTATION = """+ mutation Assign($id: ID!, $userId: ID!) {+ giftCardAssignUser(id: $id, userId: $userId) {+ giftCard {+ id+ events {+ type+ assignedTo {+ oldAssignedTo { email }+ currentAssignedTo { email }+ oldAssignedToEmail+ currentAssignedToEmail+ }+ }+ }+ errors { field code message }+ }+ }+"""+++def _assign_event(gift_card_data):+ return next(+ event+ for event in gift_card_data["events"]+ if event["type"] == GiftCardEvents.ASSIGNED_TO_USER.upper()+ )+++def _vars(gift_card, user):+ return {+ "id": graphene.Node.to_global_id("GiftCard", gift_card.pk),+ "userId": graphene.Node.to_global_id("User", user.pk),+ }+++def test_assign_user(+ staff_api_client,+ gift_card,+ customer_user,+ permission_manage_gift_card,+ permission_manage_users,+):+ # when+ response = staff_api_client.post_graphql(+ MUTATION,+ _vars(gift_card, customer_user),+ permissions=[permission_manage_gift_card, permission_manage_users],+ )++ # then+ data = get_graphql_content(response)["data"]["giftCardAssignUser"]+ assert data["errors"] == []+ gift_card.refresh_from_db()+ assert gift_card.assigned_to == customer_user+ assert gift_card.assigned_to_email == customer_user.email+ assert gift_card.events.filter(type=GiftCardEvents.ASSIGNED_TO_USER).count() == 1++ assignment = _assign_event(data["giftCard"])["assignedTo"]+ assert assignment["oldAssignedTo"] is None+ assert assignment["oldAssignedToEmail"] is None+ assert assignment["currentAssignedTo"]["email"] == customer_user.email+ assert assignment["currentAssignedToEmail"] == customer_user.email+++def test_reassign_records_previous(+ staff_api_client,+ gift_card,+ customer_user,+ staff_user,+ permission_manage_gift_card,+ permission_manage_users,+):+ # given+ assign_gift_card_to_user(gift_card, staff_user)++ # when+ response = staff_api_client.post_graphql(+ MUTATION,+ _vars(gift_card, customer_user),+ permissions=[permission_manage_gift_card, permission_manage_users],+ )++ # then+ data = get_graphql_content(response)["data"]["giftCardAssignUser"]+ assert data["errors"] == []+ event = gift_card.events.filter(type=GiftCardEvents.ASSIGNED_TO_USER).last()+ assert event.parameters["previous_assigned_to_id"] == staff_user.id+ assert event.parameters["assigned_to_id"] == customer_user.id++ assignment = _assign_event(data["giftCard"])["assignedTo"]+ assert assignment["oldAssignedTo"]["email"] == staff_user.email+ assert assignment["oldAssignedToEmail"] == staff_user.email+ assert assignment["currentAssignedTo"]["email"] == customer_user.email+ assert assignment["currentAssignedToEmail"] == customer_user.email+++def test_assigned_to_user_fields_require_manage_users(+ staff_api_client, gift_card, customer_user, permission_manage_gift_card+):+ # given a requester with MANAGE_GIFT_CARD but not MANAGE_USERS++ # when+ response = staff_api_client.post_graphql(+ MUTATION,+ _vars(gift_card, customer_user),+ permissions=[permission_manage_gift_card],+ )++ # then the User sub-field is denied while the email sub-field still resolves+ content = get_graphql_content(response, ignore_errors=True)+ data = content["data"]["giftCardAssignUser"]+ assert data["errors"] == []+ assignment = _assign_event(data["giftCard"])["assignedTo"]+ assert assignment["currentAssignedTo"] is None+ assert assignment["currentAssignedToEmail"] == customer_user.email+ assert any(+ error["message"] == "To access this path, you need one of the following "+ "permissions: MANAGE_USERS, MANAGE_STAFF, OWNER"+ for error in content["errors"]+ )+++def test_assign_blocked_when_used(+ staff_api_client, gift_card_used, customer_user, permission_manage_gift_card+):+ # given+ gift_card_used.last_used_on = timezone.now()+ gift_card_used.save(update_fields=["last_used_on"])++ # when+ response = staff_api_client.post_graphql(+ MUTATION,+ _vars(gift_card_used, customer_user),+ permissions=[permission_manage_gift_card],+ )++ # then+ data = get_graphql_content(response)["data"]["giftCardAssignUser"]+ assert len(data["errors"]) == 1+ assert data["errors"][0]["code"] == GiftCardErrorCode.CANNOT_ASSIGN.name+++def test_requires_permission(staff_api_client, gift_card, customer_user):+ # when+ response = staff_api_client.post_graphql(MUTATION, _vars(gift_card, customer_user))++ # then+ assert_no_permission(response)+ gift_card.refresh_from_db()+ assert gift_card.assigned_to is None+ assert gift_card.assigned_to_email is None+++def test_empty_gift_card_id_is_rejected(+ staff_api_client,+ customer_user,+ permission_manage_gift_card,+ permission_manage_users,+):+ # given+ variables = {+ "id": "",+ "userId": graphene.Node.to_global_id("User", customer_user.pk),+ }++ # when+ response = staff_api_client.post_graphql(+ MUTATION,+ variables,+ permissions=[permission_manage_gift_card, permission_manage_users],+ )++ # then+ data = get_graphql_content(response)["data"]["giftCardAssignUser"]+ assert len(data["errors"]) == 1+ assert data["errors"][0]["field"] == "id"+ assert data["errors"][0]["code"] == GiftCardErrorCode.NOT_FOUND.name+++def test_empty_user_id_is_rejected(+ staff_api_client, gift_card, permission_manage_gift_card, permission_manage_users+):+ # given+ variables = {+ "id": graphene.Node.to_global_id("GiftCard", gift_card.pk),+ "userId": "",+ }++ # when+ response = staff_api_client.post_graphql(+ MUTATION,+ variables,+ permissions=[permission_manage_gift_card, permission_manage_users],+ )++ # then+ data = get_graphql_content(response)["data"]["giftCardAssignUser"]+ assert len(data["errors"]) == 1+ assert data["errors"][0]["field"] == "userId"+ assert data["errors"][0]["code"] == GiftCardErrorCode.NOT_FOUND.name+ gift_card.refresh_from_db()+ assert gift_card.assigned_to is Nonediff --git a/saleor/graphql/giftcard/tests/mutations/test_gift_card_balance_adjust.py b/saleor/graphql/giftcard/tests/mutations/test_gift_card_balance_adjust.pynew file mode 100644index 0000000000..582a2426d9--- /dev/null+++ b/saleor/graphql/giftcard/tests/mutations/test_gift_card_balance_adjust.py@@ -0,0 +1,143 @@+from decimal import Decimal++import graphene++from .....giftcard import GiftCardEvents+from .....giftcard.error_codes import GiftCardErrorCode+from .....giftcard.models import GiftCardEvent+from ....tests.utils import assert_no_permission, get_graphql_content++MUTATION = """+ mutation GiftCardBalanceAdjust($id: ID!, $amount: Decimal!) {+ giftCardBalanceAdjust(id: $id, amount: $amount) {+ giftCard {+ id+ currentBalance { amount }+ initialBalance { amount }+ }+ errors { field code message }+ }+ }+"""+++def _adjust(api_client, gift_card, amount, permissions=None):+ variables = {+ "id": graphene.Node.to_global_id("GiftCard", gift_card.pk),+ "amount": str(amount),+ }+ kwargs = {"permissions": permissions} if permissions is not None else {}+ response = api_client.post_graphql(MUTATION, variables, **kwargs)+ return response+++def test_increase_balance(staff_api_client, gift_card, permission_manage_gift_card):+ # given+ gift_card.current_balance_amount = Decimal("50.00")+ gift_card.initial_balance_amount = Decimal("100.00")+ gift_card.save(update_fields=["current_balance_amount", "initial_balance_amount"])++ # when+ response = _adjust(+ staff_api_client, gift_card, Decimal("20.00"), [permission_manage_gift_card]+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["giftCardBalanceAdjust"]+ assert data["errors"] == []+ assert data["giftCard"]["currentBalance"]["amount"] == 70.0+ assert data["giftCard"]["initialBalance"]["amount"] == 100.0+ gift_card.refresh_from_db()+ assert gift_card.current_balance_amount == Decimal("70.00")+ assert gift_card.events.filter(type=GiftCardEvents.BALANCE_ADJUSTED).count() == 1+++def test_increase_above_initial_bumps_initial(+ staff_api_client, gift_card, permission_manage_gift_card+):+ # given+ gift_card.current_balance_amount = Decimal("90.00")+ gift_card.initial_balance_amount = Decimal("100.00")+ gift_card.save(update_fields=["current_balance_amount", "initial_balance_amount"])++ # when+ response = _adjust(+ staff_api_client, gift_card, Decimal("30.00"), [permission_manage_gift_card]+ )++ # then+ data = get_graphql_content(response)["data"]["giftCardBalanceAdjust"]+ assert data["giftCard"]["currentBalance"]["amount"] == 120.0+ assert data["giftCard"]["initialBalance"]["amount"] == 120.0+++def test_decrease_clamps_to_zero(+ staff_api_client, gift_card, permission_manage_gift_card+):+ # given+ gift_card.current_balance_amount = Decimal("10.00")+ gift_card.initial_balance_amount = Decimal("100.00")+ gift_card.save(update_fields=["current_balance_amount", "initial_balance_amount"])++ # when+ response = _adjust(+ staff_api_client, gift_card, Decimal("-25.00"), [permission_manage_gift_card]+ )++ # then+ data = get_graphql_content(response)["data"]["giftCardBalanceAdjust"]+ assert data["giftCard"]["currentBalance"]["amount"] == 0.0+ assert data["giftCard"]["initialBalance"]["amount"] == 100.0+++def test_zero_amount_is_rejected(+ staff_api_client, gift_card, permission_manage_gift_card+):+ # given+ balance_before = gift_card.current_balance_amount++ # when+ response = _adjust(+ staff_api_client, gift_card, Decimal(0), [permission_manage_gift_card]+ )++ # then+ data = get_graphql_content(response)["data"]["giftCardBalanceAdjust"]+ assert len(data["errors"]) == 1+ assert data["errors"][0]["field"] == "amount"+ assert data["errors"][0]["code"] == GiftCardErrorCode.INVALID.name+ gift_card.refresh_from_db()+ assert gift_card.current_balance_amount == balance_before+ assert not GiftCardEvent.objects.filter(+ gift_card=gift_card, type=GiftCardEvents.BALANCE_ADJUSTED+ ).exists()+++def test_requires_permission(staff_api_client, gift_card):+ # given+ balance_before = gift_card.current_balance_amount++ # when+ response = _adjust(staff_api_client, gift_card, Decimal("10.00"))++ # then+ assert_no_permission(response)+ gift_card.refresh_from_db()+ assert gift_card.current_balance_amount == balance_before+++def test_empty_id_is_rejected(staff_api_client, permission_manage_gift_card):+ # given+ variables = {"id": "", "amount": "10.00"}++ # when+ response = staff_api_client.post_graphql(+ MUTATION, variables, permissions=[permission_manage_gift_card]+ )++ # then+ data = get_graphql_content(response)["data"]["giftCardBalanceAdjust"]+ assert len(data["errors"]) == 1+ assert data["errors"][0]["field"] == "id"+ assert data["errors"][0]["code"] == GiftCardErrorCode.NOT_FOUND.namediff --git a/saleor/graphql/giftcard/tests/mutations/test_gift_card_create.py b/saleor/graphql/giftcard/tests/mutations/test_gift_card_create.pyindex 09404a389d..a6fcaba0b8 100644--- a/saleor/graphql/giftcard/tests/mutations/test_gift_card_create.py+++ b/saleor/graphql/giftcard/tests/mutations/test_gift_card_create.py@@ -677,6 +677,7 @@ def test_create_gift_card_trigger_webhook(permissions=[permission_manage_gift_card, permission_manage_users],)gift_card = GiftCard.objects.last()+ assert gift_card is not None# thencontent = get_graphql_content(response)@@ -751,6 +752,7 @@ def test_create_gift_card_with_email_triggers_gift_card_sent_webhook(permissions=[permission_manage_gift_card, permission_manage_users],)gift_card = GiftCard.objects.last()+ assert gift_card is not None# thencontent = get_graphql_content(response)@@ -1006,3 +1008,74 @@ def test_create_gift_card_with_private_and_public_metadata(assert data["metadata"][0]["value"] == metadata_valueassert data["privateMetadata"][0]["key"] == metadata_keyassert data["privateMetadata"][0]["value"] == metadata_value+++def test_create_with_assigned_to(+ staff_api_client, customer_user, permission_manage_gift_card+):+ # given+ query = """+ mutation Create($input: GiftCardCreateInput!) {+ giftCardCreate(input: $input) {+ giftCard { id }+ errors { field code }+ }+ }+ """+ variables = {+ "input": {+ "balance": {"amount": 100, "currency": "USD"},+ "isActive": True,+ "assignedTo": graphene.Node.to_global_id("User", customer_user.pk),+ }+ }++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_gift_card]+ )++ # then+ data = get_graphql_content(response)["data"]["giftCardCreate"]+ assert data["errors"] == []+ gift_card = GiftCard.objects.get(+ pk=graphene.Node.from_global_id(data["giftCard"]["id"])[1]+ )+ assert gift_card.assigned_to == customer_user+ assert gift_card.assigned_to_email == customer_user.email+ assert gift_card.events.filter(type=GiftCardEvents.ASSIGNED_TO_USER).count() == 1+++def test_create_with_assigned_to_not_found(+ staff_api_client, permission_manage_gift_card+):+ # given+ query = """+ mutation Create($input: GiftCardCreateInput!) {+ giftCardCreate(input: $input) {+ giftCard { id }+ errors { field code }+ }+ }+ """+ non_existing_id = graphene.Node.to_global_id("User", -1)+ variables = {+ "input": {+ "balance": {"amount": 100, "currency": "USD"},+ "isActive": True,+ "assignedTo": non_existing_id,+ }+ }++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_gift_card]+ )++ # then+ data = get_graphql_content(response)["data"]["giftCardCreate"]+ assert data["giftCard"] is None+ assert len(data["errors"]) == 1+ assert data["errors"][0]["field"] == "assignedTo"+ assert data["errors"][0]["code"] == GiftCardErrorCode.NOT_FOUND.name+ assert GiftCard.objects.count() == 0diff --git a/saleor/graphql/giftcard/tests/mutations/test_gift_card_unassign_user.py b/saleor/graphql/giftcard/tests/mutations/test_gift_card_unassign_user.pynew file mode 100644index 0000000000..6ef931de40--- /dev/null+++ b/saleor/graphql/giftcard/tests/mutations/test_gift_card_unassign_user.py@@ -0,0 +1,132 @@+import graphene++from .....giftcard import GiftCardEvents+from .....giftcard.error_codes import GiftCardErrorCode+from .....giftcard.utils import assign_gift_card_to_user+from .....permission.enums import AccountPermissions+from ....tests.utils import assert_no_permission, get_graphql_content++MUTATION = """+ mutation Unassign($id: ID!) {+ giftCardUnassignUser(id: $id) {+ giftCard {+ id+ events {+ type+ assignedTo {+ oldAssignedTo { email }+ currentAssignedTo { email }+ oldAssignedToEmail+ currentAssignedToEmail+ }+ }+ }+ errors { field code message }+ }+ }+"""+++def _unassign_event(gift_card_data):+ return next(+ event+ for event in gift_card_data["events"]+ if event["type"] == GiftCardEvents.UNASSIGNED_FROM_USER.upper()+ )+++def test_unassign_clears_fields(+ staff_api_client,+ gift_card,+ customer_user,+ permission_manage_gift_card,+ permission_manage_users,+):+ # given+ assign_gift_card_to_user(gift_card, customer_user)+ variables = {"id": graphene.Node.to_global_id("GiftCard", gift_card.pk)}++ # when+ response = staff_api_client.post_graphql(+ MUTATION,+ variables,+ permissions=[permission_manage_gift_card, permission_manage_users],+ )++ # then+ data = get_graphql_content(response)["data"]["giftCardUnassignUser"]+ assert data["errors"] == []+ gift_card.refresh_from_db()+ assert gift_card.assigned_to is None+ assert gift_card.assigned_to_email is None+ assert (+ gift_card.events.filter(type=GiftCardEvents.UNASSIGNED_FROM_USER).count() == 1+ )++ assignment = _unassign_event(data["giftCard"])["assignedTo"]+ assert assignment["oldAssignedTo"]["email"] == customer_user.email+ assert assignment["oldAssignedToEmail"] == customer_user.email+ assert assignment["currentAssignedTo"] is None+ assert assignment["currentAssignedToEmail"] is None+++def test_requires_permission(staff_api_client, gift_card, customer_user):+ # given+ assert gift_card.assigned_to is None+ assert gift_card.assigned_to_email is None+ assign_gift_card_to_user(gift_card, customer_user)++ # when+ variables = {"id": graphene.Node.to_global_id("GiftCard", gift_card.pk)}+ response = staff_api_client.post_graphql(MUTATION, variables)++ # then+ assert_no_permission(response)+ gift_card.refresh_from_db()+ assert gift_card.assigned_to == customer_user+ assert gift_card.assigned_to_email == customer_user.email+++def test_assigned_to_user_fields_require_manage_users(+ staff_api_client, gift_card, customer_user, permission_manage_gift_card+):+ # given a requester with MANAGE_GIFT_CARD but not MANAGE_USERS+ assign_gift_card_to_user(gift_card, customer_user)+ variables = {"id": graphene.Node.to_global_id("GiftCard", gift_card.pk)}++ # when+ response = staff_api_client.post_graphql(+ MUTATION, variables, permissions=[permission_manage_gift_card]+ )++ # then the event User sub-field is denied while the email sub-field resolves+ content = get_graphql_content(response, ignore_errors=True)+ data = content["data"]["giftCardUnassignUser"]+ assert data["errors"] == []+ assignment = _unassign_event(data["giftCard"])["assignedTo"]+ assert assignment["oldAssignedTo"] is None+ assert assignment["oldAssignedToEmail"] == customer_user.email+ assert any(+ AccountPermissions.MANAGE_USERS.name in error["message"]+ for error in content["errors"]+ )+++def test_empty_id_is_rejected(+ staff_api_client, permission_manage_gift_card, permission_manage_users+):+ # given+ variables = {"id": ""}++ # when+ response = staff_api_client.post_graphql(+ MUTATION,+ variables,+ permissions=[permission_manage_gift_card, permission_manage_users],+ )++ # then+ data = get_graphql_content(response)["data"]["giftCardUnassignUser"]+ assert len(data["errors"]) == 1+ assert data["errors"][0]["field"] == "id"+ assert data["errors"][0]["code"] == GiftCardErrorCode.NOT_FOUND.namediff --git a/saleor/graphql/giftcard/tests/queries/test_gift_card.py b/saleor/graphql/giftcard/tests/queries/test_gift_card.pyindex 815a4389b9..6b68875001 100644--- a/saleor/graphql/giftcard/tests/queries/test_gift_card.py+++ b/saleor/graphql/giftcard/tests/queries/test_gift_card.py@@ -7,6 +7,7 @@ from django.utils import timezonefrom .....giftcard import GiftCardEvents, eventsfrom .....giftcard.models import GiftCardEvent+from .....permission.enums import AccountPermissionsfrom ....tests.utils import (assert_no_permission,get_graphql_content,@@ -873,3 +874,83 @@ def test_query_gift_card_events_filter_by_orders_no_events(data = content["data"]["giftCard"]events_data = data["events"]assert not events_data+++ASSIGNED_TO_QUERY = """+ query GiftCard($id: ID!) {+ giftCard(id: $id) {+ assignedTo { email }+ assignedToEmail+ }+ }+"""++ASSIGNED_FIELD_QUERY = """+ query GiftCard($id: ID!) {+ giftCard(id: $id) { %s }+ }+"""+++ ("field", "extract"),+ [+ ("assignedTo { email }", lambda data: data["assignedTo"]["email"]),+ ("assignedToEmail", lambda data: data["assignedToEmail"]),+ ],+)+def test_assigned_field_visible_with_manage_users(+ field,+ extract,+ staff_api_client,+ gift_card,+ customer_user,+ permission_manage_gift_card,+ permission_manage_users,+):+ # given each assignment field is queried in isolation so a broken+ # authorization check on one cannot be masked by the other+ gift_card.assigned_to = customer_user+ gift_card.assigned_to_email = customer_user.email+ gift_card.save(update_fields=["assigned_to", "assigned_to_email"])+ variables = {"id": graphene.Node.to_global_id("GiftCard", gift_card.pk)}++ # when+ response = staff_api_client.post_graphql(+ ASSIGNED_FIELD_QUERY % field,+ variables,+ permissions=[permission_manage_gift_card, permission_manage_users],+ )++ # then+ data = get_graphql_content(response)["data"]["giftCard"]+ assert extract(data) == customer_user.email, (+ "should be visible when the user has MANAGE_USERS permission"+ )+++def test_assigned_to_requires_manage_users(+ staff_api_client, gift_card, customer_user, permission_manage_gift_card+):+ # given a requester with MANAGE_GIFT_CARD but not MANAGE_USERS+ gift_card.assigned_to = customer_user+ gift_card.assigned_to_email = customer_user.email+ gift_card.save(update_fields=["assigned_to", "assigned_to_email"])+ variables = {"id": graphene.Node.to_global_id("GiftCard", gift_card.pk)}++ # when+ response = staff_api_client.post_graphql(+ ASSIGNED_TO_QUERY, variables, permissions=[permission_manage_gift_card]+ )++ # then the assignedTo user is denied while the email (MANAGE_GIFT_CARD) resolves+ content = get_graphql_content(response, ignore_errors=True)+ data = content["data"]["giftCard"]+ assert data["assignedTo"] is None+ assert data["assignedToEmail"] == customer_user.email, (+ "should be visible when the user has MANAGE_GIFT_CARD permission"+ )+ errors = content["errors"]+ assert len(errors) == 1+ assert AccountPermissions.MANAGE_USERS.name in errors[0]["message"]+ assert errors[0]["path"] == ["giftCard", "assignedTo"]diff --git a/saleor/graphql/giftcard/tests/queries/test_gift_card_filtering.py b/saleor/graphql/giftcard/tests/queries/test_gift_card_filtering.pyindex 94c35fe10e..e6f398ffb3 100644--- a/saleor/graphql/giftcard/tests/queries/test_gift_card_filtering.py+++ b/saleor/graphql/giftcard/tests/queries/test_gift_card_filtering.py@@ -141,6 +141,37 @@ def test_query_filter_gift_cards_by_used_by_user()+def test_query_filter_gift_cards_by_assigned_to_user(+ staff_api_client,+ gift_card,+ gift_card_expiry_date,+ gift_card_used,+ customer_user,+ permission_manage_gift_card,+):+ # given+ query = QUERY_GIFT_CARDS+ gift_card_used.assigned_to = customer_user+ gift_card_used.save(update_fields=["assigned_to"])++ variables = {+ "filter": {"assignedTo": [graphene.Node.to_global_id("User", customer_user.pk)]}+ }++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_gift_card]+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["giftCards"]["edges"]+ assert len(data) == 1+ assert data[0]["node"]["id"] == graphene.Node.to_global_id(+ "GiftCard", gift_card_used.pk+ )++@pytest.mark.parametrize(("filter_value", "expected_gift_card_indexes"),[("PLN", [0]), ("USD", [1, 2]), ("EUR", []), ("", [0, 1, 2])],diff --git a/saleor/graphql/giftcard/tests/queries/test_gift_cards.py b/saleor/graphql/giftcard/tests/queries/test_gift_cards.pyindex 82efc0536c..00301e3b5d 100644--- a/saleor/graphql/giftcard/tests/queries/test_gift_cards.py+++ b/saleor/graphql/giftcard/tests/queries/test_gift_cards.py@@ -1,5 +1,7 @@import graphene+import pytest+from .....core.anonymize import obfuscate_emailfrom ....tests.utils import get_graphql_contentQUERY_GIFT_CARDS = """@@ -94,3 +96,173 @@ def test_query_own_gift_cards(assert data["edges"][0]["node"]["last4CodeChars"] == gift_card_used.display_codeassert data["edges"][0]["node"]["code"] == gift_card_used.codeassert data["totalCount"] == 1+++ME_GIFT_CARDS = """+ query { me { giftCards(first: 10) { edges { node { id } } } } }+"""+++def test_me_gift_cards_includes_assigned(user_api_client, gift_card, customer_user):+ # given+ gift_card.used_by = None+ gift_card.assigned_to = customer_user+ gift_card.assigned_to_email = customer_user.email+ gift_card.save(update_fields=["used_by", "assigned_to", "assigned_to_email"])++ # when+ response = user_api_client.post_graphql(ME_GIFT_CARDS, {})++ # then+ edges = get_graphql_content(response)["data"]["me"]["giftCards"]["edges"]+ ids = {e["node"]["id"] for e in edges}+ assert graphene.Node.to_global_id("GiftCard", gift_card.pk) in ids+++ME_ASSIGNED_FIELD = """+ query MeAssignedField {+ me {+ giftCards(first: 10) {+ edges { node { id %s } }+ }+ }+ }+"""+++ ("field", "extract"),+ [+ ("assignedTo { email }", lambda node: node["assignedTo"]["email"]),+ ("assignedToEmail", lambda node: node["assignedToEmail"]),+ ],+)+def test_me_gift_cards_assigned_field_visible_to_owner(+ field, extract, user_api_client, gift_card, customer_user+):+ # given each assignment field is queried in isolation so a broken+ # authorization check on one cannot be masked by the other+ gift_card.used_by = None+ gift_card.assigned_to = customer_user+ gift_card.assigned_to_email = customer_user.email+ gift_card.save(update_fields=["used_by", "assigned_to", "assigned_to_email"])+ gift_card_id = graphene.Node.to_global_id("GiftCard", gift_card.pk)++ # when the owner queries without MANAGE_USERS / MANAGE_GIFT_CARD permissions+ response = user_api_client.post_graphql(ME_ASSIGNED_FIELD % field, {})++ # then the owner can read the field+ edges = get_graphql_content(response)["data"]["me"]["giftCards"]["edges"]+ node = next(e["node"] for e in edges if e["node"]["id"] == gift_card_id)+ assert extract(node) == customer_user.email+++def test_me_gift_cards_assigned_to_email_requires_manage_gift_card_for_non_owner(+ user_api_client, gift_card, customer_user, customer_user2+):+ # given the requester can reach the card as its last user but is not its assignee+ gift_card.used_by = customer_user+ gift_card.used_by_email = customer_user.email+ gift_card.assigned_to = customer_user2+ gift_card.assigned_to_email = customer_user2.email+ gift_card.save(+ update_fields=[+ "used_by",+ "used_by_email",+ "assigned_to",+ "assigned_to_email",+ ]+ )+ gift_card_id = graphene.Node.to_global_id("GiftCard", gift_card.pk)++ # when the requester queries without MANAGE_GIFT_CARD permission+ response = user_api_client.post_graphql(ME_ASSIGNED_FIELD % "assignedToEmail", {})++ # then the assignee's email is obfuscated+ edges = get_graphql_content(response)["data"]["me"]["giftCards"]["edges"]+ node = next(e["node"] for e in edges if e["node"]["id"] == gift_card_id)+ assert node["assignedToEmail"] == obfuscate_email(customer_user2.email)+++CODE_QUERY = """+ query { me { giftCards(first: 10) { edges { node { id code } } } } }+"""+++def test_assigned_customer_can_read_code(user_api_client, gift_card, customer_user):+ # given (user_api_client is authenticated as customer_user)+ gift_card.assigned_to = customer_user+ gift_card.assigned_to_email = customer_user.email+ gift_card.used_by = None+ gift_card.save(update_fields=["assigned_to", "assigned_to_email", "used_by"])+ gift_card_id = graphene.Node.to_global_id("GiftCard", gift_card.pk)++ # when+ response = user_api_client.post_graphql(CODE_QUERY, {})++ # then+ edges = get_graphql_content(response)["data"]["me"]["giftCards"]["edges"]+ node = next(e["node"] for e in edges if e["node"]["id"] == gift_card_id)+ assert node["code"] == gift_card.code+++FILTER_QUERY = """+ query GiftCards($filter: GiftCardFilterInput!) {+ giftCards(first: 10, filter: $filter) {+ edges { node { id } }+ }+ }+"""+++def test_filter_by_assigned_to(+ staff_api_client,+ gift_card,+ gift_card_created_by_staff,+ customer_user,+ permission_manage_gift_card,+):+ # given a card assigned to the customer and another card assigned to nobody+ gift_card.assigned_to = customer_user+ gift_card.assigned_to_email = customer_user.email+ gift_card.save(update_fields=["assigned_to", "assigned_to_email"])+ variables = {+ "filter": {"assignedTo": [graphene.Node.to_global_id("User", customer_user.pk)]}+ }++ # when+ response = staff_api_client.post_graphql(+ FILTER_QUERY, variables, permissions=[permission_manage_gift_card]+ )++ # then only the matching card is returned+ edges = get_graphql_content(response)["data"]["giftCards"]["edges"]+ ids = {e["node"]["id"] for e in edges}+ assert ids == {graphene.Node.to_global_id("GiftCard", gift_card.pk)}+ assert (+ graphene.Node.to_global_id("GiftCard", gift_card_created_by_staff.pk) not in ids+ )+++def test_filter_by_assigned_to_does_not_require_manage_users(+ staff_api_client, gift_card, customer_user, permission_manage_gift_card+):+ # given a requester with MANAGE_GIFT_CARD but not MANAGE_USERS+ gift_card.assigned_to = customer_user+ gift_card.assigned_to_email = customer_user.email+ gift_card.save(update_fields=["assigned_to", "assigned_to_email"])+ variables = {+ "filter": {"assignedTo": [graphene.Node.to_global_id("User", customer_user.pk)]}+ }++ # when+ response = staff_api_client.post_graphql(+ FILTER_QUERY, variables, permissions=[permission_manage_gift_card]+ )++ # then filtering succeeds without MANAGE_USERS (see filter_assigned_to comment)+ content = get_graphql_content(response, ignore_errors=True)+ assert "errors" not in content+ edges = content["data"]["giftCards"]["edges"]+ ids = {e["node"]["id"] for e in edges}+ assert graphene.Node.to_global_id("GiftCard", gift_card.pk) in idsdiff --git a/saleor/graphql/giftcard/tests/test_user_delete_deactivates_assigned_cards.py b/saleor/graphql/giftcard/tests/test_user_delete_deactivates_assigned_cards.pynew file mode 100644index 0000000000..da43bc1e90--- /dev/null+++ b/saleor/graphql/giftcard/tests/test_user_delete_deactivates_assigned_cards.py@@ -0,0 +1,160 @@+import graphene++from ....account.models import User+from ....core.tokens import account_delete_token_generator+from ....giftcard import GiftCardEvents+from ....giftcard.models import GiftCardEvent+from ...tests.utils import get_graphql_content++CUSTOMER_DELETE = """+ mutation CustomerDelete($id: ID!) {+ customerDelete(id: $id) {+ errors { field message }+ user { id }+ }+ }+"""++ACCOUNT_DELETE = """+ mutation AccountDelete($token: String!) {+ accountDelete(token: $token) {+ errors { field message }+ }+ }+"""++STAFF_DELETE = """+ mutation StaffDelete($id: ID!) {+ staffDelete(id: $id) {+ errors { field message }+ }+ }+"""++CUSTOMER_BULK_DELETE = """+ mutation customerBulkDelete($ids: [ID!]!) {+ customerBulkDelete(ids: $ids) { count }+ }+"""++STAFF_BULK_DELETE = """+ mutation staffBulkDelete($ids: [ID!]!) {+ staffBulkDelete(ids: $ids) { count }+ }+"""+++def _assign(gift_card, user):+ gift_card.assigned_to = user+ gift_card.assigned_to_email = user.email+ gift_card.is_active = True+ gift_card.save(update_fields=["assigned_to", "assigned_to_email", "is_active"])+++def _assert_detached_and_deactivated(gift_card, assigned_email):+ gift_card.refresh_from_db()+ # assigned_to is nulled (otherwise on_delete=PROTECT would block the delete),+ # the card is deactivated and the assignee email is retained.+ assert gift_card.assigned_to_id is None+ assert gift_card.is_active is False+ assert gift_card.assigned_to_email == assigned_email+ assert GiftCardEvent.objects.filter(+ gift_card=gift_card, type=GiftCardEvents.DEACTIVATED+ ).exists()+++def test_customer_delete_deactivates_assigned_gift_card(+ staff_api_client, customer_user, gift_card, permission_manage_users+):+ # given+ _assign(gift_card, customer_user)+ assigned_email = customer_user.email+ variables = {"id": graphene.Node.to_global_id("User", customer_user.pk)}++ # when+ response = staff_api_client.post_graphql(+ CUSTOMER_DELETE, variables, permissions=[permission_manage_users]+ )++ # then+ data = get_graphql_content(response)["data"]["customerDelete"]+ assert data["errors"] == []+ assert not User.objects.filter(pk=customer_user.pk).exists()+ _assert_detached_and_deactivated(gift_card, assigned_email)+++def test_account_delete_deactivates_assigned_gift_card(user_api_client, gift_card):+ # given+ user = user_api_client.user+ _assign(gift_card, user)+ assigned_email = user.email+ token = account_delete_token_generator.make_token(user)++ # when+ response = user_api_client.post_graphql(ACCOUNT_DELETE, {"token": token})++ # then+ data = get_graphql_content(response)["data"]["accountDelete"]+ assert data["errors"] == []+ assert not User.objects.filter(pk=user.pk).exists()+ _assert_detached_and_deactivated(gift_card, assigned_email)+++def test_staff_delete_deactivates_assigned_gift_card(+ staff_api_client, gift_card, permission_manage_staff+):+ # given+ staff = User.objects.create(email="[email protected]", is_staff=True)+ _assign(gift_card, staff)+ assigned_email = staff.email+ variables = {"id": graphene.Node.to_global_id("User", staff.pk)}++ # when+ response = staff_api_client.post_graphql(+ STAFF_DELETE, variables, permissions=[permission_manage_staff]+ )++ # then+ data = get_graphql_content(response)["data"]["staffDelete"]+ assert data["errors"] == []+ assert not User.objects.filter(pk=staff.pk).exists()+ _assert_detached_and_deactivated(gift_card, assigned_email)+++def test_customer_bulk_delete_deactivates_assigned_gift_card(+ staff_api_client, customer_user, gift_card, permission_manage_users+):+ # given+ _assign(gift_card, customer_user)+ assigned_email = customer_user.email+ variables = {"ids": [graphene.Node.to_global_id("User", customer_user.pk)]}++ # when+ response = staff_api_client.post_graphql(+ CUSTOMER_BULK_DELETE, variables, permissions=[permission_manage_users]+ )++ # then+ assert get_graphql_content(response)["data"]["customerBulkDelete"]["count"] == 1+ assert not User.objects.filter(pk=customer_user.pk).exists()+ _assert_detached_and_deactivated(gift_card, assigned_email)+++def test_staff_bulk_delete_deactivates_assigned_gift_card(+ staff_api_client, gift_card, permission_manage_staff+):+ # given+ staff = User.objects.create(email="[email protected]", is_staff=True)+ _assign(gift_card, staff)+ assigned_email = staff.email+ variables = {"ids": [graphene.Node.to_global_id("User", staff.pk)]}++ # when+ response = staff_api_client.post_graphql(+ STAFF_BULK_DELETE, variables, permissions=[permission_manage_staff]+ )++ # then+ assert get_graphql_content(response)["data"]["staffBulkDelete"]["count"] == 1+ assert not User.objects.filter(pk=staff.pk).exists()+ _assert_detached_and_deactivated(gift_card, assigned_email)diff --git a/saleor/graphql/giftcard/types.py b/saleor/graphql/giftcard/types.pyindex 06d675b695..57e4862599 100644--- a/saleor/graphql/giftcard/types.py+++ b/saleor/graphql/giftcard/types.py@@ -24,7 +24,7 @@ from ..app.types import Appfrom ..channel.dataloaders.by_self import ChannelByIdLoaderfrom ..core.connection import CountableConnectionfrom ..core.context import ChannelContext, get_database_connection_name-from ..core.descriptions import DEFAULT_DEPRECATION_REASON+from ..core.descriptions import ADDED_IN_323, DEFAULT_DEPRECATION_REASONfrom ..core.doc_category import DOC_CATEGORY_GIFT_CARDSfrom ..core.fields import PermissionsFieldfrom ..core.scalars import Date, DateTime@@ -69,6 +69,79 @@ class GiftCardEventBalance(BaseObjectType):doc_category = DOC_CATEGORY_GIFT_CARDS+class GiftCardEventAssignment(BaseObjectType):+ old_assigned_to = graphene.Field(+ "saleor.graphql.account.types.User",+ description=(+ "The customer the gift card was assigned to before this event. "+ "\n\nRequires one of the following permissions: "+ f"{AccountPermissions.MANAGE_USERS.name}, "+ f"{AccountPermissions.MANAGE_STAFF.name}, "+ f"{AuthorizationFilters.OWNER.name}."+ ),+ )+ current_assigned_to = graphene.Field(+ "saleor.graphql.account.types.User",+ description=(+ "The customer the gift card is assigned to after this event. "+ "\n\nRequires one of the following permissions: "+ f"{AccountPermissions.MANAGE_USERS.name}, "+ f"{AccountPermissions.MANAGE_STAFF.name}, "+ f"{AuthorizationFilters.OWNER.name}."+ ),+ )+ old_assigned_to_email = graphene.String(+ description=(+ "Email of the customer the gift card was assigned to before this event."+ ),+ )+ current_assigned_to_email = graphene.String(+ description=(+ "Email of the customer the gift card is assigned to after this event."+ ),+ )++ class Meta:+ doc_category = DOC_CATEGORY_GIFT_CARDS++ @staticmethod+ def resolve_old_assigned_to(root: models.GiftCardEvent, info):+ return _resolve_assignment_user(root, info, "previous_assigned_to_id")++ @staticmethod+ def resolve_current_assigned_to(root: models.GiftCardEvent, info):+ return _resolve_assignment_user(root, info, "assigned_to_id")++ @staticmethod+ def resolve_old_assigned_to_email(root: models.GiftCardEvent, _info):+ return root.parameters.get("previous_assigned_to_email")++ @staticmethod+ def resolve_current_assigned_to_email(root: models.GiftCardEvent, _info):+ return root.parameters.get("assigned_to_email")+++def _resolve_assignment_user(root: models.GiftCardEvent, info, parameters_key: str):+ # Gate the customer identity behind MANAGE_USERS/MANAGE_STAFF only when there is an+ # assignee to protect; a null id (unassign, first assignment, deleted customer)+ # returns null without raising PermissionDenied.+ user_id = root.parameters.get(parameters_key)+ if not user_id:+ return None++ def _resolve(event_user):+ requester = get_user_or_app_from_context(info.context)+ check_is_owner_or_has_one_of_perms(+ requester,+ event_user,+ AccountPermissions.MANAGE_USERS,+ AccountPermissions.MANAGE_STAFF,+ )+ return event_user++ return UserByUserIdLoader(info.context).load(user_id).then(_resolve)++class GiftCardEvent(ModelObjectType[models.GiftCardEvent]):id = graphene.GlobalID(required=True, description="ID of the event associated with a gift card."@@ -110,6 +183,14 @@ class GiftCardEvent(ModelObjectType[models.GiftCardEvent]):description="The list of old gift card tags.",)balance = graphene.Field(GiftCardEventBalance, description="The gift card balance.")+ assigned_to = graphene.Field(+ GiftCardEventAssignment,+ description=(+ "The customer assignment change recorded by the event. Only set for "+ f"{GiftCardEvents.ASSIGNED_TO_USER.upper()} and "+ f"{GiftCardEvents.UNASSIGNED_FROM_USER.upper()} events. " + ADDED_IN_323+ ),+ )expiry_date = Date(description="The gift card expiry date.")old_expiry_date = Date(description="Previous gift card expiry date.")@@ -204,6 +285,15 @@ class GiftCardEvent(ModelObjectType[models.GiftCardEvent]):return GiftCardEventBalance(**balance_data)+ @staticmethod+ def resolve_assigned_to(root: models.GiftCardEvent, _info):+ if root.type not in (+ GiftCardEvents.ASSIGNED_TO_USER,+ GiftCardEvents.UNASSIGNED_FROM_USER,+ ):+ return None+ return root+@staticmethoddef resolve_expiry_date(root: models.GiftCardEvent, _info):expiry_date = root.parameters.get("expiry_date")@@ -288,6 +378,24 @@ class GiftCard(ModelObjectType[models.GiftCard]):description="Email address of the customer who used a gift card.",deprecation_reason=DEFAULT_DEPRECATION_REASON,)+ assigned_to = graphene.Field(+ "saleor.graphql.account.types.User",+ description=(+ "The customer the gift card usage is restricted to."+ + "\n\nRequires one of the following permissions: "+ f"{AccountPermissions.MANAGE_USERS.name}, "+ f"{AuthorizationFilters.OWNER.name}. " + ADDED_IN_323+ ),+ )+ assigned_to_email = graphene.String(+ required=False,+ description=(+ "Email of the customer the gift card is restricted to."+ + "\n\nRequires one of the following permissions: "+ f"{GiftcardPermissions.MANAGE_GIFT_CARD.name}, "+ f"{AuthorizationFilters.OWNER.name}. " + ADDED_IN_323+ ),+ )last_used_on = DateTime(description="Date and time when gift card was last used.")expiry_date = Date(description="Expiry date of the gift card.")app = graphene.Field(@@ -370,28 +478,24 @@ class GiftCard(ModelObjectType[models.GiftCard]):@staticmethoddef resolve_code(root: models.GiftCard, info):- def _resolve_code(user):- # Gift card code can be fetched by the staff user and app- # with manage gift card permission and by the card owner.- if requestor := get_user_or_app_from_context(info.context):- requestor_is_an_owner = user and requestor == user- if requestor_is_an_owner or requestor.has_perm(- GiftcardPermissions.MANAGE_GIFT_CARD- ):- return root.code-- return PermissionDenied(- permissions=[- AuthorizationFilters.OWNER,- GiftcardPermissions.MANAGE_GIFT_CARD,- ]- )-- if root.used_by_id is None:- return _resolve_code(None)-- return (- UserByUserIdLoader(info.context).load(root.used_by_id).then(_resolve_code)+ # Gift card code can be fetched by the staff user and app with manage gift+ # card permission and by the card owner (the customer who used it or the+ # customer it is assigned to).+ owner_ids = {+ uid for uid in (root.used_by_id, root.assigned_to_id) if uid is not None+ }+ requestor = get_user_or_app_from_context(info.context)+ if requestor:+ requestor_is_owner = requestor.pk in owner_ids+ if requestor_is_owner or requestor.has_perm(+ GiftcardPermissions.MANAGE_GIFT_CARD+ ):+ return root.code+ return PermissionDenied(+ permissions=[+ AuthorizationFilters.OWNER,+ GiftcardPermissions.MANAGE_GIFT_CARD,+ ])@staticmethod@@ -465,6 +569,46 @@ class GiftCard(ModelObjectType[models.GiftCard]):.then(_resolve_used_by_email))+ @staticmethod+ def resolve_assigned_to(root: models.GiftCard, info):+ def _resolve_assigned_to(user):+ requestor = get_user_or_app_from_context(info.context)+ check_is_owner_or_has_one_of_perms(+ requestor, user, AccountPermissions.MANAGE_USERS+ )+ return user++ if root.assigned_to_id is None:+ return None+ return (+ UserByUserIdLoader(info.context)+ .load(root.assigned_to_id)+ .then(_resolve_assigned_to)+ )++ @staticmethod+ def resolve_assigned_to_email(root: models.GiftCard, info):+ def _resolve_assigned_to_email(user):+ requestor = get_user_or_app_from_context(info.context)+ # Intentional access-control decision (not broken access control):+ # the denormalized email identifier is readable with MANAGE_GIFT_CARD+ # alone, so staff can reason about who a card belongs to without also+ # holding MANAGE_USERS. Fetching the full User object is stricter and+ # is gated behind MANAGE_USERS in `resolve_assigned_to`. See ADR 0005.+ if is_owner_or_has_one_of_perms(+ requestor, user, GiftcardPermissions.MANAGE_GIFT_CARD+ ):+ return user.email if user else root.assigned_to_email+ return obfuscate_email(user.email if user else root.assigned_to_email)++ if root.assigned_to_id is None:+ return _resolve_assigned_to_email(None)+ return (+ UserByUserIdLoader(info.context)+ .load(root.assigned_to_id)+ .then(_resolve_assigned_to_email)+ )+@staticmethoddef resolve_app(root: models.GiftCard, info):def _resolve_app(app):diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 866e32e845..bd6079b812 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -11262,6 +11262,24 @@ type GiftCard implements Node & ObjectWithMetadata @doc(category: "Gift cards")"""Email address of the customer who used a gift card."""usedByEmail: String @deprecated+ """+ The customer the gift card usage is restricted to.++ Requires one of the following permissions: MANAGE_USERS, OWNER.++ Added in Saleor 3.23.+ """+ assignedTo: User++ """+ Email of the customer the gift card is restricted to.++ Requires one of the following permissions: MANAGE_GIFT_CARD, OWNER.++ Added in Saleor 3.23.+ """+ assignedToEmail: String+"""Date and time when gift card was last used."""lastUsedOn: DateTime@@ -11353,6 +11371,13 @@ type GiftCardEvent implements Node @doc(category: "Gift cards") {"""The gift card balance."""balance: GiftCardEventBalance+ """+ The customer assignment change recorded by the event. Only set for ASSIGNED_TO_USER and UNASSIGNED_FROM_USER events.++ Added in Saleor 3.23.+ """+ assignedTo: GiftCardEventAssignment+"""The gift card expiry date."""expiryDate: Date@@ -11374,6 +11399,9 @@ enum GiftCardEventsEnum @doc(category: "Gift cards") {NOTE_ADDEDUSED_IN_ORDERREFUNDED_IN_ORDER+ BALANCE_ADJUSTED+ ASSIGNED_TO_USER+ UNASSIGNED_FROM_USER}type GiftCardEventBalance @doc(category: "Gift cards") {@@ -11390,6 +11418,28 @@ type GiftCardEventBalance @doc(category: "Gift cards") {oldCurrentBalance: Money}+type GiftCardEventAssignment @doc(category: "Gift cards") {+ """+ The customer the gift card was assigned to before this event.++ Requires one of the following permissions: MANAGE_USERS, MANAGE_STAFF, OWNER.+ """+ oldAssignedTo: User++ """+ The customer the gift card is assigned to after this event.++ Requires one of the following permissions: MANAGE_USERS, MANAGE_STAFF, OWNER.+ """+ currentAssignedTo: User++ """Email of the customer the gift card was assigned to before this event."""+ oldAssignedToEmail: String++ """Email of the customer the gift card is assigned to after this event."""+ currentAssignedToEmail: String+}+input GiftCardEventFilterInput @doc(category: "Gift cards") {type: GiftCardEventsEnumorders: [ID!]@@ -16141,7 +16191,16 @@ input GiftCardFilterInput @doc(category: "Gift cards") {metadata: [MetadataFilter!]tags: [String!]products: [ID!]- usedBy: [ID!]++ """Filter by the customer who used a gift card."""+ usedBy: [ID!] @deprecated++ """+ Filter by the customer the gift card usage is restricted to.++ Added in Saleor 3.23.+ """+ assignedTo: [ID!]used: Booleancurrency: StringcurrentBalance: PriceRangeInput@@ -19962,6 +20021,61 @@ type Mutation {id: ID!): GiftCardActivate @doc(category: "Gift cards") @webhookEventsInfo(asyncEvents: [GIFT_CARD_STATUS_CHANGED], syncEvents: [])+ """+ Restrict a gift card so only the given customer can use it.++ Added in Saleor 3.23.++ Requires one of the following permissions: MANAGE_GIFT_CARD.++ Triggers the following webhook events:+ - GIFT_CARD_UPDATED (async): A gift card was updated.+ """+ giftCardAssignUser(+ """ID of the gift card."""+ id: ID!++ """ID of the customer to restrict the card to."""+ userId: ID!+ ): GiftCardAssignUser @doc(category: "Gift cards") @webhookEventsInfo(asyncEvents: [GIFT_CARD_UPDATED], syncEvents: [])++ """+ Remove a customer restriction from a gift card.++ Added in Saleor 3.23.++ Requires one of the following permissions: MANAGE_GIFT_CARD.++ Triggers the following webhook events:+ - GIFT_CARD_UPDATED (async): A gift card was updated.+ """+ giftCardUnassignUser(+ """ID of the gift card."""+ id: ID!+ ): GiftCardUnassignUser @doc(category: "Gift cards") @webhookEventsInfo(asyncEvents: [GIFT_CARD_UPDATED], syncEvents: [])++ """+ Adjust a gift card's balance by a delta.++ Added in Saleor 3.23.++ Requires one of the following permissions: MANAGE_GIFT_CARD.++ Triggers the following webhook events:+ - GIFT_CARD_UPDATED (async): A gift card was updated.+ """+ giftCardBalanceAdjust(+ """+ Signed amount to adjust the current balance by. Positive tops up, negative deducts. A deduction below zero clamps the balance to zero. A top-up above the initial balance raises the initial balance to the new current balance.++ Added in Saleor 3.23.+ """+ amount: Decimal!++ """ID of the gift card to adjust."""+ id: ID!+ ): GiftCardBalanceAdjust @doc(category: "Gift cards") @webhookEventsInfo(asyncEvents: [GIFT_CARD_UPDATED], syncEvents: [])+"""Creates a new gift card.@@ -28846,6 +28960,58 @@ enum GiftCardErrorCode @doc(category: "Gift cards") {UNIQUEEXPIRED_GIFT_CARDDUPLICATED_INPUT_ITEM+ CANNOT_ASSIGN+}++"""+Restrict a gift card so only the given customer can use it.++Added in Saleor 3.23.++Requires one of the following permissions: MANAGE_GIFT_CARD.++Triggers the following webhook events:+- GIFT_CARD_UPDATED (async): A gift card was updated.+"""+type GiftCardAssignUser @doc(category: "Gift cards") @webhookEventsInfo(asyncEvents: [GIFT_CARD_UPDATED], syncEvents: []) {+ """The assigned gift card."""+ giftCard: GiftCard+ giftCardErrors: [GiftCardError!]! @deprecated(reason: "Use `errors` field instead.")+ errors: [GiftCardError!]!+}++"""+Remove a customer restriction from a gift card.++Added in Saleor 3.23.++Requires one of the following permissions: MANAGE_GIFT_CARD.++Triggers the following webhook events:+- GIFT_CARD_UPDATED (async): A gift card was updated.+"""+type GiftCardUnassignUser @doc(category: "Gift cards") @webhookEventsInfo(asyncEvents: [GIFT_CARD_UPDATED], syncEvents: []) {+ """The unassigned gift card."""+ giftCard: GiftCard+ giftCardErrors: [GiftCardError!]! @deprecated(reason: "Use `errors` field instead.")+ errors: [GiftCardError!]!+}++"""+Adjust a gift card's balance by a delta.++Added in Saleor 3.23.++Requires one of the following permissions: MANAGE_GIFT_CARD.++Triggers the following webhook events:+- GIFT_CARD_UPDATED (async): A gift card was updated.+"""+type GiftCardBalanceAdjust @doc(category: "Gift cards") @webhookEventsInfo(asyncEvents: [GIFT_CARD_UPDATED], syncEvents: []) {+ """The adjusted gift card."""+ giftCard: GiftCard+ giftCardErrors: [GiftCardError!]! @deprecated(reason: "Use `errors` field instead.")+ errors: [GiftCardError!]!}"""@@ -28907,6 +29073,13 @@ input GiftCardCreateInput @doc(category: "Gift cards") {"""The gift card note from the staff member."""note: String++ """+ ID of the customer the gift card is restricted to.++ Added in Saleor 3.23.+ """+ assignedTo: ID}input PriceInput {