Skip to lesson content

PROJECT 7 · LESSON 14 OF 16

Manage fulfillment and verify the complete application

Use staff permissions for order fulfillment and test meaningful application guarantees.

  • admin permissions
  • read-only history
  • TestCase
  • rollback tests

Your workspace: edushop

Continue from lesson 13: Build cash-on-delivery checkout and order history. Keep existing files; create or replace the complete files listed below.

Extract the ZIP and open the folder containing manage.py. Create a Python virtual environment, install requirements.txt and run migrate. Read README.md for checkpoint-specific commands and LESSON.md for offline explanations. Checkpoints contain no database records or private credentials.

1. Understand the problem and the concepts

Why we need this feature

The customer flow is only half of ecommerce. Staff need controlled catalog and fulfillment tools, and you need repeatable evidence that important rules still hold after changes.

Staff manage products through the existing Product admin and ship orders through a dedicated action. Order totals and snapshots remain read-only so fulfillment does not rewrite a purchase.

The test database is separate from development records. Tests create synthetic users and products. SQLite tests verify functional behavior, but they do not establish PostgreSQL row-lock guarantees; deployment verification includes the last-unit concurrency test.

Separate customer identity from staff capability

A customer can register and view their own orders. A staff account can access admin only when is_staff is enabled and the relevant model permissions are granted. A superuser has broad privileges and is useful for initial setup, but routine staff should receive the smallest necessary set of permissions.

Use admin’s Users and Groups screens to create a fulfillment group with view and change order permissions, and catalog permissions only when needed. Keep add/delete order permissions absent. Test the staff account separately from the superuser; a superuser can hide missing-permission mistakes because it bypasses ordinary permission checks.

Historical orders are not editable catalog records

Product admin permits catalog updates. Order admin makes customer details, totals and snapshot lines read-only and disables creating or deleting orders manually. The mark-shipped action changes only placed orders when the staff user has change permission. This preserves the meaning of the checkout service as the source of order creation.

This workflow covers placed to shipped fulfillment. It does not implement returns, cancellation stock restoration, shipping-provider integration or payment settlement. Add each as an explicit state transition with its own permissions and tests instead of allowing arbitrary edits to historical totals.

Tests should challenge business rules

Django TestCase creates an isolated test database and clears state between tests. The test client sends requests without opening a browser. force_login is useful when testing authorization after authentication; it does not test password verification. Client(enforce_csrf_checks=True) explicitly enables CSRF enforcement for that security test.

The suite checks foreign task access, own-task CRUD, invalid input, POST-only cart actions, missing CSRF, snapshot prices, duplicate checkout, rollback, private order history and tampered checkout tokens. These tests assert observable outcomes such as stock and record count rather than copying implementation statements.

Run tests from the directory containing manage.py. From production-settings checkpoints onward run collectstatic before the tests because DEBUG=False in tests activates manifest lookup. The suite runs on SQLite locally. It verifies rollback and idempotent behavior sequentially; it does not simulate PostgreSQL row locks or prove concurrent checkout correctness.

2. Follow the execution flow

Read this sequence before the source. Identify the input, the component or function that handles it, and the result the learner sees.

  1. Create or grant a staff account the required model permissions.

  2. Staff open admin and inspect immutable order details.

  3. The fulfillment action checks permission and updates eligible placed orders.

  4. The test runner builds an isolated database and creates two customers and products.

  5. Requests and service calls exercise allowed, forbidden and repeated actions, then assert database outcomes.

Verify the permission boundary

  1. Log in as a normal customer and confirm /admin/ is unavailable.
  2. Grant a separate staff account order view/change permissions. It can inspect and mark eligible orders shipped, but cannot rewrite item prices.
  3. Run the regression suite and inspect the test count and final OK, not just the absence of a traceback.

3. Build it, one file at a time

  1. Add orders/admin.py and the test module. Run python manage.py test.
  2. Create a staff account through a superuser and assign only the required Product and Order view/change permissions. Do not make every employee a superuser.
  3. Place a test order as a customer. In /admin/orders/order/, select it and run Mark placed orders as shipped. Reopen customer history.
Terminal
python manage.py test orders
python manage.py check
python manage.py makemigrations --check --dry-run

The paths below are relative to your practice project. Each block is the complete file at this checkpoint. Read its responsibility first, type or copy the code, then use the walkthrough to explain the important statements.

