{"id":"6b093dc291bd8fbaf2a0c8e4","slug":"subscription-state","title":"Cykl życia subskrypcji jako maszyna stanów","summary":"Subskrypcja SaaS przechodzi przez okres próbny, aktywność, zaległość i anulowanie. Każdy stan to osobna klasa, która sama decyduje o przejściach – bez rozrastającego się switcha.","servedLang":"pl","availableLangs":["pl","en"],"kind":"code","category":"pattern","status":"published","difficulty":"medium","topics":["state"],"techs":["typescript","javascript","python","dotnet","java","go"],"tags":["state","state-machine","subscriptions","billing","behavioral"],"languages":[{"lang":"typescript","runner":"browser","starter":"/**\n * One state of the subscription. States decide about transitions by calling subscription.transitionTo(...).\n * Status names: 'trial' | 'active' | 'past-due' | 'cancelled'.\n */\ninterface SubscriptionState {\n  readonly name: string;\n  pay(subscription: Subscription): void;\n  paymentFailed(subscription: Subscription): void;\n  cancel(subscription: Subscription): void;\n  hasAccess(): boolean;\n}\n\n/** Context: keeps the current state and delegates every operation to it. */\nclass Subscription {\n  private state: SubscriptionState = new TrialState();\n  private readonly entered: string[] = ['trial'];\n\n  get status(): string {\n    return this.state.name;\n  }\n\n  /** Names of the states entered so far (a copy). */\n  get history(): string[] {\n    return [...this.entered];\n  }\n\n  /** Called by the states; every call is recorded in the history. */\n  transitionTo(state: SubscriptionState): void {\n    this.state = state;\n    this.entered.push(state.name);\n  }\n\n  pay(): void {\n    // TODO: delegate to the current state\n    throw new Error('Not implemented');\n  }\n\n  paymentFailed(): void {\n    throw new Error('Not implemented');\n  }\n\n  cancel(): void {\n    throw new Error('Not implemented');\n  }\n\n  hasAccess(): boolean {\n    throw new Error('Not implemented');\n  }\n}\n\n/** pay → active; paymentFailed → cancelled; cancel → cancelled; access: yes. */\nclass TrialState implements SubscriptionState {\n  readonly name = 'trial';\n  pay(subscription: Subscription): void { throw new Error('Not implemented'); }\n  paymentFailed(subscription: Subscription): void { throw new Error('Not implemented'); }\n  cancel(subscription: Subscription): void { throw new Error('Not implemented'); }\n  hasAccess(): boolean { throw new Error('Not implemented'); }\n}\n\n/** pay → stays active (no transition); paymentFailed → past-due; cancel → cancelled; access: yes. */\nclass ActiveState implements SubscriptionState {\n  readonly name = 'active';\n  pay(subscription: Subscription): void { throw new Error('Not implemented'); }\n  paymentFailed(subscription: Subscription): void { throw new Error('Not implemented'); }\n  cancel(subscription: Subscription): void { throw new Error('Not implemented'); }\n  hasAccess(): boolean { throw new Error('Not implemented'); }\n}\n\n/**\n * Counts failed payments in a row (entered with 1). pay → active; paymentFailed → counter + 1 and at 3 → cancelled\n * (below 3 no transition); cancel → cancelled; access: yes (grace period).\n */\nclass PastDueState implements SubscriptionState {\n  readonly name = 'past-due';\n  pay(subscription: Subscription): void { throw new Error('Not implemented'); }\n  paymentFailed(subscription: Subscription): void { throw new Error('Not implemented'); }\n  cancel(subscription: Subscription): void { throw new Error('Not implemented'); }\n  hasAccess(): boolean { throw new Error('Not implemented'); }\n}\n\n/** pay / paymentFailed → Error('Subscription is cancelled'); cancel → nothing happens; access: no. */\nclass CancelledState implements SubscriptionState {\n  readonly name = 'cancelled';\n  pay(subscription: Subscription): void { throw new Error('Not implemented'); }\n  paymentFailed(subscription: Subscription): void { throw new Error('Not implemented'); }\n  cancel(subscription: Subscription): void { throw new Error('Not implemented'); }\n  hasAccess(): boolean { throw new Error('Not implemented'); }\n}\n","testCount":9,"tests":"function activeSubscription() {\n  const subscription = new Subscription();\n  subscription.pay();\n  return subscription;\n}\n\ntest('a new subscription starts as a trial with access', () => {\n  const subscription = new Subscription();\n  expect(subscription.status).toBe('trial');\n  expect(subscription.hasAccess()).toBe(true);\n  expect(subscription.history).toEqual(['trial']);\n});\n\ntest('paying ends the trial; paying while active keeps it active', () => {\n  const subscription = new Subscription();\n  subscription.pay();\n  expect(subscription.status).toBe('active');\n  subscription.pay();\n  expect(subscription.status).toBe('active');\n  expect(subscription.history).toEqual(['trial', 'active']);\n});\n\ntest('a failed payment makes it past due and a payment brings it back', () => {\n  const subscription = activeSubscription();\n  subscription.paymentFailed();\n  expect(subscription.status).toBe('past-due');\n  expect(subscription.hasAccess()).toBe(true);\n  subscription.pay();\n  expect(subscription.status).toBe('active');\n  expect(subscription.history).toEqual(['trial', 'active', 'past-due', 'active']);\n});\n\ntest('three failed payments in a row cancel the subscription', () => {\n  const subscription = activeSubscription();\n  subscription.paymentFailed();\n  subscription.paymentFailed();\n  expect(subscription.status).toBe('past-due');\n  subscription.paymentFailed();\n  expect(subscription.status).toBe('cancelled');\n  expect(subscription.hasAccess()).toBe(false);\n  expect(subscription.history).toEqual(['trial', 'active', 'past-due', 'cancelled']);\n});\n\ntest('a payment resets the count of failed payments', () => {\n  const subscription = activeSubscription();\n  subscription.paymentFailed();\n  subscription.paymentFailed();\n  subscription.pay();\n  subscription.paymentFailed();\n  subscription.paymentFailed();\n  expect(subscription.status).toBe('past-due');\n  subscription.paymentFailed();\n  expect(subscription.status).toBe('cancelled');\n});\n\ntest('a cancelled subscription rejects payments and cancel is idempotent', () => {\n  const subscription = new Subscription();\n  subscription.cancel();\n  expect(subscription.status).toBe('cancelled');\n  expect(() => subscription.pay()).toThrow('Subscription is cancelled');\n  expect(() => subscription.paymentFailed()).toThrow('Subscription is cancelled');\n  expect(() => subscription.cancel()).not.toThrow();\n  expect(subscription.history).toEqual(['trial', 'cancelled']);\n});\n\ntest('a failed trial conversion or cancelling an active plan ends it', () => {\n  const trial = new Subscription();\n  trial.paymentFailed();\n  expect(trial.status).toBe('cancelled');\n  const active = activeSubscription();\n  active.cancel();\n  expect(active.status).toBe('cancelled');\n  expect(active.hasAccess()).toBe(false);\n});\n\ntest('every subscription counts its own failed payments', () => {\n  const a = activeSubscription();\n  const b = activeSubscription();\n  a.paymentFailed();\n  a.paymentFailed();\n  b.paymentFailed();\n  b.paymentFailed();\n  expect(b.status).toBe('past-due');\n  a.paymentFailed();\n  expect(a.status).toBe('cancelled');\n  expect(b.status).toBe('past-due');\n});\n\ntest('Subscription delegates to whatever state object it holds', () => {\n  class FrozenState {\n    name = 'frozen';\n    pay(subscription) { subscription.transitionTo(new ActiveState()); }\n    paymentFailed() {}\n    cancel() {}\n    hasAccess() { return false; }\n  }\n  const subscription = activeSubscription();\n  subscription.transitionTo(new FrozenState());\n  expect(subscription.status).toBe('frozen');\n  expect(subscription.hasAccess()).toBe(false);\n  subscription.paymentFailed();\n  expect(subscription.status).toBe('frozen');\n  subscription.pay();\n  expect(subscription.status).toBe('active');\n  expect(subscription.history).toEqual(['trial', 'active', 'frozen', 'active']);\n});\n"},{"lang":"javascript","runner":"browser","starter":"// A state is an object with: name, pay(subscription), paymentFailed(subscription), cancel(subscription), hasAccess().\n// States decide about transitions by calling subscription.transitionTo(...).\n// Status names: 'trial' | 'active' | 'past-due' | 'cancelled'.\n\n/** Context: keeps the current state and delegates every operation to it. */\nclass Subscription {\n  #state = new TrialState();\n  #entered = ['trial'];\n\n  get status() {\n    return this.#state.name;\n  }\n\n  /** Names of the states entered so far (a copy). */\n  get history() {\n    return [...this.#entered];\n  }\n\n  /** Called by the states; every call is recorded in the history. */\n  transitionTo(state) {\n    this.#state = state;\n    this.#entered.push(state.name);\n  }\n\n  pay() {\n    // TODO: delegate to the current state\n    throw new Error('Not implemented');\n  }\n\n  paymentFailed() {\n    throw new Error('Not implemented');\n  }\n\n  cancel() {\n    throw new Error('Not implemented');\n  }\n\n  hasAccess() {\n    throw new Error('Not implemented');\n  }\n}\n\n/** pay → active; paymentFailed → cancelled; cancel → cancelled; access: yes. */\nclass TrialState {\n  name = 'trial';\n  pay(subscription) { throw new Error('Not implemented'); }\n  paymentFailed(subscription) { throw new Error('Not implemented'); }\n  cancel(subscription) { throw new Error('Not implemented'); }\n  hasAccess() { throw new Error('Not implemented'); }\n}\n\n/** pay → stays active (no transition); paymentFailed → past-due; cancel → cancelled; access: yes. */\nclass ActiveState {\n  name = 'active';\n  pay(subscription) { throw new Error('Not implemented'); }\n  paymentFailed(subscription) { throw new Error('Not implemented'); }\n  cancel(subscription) { throw new Error('Not implemented'); }\n  hasAccess() { throw new Error('Not implemented'); }\n}\n\n/**\n * Counts failed payments in a row (entered with 1). pay → active; paymentFailed → counter + 1 and at 3 → cancelled\n * (below 3 no transition); cancel → cancelled; access: yes (grace period).\n */\nclass PastDueState {\n  name = 'past-due';\n  pay(subscription) { throw new Error('Not implemented'); }\n  paymentFailed(subscription) { throw new Error('Not implemented'); }\n  cancel(subscription) { throw new Error('Not implemented'); }\n  hasAccess() { throw new Error('Not implemented'); }\n}\n\n/** pay / paymentFailed → Error('Subscription is cancelled'); cancel → nothing happens; access: no. */\nclass CancelledState {\n  name = 'cancelled';\n  pay(subscription) { throw new Error('Not implemented'); }\n  paymentFailed(subscription) { throw new Error('Not implemented'); }\n  cancel(subscription) { throw new Error('Not implemented'); }\n  hasAccess() { throw new Error('Not implemented'); }\n}\n","testCount":9,"tests":"function activeSubscription() {\n  const subscription = new Subscription();\n  subscription.pay();\n  return subscription;\n}\n\ntest('a new subscription starts as a trial with access', () => {\n  const subscription = new Subscription();\n  expect(subscription.status).toBe('trial');\n  expect(subscription.hasAccess()).toBe(true);\n  expect(subscription.history).toEqual(['trial']);\n});\n\ntest('paying ends the trial; paying while active keeps it active', () => {\n  const subscription = new Subscription();\n  subscription.pay();\n  expect(subscription.status).toBe('active');\n  subscription.pay();\n  expect(subscription.status).toBe('active');\n  expect(subscription.history).toEqual(['trial', 'active']);\n});\n\ntest('a failed payment makes it past due and a payment brings it back', () => {\n  const subscription = activeSubscription();\n  subscription.paymentFailed();\n  expect(subscription.status).toBe('past-due');\n  expect(subscription.hasAccess()).toBe(true);\n  subscription.pay();\n  expect(subscription.status).toBe('active');\n  expect(subscription.history).toEqual(['trial', 'active', 'past-due', 'active']);\n});\n\ntest('three failed payments in a row cancel the subscription', () => {\n  const subscription = activeSubscription();\n  subscription.paymentFailed();\n  subscription.paymentFailed();\n  expect(subscription.status).toBe('past-due');\n  subscription.paymentFailed();\n  expect(subscription.status).toBe('cancelled');\n  expect(subscription.hasAccess()).toBe(false);\n  expect(subscription.history).toEqual(['trial', 'active', 'past-due', 'cancelled']);\n});\n\ntest('a payment resets the count of failed payments', () => {\n  const subscription = activeSubscription();\n  subscription.paymentFailed();\n  subscription.paymentFailed();\n  subscription.pay();\n  subscription.paymentFailed();\n  subscription.paymentFailed();\n  expect(subscription.status).toBe('past-due');\n  subscription.paymentFailed();\n  expect(subscription.status).toBe('cancelled');\n});\n\ntest('a cancelled subscription rejects payments and cancel is idempotent', () => {\n  const subscription = new Subscription();\n  subscription.cancel();\n  expect(subscription.status).toBe('cancelled');\n  expect(() => subscription.pay()).toThrow('Subscription is cancelled');\n  expect(() => subscription.paymentFailed()).toThrow('Subscription is cancelled');\n  expect(() => subscription.cancel()).not.toThrow();\n  expect(subscription.history).toEqual(['trial', 'cancelled']);\n});\n\ntest('a failed trial conversion or cancelling an active plan ends it', () => {\n  const trial = new Subscription();\n  trial.paymentFailed();\n  expect(trial.status).toBe('cancelled');\n  const active = activeSubscription();\n  active.cancel();\n  expect(active.status).toBe('cancelled');\n  expect(active.hasAccess()).toBe(false);\n});\n\ntest('every subscription counts its own failed payments', () => {\n  const a = activeSubscription();\n  const b = activeSubscription();\n  a.paymentFailed();\n  a.paymentFailed();\n  b.paymentFailed();\n  b.paymentFailed();\n  expect(b.status).toBe('past-due');\n  a.paymentFailed();\n  expect(a.status).toBe('cancelled');\n  expect(b.status).toBe('past-due');\n});\n\ntest('Subscription delegates to whatever state object it holds', () => {\n  class FrozenState {\n    name = 'frozen';\n    pay(subscription) { subscription.transitionTo(new ActiveState()); }\n    paymentFailed() {}\n    cancel() {}\n    hasAccess() { return false; }\n  }\n  const subscription = activeSubscription();\n  subscription.transitionTo(new FrozenState());\n  expect(subscription.status).toBe('frozen');\n  expect(subscription.hasAccess()).toBe(false);\n  subscription.paymentFailed();\n  expect(subscription.status).toBe('frozen');\n  subscription.pay();\n  expect(subscription.status).toBe('active');\n  expect(subscription.history).toEqual(['trial', 'active', 'frozen', 'active']);\n});\n"},{"lang":"python","runner":"browser","starter":"from abc import ABC, abstractmethod\n\n\nclass SubscriptionState(ABC):\n    \"\"\"One state of the subscription. States decide about transitions by calling subscription.transition_to(...).\n    Status names: 'trial' | 'active' | 'past-due' | 'cancelled'.\"\"\"\n\n    name: str = \"\"\n\n    @abstractmethod\n    def pay(self, subscription: \"Subscription\") -> None: ...\n\n    @abstractmethod\n    def payment_failed(self, subscription: \"Subscription\") -> None: ...\n\n    @abstractmethod\n    def cancel(self, subscription: \"Subscription\") -> None: ...\n\n    @abstractmethod\n    def has_access(self) -> bool: ...\n\n\nclass Subscription:\n    \"\"\"Context: keeps the current state and delegates every operation to it.\"\"\"\n\n    def __init__(self):\n        self._state: SubscriptionState = TrialState()\n        self._entered = [\"trial\"]\n\n    @property\n    def status(self) -> str:\n        return self._state.name\n\n    @property\n    def history(self) -> list[str]:\n        \"\"\"Names of the states entered so far (a copy).\"\"\"\n        return list(self._entered)\n\n    def transition_to(self, state: SubscriptionState) -> None:\n        \"\"\"Called by the states; every call is recorded in the history.\"\"\"\n        self._state = state\n        self._entered.append(state.name)\n\n    def pay(self) -> None:\n        raise NotImplementedError  # TODO: delegate to the current state\n\n    def payment_failed(self) -> None:\n        raise NotImplementedError\n\n    def cancel(self) -> None:\n        raise NotImplementedError\n\n    def has_access(self) -> bool:\n        raise NotImplementedError\n\n\nclass TrialState(SubscriptionState):\n    \"\"\"pay → active; payment_failed → cancelled; cancel → cancelled; access: yes.\"\"\"\n\n    name = \"trial\"\n\n    def pay(self, subscription): raise NotImplementedError\n    def payment_failed(self, subscription): raise NotImplementedError\n    def cancel(self, subscription): raise NotImplementedError\n    def has_access(self): raise NotImplementedError\n\n\nclass ActiveState(SubscriptionState):\n    \"\"\"pay → stays active (no transition); payment_failed → past-due; cancel → cancelled; access: yes.\"\"\"\n\n    name = \"active\"\n\n    def pay(self, subscription): raise NotImplementedError\n    def payment_failed(self, subscription): raise NotImplementedError\n    def cancel(self, subscription): raise NotImplementedError\n    def has_access(self): raise NotImplementedError\n\n\nclass PastDueState(SubscriptionState):\n    \"\"\"Counts failed payments in a row (entered with 1). pay → active; payment_failed → counter + 1 and at 3\n    → cancelled (below 3 no transition); cancel → cancelled; access: yes (grace period).\"\"\"\n\n    name = \"past-due\"\n\n    def pay(self, subscription): raise NotImplementedError\n    def payment_failed(self, subscription): raise NotImplementedError\n    def cancel(self, subscription): raise NotImplementedError\n    def has_access(self): raise NotImplementedError\n\n\nclass CancelledState(SubscriptionState):\n    \"\"\"pay / payment_failed → RuntimeError('Subscription is cancelled'); cancel → nothing happens; access: no.\"\"\"\n\n    name = \"cancelled\"\n\n    def pay(self, subscription): raise NotImplementedError\n    def payment_failed(self, subscription): raise NotImplementedError\n    def cancel(self, subscription): raise NotImplementedError\n    def has_access(self): raise NotImplementedError\n","testCount":9,"tests":"def active_subscription():\n    subscription = Subscription()\n    subscription.pay()\n    return subscription\n\n\ndef expect_status(subscription, want):\n    assert subscription.status == want, f\"expected status {want!r}, got {subscription.status!r}\"\n\n\ndef test_a_new_subscription_starts_as_a_trial_with_access():\n    subscription = Subscription()\n    expect_status(subscription, \"trial\")\n    assert subscription.has_access() is True\n    assert subscription.history == [\"trial\"], f\"got {subscription.history}\"\n\n\ndef test_paying_ends_the_trial_and_paying_while_active_keeps_it_active():\n    subscription = Subscription()\n    subscription.pay()\n    expect_status(subscription, \"active\")\n    subscription.pay()\n    expect_status(subscription, \"active\")\n    assert subscription.history == [\"trial\", \"active\"], f\"got {subscription.history}\"\n\n\ndef test_a_failed_payment_makes_it_past_due_and_a_payment_brings_it_back():\n    subscription = active_subscription()\n    subscription.payment_failed()\n    expect_status(subscription, \"past-due\")\n    assert subscription.has_access() is True, \"past-due still has access (grace period)\"\n    subscription.pay()\n    expect_status(subscription, \"active\")\n    assert subscription.history == [\"trial\", \"active\", \"past-due\", \"active\"], f\"got {subscription.history}\"\n\n\ndef test_three_failed_payments_in_a_row_cancel_the_subscription():\n    subscription = active_subscription()\n    subscription.payment_failed()\n    subscription.payment_failed()\n    expect_status(subscription, \"past-due\")\n    subscription.payment_failed()\n    expect_status(subscription, \"cancelled\")\n    assert subscription.has_access() is False\n    assert subscription.history == [\"trial\", \"active\", \"past-due\", \"cancelled\"], f\"got {subscription.history}\"\n\n\ndef test_a_payment_resets_the_count_of_failed_payments():\n    subscription = active_subscription()\n    subscription.payment_failed()\n    subscription.payment_failed()\n    subscription.pay()\n    subscription.payment_failed()\n    subscription.payment_failed()\n    expect_status(subscription, \"past-due\")\n    subscription.payment_failed()\n    expect_status(subscription, \"cancelled\")\n\n\ndef test_a_cancelled_subscription_rejects_payments_and_cancel_is_idempotent():\n    subscription = Subscription()\n    subscription.cancel()\n    expect_status(subscription, \"cancelled\")\n    with raises(RuntimeError, match=\"Subscription is cancelled\"):\n        subscription.pay()\n    with raises(RuntimeError, match=\"Subscription is cancelled\"):\n        subscription.payment_failed()\n    subscription.cancel()\n    assert subscription.history == [\"trial\", \"cancelled\"], f\"got {subscription.history}\"\n\n\ndef test_a_failed_trial_conversion_or_cancelling_an_active_plan_ends_it():\n    trial = Subscription()\n    trial.payment_failed()\n    expect_status(trial, \"cancelled\")\n    active = active_subscription()\n    active.cancel()\n    expect_status(active, \"cancelled\")\n    assert active.has_access() is False\n\n\ndef test_every_subscription_counts_its_own_failed_payments():\n    a, b = active_subscription(), active_subscription()\n    a.payment_failed()\n    a.payment_failed()\n    b.payment_failed()\n    b.payment_failed()\n    expect_status(b, \"past-due\")\n    a.payment_failed()\n    expect_status(a, \"cancelled\")\n    expect_status(b, \"past-due\")\n\n\ndef test_subscription_delegates_to_whatever_state_object_it_holds():\n    class FrozenState(SubscriptionState):\n        name = \"frozen\"\n\n        def pay(self, subscription):\n            subscription.transition_to(ActiveState())\n\n        def payment_failed(self, subscription):\n            pass\n\n        def cancel(self, subscription):\n            pass\n\n        def has_access(self):\n            return False\n\n    subscription = active_subscription()\n    subscription.transition_to(FrozenState())\n    expect_status(subscription, \"frozen\")\n    assert subscription.has_access() is False\n    subscription.payment_failed()\n    expect_status(subscription, \"frozen\")\n    subscription.pay()\n    expect_status(subscription, \"active\")\n    assert subscription.history == [\"trial\", \"active\", \"frozen\", \"active\"], f\"got {subscription.history}\"\n"},{"lang":"csharp","runner":"judge0","starter":"using System;\nusing System.Collections.Generic;\n\n/// <summary>\n/// One state of the subscription. States decide about transitions by calling subscription.TransitionTo(...).\n/// Status names: \"trial\" | \"active\" | \"past-due\" | \"cancelled\".\n/// </summary>\npublic interface ISubscriptionState\n{\n    string Name { get; }\n    bool HasAccess { get; }\n    void Pay(Subscription subscription);\n    void PaymentFailed(Subscription subscription);\n    void Cancel(Subscription subscription);\n}\n\n/// <summary>Context: keeps the current state and delegates every operation to it.</summary>\npublic class Subscription\n{\n    private readonly List<string> entered = new List<string> { \"trial\" };\n    private ISubscriptionState state = new TrialState();\n\n    public string Status { get { return state.Name; } }\n\n    /// <summary>Names of the states entered so far.</summary>\n    public IReadOnlyList<string> History { get { return entered.AsReadOnly(); } }\n\n    /// <summary>Called by the states; every call is recorded in the history.</summary>\n    public void TransitionTo(ISubscriptionState next)\n    {\n        state = next;\n        entered.Add(next.Name);\n    }\n\n    // TODO: delegate to the current state\n    public bool HasAccess { get { throw new NotImplementedException(); } }\n    public void Pay() { throw new NotImplementedException(); }\n    public void PaymentFailed() { throw new NotImplementedException(); }\n    public void Cancel() { throw new NotImplementedException(); }\n}\n\n/// <summary>Pay → active; PaymentFailed → cancelled; Cancel → cancelled; access: yes.</summary>\npublic class TrialState : ISubscriptionState\n{\n    public string Name { get { return \"trial\"; } }\n    public bool HasAccess { get { throw new NotImplementedException(); } }\n    public void Pay(Subscription subscription) { throw new NotImplementedException(); }\n    public void PaymentFailed(Subscription subscription) { throw new NotImplementedException(); }\n    public void Cancel(Subscription subscription) { throw new NotImplementedException(); }\n}\n\n/// <summary>Pay → stays active (no transition); PaymentFailed → past-due; Cancel → cancelled; access: yes.</summary>\npublic class ActiveState : ISubscriptionState\n{\n    public string Name { get { return \"active\"; } }\n    public bool HasAccess { get { throw new NotImplementedException(); } }\n    public void Pay(Subscription subscription) { throw new NotImplementedException(); }\n    public void PaymentFailed(Subscription subscription) { throw new NotImplementedException(); }\n    public void Cancel(Subscription subscription) { throw new NotImplementedException(); }\n}\n\n/// <summary>\n/// Counts failed payments in a row (entered with 1). Pay → active; PaymentFailed → counter + 1 and at 3 → cancelled\n/// (below 3 no transition); Cancel → cancelled; access: yes (grace period).\n/// </summary>\npublic class PastDueState : ISubscriptionState\n{\n    public string Name { get { return \"past-due\"; } }\n    public bool HasAccess { get { throw new NotImplementedException(); } }\n    public void Pay(Subscription subscription) { throw new NotImplementedException(); }\n    public void PaymentFailed(Subscription subscription) { throw new NotImplementedException(); }\n    public void Cancel(Subscription subscription) { throw new NotImplementedException(); }\n}\n\n/// <summary>Pay / PaymentFailed → InvalidOperationException(\"Subscription is cancelled\"); Cancel → nothing; access: no.</summary>\npublic class CancelledState : ISubscriptionState\n{\n    public string Name { get { return \"cancelled\"; } }\n    public bool HasAccess { get { throw new NotImplementedException(); } }\n    public void Pay(Subscription subscription) { throw new NotImplementedException(); }\n    public void PaymentFailed(Subscription subscription) { throw new NotImplementedException(); }\n    public void Cancel(Subscription subscription) { throw new NotImplementedException(); }\n}\n","testCount":9},{"lang":"java","runner":"judge0","starter":"import java.util.ArrayList;\nimport java.util.List;\n\n/**\n * One state of the subscription. States decide about transitions by calling subscription.transitionTo(...).\n * Status names: \"trial\" | \"active\" | \"past-due\" | \"cancelled\".\n */\ninterface SubscriptionState {\n    String name();\n    boolean hasAccess();\n    void pay(Subscription subscription);\n    void paymentFailed(Subscription subscription);\n    void cancel(Subscription subscription);\n}\n\n/** Context: keeps the current state and delegates every operation to it. */\nclass Subscription {\n    private final List<String> entered = new ArrayList<>(List.of(\"trial\"));\n    private SubscriptionState state = new TrialState();\n\n    String status() { return state.name(); }\n\n    /** Names of the states entered so far (a copy). */\n    List<String> history() { return new ArrayList<>(entered); }\n\n    /** Called by the states; every call is recorded in the history. */\n    void transitionTo(SubscriptionState next) {\n        state = next;\n        entered.add(next.name());\n    }\n\n    // TODO: delegate to the current state\n    boolean hasAccess() { throw new UnsupportedOperationException(\"Not implemented\"); }\n    void pay() { throw new UnsupportedOperationException(\"Not implemented\"); }\n    void paymentFailed() { throw new UnsupportedOperationException(\"Not implemented\"); }\n    void cancel() { throw new UnsupportedOperationException(\"Not implemented\"); }\n}\n\n/** pay → active; paymentFailed → cancelled; cancel → cancelled; access: yes. */\nclass TrialState implements SubscriptionState {\n    @Override public String name() { return \"trial\"; }\n    @Override public boolean hasAccess() { throw new UnsupportedOperationException(\"Not implemented\"); }\n    @Override public void pay(Subscription s) { throw new UnsupportedOperationException(\"Not implemented\"); }\n    @Override public void paymentFailed(Subscription s) { throw new UnsupportedOperationException(\"Not implemented\"); }\n    @Override public void cancel(Subscription s) { throw new UnsupportedOperationException(\"Not implemented\"); }\n}\n\n/** pay → stays active (no transition); paymentFailed → past-due; cancel → cancelled; access: yes. */\nclass ActiveState implements SubscriptionState {\n    @Override public String name() { return \"active\"; }\n    @Override public boolean hasAccess() { throw new UnsupportedOperationException(\"Not implemented\"); }\n    @Override public void pay(Subscription s) { throw new UnsupportedOperationException(\"Not implemented\"); }\n    @Override public void paymentFailed(Subscription s) { throw new UnsupportedOperationException(\"Not implemented\"); }\n    @Override public void cancel(Subscription s) { throw new UnsupportedOperationException(\"Not implemented\"); }\n}\n\n/**\n * Counts failed payments in a row (entered with 1). pay → active; paymentFailed → counter + 1 and at 3 → cancelled\n * (below 3 no transition); cancel → cancelled; access: yes (grace period).\n */\nclass PastDueState implements SubscriptionState {\n    @Override public String name() { return \"past-due\"; }\n    @Override public boolean hasAccess() { throw new UnsupportedOperationException(\"Not implemented\"); }\n    @Override public void pay(Subscription s) { throw new UnsupportedOperationException(\"Not implemented\"); }\n    @Override public void paymentFailed(Subscription s) { throw new UnsupportedOperationException(\"Not implemented\"); }\n    @Override public void cancel(Subscription s) { throw new UnsupportedOperationException(\"Not implemented\"); }\n}\n\n/** pay / paymentFailed → IllegalStateException(\"Subscription is cancelled\"); cancel → nothing; access: no. */\nclass CancelledState implements SubscriptionState {\n    @Override public String name() { return \"cancelled\"; }\n    @Override public boolean hasAccess() { throw new UnsupportedOperationException(\"Not implemented\"); }\n    @Override public void pay(Subscription s) { throw new UnsupportedOperationException(\"Not implemented\"); }\n    @Override public void paymentFailed(Subscription s) { throw new UnsupportedOperationException(\"Not implemented\"); }\n    @Override public void cancel(Subscription s) { throw new UnsupportedOperationException(\"Not implemented\"); }\n}\n","testCount":9},{"lang":"go","runner":"judge0","starter":"package main\n\nimport \"errors\"\n\n// ErrCancelled is returned by Pay and PaymentFailed on a cancelled subscription.\nvar ErrCancelled = errors.New(\"subscription is cancelled\")\n\n// State is one state of the subscription. States decide about transitions by calling s.TransitionTo(...).\n// Status names: \"trial\" | \"active\" | \"past-due\" | \"cancelled\".\ntype State interface {\n\tName() string\n\tHasAccess() bool\n\tPay(s *Subscription) error\n\tPaymentFailed(s *Subscription) error\n\tCancel(s *Subscription) error\n}\n\n// Subscription is the context: it keeps the current state and delegates every operation to it.\ntype Subscription struct {\n\tstate   State\n\tentered []string\n}\n\n// NewSubscription starts in the trial state.\nfunc NewSubscription() *Subscription {\n\treturn &Subscription{state: &TrialState{}, entered: []string{\"trial\"}}\n}\n\n// Status is the name of the current state.\nfunc (s *Subscription) Status() string { return s.state.Name() }\n\n// History returns the names of the states entered so far (a copy).\nfunc (s *Subscription) History() []string { return append([]string(nil), s.entered...) }\n\n// TransitionTo is called by the states; every call is recorded in the history.\nfunc (s *Subscription) TransitionTo(next State) {\n\ts.state = next\n\ts.entered = append(s.entered, next.Name())\n}\n\n// TODO: delegate to the current state\nfunc (s *Subscription) HasAccess() bool     { return false }\nfunc (s *Subscription) Pay() error           { return nil }\nfunc (s *Subscription) PaymentFailed() error { return nil }\nfunc (s *Subscription) Cancel() error        { return nil }\n\n// TrialState: Pay → active; PaymentFailed → cancelled; Cancel → cancelled; access: yes.\ntype TrialState struct{}\n\nfunc (*TrialState) Name() string                        { return \"trial\" }\nfunc (*TrialState) HasAccess() bool                     { return false } // TODO\nfunc (*TrialState) Pay(s *Subscription) error           { return nil }   // TODO\nfunc (*TrialState) PaymentFailed(s *Subscription) error { return nil }   // TODO\nfunc (*TrialState) Cancel(s *Subscription) error        { return nil }   // TODO\n\n// ActiveState: Pay → stays active (no transition); PaymentFailed → past-due; Cancel → cancelled; access: yes.\ntype ActiveState struct{}\n\nfunc (*ActiveState) Name() string                        { return \"active\" }\nfunc (*ActiveState) HasAccess() bool                     { return false } // TODO\nfunc (*ActiveState) Pay(s *Subscription) error           { return nil }   // TODO\nfunc (*ActiveState) PaymentFailed(s *Subscription) error { return nil }   // TODO\nfunc (*ActiveState) Cancel(s *Subscription) error        { return nil }   // TODO\n\n// PastDueState counts failed payments in a row (entered with 1). Pay → active; PaymentFailed → counter + 1\n// and at 3 → cancelled (below 3 no transition); Cancel → cancelled; access: yes (grace period).\ntype PastDueState struct{}\n\nfunc (*PastDueState) Name() string                        { return \"past-due\" }\nfunc (*PastDueState) HasAccess() bool                     { return false } // TODO\nfunc (*PastDueState) Pay(s *Subscription) error           { return nil }   // TODO\nfunc (*PastDueState) PaymentFailed(s *Subscription) error { return nil }   // TODO\nfunc (*PastDueState) Cancel(s *Subscription) error        { return nil }   // TODO\n\n// CancelledState: Pay / PaymentFailed → ErrCancelled; Cancel → nothing happens (nil); access: no.\ntype CancelledState struct{}\n\nfunc (*CancelledState) Name() string                        { return \"cancelled\" }\nfunc (*CancelledState) HasAccess() bool                     { return true } // TODO\nfunc (*CancelledState) Pay(s *Subscription) error           { return nil }  // TODO\nfunc (*CancelledState) PaymentFailed(s *Subscription) error { return nil }  // TODO\nfunc (*CancelledState) Cancel(s *Subscription) error        { return nil }  // TODO\n","testCount":9}],"questionCount":null,"xp":20,"stats":{"attempts":0,"solves":0,"solutions":0,"comments":0},"solveRate":null,"publishedAt":"2026-11-27T08:22:26.723Z","requestedLang":"pl","statement":{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"Platforma kursów online sprzedaje subskrypcje. Metoda "},{"type":"text","text":"pay()","marks":[{"type":"code"}]},{"type":"text","text":" ma dziś pięć gałęzi "},{"type":"text","text":"switch (status)","marks":[{"type":"code"}]},{"type":"text","text":", a "},{"type":"text","text":"paymentFailed()","marks":[{"type":"code"}]},{"type":"text","text":" i "},{"type":"text","text":"cancel()","marks":[{"type":"code"}]},{"type":"text","text":" – kolejne, z licznikiem nieudanych płatności trzymanym w polu, które ma sens tylko w jednym statusie. Każda nowa reguła oznacza zmiany w trzech miejscach. Wzorzec "},{"type":"text","text":"Stan","marks":[{"type":"bold"}]},{"type":"text","text":" (ang. "},{"type":"text","text":"State","marks":[{"type":"italic"}]},{"type":"text","text":") zamienia statusy w obiekty: subskrypcja (kontekst) deleguje każdą operację do bieżącego stanu, a stan sam decyduje, czy i dokąd przejść."}]},{"type":"heading","attrs":{"level":2,"id":"zadanie"},"content":[{"type":"text","text":"Zadanie"}]},{"type":"paragraph","content":[{"type":"text","text":"Kontekst "},{"type":"text","text":"Subscription","marks":[{"type":"code"}]},{"type":"text","text":" jest prawie gotowy: przechowuje bieżący stan, historię odwiedzonych stanów i metodę "},{"type":"text","text":"transitionTo(state)","marks":[{"type":"code"}]},{"type":"text","text":", z której korzystają stany. Brakuje delegowania – "},{"type":"text","text":"pay()","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"paymentFailed()","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"cancel()","marks":[{"type":"code"}]},{"type":"text","text":" i "},{"type":"text","text":"hasAccess()","marks":[{"type":"code"}]},{"type":"text","text":" mają przekazywać wywołanie bieżącemu stanowi. Do napisania są cztery stany:"}]},{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Stan"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"pay()","marks":[{"type":"code"}]}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"paymentFailed()","marks":[{"type":"code"}]}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"cancel()","marks":[{"type":"code"}]}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Dostęp"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"trial","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"→ "},{"type":"text","text":"active","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"→ "},{"type":"text","text":"cancelled","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"→ "},{"type":"text","text":"cancelled","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"tak"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"active","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"bez zmiany"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"→ "},{"type":"text","text":"past-due","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"→ "},{"type":"text","text":"cancelled","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"tak"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"past-due","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"→ "},{"type":"text","text":"active","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"licznik + 1; przy 3 → "},{"type":"text","text":"cancelled","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"→ "},{"type":"text","text":"cancelled","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"tak (okres karencji)"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"cancelled","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"błąd"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"błąd"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"nic się nie dzieje"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"nie"}]}]}]}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Stan "},{"type":"text","text":"past-due","marks":[{"type":"code"}]},{"type":"text","text":" zaczyna z licznikiem równym 1; trzecia nieudana płatność "},{"type":"text","text":"z rzędu","marks":[{"type":"bold"}]},{"type":"text","text":" anuluje subskrypcję. Płatność zeruje licznik (powrót do "},{"type":"text","text":"active","marks":[{"type":"code"}]},{"type":"text","text":")."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Licznik należy do konkretnej subskrypcji – dwie subskrypcje w zaległości nie mogą go współdzielić."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Błąd w stanie "},{"type":"text","text":"cancelled","marks":[{"type":"code"}]},{"type":"text","text":" ma komunikat "},{"type":"text","text":"Subscription is cancelled","marks":[{"type":"code"}]},{"type":"text","text":" (Go: "},{"type":"text","text":"ErrCancelled","marks":[{"type":"code"}]},{"type":"text","text":")."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"„Bez zmiany” oznacza brak wywołania "},{"type":"text","text":"transitionTo","marks":[{"type":"code"}]},{"type":"text","text":" – historia nie dostaje nowego wpisu."}]}]}]},{"type":"paragraph","content":[{"type":"text","text":"Testy podstawiają też własny stan (zamrożenie konta) przez "},{"type":"text","text":"transitionTo","marks":[{"type":"code"}]},{"type":"text","text":" i sprawdzają, że subskrypcja naprawdę deleguje do obiektu stanu. Różnice językowe: "},{"type":"text","text":"payment_failed","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"has_access()","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"transition_to","marks":[{"type":"code"}]},{"type":"text","text":" i "},{"type":"text","text":"RuntimeError","marks":[{"type":"code"}]},{"type":"text","text":" (Python); "},{"type":"text","text":"HasAccess","marks":[{"type":"code"}]},{"type":"text","text":" jako właściwość, "},{"type":"text","text":"InvalidOperationException","marks":[{"type":"code"}]},{"type":"text","text":" (C#); "},{"type":"text","text":"IllegalStateException","marks":[{"type":"code"}]},{"type":"text","text":" (Java); w Go metody zwracają "},{"type":"text","text":"error","marks":[{"type":"code"}]},{"type":"text","text":", a "},{"type":"text","text":"NewSubscription()","marks":[{"type":"code"}]},{"type":"text","text":" tworzy subskrypcję w stanie próbnym."}]}]},"hints":[],"hintsCount":3,"quiz":null,"solutionNotes":null,"unlocked":false,"external":[],"articles":[{"id":"6b08bd3d80884893657cca0f","slug":"state","title":"Stan (State): obiekt, który zmienia zachowanie razem z etapem życia"},{"id":"6b093dbf91bd8fbaf2a0c8a7","slug":"circuit-breaker","title":"Circuit breaker: bezpiecznik, który zamienia wolną awarię w szybką"}],"topicsInfo":[{"slug":"state","title":"Stan","group":"behavioral","icon":"toggle-right"}],"author":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","community":false},"capabilities":{"judge0":false,"aiReview":false},"createdAt":"2026-11-27T08:22:26.724Z","updatedAt":"2026-11-27T08:22:26.724Z"}