from datetime import datetime from decimal import Decimal from zoneinfo import ZoneInfo from django.core.exceptions import ValidationError from django.core.management import call_command from django.core.management.base import CommandError from django.test import TestCase, override_settings from django.urls import reverse from accounts.forms import RegistrationForm from accounts.models import User from control.forms import PlanApplicationForm from control.models import Node, Plan, PlanApplication, Subscription from control.services import desired_subscriptions_for_node @override_settings(SECURE_SSL_REDIRECT=False, WECOM_ENABLED=False, STORAGES={"default": {"BACKEND": "django.core.files.storage.FileSystemStorage"}, "staticfiles": {"BACKEND": "django.contrib.staticfiles.storage.StaticFilesStorage"}}) class EmployeeBillingTests(TestCase): def setUp(self): self.employee = User.objects.create_user(username="employee", email="employee@example.invalid", identity_type="employee", account_status="active") self.external = User.objects.create_user(username="outside", email="outside@example.invalid", account_status="active") self.reviewer = User.objects.create_superuser(username="reviewer-bill", email="reviewer-bill@example.invalid", password="fixture") self.plan = Plan.objects.create(name="Monthly fixture", slug="month-fixture", audience="all", price_cny=Decimal("8.00"), traffic_limit_gb=1024, billing_months=1, duration_days=0) def test_internal_employee_is_free_and_auto_subscribed_on_approval(self): app = PlanApplication.submit(user=self.employee, plan=self.plan) self.assertEqual(app.payment_status, "not_required") subscription = app.approve(self.reviewer) app.refresh_from_db() self.assertEqual(app.subscription_id, subscription.pk) self.assertEqual(subscription.traffic_limit_bytes, 1024 ** 4) self.assertEqual(app.payment_status, "not_required") def test_external_needs_payment_and_admin_flag_alone_is_not_free(self): self.external.is_staff = True self.external.save(update_fields=["is_staff"]) self.assertEqual(self.plan.price_for_user(self.external), Decimal("8.00")) app = PlanApplication.submit(user=self.external, plan=self.plan) self.assertEqual(app.payment_status, "unpaid") with self.assertRaises(ValidationError): app.approve(self.reviewer) def test_employee_reclassification_waives_pending_unpaid_request(self): app = PlanApplication.submit(user=self.external, plan=self.plan) User.objects.filter(pk=self.external.pk).update(identity_type="employee") app.approve(self.reviewer) app.refresh_from_db() self.assertEqual(app.payment_status, "not_required") def test_losing_employee_identity_cannot_keep_free_payment_status(self): app = PlanApplication.submit(user=self.employee, plan=self.plan) User.objects.filter(pk=self.employee.pk).update(identity_type="external") with self.assertRaises(ValidationError): app.approve(self.reviewer) self.assertFalse(Subscription.objects.exists()) def test_paid_history_is_not_relabelled_as_refunded_or_free(self): app = PlanApplication.objects.create(user=self.employee, plan=self.plan, payment_status="paid") app.approve(self.reviewer) app.refresh_from_db() self.assertEqual(app.payment_status, "paid") def test_one_calendar_month_clamps_end_of_month(self): zone = ZoneInfo("Asia/Shanghai") for year, last_day in ((2026, 28), (2028, 29)): start = datetime(year, 1, 31, 15, 12, tzinfo=zone) self.assertEqual(self.plan.period_end(start), datetime(year, 2, last_day, 15, 12, tzinfo=zone)) def test_legacy_30_day_plans_are_unchanged(self): self.plan.billing_months = 0 self.plan.duration_days = 30 start = datetime(2026, 1, 31, tzinfo=ZoneInfo("Asia/Shanghai")) self.assertEqual((self.plan.period_end(start) - start).days, 30) def test_prepare_draft_is_idempotent_and_does_not_change_existing_subscription(self): sub = Subscription.objects.create(user=self.employee, plan=self.plan, upload_bytes=99) call_command("prepare_monthly_1024g", verbosity=0) call_command("prepare_monthly_1024g", verbosity=0) draft = Plan.objects.get(slug="monthly-1024g") self.assertEqual(draft.price_cny, Decimal("8.00")) self.assertEqual(draft.traffic_limit_gb, 1024) self.assertEqual(draft.billing_months, 1) self.assertFalse(draft.active) self.assertTrue(draft.online_payment_required) self.assertNotIn(draft, RegistrationForm().fields["plan"].queryset) self.assertNotIn(draft, PlanApplicationForm(user=self.external).fields["plan"].queryset) sub.refresh_from_db() self.assertEqual(sub.upload_bytes, 99) self.assertEqual(sub.plan_id, self.plan.pk) def test_draft_does_not_override_existing_commercial_settings(self): call_command("prepare_monthly_1024g", verbosity=0) Plan.objects.filter(slug="monthly-1024g").update(price_cny=9) with self.assertRaises(CommandError): call_command("prepare_monthly_1024g", verbosity=0) self.assertEqual(Plan.objects.get(slug="monthly-1024g").price_cny, Decimal("9.00")) def test_online_plan_accepts_pending_requests_but_not_forged_payment(self): self.plan.online_payment_required = True self.plan.save() self.plan.full_clean() app = PlanApplication.submit(user=self.external, plan=self.plan) self.assertEqual(app.payment_status, "unpaid") self.assertEqual(app.status, "pending") self.assertFalse(Subscription.objects.exists()) app.payment_status = "paid" app.save() with self.assertRaises(ValidationError): app.approve(self.reviewer) app.refresh_from_db() self.assertEqual(app.status, "pending") self.assertIsNone(app.subscription_id) with self.assertRaises(ValidationError): Subscription(user=self.external, plan=self.plan).activate() def test_list_command_enables_catalog_idempotently_without_downgrading_or_repricing(self): call_command("prepare_monthly_1024g", verbosity=0) call_command("prepare_monthly_1024g", list_plan=True, verbosity=0) call_command("prepare_monthly_1024g", list_plan=True, verbosity=0) call_command("prepare_monthly_1024g", verbosity=0) plan = Plan.objects.get(slug="monthly-1024g") self.assertTrue(plan.active) self.assertEqual(plan.price_cny, Decimal("8.00")) self.assertIn(plan, RegistrationForm().fields["plan"].queryset) self.assertIn(plan, PlanApplicationForm(user=self.external).fields["plan"].queryset) Plan.objects.filter(pk=plan.pk).update(price_cny=9) with self.assertRaises(CommandError): call_command("prepare_monthly_1024g", list_plan=True, verbosity=0) plan.refresh_from_db() self.assertEqual(plan.price_cny, Decimal("9.00")) def test_employee_online_plan_is_free_and_can_be_auto_subscribed(self): self.plan.online_payment_required = True self.plan.save() app = PlanApplication.submit(user=self.employee, plan=self.plan) subscription = app.approve(self.reviewer) self.assertEqual(app.payment_status, "not_required") self.assertEqual(subscription.status, "active") self.assertEqual(subscription.traffic_limit_bytes, 1024 ** 4) self.assertEqual(app.approve(self.reviewer).pk, subscription.pk) self.assertEqual(Subscription.objects.count(), 1) def test_external_cannot_activate_online_plan_through_admin_form_or_raw_row(self): self.plan.online_payment_required = True self.plan.save() sub = Subscription(user=self.external, plan=self.plan, status="active", provisioning_state="active") with self.assertRaises(ValidationError): sub.full_clean() # ORM writes bypass ModelForm validation: read/config and node gates # still must not accept this row as proof that money was received. sub.save() self.assertFalse(sub.is_usable) node = Node.objects.create(name="fixture", slug="node-fixture", server="example.invalid", port=11082) self.assertNotIn(sub, desired_subscriptions_for_node(node)) employee_sub = Subscription.objects.create(user=self.employee, plan=self.plan, status="active", provisioning_state="active") self.assertTrue(employee_sub.is_usable) self.assertIn(employee_sub, desired_subscriptions_for_node(node)) def test_listed_plan_labels_and_portal_are_honest_about_payment(self): call_command("prepare_monthly_1024g", list_plan=True, verbosity=0) plan = Plan.objects.get(slug="monthly-1024g") self.assertIn("8.00元/月", plan.application_label()) self.assertIn("暂未开放付款", plan.application_label(self.external)) self.assertIn("内部员工免费", plan.application_label(self.employee)) self.assertNotIn("暂未开放付款", plan.application_label(self.employee)) response = self.client.get(reverse("register")) self.assertContains(response, "8.00元/月") self.assertContains(response, "暂未开放付款") self.client.force_login(self.external) response = self.client.get(reverse("portal-dashboard")) self.assertContains(response, "1024G 月度套餐") self.assertContains(response, "暂未开放付款") response = self.client.post(reverse("apply-plan"), {"plan": plan.pk, "note": "fixture request"}, follow=True) self.assertContains(response, "未扣款、未开通付费服务") self.assertEqual(PlanApplication.objects.get(user=self.external).payment_status, "unpaid") self.assertFalse(Subscription.objects.exists()) def test_registration_submits_listed_plan_without_granting_employee_or_subscription(self): call_command("prepare_monthly_1024g", list_plan=True, verbosity=0) plan = Plan.objects.get(slug="monthly-1024g") response = self.client.post(reverse("register"), { "username": "new-applicant", "display_name": "Fixture Applicant", "email": "new-applicant@example.invalid", "password1": "testing-Qp78-vNw4!", "password2": "testing-Qp78-vNw4!", "plan": plan.pk, "accept_terms": "on", "identity_type": "employee", "payment_status": "paid", }, follow=True) self.assertContains(response, "暂未开放付款,未扣款、未开通付费服务") user = User.objects.get(username="new-applicant") self.assertEqual(user.identity_type, "external") self.assertEqual(user.account_status, "pending") self.assertEqual(PlanApplication.objects.get(user=user).payment_status, "unpaid") self.assertFalse(Subscription.objects.filter(user=user).exists())