orders/admin.py

Expose fulfillment without allowing staff to create or rewrite order history.

orders/admin.py
from django.contrib import admin
from .models import Order, OrderItem


class OrderItemInline(admin.TabularInline):
    model = OrderItem
    extra = 0
    can_delete = False
    fields = ["product", "name", "price", "quantity"]
    readonly_fields = fields

    def has_add_permission(self, request, obj=None):
        return False


@admin.register(Order)
class OrderAdmin(admin.ModelAdmin):
    list_display = ["id", "user", "total", "status", "created_at"]
    list_filter = ["status", "created_at"]
    search_fields = ["recipient", "user__username"]
    readonly_fields = ["user", "token", "recipient", "address", "postal_code", "phone", "total", "status", "created_at"]
    inlines = [OrderItemInline]
    actions = ["mark_shipped"]

    def has_add_permission(self, request):
        return False

    def has_delete_permission(self, request, obj=None):
        return False

    @admin.action(description="Mark placed orders as shipped", permissions=["change"])
    def mark_shipped(self, request, queryset):
        count = queryset.filter(status=Order.Status.PLACED).update(status=Order.Status.SHIPPED)
        self.message_user(request, f"{count} orders marked shipped.")

Read the code

  1. The inline displays saved line items read-only and disallows adding or deleting them. Order header fields are also read-only.
  2. mark_shipped requires change permission and changes only placed orders. Repeating it does not deduct stock again.
  3. Django admin’s Delete action is disabled for orders. A real cancellation process needs an explicit stock/refund policy rather than deletion.

orders/tests.py

Verify ownership, form behavior, CSRF, server prices, rollback and replay protection.

orders/tests.py
import uuid
from decimal import Decimal
from django.contrib.auth import get_user_model
from django.test import TestCase, Client
from django.urls import reverse
from shop.models import Product
from tasks.models import Task
from .models import Order
from .services import CheckoutError, place_order


class StoreTests(TestCase):
    def setUp(self):
        self.a = get_user_model().objects.create_user(username="alice", password="Learn-Test-94!")
        self.b = get_user_model().objects.create_user(username="bob", password="Learn-Test-95!")
        self.product = Product.objects.create(name="Notebook", slug="notebook", price=Decimal("249.00"), stock=3)
        self.delivery = dict(recipient="Learner", address="Test address only", postal_code="500001", phone="0000000000")

    def test_foreign_task_is_inaccessible(self):
        task = Task.objects.create(title="Alice task", owner=self.a)
        self.client.force_login(self.b)
        for action in ("edit", "delete"):
            url = reverse(f"tasks:{action}", args=[task.pk])
            self.assertEqual(self.client.get(url).status_code, 404)
            self.assertEqual(self.client.post(url, {"title": "Changed"}).status_code, 404)
        task.refresh_from_db()
        self.assertEqual(task.title, "Alice task")

    def test_task_crud_and_validation(self):
        self.client.force_login(self.a)
        self.client.post(reverse("tasks:create"), {"title": "  Study  "})
        task = Task.objects.get(owner=self.a)
        self.assertEqual(task.title, "Study")
        self.client.post(reverse("tasks:edit", args=[task.pk]), {"title": "Practice", "completed": "on"})
        task.refresh_from_db()
        self.assertTrue(task.completed)
        self.client.get(reverse("tasks:delete", args=[task.pk]))
        self.assertTrue(Task.objects.filter(pk=task.pk).exists())
        self.client.post(reverse("tasks:delete", args=[task.pk]))
        self.assertFalse(Task.objects.exists())
        self.client.post(reverse("tasks:create"), {"title": "   "})
        self.assertFalse(Task.objects.exists())

    def test_cart_post_and_csrf(self):
        url = reverse("shop:cart-add", args=[self.product.pk])
        self.assertEqual(self.client.get(url).status_code, 405)
        self.assertEqual(Client(enforce_csrf_checks=True).post(url).status_code, 403)
        self.client.post(url)
        self.assertEqual(self.client.session["cart"][str(self.product.pk)], 1)
        self.client.post(reverse("shop:cart-update", args=[self.product.pk]), {"quantity": "-2"})
        self.assertEqual(self.client.session["cart"][str(self.product.pk)], 1)

    def test_idempotent_order_and_snapshot(self):
        token = uuid.uuid4()
        order = place_order(user=self.a, token=token, cart={str(self.product.pk): 2}, delivery=self.delivery)
        replay = place_order(user=self.a, token=token, cart={}, delivery=self.delivery)
        self.assertEqual(order.pk, replay.pk)
        self.assertEqual(Order.objects.count(), 1)
        self.product.refresh_from_db()
        self.assertEqual(self.product.stock, 1)
        self.assertEqual(order.total, Decimal("498.00"))
        self.product.price = Decimal("999.00")
        self.product.save()
        self.assertEqual(order.items.get().price, Decimal("249.00"))

    def test_multiline_failure_rolls_back_stock(self):
        empty = Product.objects.create(name="Lamp", slug="lamp", price=Decimal("10.00"), stock=0)
        with self.assertRaises(CheckoutError):
            place_order(user=self.a, token=uuid.uuid4(), cart={str(self.product.pk): 1, str(empty.pk): 1}, delivery=self.delivery)
        self.product.refresh_from_db()
        self.assertEqual(self.product.stock, 3)
        self.assertFalse(Order.objects.exists())

    def test_checkout_view_and_private_history(self):
        self.client.force_login(self.a)
        self.client.post(reverse("shop:cart-add", args=[self.product.pk]))
        page = self.client.get(reverse("orders:checkout"))
        token = page.context["form"].initial["token"]
        response = self.client.post(reverse("orders:checkout"), {**self.delivery, "token": token, "total": "0.01"})
        order = Order.objects.get()
        self.assertRedirects(response, reverse("orders:detail", args=[order.pk]))
        self.assertEqual(order.total, Decimal("249.00"))
        self.client.post(reverse("orders:checkout"), {**self.delivery, "token": token})
        self.assertEqual(Order.objects.count(), 1)
        self.client.force_login(self.b)
        self.assertEqual(self.client.get(reverse("orders:detail", args=[order.pk])).status_code, 404)
        self.assertNotContains(self.client.get(reverse("orders:list")), "Order " + str(order.pk))
        self.assertEqual(self.client.get("/admin/").status_code, 302)

    def test_tampered_checkout_token(self):
        self.client.force_login(self.a)
        response = self.client.post(reverse("orders:checkout"), {**self.delivery, "token": "tampered"})
        self.assertContains(response, "Checkout expired")
        self.assertFalse(Order.objects.exists())

Read the code

  1. force_login is a test helper, not production authentication. The tests deliberately use two identities to probe access boundaries.
  2. The multiline failure test checks that an earlier stock deduction is rolled back when a later line fails.
  3. The checkout view test submits a fake total and confirms the database price wins. The replay test verifies one order and one deduction for the same token.

4. Run it and check your result

  • All seven tests pass on the learning database backend.
  • A normal customer cannot access staff admin; permitted staff can mark a placed order shipped.
  • Order history retains the original total and displays the new fulfillment status.

5. Predict, change and observe

Temporarily remove owner filtering from one task lookup and run the tests.

Compare your prediction with the expected result

What you should observe

The foreign-task test fails. Restore the filter and rerun.

Why it happens

The test expresses the privacy requirement independently of the view’s current implementation, so it detects this meaningful regression.

6. Troubleshoot with evidence

A common mistake

Changing absolute stock in an old admin form can overwrite a concurrent adjustment. In a busy store, use audited inventory adjustments or optimistic version checks.

Ran 0 tests

Likely cause: The command ran from an unexpected directory or the app label was omitted in a different working context.

Check and correct: Open the directory containing manage.py and run python manage.py test orders --verbosity 2.

Missing staticfiles manifest entry

Likely cause: Production storage is configured but collectstatic has not generated its manifest.

Check and correct: Run python manage.py collectstatic --noinput before the test suite in the final checkpoints.

7. Practice and explain it back

Your independent task

Add a test that archived products cannot be ordered, then implement any missing behavior.

Attempt these questions before opening the explanations. Use the source above to justify your answer.

Why not test only successful checkout?

Failures can corrupt stock or disclose data. Rollback, replay and ownership tests cover different business guarantees than the happy path.

Does a passing SQLite suite prove row-lock behavior?

No. PostgreSQL concurrency must be exercised separately against PostgreSQL, ideally with independent connections and simultaneous checkout attempts.