{
  "repo": "tidbcloud/billing",
  "binary": "server",
  "binary_path": "cmd/server/main.go",
  "dependencies": {
    "BillingServerLifecycle.LoadConfig": {
      "infrastructure": {
        "filesystem": {
          "conditions": [
            "Always at process startup before any DB, cache, or listener initialization"
          ],
          "operations": [
            {
              "operation": "READ FILE",
              "trigger": "Load billing config from env-backed config sources before constructing any server dependencies",
              "conditions": [
                "main() reached config.Init()"
              ],
              "implementation": "config.Init()"
            }
          ]
        }
      },
      "services": []
    },
    "BillingServerLifecycle.InitializeDatabase": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Always after config.Init() succeeds"
          ],
          "operations": [
            {
              "operation": "CONNECT",
              "trigger": "Create the shared primary and read-only GORM handles used by all billing HTTP handlers",
              "conditions": [
                "config.Init() succeeded"
              ],
              "implementation": "db.Initialize() -> initializeDB(getDBAuthConfig(false)); initializeDB(getReadOnlyAuthConfig())"
            }
          ]
        }
      },
      "services": []
    },
    "BillingServerLifecycle.InitializeCache": {
      "infrastructure": {
        "redis": {
          "conditions": [
            "Always at startup even though many cache reads are feature-gated later"
          ],
          "operations": [
            {
              "operation": "CONNECT",
              "trigger": "Initialize the shared Redis cache client consumed by cost explorer, MSP bills, and payment helpers",
              "conditions": [
                "main() reached cachehandler.Init()"
              ],
              "implementation": "cachehandler.Init() -> redis.NewClient(&redis.Options{Addr: RedisHost, DB: RedisDB})"
            }
          ]
        }
      },
      "services": []
    },
    "BillingServerLifecycle.InitializeRateLimiter": {
      "infrastructure": {},
      "services": []
    },
    "BillingServerLifecycle.InitializeWebIdentity": {
      "infrastructure": {},
      "services": []
    },
    "BillingServerLifecycle.InitializeLoggerAndSentry": {
      "infrastructure": {},
      "services": []
    },
    "BillingServerLifecycle.BuildHTTPServer": {
      "infrastructure": {},
      "services": [
        {
          "name": "account-svc",
          "target_interface": "account client initialization",
          "operation_type": "client_init",
          "conditions": [
            "Always while building the gin engine"
          ],
          "operations": [
            {
              "operation": "INITIALIZE CLIENT",
              "trigger": "Prime the shared account gRPC client before auth middlewares and partner/MSP routes start serving",
              "conditions": [
                "api.NewService() reached auth.InitAccountClientByEndpoint(config.AccountSvcAddress, 0)"
              ],
              "implementation": "auth.InitAccountClientByEndpoint(config.Get().GetString(config.AccountSvcAddress), 0)"
            }
          ]
        }
      ]
    },
    "BillingServerLifecycle.RegisterPprof": {
      "infrastructure": {},
      "services": []
    },
    "BillingServerLifecycle.InitializeAuditLog": {
      "infrastructure": {},
      "services": []
    },
    "BillingServerLifecycle.InitializeMeasureSender": {
      "infrastructure": {},
      "services": [
        {
          "name": "measure-sqs",
          "target_repo": "tidbcloud/tiinf",
          "target_interface": "measure.MeasureSQSImpl.InitMeasureSqsHandler",
          "operation_type": "client_init",
          "conditions": [
            "Always at startup"
          ],
          "operations": [
            {
              "operation": "INITIALIZE SENDER",
              "trigger": "Prepare the shared measure sender used by queue-backed billing measure flows",
              "conditions": [
                "main() reached sqsmeasurehandler.SetDefaultMeasureSender()"
              ],
              "implementation": "sqsmeasurehandler.SetDefaultMeasureSender() -> NewSQSMeasureSender() -> measure.MeasureSQSImpl.InitMeasureSqsHandler(config.Get().GetString(config.ENV), \"\")"
            }
          ]
        }
      ]
    },
    "BillingServerLifecycle.StartConditionalSqsMeasure": {
      "infrastructure": {
        "sqs": {
          "conditions": [
            "Only when utils.GetContainerAppName() == constant.ContainerAppNameBilling2"
          ],
          "operations": [
            {
              "operation": "RECEIVE",
              "trigger": "Start the background SQS measure consumer only in the billing2 application container",
              "conditions": [
                "utils.GetContainerAppName() == constant.ContainerAppNameBilling2"
              ],
              "implementation": "sqsmeasurehandler.Get().RunSqsMeasure()"
            }
          ]
        }
      },
      "services": []
    },
    "BillingServerLifecycle.StartEventBus": {
      "infrastructure": {},
      "services": []
    },
    "BillingServerLifecycle.ConfigurePaymentHandler": {
      "infrastructure": {},
      "services": []
    },
    "BillingServerLifecycle.ConfigureMarketplaceHandler": {
      "infrastructure": {},
      "services": []
    },
    "BillingServerLifecycle.StartHTTPServer": {
      "infrastructure": {
        "tcp": {
          "conditions": [
            "Always after startup initialization and router construction succeed"
          ],
          "operations": [
            {
              "operation": "LISTEN",
              "trigger": "Serve the main billing HTTP listener on BillingServerPort",
              "conditions": [
                "engine.Run(fmt.Sprintf(\":%d\", config.Get().GetInt(config.BillingServerPort))) is reached"
              ],
              "implementation": "engine.Run(fmt.Sprintf(\":%d\", config.Get().GetInt(config.BillingServerPort)))"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /metrics": {
      "infrastructure": {},
      "services": []
    },
    "HTTP OPTIONS /v1beta1/partners/*any": {
      "infrastructure": {},
      "services": []
    },
    "HTTP GET /debug/pprof/*": {
      "infrastructure": {},
      "services": []
    },
    "HTTP POST /debug/pprof/symbol": {
      "infrastructure": {},
      "services": []
    },
    "HTTP POST /api/v1/billing/tenants/:tenant_id/costexplorer": {
      "infrastructure": {
        "mysql": {
          "conditions": ["Always"],
          "operations": [
            {"operation": "SELECT", "table": "user_unit_costs", "trigger": "Query billing costs from database"},
            {"operation": "SELECT", "table": "invoices", "trigger": "Get invoice data"},
            {"operation": "SELECT", "table": "billing_configs", "trigger": "Get billing configuration"},
            {"operation": "SELECT", "table": "tenant_plans", "trigger": "Get tenant plan info"},
            {"operation": "SELECT", "table": "credits_packages", "trigger": "Calculate credits"}
          ]
        },
        "redis": {
          "conditions": ["EnableCache == true"],
          "operations": [
            {"operation": "GET", "trigger": "Cache lookup for cost explorer results"},
            {"operation": "SET", "trigger": "Cache cost explorer results"}
          ]
        }
      },
      "services": [
        {
          "name": "account-svc",
          "target_interface": "AccountAPIService.GetOrgByID",
          "operation_type": "grpc_unary",
          "conditions": ["DBaaSCentralEnable == true"],
          "operations": [{"operation": "gRPC GetOrgByID", "trigger": "Get tenant info for bills"}]
        },
        {
          "name": "account-svc",
          "target_interface": "AccountAPIService.ListProjects",
          "operation_type": "grpc_unary",
          "conditions": ["DBaaSCentralEnable == true"],
          "operations": [{"operation": "gRPC ListProjects", "trigger": "Get project list for cost breakdown"}]
        },
        {
          "name": "infra-svc",
          "target_interface": "CoreService.ListClusters",
          "operation_type": "grpc_unary",
          "conditions": ["breakdown by cluster"],
          "operations": [{"operation": "gRPC ListClusters", "trigger": "Get cluster list for cost breakdown"}]
        }
      ]
    },
    "HTTP POST /api/v1/billing/tenants/:tenant_id/costexplorer/trends": {
      "infrastructure": {
        "mysql": {
          "conditions": ["Always"],
          "operations": [
            {"operation": "SELECT", "table": "user_unit_costs", "trigger": "Query billing costs from database"},
            {"operation": "SELECT", "table": "billing_configs", "trigger": "Get billing configuration"}
          ]
        },
        "redis": {
          "conditions": ["EnableCache == true"],
          "operations": [
            {"operation": "GET", "trigger": "Cache lookup for trends results"},
            {"operation": "SET", "trigger": "Cache trends results"}
          ]
        }
      },
      "services": [
        {
          "name": "account-svc",
          "target_interface": "AccountAPIService.GetOrgByID",
          "operation_type": "grpc_unary",
          "conditions": ["DBaaSCentralEnable == true"],
          "operations": [{"operation": "gRPC GetOrgByID", "trigger": "Get tenant info"}]
        },
        {
          "name": "account-svc",
          "target_interface": "AccountAPIService.ListProjects",
          "operation_type": "grpc_unary",
          "conditions": ["breakdown by project"],
          "operations": [{"operation": "gRPC ListProjects", "trigger": "Get project list"}]
        },
        {
          "name": "account-svc",
          "target_interface": "AccountAPIService.ListPartnerCustomers",
          "operation_type": "grpc_unary",
          "conditions": ["breakdown by customer"],
          "operations": [{"operation": "gRPC ListPartnerCustomers", "trigger": "Get partner customers"}]
        },
        {
          "name": "infra-svc",
          "target_interface": "CoreService.ListClusters",
          "operation_type": "grpc_unary",
          "conditions": ["breakdown by cluster"],
          "operations": [{"operation": "gRPC ListClusters", "trigger": "Get cluster list"}]
        }
      ]
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/costexplorer/args": {
      "infrastructure": {
        "mysql": {
          "conditions": ["Always"],
          "operations": [
            {"operation": "SELECT", "table": "user_unit_costs", "trigger": "Query distinct values for args"}
          ]
        },
        "redis": {
          "conditions": ["EnableCache == true"],
          "operations": [
            {"operation": "GET", "trigger": "Cache lookup for args"},
            {"operation": "SET", "trigger": "Cache args"}
          ]
        }
      },
      "services": [
        {
          "name": "account-svc",
          "target_interface": "AccountAPIService.ListProjects",
          "operation_type": "grpc_unary",
          "conditions": ["DBaaSCentralEnable == true"],
          "operations": [{"operation": "gRPC ListProjects", "trigger": "Get project list for args"}]
        },
        {
          "name": "infra-svc",
          "target_interface": "CoreService.ListClusters",
          "operation_type": "grpc_unary",
          "conditions": ["Always"],
          "operations": [{"operation": "gRPC ListClusters", "trigger": "Get cluster list for args"}]
        }
      ]
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/payments": {
      "infrastructure": {
        "mysql": {
          "conditions": ["Always"],
          "operations": [
            {"operation": "SELECT", "table": "payment_methods", "trigger": "Query payment methods"}
          ]
        }
      },
      "services": [
        {
          "name": "account-svc",
          "target_interface": "AccountAPIService.GetOrgByID",
          "operation_type": "grpc_unary",
          "conditions": ["DBaaSCentralEnable == true"],
          "operations": [{"operation": "gRPC GetOrgByID", "trigger": "Get tenant info"}]
        }
      ]
    },
    "HTTP POST /api/v1/billing/tenants/:tenant_id/payments/setup/:payment_type": {
      "infrastructure": {
        "mysql": {
          "conditions": ["Always"],
          "operations": [
            {"operation": "SELECT", "table": "payment_methods", "trigger": "Check existing payment methods"},
            {"operation": "INSERT", "table": "payment_methods", "trigger": "Create payment method"},
            {"operation": "UPDATE", "table": "payment_methods", "trigger": "Update payment method status"}
          ]
        }
      },
      "services": [
        {
          "name": "account-svc",
          "target_interface": "AccountAPIService.GetOrgByID",
          "operation_type": "grpc_unary",
          "conditions": ["DBaaSCentralEnable == true"],
          "operations": [{"operation": "gRPC GetOrgByID", "trigger": "Get tenant info"}]
        }
      ]
    },
    "HTTP POST /api/v1/billing/tenants/:tenant_id/payments/stripe/setup_intent": {
      "infrastructure": {
        "mysql": {
          "conditions": ["Always"],
          "operations": [
            {"operation": "SELECT", "table": "payment_methods", "trigger": "Get Stripe payment info"},
            {"operation": "UPDATE", "table": "payment_methods", "trigger": "Update payable status"},
            {"operation": "SELECT", "table": "billing_configs", "trigger": "Get billing config"}
          ]
        }
      },
      "services": [
        {
          "name": "stripe-api",
          "target_interface": "POST /v1/setup_intents",
          "operation_type": "http_post",
          "conditions": ["StripePaymentEnable == true"],
          "operations": [{"operation": "HTTP SetupIntent", "trigger": "Create Stripe setup intent"}]
        },
        {
          "name": "stripe-api",
          "target_interface": "POST /v1/customers",
          "operation_type": "http_post",
          "conditions": ["StripePaymentEnable == true", "customer not exists"],
          "operations": [{"operation": "HTTP CreateCustomer", "trigger": "Create Stripe customer"}]
        }
      ]
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/payments/stripe/invoices": {
      "infrastructure": {
        "mysql": {
          "conditions": ["Always"],
          "operations": [
            {"operation": "SELECT", "table": "payment_methods", "trigger": "Get Stripe payment info"},
            {"operation": "SELECT", "table": "billing_configs", "trigger": "Get billing config"}
          ]
        },
        "redis": {
          "conditions": ["EnableCache == true"],
          "operations": [
            {"operation": "GET", "trigger": "Get cached Stripe invoices"},
            {"operation": "SET", "trigger": "Cache Stripe invoices"}
          ]
        }
      },
      "services": [
        {
          "name": "stripe-api",
          "target_interface": "GET /v1/invoices",
          "operation_type": "http_get",
          "conditions": ["StripePaymentEnable == true"],
          "operations": [{"operation": "HTTP ListInvoices", "trigger": "List Stripe invoices"}]
        }
      ]
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/payments/stripe/payment_methods": {
      "infrastructure": {
        "mysql": {
          "conditions": ["Always"],
          "operations": [
            {"operation": "SELECT", "table": "payment_methods", "trigger": "Get Stripe payment info"}
          ]
        }
      },
      "services": [
        {
          "name": "stripe-api",
          "target_interface": "GET /v1/payment_methods",
          "operation_type": "http_get",
          "conditions": ["StripePaymentEnable == true"],
          "operations": [{"operation": "HTTP ListPaymentMethods", "trigger": "List payment methods"}]
        }
      ]
    },
    "HTTP PUT /api/v1/billing/tenants/:tenant_id/payments/stripe/payment_methods/:payment_method_id": {
      "infrastructure": {
        "mysql": {
          "conditions": ["Always"],
          "operations": [
            {"operation": "SELECT", "table": "payment_methods", "trigger": "Get Stripe payment info"}
          ]
        }
      },
      "services": [
        {
          "name": "stripe-api",
          "target_interface": "POST /v1/payment_methods/:id",
          "operation_type": "http_post",
          "conditions": ["StripePaymentEnable == true"],
          "operations": [{"operation": "HTTP UpdatePaymentMethod", "trigger": "Update payment method"}]
        }
      ]
    },
    "HTTP DELETE /api/v1/billing/tenants/:tenant_id/payments/stripe/payment_methods/:payment_method_id": {
      "infrastructure": {
        "mysql": {
          "conditions": ["Always"],
          "operations": [
            {"operation": "SELECT", "table": "payment_methods", "trigger": "Get Stripe payment info"},
            {"operation": "DELETE", "table": "payment_methods", "trigger": "Delete payment method"}
          ]
        }
      },
      "services": [
        {
          "name": "stripe-api",
          "target_interface": "DELETE /v1/payment_methods/:id",
          "operation_type": "http_delete",
          "conditions": ["StripePaymentEnable == true"],
          "operations": [{"operation": "HTTP DetachPaymentMethod", "trigger": "Detach payment method from customer"}]
        }
      ]
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/credits": {
      "infrastructure": {
        "mysql": {
          "conditions": ["Always"],
          "operations": [
            {"operation": "SELECT", "table": "credits_packages", "trigger": "Query credits"},
            {"operation": "SELECT", "table": "unit_filters", "trigger": "Get unit filter info"}
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/tenants/:tenant_id/credits": {
      "infrastructure": {
        "mysql": {
          "conditions": ["Always"],
          "operations": [
            {"operation": "SELECT", "table": "credits_packages", "trigger": "Check existing credits"},
            {"operation": "INSERT", "table": "credits_packages", "trigger": "Create credits package"},
            {"operation": "SELECT", "table": "unit_filters", "trigger": "Get unit filter info"}
          ]
        }
      },
      "services": [
        {
          "name": "account-svc",
          "target_interface": "AccountAPIService.GetOrgByID",
          "operation_type": "grpc_unary",
          "conditions": ["DBaaSCentralEnable == true"],
          "operations": [{"operation": "gRPC GetOrgByID", "trigger": "Get tenant info"}]
        }
      ]
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/contracts": {
      "infrastructure": {
        "mysql": {
          "conditions": ["Always"],
          "operations": [
            {"operation": "SELECT", "table": "contracts", "trigger": "Query contracts"}
          ]
        },
        "s3": {
          "conditions": ["contract file exists"],
          "operations": [
            {"operation": "GET", "trigger": "Download contract file"}
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/tenants/:tenant_id/contracts": {
      "infrastructure": {
        "mysql": {
          "conditions": ["Always"],
          "operations": [
            {"operation": "SELECT", "table": "contracts", "trigger": "Check existing contracts"},
            {"operation": "INSERT", "table": "contracts", "trigger": "Create contract"}
          ]
        },
        "s3": {
          "conditions": ["contract file uploaded"],
          "operations": [
            {"operation": "PUT", "trigger": "Upload contract file"}
          ]
        }
      },
      "services": [
        {
          "name": "account-svc",
          "target_interface": "AccountAPIService.DownloadFile",
          "operation_type": "grpc_unary",
          "conditions": ["DBaaSCentralEnable == true", "central file exists"],
          "operations": [{"operation": "gRPC DownloadFile", "trigger": "Download contract from central"}]
        }
      ]
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/invoices": {
      "infrastructure": {
        "mysql": {
          "conditions": ["Always"],
          "operations": [
            {"operation": "SELECT", "table": "invoices", "trigger": "Query invoices"},
            {"operation": "SELECT", "table": "invoice_items", "trigger": "Get invoice items"},
            {"operation": "SELECT", "table": "billing_configs", "trigger": "Get billing config"}
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/tenants/:tenant_id/invoices": {
      "infrastructure": {
        "mysql": {
          "conditions": ["Always"],
          "operations": [
            {"operation": "SELECT", "table": "billing_configs", "trigger": "Get billing config"},
            {"operation": "SELECT", "table": "payment_methods", "trigger": "Get payment method"},
            {"operation": "INSERT", "table": "invoices", "trigger": "Create invoice"},
            {"operation": "INSERT", "table": "invoice_items", "trigger": "Create invoice items"}
          ]
        },
        "s3": {
          "conditions": ["EnablePutARTableToS3 == true"],
          "operations": [
            {"operation": "PUT", "trigger": "Upload AR table to S3"}
          ]
        }
      },
      "services": [
        {
          "name": "stripe-api",
          "target_interface": "POST /v1/invoices",
          "operation_type": "http_post",
          "conditions": ["payment type == STRIPE"],
          "operations": [{"operation": "HTTP CreateInvoice", "trigger": "Create Stripe invoice"}]
        }
      ]
    },
    "HTTP PUT /api/v1/billing/tenants/:tenant_id/invoices/:invoice_id/confirm": {
      "infrastructure": {
        "mysql": {
          "conditions": ["Always"],
          "operations": [
            {"operation": "SELECT", "table": "invoices", "trigger": "Get invoice"},
            {"operation": "UPDATE", "table": "invoices", "trigger": "Update invoice status"}
          ]
        }
      },
      "services": [
        {
          "name": "stripe-api",
          "target_interface": "POST /v1/invoices/:id/pay",
          "operation_type": "http_post",
          "conditions": ["payment type == STRIPE"],
          "operations": [{"operation": "HTTP PayInvoice", "trigger": "Pay Stripe invoice"}]
        }
      ]
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/billing_info": {
      "infrastructure": {
        "mysql": {
          "conditions": ["Always"],
          "operations": [
            {"operation": "SELECT", "table": "billing_companies", "trigger": "Get billing company"},
            {"operation": "SELECT", "table": "billing_configs", "trigger": "Get billing config"}
          ]
        }
      },
      "services": []
    },
    "HTTP PUT /api/v1/billing/tenants/:tenant_id/billing_info": {
      "infrastructure": {
        "mysql": {
          "conditions": ["Always"],
          "operations": [
            {"operation": "SELECT", "table": "billing_companies", "trigger": "Get billing company"},
            {"operation": "INSERT", "table": "billing_companies", "trigger": "Create billing company"},
            {"operation": "UPDATE", "table": "billing_companies", "trigger": "Update billing company"}
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/support_plan": {
      "infrastructure": {
        "mysql": {
          "conditions": ["Always"],
          "operations": [
            {"operation": "SELECT", "table": "support_plans", "trigger": "Get support plans"}
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/tenants/:tenant_id/binded_support_plan/public": {
      "infrastructure": {
        "mysql": {
          "conditions": ["Always"],
          "operations": [
            {"operation": "SELECT", "table": "support_plans", "trigger": "Get support plan"},
            {"operation": "SELECT", "table": "binded_support_plans", "trigger": "Check existing binding"},
            {"operation": "INSERT", "table": "binded_support_plans", "trigger": "Bind support plan"}
          ]
        },
        "redis": {
          "conditions": ["EnableCache == true"],
          "operations": [
            {"operation": "DEL", "trigger": "Clear cached support plan data"}
          ]
        }
      },
      "services": []
    },
    "HTTP DELETE /api/v1/billing/tenants/:tenant_id/binded_support_plan/public": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant path binding succeeds and the tenant has an active support-plan binding"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "binded_support_plans",
              "trigger": "Load the active tenant binding before validating whether the bound support plan is public",
              "conditions": [
                "getTenantIDFromURI(c) succeeded"
              ],
              "implementation": "marketing.SupportPlanModel.GetTenantActiveBindedPlan(tenantID)"
            },
            {
              "operation": "SELECT",
              "table": "support_plans",
              "trigger": "Hydrate the bound support-plan attributes so the public flag can be checked",
              "conditions": [
                "GetTenantActiveBindedPlan(tenantID) returned a persisted binding"
              ],
              "implementation": "marketing.SupportPlanModel.GetTenantActiveBindedPlan(tenantID)"
            },
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the active billing config before checking whether the tenant is an AliCloud marketplace subscriber",
              "conditions": [
                "the active binded support plan is public"
              ],
              "implementation": "paymentsub.PaymentModel.GetPaymentMethodWithPaymentTypeCurrentBillingConfig(tenantID, ALI_CLOUD) -> billingconfig.BillingConfigModel.GetActiveBillingConfigID(tenantID)"
            },
            {
              "operation": "SELECT",
              "table": "payment_methods",
              "trigger": "Block self-cancel for payable AliCloud marketplace subscribers",
              "conditions": [
                "the active binded support plan is public"
              ],
              "implementation": "paymentsub.PaymentModel.GetPaymentMethodWithPaymentTypeCurrentBillingConfig(tenantID, ALI_CLOUD)"
            },
            {
              "operation": "UPDATE",
              "table": "binded_support_plans",
              "trigger": "Mark the current active support-plan binding canceled and stamp its closed date",
              "conditions": [
                "either no AliCloud payment method exists or the AliCloud payment method is not payable"
              ],
              "implementation": "marketing.SupportPlanModel.CancelBindedSupportPlan(info.BindedSupportPlanID)"
            },
            {
              "operation": "INSERT",
              "table": "support_plan_metering_records",
              "trigger": "Persist catch-up normal and commitment metering rows when canceling an active or expired support plan",
              "conditions": [
                "CancelBindedSupportPlan(...) reached SendNormalMetering(...) or SendCommitmentMetering(...)"
              ],
              "implementation": "marketing.SupportPlanModel.CancelBindedSupportPlan(...) -> SendNormalMetering(...) / SendCommitmentMetering(...)"
            }
          ]
        }
      },
      "services": [
        {
          "name": "measure-sqs",
          "target_repo": "tidbcloud/tiinf",
          "target_interface": "billing.MeasureModel.SecondaryMeasure",
          "operation_type": "async_measure",
          "conditions": [
            "Only when the canceled binded support plan had ACTIVE or EXPIRED status and the recomputed normal or commitment metering amount is non-zero"
          ],
          "operations": [
            {
              "operation": "SEND SECONDARY MEASURE",
              "trigger": "Reissue support-plan metering after cancellation recalculates the remaining billable window",
              "conditions": [
                "CancelBindedSupportPlan(...) reached SendNormalMetering(...) or SendCommitmentMetering(...)"
              ],
              "implementation": "billing.MeasureModel.SecondaryMeasure(...)"
            }
          ]
        },
        {
          "name": "account-svc",
          "target_interface": "GetOrgByID",
          "operation_type": "grpc",
          "conditions": [
            "Only when support-plan cancellation completed and in-app notification sync is enabled"
          ],
          "operations": [
            {
              "operation": "GRPC GetOrgByID",
              "trigger": "Load tenant metadata so the support-plan change notification can include org name",
              "conditions": [
                "marketing.SupportPlanModel.CancelBindedSupportPlan(...) reached sendBindedSupportPlanUpdateNotification(...)"
              ],
              "implementation": "centralhandler.GetCentralHandler().GetTenant(tenantID) -> account.GetOrgByID(IsBrief=true)"
            }
          ]
        },
        {
          "name": "eventbus",
          "target_interface": "PublishEventWithTransaction",
          "operation_type": "transactional_publish",
          "conditions": [
            "Only when SupportPlanUpdateSyncToEventBusEnable == true and support-plan cancellation completed"
          ],
          "operations": [
            {
              "operation": "PUBLISH EVENT",
              "trigger": "Publish the downgraded default support-plan state to the event bus after cancellation",
              "conditions": [
                "marketing.SupportPlanModel.CancelBindedSupportPlan(...) completed"
              ],
              "implementation": "marketing.SupportPlanModel.SyncCurrentSupportToEventBus(DefaultBindedSupportPlan(tenantID)) -> eventbushandler.Get().PublishEventWithTransaction(...)"
            }
          ]
        },
        {
          "name": "novu-api",
          "target_interface": "POST /v1/events/trigger/bulk",
          "operation_type": "http_post",
          "conditions": [
            "Only when InAPPNotificationEnable == true and support-plan cancellation completed"
          ],
          "operations": [
            {
              "operation": "HTTP BulkTriggerEvent",
              "trigger": "Notify org users that the tenant support plan changed after cancellation",
              "conditions": [
                "marketing.SupportPlanModel.CancelBindedSupportPlan(...) reached sendBindedSupportPlanUpdateNotification(...)"
              ],
              "implementation": "uncutils.SendInAppNotification(...) -> novuhandler.Get().BulkTriggerEvent(...)"
            }
          ]
        }
      ]
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/binded_support_plan": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant path binding succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the active billing config before checking whether support-plan ownership is delegated to an MSP tenant",
              "conditions": [
                "getBillingCfgFromURI(c) succeeded"
              ],
              "implementation": "getBillingCfgFromURI(c)"
            },
            {
              "operation": "SELECT",
              "table": "payment_methods",
              "trigger": "Check whether the active payment method delegates support-plan ownership to an MSP tenant",
              "conditions": [
                "billingCfgStruct.TenantID and billingCfgStruct.BillingConfigID resolved successfully"
              ],
              "implementation": "paymentModel.GetActivePaymentMethod(billingCfgStruct.TenantID, billingCfgStruct.BillingConfigID)"
            },
            {
              "operation": "SELECT",
              "table": "binded_support_plans",
              "trigger": "Read the active binded support plan for either the tenant itself or the delegated MSP tenant",
              "conditions": [
                "payment method lookup succeeded or returned ObjectNotExists"
              ],
              "implementation": "marketing.SupportPlanModel.GetTenantActiveBindedPlan(targetTenantID)"
            },
            {
              "operation": "SELECT",
              "table": "support_plans",
              "trigger": "Hydrate support-plan attributes referenced by the active tenant binding",
              "conditions": [
                "GetTenantActiveBindedPlan(targetTenantID) returned a persisted binding"
              ],
              "implementation": "marketing.SupportPlanModel.GetTenantActiveBindedPlan(targetTenantID)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/binded_support_plan/list": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant path binding succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the active billing config before deciding whether support-plan listing should follow MSP delegation",
              "conditions": [
                "getBillingCfgFromURI(c) succeeded"
              ],
              "implementation": "getBillingCfgFromURI(c)"
            },
            {
              "operation": "SELECT",
              "table": "payment_methods",
              "trigger": "Determine whether the tenant is billed through MSP and should inherit the MSP tenant's single active plan",
              "conditions": [
                "billingCfgStruct.TenantID and billingCfgStruct.BillingConfigID resolved successfully"
              ],
              "implementation": "paymentModel.GetActivePaymentMethod(billingCfgStruct.TenantID, billingCfgStruct.BillingConfigID)"
            },
            {
              "operation": "SELECT",
              "table": "binded_support_plans",
              "trigger": "List the tenant's bindings grouped by ACTIVE, TOBEACTIVATED, EXPIRED, and CANCELED status when not delegated to MSP",
              "conditions": [
                "either no active MSP payment method exists or the request is not delegated to MSP"
              ],
              "implementation": "marketing.SupportPlanModel.ListTenantsBindedSupportPlan(billingCfgStruct.TenantID, status)"
            },
            {
              "operation": "SELECT",
              "table": "support_plans",
              "trigger": "Hydrate each listed binding's referenced support-plan definition",
              "conditions": [
                "ListTenantsBindedSupportPlan(...) returned persisted bindings"
              ],
              "implementation": "marketing.SupportPlanModel.ListTenantsBindedSupportPlan(...)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/binded_support_plan/details": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant path binding succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the tenant's billing config before listing all support-plan bindings for free-trial eligibility",
              "conditions": [
                "getBillingCfgFromURI(c) succeeded"
              ],
              "implementation": "getBillingCfgFromURI(c)"
            },
            {
              "operation": "SELECT",
              "table": "binded_support_plans",
              "trigger": "List all active, expired, canceled, and to-be-activated support-plan bindings for the tenant",
              "conditions": [
                "billingCfgStruct.TenantID resolved successfully"
              ],
              "implementation": "marketing.SupportPlanModel.ListTenantsBindedSupportPlan(billingCfgStruct.TenantID, ACTIVE, EXPIRED, CANCELED, TOBEACTIVATED)"
            },
            {
              "operation": "SELECT",
              "table": "support_plans",
              "trigger": "Hydrate support-plan attributes for every returned binding",
              "conditions": [
                "ListTenantsBindedSupportPlan(...) returned persisted bindings"
              ],
              "implementation": "marketing.SupportPlanModel.ListTenantsBindedSupportPlan(...)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/tenants/:tenant_id/binded_support_plan/private": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant path binding and request-body validation succeed"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Reject MSP customers before private support-plan creation and binding",
              "conditions": [
                "input.ActiveDate normalized successfully",
                "input.Public == false"
              ],
              "implementation": "billingconfig.BillingConfigModel.IsMspCustomer(tenantID)"
            },
            {
              "operation": "INSERT",
              "table": "support_plans",
              "trigger": "Create the tenant-private support-plan definition before binding it",
              "conditions": [
                "tenant is not an MSP customer"
              ],
              "implementation": "marketing.SupportPlanModel.CreateSupportPlan(&input.SupportPlan)"
            },
            {
              "operation": "SELECT",
              "table": "payment_methods",
              "trigger": "Verify the tenant is payable before the new private support plan can be bound",
              "conditions": [
                "CreateSupportPlan(...) succeeded"
              ],
              "implementation": "marketing.SupportPlanModel.BindSupportPlanForPayableCustomer(...) -> paymentsub.PaymentModel.Payable(tenantID)"
            },
            {
              "operation": "SELECT",
              "table": "binded_support_plans",
              "trigger": "Load overlapping ACTIVE and TOBEACTIVATED support-plan bindings to resolve date conflicts",
              "conditions": [
                "PaymentModel.Payable(tenantID) == true"
              ],
              "implementation": "marketing.SupportPlanModel.bindSupportPlan(...) -> entity.NewBindedSupportPlanQuerySet(...).StatusIn(ACTIVE, TOBEACTIVATED).All(&currentPlans)"
            },
            {
              "operation": "UPDATE",
              "table": "binded_support_plans",
              "trigger": "Shorten or cancel conflicting existing support-plan bindings when the new private binding overlaps them",
              "conditions": [
                "at least one existing ACTIVE or TOBEACTIVATED binding overlaps the requested interval"
              ],
              "implementation": "marketing.SupportPlanModel.bindSupportPlan(...)"
            },
            {
              "operation": "INSERT",
              "table": "binded_support_plans",
              "trigger": "Create the new private support-plan binding in ACTIVE or TOBEACTIVATED status",
              "conditions": [
                "interval validation passed and conflict handling completed"
              ],
              "implementation": "marketing.SupportPlanModel.bindSupportPlan(...) -> bindedSupportPlanEntity.Create(tx)"
            }
          ]
        }
      },
      "services": [
        {
          "name": "account-svc",
          "target_interface": "GetOrgByID",
          "operation_type": "grpc",
          "conditions": [
            "Only when the new private support plan becomes ACTIVE immediately and in-app notification sync is reached"
          ],
          "operations": [
            {
              "operation": "GRPC GetOrgByID",
              "trigger": "Load tenant metadata so the immediate support-plan update notification can include org name",
              "conditions": [
                "marketing.SupportPlanModel.bindSupportPlan(...) created an ACTIVE binding"
              ],
              "implementation": "centralhandler.GetCentralHandler().GetTenant(tenantID) -> account.GetOrgByID(IsBrief=true)"
            }
          ]
        },
        {
          "name": "eventbus",
          "target_interface": "PublishEventWithTransaction",
          "operation_type": "transactional_publish",
          "conditions": [
            "Only when the new private support plan becomes ACTIVE immediately and SupportPlanUpdateSyncToEventBusEnable == true"
          ],
          "operations": [
            {
              "operation": "PUBLISH EVENT",
              "trigger": "Publish the new current support-plan state after the private plan activates immediately",
              "conditions": [
                "marketing.SupportPlanModel.bindSupportPlan(...) created an ACTIVE binding"
              ],
              "implementation": "marketing.SupportPlanModel.SyncCurrentSupportToEventBus(support) -> eventbushandler.Get().PublishEventWithTransaction(...)"
            }
          ]
        },
        {
          "name": "novu-api",
          "target_interface": "POST /v1/events/trigger/bulk",
          "operation_type": "http_post",
          "conditions": [
            "Only when the new private support plan becomes ACTIVE immediately and InAPPNotificationEnable == true"
          ],
          "operations": [
            {
              "operation": "HTTP BulkTriggerEvent",
              "trigger": "Notify org users that the tenant support plan changed immediately after private-plan binding",
              "conditions": [
                "marketing.SupportPlanModel.bindSupportPlan(...) created an ACTIVE binding"
              ],
              "implementation": "uncutils.SendInAppNotification(...) -> novuhandler.Get().BulkTriggerEvent(...)"
            }
          ]
        }
      ]
    },
    "HTTP DELETE /api/v1/billing/tenants/:tenant_id/binded_support_plan": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant path binding succeeds and the tenant has an active support-plan binding"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "binded_support_plans",
              "trigger": "Load the active tenant binding before canceling it",
              "conditions": [
                "getTenantIDFromURI(c) succeeded"
              ],
              "implementation": "marketing.SupportPlanModel.GetTenantActiveBindedPlan(tenantID)"
            },
            {
              "operation": "SELECT",
              "table": "support_plans",
              "trigger": "Hydrate support-plan attributes referenced by the active tenant binding",
              "conditions": [
                "GetTenantActiveBindedPlan(tenantID) returned a persisted binding"
              ],
              "implementation": "marketing.SupportPlanModel.GetTenantActiveBindedPlan(tenantID)"
            },
            {
              "operation": "UPDATE",
              "table": "binded_support_plans",
              "trigger": "Mark the current active support-plan binding canceled and stamp its closed date",
              "conditions": [
                "GetTenantActiveBindedPlan(tenantID) succeeded"
              ],
              "implementation": "marketing.SupportPlanModel.CancelBindedSupportPlan(info.BindedSupportPlanID)"
            },
            {
              "operation": "INSERT",
              "table": "support_plan_metering_records",
              "trigger": "Persist catch-up normal and commitment metering rows when canceling an active or expired support plan",
              "conditions": [
                "CancelBindedSupportPlan(...) reached SendNormalMetering(...) or SendCommitmentMetering(...)"
              ],
              "implementation": "marketing.SupportPlanModel.CancelBindedSupportPlan(...) -> SendNormalMetering(...) / SendCommitmentMetering(...)"
            }
          ]
        }
      },
      "services": [
        {
          "name": "measure-sqs",
          "target_repo": "tidbcloud/tiinf",
          "target_interface": "billing.MeasureModel.SecondaryMeasure",
          "operation_type": "async_measure",
          "conditions": [
            "Only when the canceled binded support plan had ACTIVE or EXPIRED status and the recomputed normal or commitment metering amount is non-zero"
          ],
          "operations": [
            {
              "operation": "SEND SECONDARY MEASURE",
              "trigger": "Reissue support-plan metering after cancellation recalculates the remaining billable window",
              "conditions": [
                "CancelBindedSupportPlan(...) reached SendNormalMetering(...) or SendCommitmentMetering(...)"
              ],
              "implementation": "billing.MeasureModel.SecondaryMeasure(...)"
            }
          ]
        },
        {
          "name": "account-svc",
          "target_interface": "GetOrgByID",
          "operation_type": "grpc",
          "conditions": [
            "Only when support-plan cancellation completed and in-app notification sync is enabled"
          ],
          "operations": [
            {
              "operation": "GRPC GetOrgByID",
              "trigger": "Load tenant metadata so the support-plan change notification can include org name",
              "conditions": [
                "marketing.SupportPlanModel.CancelBindedSupportPlan(...) reached sendBindedSupportPlanUpdateNotification(...)"
              ],
              "implementation": "centralhandler.GetCentralHandler().GetTenant(tenantID) -> account.GetOrgByID(IsBrief=true)"
            }
          ]
        },
        {
          "name": "eventbus",
          "target_interface": "PublishEventWithTransaction",
          "operation_type": "transactional_publish",
          "conditions": [
            "Only when SupportPlanUpdateSyncToEventBusEnable == true and support-plan cancellation completed"
          ],
          "operations": [
            {
              "operation": "PUBLISH EVENT",
              "trigger": "Publish the downgraded default support-plan state to the event bus after cancellation",
              "conditions": [
                "marketing.SupportPlanModel.CancelBindedSupportPlan(...) completed"
              ],
              "implementation": "marketing.SupportPlanModel.SyncCurrentSupportToEventBus(DefaultBindedSupportPlan(tenantID)) -> eventbushandler.Get().PublishEventWithTransaction(...)"
            }
          ]
        },
        {
          "name": "novu-api",
          "target_interface": "POST /v1/events/trigger/bulk",
          "operation_type": "http_post",
          "conditions": [
            "Only when InAPPNotificationEnable == true and support-plan cancellation completed"
          ],
          "operations": [
            {
              "operation": "HTTP BulkTriggerEvent",
              "trigger": "Notify org users that the tenant support plan changed after cancellation",
              "conditions": [
                "marketing.SupportPlanModel.CancelBindedSupportPlan(...) reached sendBindedSupportPlanUpdateNotification(...)"
              ],
              "implementation": "uncutils.SendInAppNotification(...) -> novuhandler.Get().BulkTriggerEvent(...)"
            }
          ]
        }
      ]
    },
    "HTTP DELETE /api/v1/billing/tenants/:tenant_id/binded_support_plan/:binded_support_plan_id": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant and binded-support-plan path binding succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "binded_support_plans",
              "trigger": "Load the target support-plan binding before canceling it",
              "conditions": [
                "c.ShouldBindUri(&params) succeeded"
              ],
              "implementation": "marketing.SupportPlanModel.GetBindedSupportPlan(params.BindedSupportPlanID)"
            },
            {
              "operation": "SELECT",
              "table": "support_plans",
              "trigger": "Hydrate support-plan attributes referenced by the target binding",
              "conditions": [
                "GetBindedSupportPlan(params.BindedSupportPlanID) returned a persisted binding"
              ],
              "implementation": "marketing.SupportPlanModel.GetBindedSupportPlan(params.BindedSupportPlanID)"
            },
            {
              "operation": "UPDATE",
              "table": "binded_support_plans",
              "trigger": "Mark the requested support-plan binding canceled and stamp its closed date",
              "conditions": [
                "GetBindedSupportPlan(...) succeeded"
              ],
              "implementation": "marketing.SupportPlanModel.CancelBindedSupportPlan(info.BindedSupportPlanID)"
            },
            {
              "operation": "INSERT",
              "table": "support_plan_metering_records",
              "trigger": "Persist catch-up normal and commitment metering rows when canceling an active or expired support plan",
              "conditions": [
                "CancelBindedSupportPlan(...) reached SendNormalMetering(...) or SendCommitmentMetering(...)"
              ],
              "implementation": "marketing.SupportPlanModel.CancelBindedSupportPlan(...) -> SendNormalMetering(...) / SendCommitmentMetering(...)"
            }
          ]
        }
      },
      "services": [
        {
          "name": "measure-sqs",
          "target_repo": "tidbcloud/tiinf",
          "target_interface": "billing.MeasureModel.SecondaryMeasure",
          "operation_type": "async_measure",
          "conditions": [
            "Only when the canceled binded support plan had ACTIVE or EXPIRED status and the recomputed normal or commitment metering amount is non-zero"
          ],
          "operations": [
            {
              "operation": "SEND SECONDARY MEASURE",
              "trigger": "Reissue support-plan metering after cancellation recalculates the remaining billable window",
              "conditions": [
                "CancelBindedSupportPlan(...) reached SendNormalMetering(...) or SendCommitmentMetering(...)"
              ],
              "implementation": "billing.MeasureModel.SecondaryMeasure(...)"
            }
          ]
        },
        {
          "name": "account-svc",
          "target_interface": "GetOrgByID",
          "operation_type": "grpc",
          "conditions": [
            "Only when support-plan cancellation completed and in-app notification sync is enabled"
          ],
          "operations": [
            {
              "operation": "GRPC GetOrgByID",
              "trigger": "Load tenant metadata so the support-plan change notification can include org name",
              "conditions": [
                "marketing.SupportPlanModel.CancelBindedSupportPlan(...) reached sendBindedSupportPlanUpdateNotification(...)"
              ],
              "implementation": "centralhandler.GetCentralHandler().GetTenant(tenantID) -> account.GetOrgByID(IsBrief=true)"
            }
          ]
        },
        {
          "name": "eventbus",
          "target_interface": "PublishEventWithTransaction",
          "operation_type": "transactional_publish",
          "conditions": [
            "Only when SupportPlanUpdateSyncToEventBusEnable == true and support-plan cancellation completed"
          ],
          "operations": [
            {
              "operation": "PUBLISH EVENT",
              "trigger": "Publish the downgraded default support-plan state to the event bus after cancellation",
              "conditions": [
                "marketing.SupportPlanModel.CancelBindedSupportPlan(...) completed"
              ],
              "implementation": "marketing.SupportPlanModel.SyncCurrentSupportToEventBus(DefaultBindedSupportPlan(tenantID)) -> eventbushandler.Get().PublishEventWithTransaction(...)"
            }
          ]
        },
        {
          "name": "novu-api",
          "target_interface": "POST /v1/events/trigger/bulk",
          "operation_type": "http_post",
          "conditions": [
            "Only when InAPPNotificationEnable == true and support-plan cancellation completed"
          ],
          "operations": [
            {
              "operation": "HTTP BulkTriggerEvent",
              "trigger": "Notify org users that the tenant support plan changed after cancellation",
              "conditions": [
                "marketing.SupportPlanModel.CancelBindedSupportPlan(...) reached sendBindedSupportPlanUpdateNotification(...)"
              ],
              "implementation": "uncutils.SendInAppNotification(...) -> novuhandler.Get().BulkTriggerEvent(...)"
            }
          ]
        }
      ]
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/billing_config_id/:billing_config_id/binded_support_plan": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant and billing-config path binding succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the explicit billing config before checking whether support-plan ownership is delegated to an MSP tenant",
              "conditions": [
                "getBillingCfgFromURI(c) succeeded"
              ],
              "implementation": "getBillingCfgFromURI(c)"
            },
            {
              "operation": "SELECT",
              "table": "payment_methods",
              "trigger": "Check whether the explicit billing config delegates support-plan ownership to an MSP tenant",
              "conditions": [
                "billingCfgStruct.TenantID and billingCfgStruct.BillingConfigID resolved successfully"
              ],
              "implementation": "paymentModel.GetActivePaymentMethod(billingCfgStruct.TenantID, billingCfgStruct.BillingConfigID)"
            },
            {
              "operation": "SELECT",
              "table": "binded_support_plans",
              "trigger": "Read the active binded support plan for either the tenant itself or the delegated MSP tenant",
              "conditions": [
                "payment method lookup succeeded or returned ObjectNotExists"
              ],
              "implementation": "marketing.SupportPlanModel.GetTenantActiveBindedPlan(targetTenantID)"
            },
            {
              "operation": "SELECT",
              "table": "support_plans",
              "trigger": "Hydrate support-plan attributes referenced by the active tenant binding",
              "conditions": [
                "GetTenantActiveBindedPlan(targetTenantID) returned a persisted binding"
              ],
              "implementation": "marketing.SupportPlanModel.GetTenantActiveBindedPlan(targetTenantID)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/billing_config_id/:billing_config_id/binded_support_plan/list": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant and billing-config path binding succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the explicit billing config before deciding whether support-plan listing should follow MSP delegation",
              "conditions": [
                "getBillingCfgFromURI(c) succeeded"
              ],
              "implementation": "getBillingCfgFromURI(c)"
            },
            {
              "operation": "SELECT",
              "table": "payment_methods",
              "trigger": "Determine whether the explicit billing config is billed through MSP and should inherit the MSP tenant's single active plan",
              "conditions": [
                "billingCfgStruct.TenantID and billingCfgStruct.BillingConfigID resolved successfully"
              ],
              "implementation": "paymentModel.GetActivePaymentMethod(billingCfgStruct.TenantID, billingCfgStruct.BillingConfigID)"
            },
            {
              "operation": "SELECT",
              "table": "binded_support_plans",
              "trigger": "List the tenant's bindings grouped by ACTIVE, TOBEACTIVATED, EXPIRED, and CANCELED status when not delegated to MSP",
              "conditions": [
                "either no active MSP payment method exists or the request is not delegated to MSP"
              ],
              "implementation": "marketing.SupportPlanModel.ListTenantsBindedSupportPlan(billingCfgStruct.TenantID, status)"
            },
            {
              "operation": "SELECT",
              "table": "support_plans",
              "trigger": "Hydrate each listed binding's referenced support-plan definition",
              "conditions": [
                "ListTenantsBindedSupportPlan(...) returned persisted bindings"
              ],
              "implementation": "marketing.SupportPlanModel.ListTenantsBindedSupportPlan(...)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/spend_limits": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant path binding and query binding succeed"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the active billing config so the BillsInvisibleList restriction can be checked for tenant-scoped spend-limit listing",
              "conditions": [
                "getBillingCfgFromURI(c) succeeded"
              ],
              "implementation": "getBillingCfgFromURI(c)"
            },
            {
              "operation": "SELECT",
              "table": "spend_limit_settings",
              "trigger": "List spend-limit settings for the tenant with optional rangeType/rangeID/bizType/serverless filters",
              "conditions": [
                "either query.RangeID != 0 or BillsInvisibleList does not hide the tenant/billing-config pair"
              ],
              "implementation": "spend_limit.SpendLimitModel.ListSpendLimitSettings(tenantID, query, nil)"
            },
            {
              "operation": "SELECT",
              "table": "recharge_credits_plan_records",
              "trigger": "Hydrate active free-credit and remaining-credit metadata for serverless spend-limit rows during list-time biz processing",
              "conditions": [
                "listed settings contain BizType == ServerlessCluster and TenantRechargePlanID != 0"
              ],
              "implementation": "SpendLimitModel.bizProcessOnListing(...) -> serverlessProcessOnListing(...)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/spend_limits/info": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant path binding and query binding succeed"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the active billing config so the BillsInvisibleList restriction can be checked before computing spend-limit info",
              "conditions": [
                "ListTenantSpendLimitSetting(...) reached getBillingCfgFromURI(c)"
              ],
              "implementation": "getBillingCfgFromURI(c)"
            },
            {
              "operation": "SELECT",
              "table": "spend_limit_settings",
              "trigger": "List spend-limit settings that will each be expanded into SpendLimitInfo",
              "conditions": [
                "either query.RangeID != 0 or BillsInvisibleList does not hide the tenant/billing-config pair"
              ],
              "implementation": "spend_limit.SpendLimitModel.ListSpendLimitSettings(tenantID, query, nil)"
            },
            {
              "operation": "SELECT",
              "table": "recharge_credits_plan_records",
              "trigger": "Hydrate active free-credit and remaining-credit metadata for serverless spend-limit rows before info expansion",
              "conditions": [
                "listed settings contain BizType == ServerlessCluster and TenantRechargePlanID != 0"
              ],
              "implementation": "SpendLimitModel.bizProcessOnListing(...) -> serverlessProcessOnListing(...)"
            },
            {
              "operation": "SELECT",
              "table": "user_unit_costs",
              "trigger": "Compute current-month cost for each spend-limit row while expanding SpendLimitInfo",
              "conditions": [
                "SpendLimitSettingWithCost(...) reached a tenant/project/cluster/customer monthly-cost query"
              ],
              "implementation": "SpendLimitModel.SpendLimitSettingWithCost(...) -> costexplorer.CostExplorerModel.Get*MonthlyCost(...)"
            }
          ]
        },
        "redis": {
          "conditions": [
            "Always around costexplorer monthly-cost cache lookups"
          ],
          "operations": [
            {
              "operation": "GET",
              "trigger": "Try monthly-cost caches while computing SpendLimitInfo for each listed row",
              "conditions": [
                "SpendLimitSettingWithCost(...) reached costexplorer monthly-cost helpers"
              ],
              "implementation": "costexplorer monthly-cost cache lookups"
            },
            {
              "operation": "SET",
              "trigger": "Populate monthly-cost caches after recomputing SpendLimitInfo from DB",
              "conditions": [
                "costexplorer monthly-cost helpers missed cache"
              ],
              "implementation": "costexplorer monthly-cost cache writes"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/tenants/:tenant_id/spend_limits": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant path binding and request-body validation succeed"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "spend_limit_settings",
              "trigger": "Check BizUniqueKey uniqueness before creating the new spend-limit setting",
              "conditions": [
                "validateInput(setting) succeeded"
              ],
              "implementation": "SpendLimitModel.checkBizUniqueKey(setting.BizUniqueKey)"
            },
            {
              "operation": "INSERT",
              "table": "unit_filters",
              "trigger": "Create the internal unit filter used by serverless-cluster spend limits to scope free credits and recharge plans",
              "conditions": [
                "setting.BizType == ServerlessCluster",
                "bizData.RechargePlanID != 0 or bizData.FreeCredits > 0"
              ],
              "implementation": "SpendLimitModel.createServerlessRechargePlan(...) -> unit_filter.Model.CreateUnitFilterWithTx(...)"
            },
            {
              "operation": "INSERT",
              "table": "recharge_credits_plans",
              "trigger": "Create the internal recharge plan when a new serverless-cluster spend limit needs free credits but no reusable main plan was supplied",
              "conditions": [
                "setting.BizType == ServerlessCluster",
                "bizData.RechargePlanID == 0",
                "bizData.FreeCredits > 0"
              ],
              "implementation": "SpendLimitModel.createServerlessRechargePlan(...) -> rechargePlanModel.CreateRechargePlanWithTx(...)"
            },
            {
              "operation": "INSERT",
              "table": "tenant_recharge_plans",
              "trigger": "Enable the tenant-scoped recharge plan for serverless-cluster spend limits",
              "conditions": [
                "setting.BizType == ServerlessCluster",
                "bizData.RechargePlanID != 0 or bizData.FreeCredits > 0"
              ],
              "implementation": "SpendLimitModel.createServerlessRechargePlan(...) -> rechargePlanModel.EnableTenantRechargePlanWithTx(...)"
            },
            {
              "operation": "INSERT",
              "table": "tiered_billings",
              "trigger": "Create the serverless tiered-billing cap linked to the spend-limit invoice limit",
              "conditions": [
                "setting.BizType == ServerlessCluster"
              ],
              "implementation": "SpendLimitModel.createServerlessTieredBilling(...)"
            },
            {
              "operation": "INSERT",
              "table": "spend_limit_settings",
              "trigger": "Create the spend-limit setting row in FIT status",
              "conditions": [
                "biz-process prechecks and serverless setup succeeded"
              ],
              "implementation": "entity.SpendLimitSetting.Create(tx)"
            },
            {
              "operation": "UPDATE",
              "table": "spend_limit_settings",
              "trigger": "Flush watermark or final status after post-create cost evaluation and spend-limit checks",
              "conditions": [
                "spend limit creation committed successfully"
              ],
              "implementation": "normalProcessAfterCreating(...) + CheckSpendLimit(...)"
            },
            {
              "operation": "SELECT",
              "table": "user_unit_costs",
              "trigger": "Compute the current-month cost immediately after creation so watermark and threshold state are initialized correctly",
              "conditions": [
                "CreateSpendLimitSetting(...) reached SpendLimitSettingWithCost(...)"
              ],
              "implementation": "SpendLimitModel.SpendLimitSettingWithCost(...) -> costexplorer.CostExplorerModel.Get*MonthlyCost(...)"
            }
          ]
        },
        "redis": {
          "conditions": [
            "Always around costexplorer monthly-cost cache lookups during post-create checks"
          ],
          "operations": [
            {
              "operation": "GET",
              "trigger": "Try monthly-cost caches while initializing watermark and threshold state for the new spend limit",
              "conditions": [
                "CreateSpendLimitSetting(...) reached SpendLimitSettingWithCost(...)"
              ],
              "implementation": "costexplorer monthly-cost cache lookups"
            },
            {
              "operation": "SET",
              "trigger": "Populate monthly-cost caches after recomputing post-create spend-limit cost from DB",
              "conditions": [
                "costexplorer monthly-cost helpers missed cache"
              ],
              "implementation": "costexplorer monthly-cost cache writes"
            }
          ]
        }
      },
      "services": [
        {
          "name": "eventbus",
          "target_interface": "PublishEventWithTransaction",
          "operation_type": "transactional_publish",
          "conditions": [
            "Only when post-create CheckSpendLimit(...) changes status or crosses a configured threshold"
          ],
          "operations": [
            {
              "operation": "PUBLISH EVENT",
              "trigger": "Emit spend-limit status or threshold events after the newly created setting is evaluated against current-month cost",
              "conditions": [
                "CheckSpendLimit(...) detected status/proportion changes"
              ],
              "implementation": "sendSpendLimitStatusChangeEvent(...) / sendSpendLimitProportionChangeEvent(...)"
            }
          ]
        },
        {
          "name": "novu-api",
          "target_interface": "POST /v1/events/trigger/bulk",
          "operation_type": "http_post",
          "conditions": [
            "Only when post-create threshold evaluation fires an in-app budget notification and InAPPNotificationEnable == true"
          ],
          "operations": [
            {
              "operation": "HTTP BulkTriggerEvent",
              "trigger": "Notify org, project, or cluster stakeholders that the newly created spend limit is already at or above a threshold",
              "conditions": [
                "checkSpendLimitProportion(...) emitted an alert"
              ],
              "implementation": "sendSpendLimitReachedNotification(...) -> uncutils.SendInAppNotification(...) -> novuhandler.Get().BulkTriggerEvent(...)"
            }
          ]
        }
      ]
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/spend_limits/:spend_limit_setting_id": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant and spend-limit path binding succeed"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "spend_limit_settings",
              "trigger": "Load the requested spend-limit setting by tenant and ID",
              "conditions": [
                "getSpendLimitURIParams(c) succeeded"
              ],
              "implementation": "SpendLimitModel.GetSpendLimitSetting(tenantID, spendLimitSettingID)"
            },
            {
              "operation": "SELECT",
              "table": "recharge_credits_plan_records",
              "trigger": "Hydrate free-credit and remaining-credit metadata when the setting belongs to a serverless cluster",
              "conditions": [
                "loaded setting.BizType == ServerlessCluster",
                "TenantRechargePlanID != 0"
              ],
              "implementation": "SpendLimitModel.bizProcessOnGetting(...) -> serverlessProcessOnGetting(...)"
            },
            {
              "operation": "UPDATE",
              "table": "spend_limit_settings",
              "trigger": "Refresh stale RECOVERED status while serving the get request",
              "conditions": [
                "ret.Status == RECOVERED"
              ],
              "implementation": "GetSpendLimitSetting(...) -> checkSpendLimitStatus(...)"
            },
            {
              "operation": "SELECT",
              "table": "user_unit_costs",
              "trigger": "Recompute current-month cost if the loaded setting is in RECOVERED state and must be refreshed before returning",
              "conditions": [
                "ret.Status == RECOVERED"
              ],
              "implementation": "GetSpendLimitSetting(...) -> SpendLimitSettingWithCost(...) -> costexplorer.CostExplorerModel.Get*MonthlyCost(...)"
            }
          ]
        }
      },
      "services": [
        {
          "name": "eventbus",
          "target_interface": "PublishEventWithTransaction",
          "operation_type": "transactional_publish",
          "conditions": [
            "Only when serving a RECOVERED spend limit causes status refresh"
          ],
          "operations": [
            {
              "operation": "PUBLISH EVENT",
              "trigger": "Emit the refreshed spend-limit status while resolving a recovered setting",
              "conditions": [
                "GetSpendLimitSetting(...) reached checkSpendLimitStatus(...)"
              ],
              "implementation": "sendSpendLimitStatusChangeEvent(...)"
            }
          ]
        }
      ]
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/spend_limits/:spend_limit_setting_id/info": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant and spend-limit path binding succeed"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "spend_limit_settings",
              "trigger": "Load the requested spend-limit setting before expanding it into SpendLimitInfo",
              "conditions": [
                "getSpendLimitURIParams(c) succeeded"
              ],
              "implementation": "SpendLimitModel.GetSpendLimitSetting(tenantID, spendLimitSettingID)"
            },
            {
              "operation": "SELECT",
              "table": "recharge_credits_plan_records",
              "trigger": "Hydrate free-credit and remaining-credit metadata when the setting belongs to a serverless cluster",
              "conditions": [
                "loaded setting.BizType == ServerlessCluster",
                "TenantRechargePlanID != 0"
              ],
              "implementation": "SpendLimitModel.bizProcessOnGetting(...) -> serverlessProcessOnGetting(...)"
            },
            {
              "operation": "SELECT",
              "table": "user_unit_costs",
              "trigger": "Compute the current-month cost for the requested spend-limit setting",
              "conditions": [
                "GetSpendLimitInfo(...) reached SpendLimitSettingWithCost(...)"
              ],
              "implementation": "SpendLimitModel.SpendLimitSettingWithCost(...) -> costexplorer.CostExplorerModel.Get*MonthlyCost(...)"
            }
          ]
        },
        "redis": {
          "conditions": [
            "Always around costexplorer monthly-cost cache lookups while building SpendLimitInfo"
          ],
          "operations": [
            {
              "operation": "GET",
              "trigger": "Try monthly-cost caches before recomputing SpendLimitInfo from DB",
              "conditions": [
                "GetSpendLimitInfo(...) reached SpendLimitSettingWithCost(...)"
              ],
              "implementation": "costexplorer monthly-cost cache lookups"
            },
            {
              "operation": "SET",
              "trigger": "Populate monthly-cost caches after recomputing SpendLimitInfo from DB",
              "conditions": [
                "costexplorer monthly-cost helpers missed cache"
              ],
              "implementation": "costexplorer monthly-cost cache writes"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP PUT /api/v1/billing/tenants/:tenant_id/spend_limits/:spend_limit_setting_id": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant/spend-limit path binding and request-body validation succeed"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "spend_limit_settings",
              "trigger": "Load and lock the existing spend-limit setting before validating updates and preserving BizUniqueKey invariants",
              "conditions": [
                "validateInput(setting) succeeded"
              ],
              "implementation": "SpendLimitModel.UpdateSpendLimitSettings(...) -> query with clause.Locking{Strength:\"UPDATE\"}"
            },
            {
              "operation": "UPDATE",
              "table": "tiered_billings",
              "trigger": "Update the linked serverless tiered-billing cap when invoice-limit settings change",
              "conditions": [
                "origin.BizType == ServerlessCluster",
                "updated bizData.InvoiceLimit != originBizData.InvoiceLimit"
              ],
              "implementation": "SpendLimitModel.serverlessProcessOnUpdating(...) -> updateServerlessTieredBilling(...)"
            },
            {
              "operation": "UPDATE",
              "table": "spend_limit_settings",
              "trigger": "Persist the updated spend-limit setting fields and any refreshed watermark",
              "conditions": [
                "biz-process update hooks succeeded"
              ],
              "implementation": "UpdateSpendLimitSettings(...) + normalProcessOnUpdating(...)"
            },
            {
              "operation": "SELECT",
              "table": "user_unit_costs",
              "trigger": "Recompute current-month cost after the update so status and thresholds are refreshed correctly",
              "conditions": [
                "UpdateSpendLimitSettings(...) committed successfully"
              ],
              "implementation": "CheckSpendLimit(...) -> SpendLimitSettingWithCost(...) -> costexplorer.CostExplorerModel.Get*MonthlyCost(...)"
            }
          ]
        },
        "redis": {
          "conditions": [
            "Always around costexplorer monthly-cost cache lookups during post-update checks"
          ],
          "operations": [
            {
              "operation": "GET",
              "trigger": "Try monthly-cost caches while reevaluating the updated spend limit",
              "conditions": [
                "UpdateSpendLimitSettings(...) reached CheckSpendLimit(...)"
              ],
              "implementation": "costexplorer monthly-cost cache lookups"
            },
            {
              "operation": "SET",
              "trigger": "Populate monthly-cost caches after recomputing post-update spend-limit cost from DB",
              "conditions": [
                "costexplorer monthly-cost helpers missed cache"
              ],
              "implementation": "costexplorer monthly-cost cache writes"
            }
          ]
        }
      },
      "services": [
        {
          "name": "eventbus",
          "target_interface": "PublishEventWithTransaction",
          "operation_type": "transactional_publish",
          "conditions": [
            "Only when post-update CheckSpendLimit(...) changes status or crosses a configured threshold"
          ],
          "operations": [
            {
              "operation": "PUBLISH EVENT",
              "trigger": "Emit spend-limit status or threshold events after the updated setting is reevaluated",
              "conditions": [
                "CheckSpendLimit(...) detected status/proportion changes"
              ],
              "implementation": "sendSpendLimitStatusChangeEvent(...) / sendSpendLimitProportionChangeEvent(...)"
            }
          ]
        },
        {
          "name": "novu-api",
          "target_interface": "POST /v1/events/trigger/bulk",
          "operation_type": "http_post",
          "conditions": [
            "Only when post-update threshold evaluation fires an in-app budget notification and InAPPNotificationEnable == true"
          ],
          "operations": [
            {
              "operation": "HTTP BulkTriggerEvent",
              "trigger": "Notify org, project, or cluster stakeholders that the updated spend limit is at or above a threshold",
              "conditions": [
                "checkSpendLimitProportion(...) emitted an alert"
              ],
              "implementation": "sendSpendLimitReachedNotification(...) -> uncutils.SendInAppNotification(...) -> novuhandler.Get().BulkTriggerEvent(...)"
            }
          ]
        }
      ]
    },
    "HTTP DELETE /api/v1/billing/tenants/:tenant_id/spend_limits/:spend_limit_setting_id": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant and spend-limit path binding succeed"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "spend_limit_settings",
              "trigger": "Load the spend-limit info and then lock the concrete setting row before deletion",
              "conditions": [
                "getSpendLimitURIParams(c) succeeded"
              ],
              "implementation": "DeleteSpendLimitSetting(...) -> GetSpendLimitInfo(...) + lock spend_limit_settings row"
            },
            {
              "operation": "UPDATE",
              "table": "spend_limit_settings",
              "trigger": "Mark the setting deprecated and clear BizUniqueKey before deleting the row",
              "conditions": [
                "the spend-limit row exists and is not already deprecated"
              ],
              "implementation": "query.GetUpdater().SetStatus(DEPRECATED).SetBizUniqueKey(nil).Update()"
            },
            {
              "operation": "UPDATE",
              "table": "tenant_recharge_plans",
              "trigger": "Disable the tenant recharge plan when deleting a serverless-cluster spend limit",
              "conditions": [
                "settings.BizType == ServerlessCluster",
                "bizData.TenantRechargePlanID != 0"
              ],
              "implementation": "SpendLimitModel.serverlessProcessOnDeleting(...) -> disableServerlessRechargePlan(...)"
            },
            {
              "operation": "UPDATE",
              "table": "recharge_credits_plans",
              "trigger": "Disable the underlying main recharge plan when deleting a serverless-cluster spend limit backed by a system plan",
              "conditions": [
                "settings.BizType == ServerlessCluster",
                "mainPlan.Source == SYSTEM"
              ],
              "implementation": "disableServerlessRechargePlan(...) -> rechargePlanModel.DisableRechargePlanWithTx(...)"
            },
            {
              "operation": "DELETE",
              "table": "tiered_billings",
              "trigger": "Delete the linked serverless tiered-billing cap when deleting a serverless-cluster spend limit",
              "conditions": [
                "settings.BizType == ServerlessCluster"
              ],
              "implementation": "SpendLimitModel.serverlessProcessOnDeleting(...) -> deleteServerlessTieredBilling(...)"
            },
            {
              "operation": "DELETE",
              "table": "spend_limit_settings",
              "trigger": "Delete the spend-limit row after status event publication and biz-process cleanup succeed",
              "conditions": [
                "sendSpendLimitStatusChangeEvent(...) and bizProcessOnDeleting(...) succeeded"
              ],
              "implementation": "query.Delete()"
            }
          ]
        }
      },
      "services": [
        {
          "name": "eventbus",
          "target_interface": "PublishEventWithTransaction",
          "operation_type": "transactional_publish",
          "conditions": [
            "Always once the row is marked deprecated inside the delete transaction"
          ],
          "operations": [
            {
              "operation": "PUBLISH EVENT",
              "trigger": "Emit the deprecated spend-limit status before the row is removed",
              "conditions": [
                "query.GetUpdater().SetStatus(DEPRECATED)... succeeded"
              ],
              "implementation": "sendSpendLimitStatusChangeEvent(...)"
            }
          ]
        }
      ]
    },
    "HTTP GET /api/v1/billing/credit_risk_levels": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Always"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "credit_risk_levels",
              "trigger": "List all credit-risk-level rows",
              "implementation": "creditriskcontrol.CreditRiskLevelModel.ListAllCreditRiskLevels()"
            },
            {
              "operation": "SELECT",
              "table": "cost_quota_credit_risk_levels",
              "trigger": "Hydrate the cost quota attached to each listed credit-risk level",
              "conditions": [
                "for each listed credit_risk_level row"
              ],
              "implementation": "creditRiskLevelInfoFromEntity(...) -> CostQuotaModel.GetCreditRiskLevelQuota(...)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/credit_risk_levels/:credit_risk_level_id": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after credit-risk-level path binding succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "credit_risk_levels",
              "trigger": "Load the requested credit-risk level row",
              "conditions": [
                "getCreditRiskLevelIDFromURI(c) succeeded"
              ],
              "implementation": "creditriskcontrol.CreditRiskLevelModel.GetCreditRiskLevel(creditRiskLevelID)"
            },
            {
              "operation": "SELECT",
              "table": "cost_quota_credit_risk_levels",
              "trigger": "Hydrate the cost quota attached to the requested credit-risk level",
              "conditions": [
                "credit risk level row exists"
              ],
              "implementation": "creditRiskLevelInfoFromEntity(...) -> CostQuotaModel.GetCreditRiskLevelQuota(...)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/credit_risk_levels": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after request-body binding succeeds"
          ],
          "operations": [
            {
              "operation": "INSERT",
              "table": "credit_risk_levels",
              "trigger": "Create the new credit-risk level row",
              "conditions": [
                "c.ShouldBindJSON(input) succeeded"
              ],
              "implementation": "creditriskcontrol.CreditRiskLevelModel.CreateCreditRiskLevel(input)"
            },
            {
              "operation": "SELECT",
              "table": "cost_quota_credit_risk_levels",
              "trigger": "Hydrate any explicit risk-level cost quota while building the create response",
              "conditions": [
                "credit risk level row created successfully"
              ],
              "implementation": "CreateCreditRiskLevel(...) -> GetCreditRiskLevel(...) -> CostQuotaModel.GetCreditRiskLevelQuota(...)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP PUT /api/v1/billing/credit_risk_levels/:credit_risk_level_id": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after credit-risk-level path binding and request-body binding succeed"
          ],
          "operations": [
            {
              "operation": "UPDATE",
              "table": "credit_risk_levels",
              "trigger": "Update the display name of the selected credit-risk level",
              "conditions": [
                "getCreditRiskLevelIDFromURI(c) succeeded",
                "c.ShouldBindJSON(input) succeeded"
              ],
              "implementation": "creditriskcontrol.CreditRiskLevelModel.UpdateCreditRiskLevel(creditRiskLevelID, input)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP DELETE /api/v1/billing/credit_risk_levels/:credit_risk_level_id": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after credit-risk-level path binding succeeds and the target is not the configured default level"
          ],
          "operations": [
            {
              "operation": "DELETE",
              "table": "tenant_credit_risk_levels",
              "trigger": "Remove tenant-level assignments that point to the deleted credit-risk level",
              "conditions": [
                "creditRiskLevelID != DefaultCreditRiskLevel"
              ],
              "implementation": "entity.NewTenantCreditRiskLevelQuerySet(db.GetDB()).CreditRiskLevelIDEq(creditRiskLevelID).Delete()"
            },
            {
              "operation": "DELETE",
              "table": "credit_risk_levels",
              "trigger": "Delete the credit-risk level row itself",
              "conditions": [
                "tenant_credit_risk_levels cleanup succeeded"
              ],
              "implementation": "creditriskcontrol.CreditRiskLevelModel.DeleteCreditRiskLevel(creditRiskLevelID)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/credit_risk_levels/:credit_risk_level_id/cost_quota": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after credit-risk-level path binding succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "cost_quota_credit_risk_levels",
              "trigger": "Read the configured quota override for the selected credit-risk level",
              "conditions": [
                "getCreditRiskLevelIDFromURI(c) succeeded"
              ],
              "implementation": "creditriskcontrol.CostQuotaModel.GetCreditRiskLevelQuota(creditRiskLevelID)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP PUT /api/v1/billing/credit_risk_levels/:credit_risk_level_id/cost_quota": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after credit-risk-level path binding and request-body binding succeed"
          ],
          "operations": [
            {
              "operation": "UPSERT",
              "table": "cost_quota_credit_risk_levels",
              "trigger": "Create or replace the quota override for the selected credit-risk level",
              "conditions": [
                "getCreditRiskLevelIDFromURI(c) succeeded",
                "c.ShouldBindJSON(input) succeeded"
              ],
              "implementation": "creditriskcontrol.CostQuotaModel.SetCreditRiskLevelQuota(creditRiskLevelID, input)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/credit_risk_level": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant path binding succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "tenant_credit_risk_levels",
              "trigger": "Resolve the tenant's explicitly assigned credit-risk level ID or fall back to the configured default",
              "conditions": [
                "getTenantIDFromURI(c) succeeded"
              ],
              "implementation": "creditriskcontrol.CreditRiskLevelModel.GetTenantCreditRiskLevelID(tenantID)"
            },
            {
              "operation": "SELECT",
              "table": "credit_risk_levels",
              "trigger": "Load the resolved credit-risk level row",
              "conditions": [
                "GetTenantCreditRiskLevelID(tenantID) succeeded"
              ],
              "implementation": "creditriskcontrol.CreditRiskLevelModel.GetCreditRiskLevel(creditRiskLevelID)"
            },
            {
              "operation": "SELECT",
              "table": "cost_quota_credit_risk_levels",
              "trigger": "Hydrate the cost quota attached to the resolved credit-risk level",
              "conditions": [
                "credit risk level row exists"
              ],
              "implementation": "creditRiskLevelInfoFromEntity(...) -> CostQuotaModel.GetCreditRiskLevelQuota(...)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP PUT /api/v1/billing/tenants/:tenant_id/credit_risk_level": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant path binding and request-body binding succeed"
          ],
          "operations": [
            {
              "operation": "UPSERT",
              "table": "tenant_credit_risk_levels",
              "trigger": "Create or replace the tenant-to-credit-risk-level assignment",
              "conditions": [
                "getTenantIDFromURI(c) succeeded",
                "c.ShouldBindJSON(input) succeeded"
              ],
              "implementation": "creditriskcontrol.CreditRiskLevelModel.SetTenantCreditRiskLevel(tenantID, input.CreditRiskLevelID)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/cost_quota": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant path binding and billing-config resolution succeed"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the active or explicit billing config used to evaluate special no-limit payment types",
              "conditions": [
                "getBillingCfgFromURI(c) succeeded"
              ],
              "implementation": "getBillingCfgFromURI(c)"
            },
            {
              "operation": "SELECT",
              "table": "payment_methods",
              "trigger": "Check whether AWS/GCP/MSP/managed-by-sales payment methods force unlimited cost quota",
              "conditions": [
                "billingCfgStruct.TenantID and billingCfgStruct.BillingConfigID resolved successfully"
              ],
              "implementation": "paymentsub.PaymentModel.GetActivePaymentMethod(tenantID, billingConfigID)"
            },
            {
              "operation": "SELECT",
              "table": "cost_quotas",
              "trigger": "Read the tenant-specific quota override when the payment method does not force unlimited quota",
              "conditions": [
                "payment method lookup returned ObjectNotExists or a quota-limited payment type"
              ],
              "implementation": "entity.NewCostQuotaQuerySet(db.GetDB()).TenantIDEq(tenantID).One(costQuota)"
            },
            {
              "operation": "SELECT",
              "table": "tenant_credit_risk_levels",
              "trigger": "Resolve the tenant's credit-risk level when no tenant-specific quota override exists",
              "conditions": [
                "tenant cost_quota row does not exist"
              ],
              "implementation": "creditriskcontrol.CreditRiskLevelModel.GetTenantCreditRiskLevelID(tenantID)"
            },
            {
              "operation": "SELECT",
              "table": "cost_quota_credit_risk_levels",
              "trigger": "Read the quota inherited from the tenant's credit-risk level when no tenant-specific override exists",
              "conditions": [
                "GetTenantCreditRiskLevelID(tenantID) succeeded"
              ],
              "implementation": "creditriskcontrol.CostQuotaModel.GetCreditRiskLevelQuota(creditRiskLevelID)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP PUT /api/v1/billing/tenants/:tenant_id/cost_quota": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant path binding and request-body binding succeed"
          ],
          "operations": [
            {
              "operation": "UPSERT",
              "table": "cost_quotas",
              "trigger": "Create or replace the tenant-specific cost-quota override",
              "conditions": [
                "getTenantIDFromURI(c) succeeded",
                "c.ShouldBindJSON(input) succeeded"
              ],
              "implementation": "creditriskcontrol.CostQuotaModel.SetTenantCostQuota(tenantID, input)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/credit_risk_levels/:credit_risk_level_id/risk_close_policy": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after credit-risk-level path binding succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "tenant_close_policies",
              "trigger": "Load the risky close policy attached to the selected credit-risk level",
              "conditions": [
                "getCreditRiskLevelIDFromURI(c) succeeded"
              ],
              "implementation": "TenantCloseModel.GetTenantClosePolicyByCreditRiskLevel(creditRiskLevelID)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP PUT /api/v1/billing/credit_risk_levels/:credit_risk_level_id/risk_close_policy": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after credit-risk-level path binding and request-body binding succeed"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "tenant_close_policies",
              "trigger": "Check whether a risky close policy already exists for the selected credit-risk level",
              "conditions": [
                "getCreditRiskLevelIDFromURI(c) succeeded",
                "c.ShouldBindJSON(policy) succeeded"
              ],
              "implementation": "TenantCloseModel.GetTenantClosePolicyByCreditRiskLevel(creditRiskLevelID)"
            },
            {
              "operation": "SELECT",
              "table": "credit_risk_levels",
              "trigger": "Validate the referenced credit-risk level before creating a new risky close policy",
              "conditions": [
                "no existing risky close policy was found"
              ],
              "implementation": "TenantCloseModel.CreateTenantRiskClosePolicy(...) -> CreditRiskLevelModel.GetCreditRiskLevel(...)"
            },
            {
              "operation": "INSERT",
              "table": "tenant_close_policies",
              "trigger": "Create the risky close policy when none existed previously",
              "conditions": [
                "no existing risky close policy was found"
              ],
              "implementation": "TenantCloseModel.CreateTenantRiskClosePolicy(...)"
            },
            {
              "operation": "UPDATE",
              "table": "tenant_close_policies",
              "trigger": "Update the existing risky close policy in place",
              "conditions": [
                "an existing risky close policy was found"
              ],
              "implementation": "TenantCloseModel.UpdateTenantRiskClosePolicy(creditRiskLevelID, policy)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP DELETE /api/v1/billing/credit_risk_levels/:credit_risk_level_id/risk_close_policy": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after credit-risk-level path binding succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "tenant_close_policies",
              "trigger": "Resolve the risky close policy row that will be deleted",
              "conditions": [
                "getCreditRiskLevelIDFromURI(c) succeeded"
              ],
              "implementation": "TenantCloseModel.GetTenantClosePolicy(risky, creditRiskLevelID)"
            },
            {
              "operation": "UPDATE",
              "table": "tenant_close_policies",
              "trigger": "Rename the policy reason to a deleted-* tombstone before physical deletion",
              "conditions": [
                "policy row exists"
              ],
              "implementation": "TenantCloseModel.DeleteTenantClosePolicy(policyID) -> SetReason(fmt.Sprintf(\"deleted-%s-%s\", uuid.NewString(), ent.Reason)).Update()"
            },
            {
              "operation": "DELETE",
              "table": "tenant_close_policies",
              "trigger": "Delete the risky close policy row after the tombstone rename succeeds",
              "conditions": [
                "tombstone reason update succeeded"
              ],
              "implementation": "TenantCloseModel.DeleteTenantClosePolicy(policyID)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/risk_close_policy": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant path binding succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "tenant_credit_risk_levels",
              "trigger": "Resolve the tenant's credit-risk level before fetching its risky close policy",
              "conditions": [
                "getTenantIDFromURI(c) succeeded"
              ],
              "implementation": "TenantCloseModel.GetTenantRiskClosePolicyByTenantID(tenantID) -> CreditRiskLevelModel.GetTenantCreditRiskLevel(tenantID)"
            },
            {
              "operation": "SELECT",
              "table": "credit_risk_levels",
              "trigger": "Load the tenant's resolved credit-risk level row",
              "conditions": [
                "tenant credit-risk level ID resolved successfully"
              ],
              "implementation": "CreditRiskLevelModel.GetCreditRiskLevel(creditRiskLevelID)"
            },
            {
              "operation": "SELECT",
              "table": "tenant_close_policies",
              "trigger": "Read the risky close policy attached to the tenant's credit-risk level",
              "conditions": [
                "credit risk level lookup succeeded"
              ],
              "implementation": "TenantCloseModel.GetTenantClosePolicyByCreditRiskLevel(level.CreditRiskLevelID)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/tenant_risk_close": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant path binding succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "tenant_close_records",
              "trigger": "Load the tenant's current close record if one exists",
              "conditions": [
                "getTenantIDFromURI(c) succeeded"
              ],
              "implementation": "TenantCloseModel.GetTenantCloseInfo(tenantID)"
            },
            {
              "operation": "SELECT",
              "table": "tenant_close_policies",
              "trigger": "Fallback to the tenant risky close policy when no close record exists",
              "conditions": [
                "GetTenantCloseInfo(tenantID) returned ObjectNotExists"
              ],
              "implementation": "API fallback path currently calls TenantCloseModel.GetTenantClosePolicyByCreditRiskLevel(tenantID)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/tenants/:tenant_id/tenant_risk_close/actions/run": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant path binding succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "tenant_close_records",
              "trigger": "Check for an existing close record before starting a new risky close flow",
              "conditions": [
                "getTenantIDFromURI(c) succeeded"
              ],
              "implementation": "TenantCloseModel.RunTenantClose(tenantID, RISKY) -> GetTenantCloseInfo(tenantID)"
            },
            {
              "operation": "DELETE",
              "table": "tenant_close_records",
              "trigger": "Delete a previous DONE or CANCELED close record before starting a fresh risky close flow",
              "conditions": [
                "existing close record status in {DONE, CANCELED}"
              ],
              "implementation": "TenantCloseModel.DeleteTenantCloseRecord(tenantID)"
            },
            {
              "operation": "SELECT",
              "table": "tenant_credit_risk_levels",
              "trigger": "Resolve the tenant's credit-risk level before selecting the risky close policy",
              "conditions": [
                "either no prior close record existed or stale record cleanup succeeded"
              ],
              "implementation": "TenantCloseModel.GetTenantClosePolicyByTenantID(tenantID, RISKY) -> CreditRiskLevelModel.GetTenantCreditRiskLevel(tenantID)"
            },
            {
              "operation": "SELECT",
              "table": "tenant_close_policies",
              "trigger": "Load the risky close policy that will seed the new close record",
              "conditions": [
                "tenant credit-risk level resolved successfully"
              ],
              "implementation": "TenantCloseModel.GetTenantClosePolicyByTenantID(tenantID, RISKY)"
            },
            {
              "operation": "INSERT",
              "table": "tenant_close_records",
              "trigger": "Create the RUNNING risky close record; actual close actions are deferred to the background close processor",
              "conditions": [
                "policy lookup succeeded"
              ],
              "implementation": "TenantCloseModel.RunTenantClose(tenantID, RISKY)"
            }
          ]
        },
        "redis": {
          "conditions": [
            "Always after RunTenantClose(...) succeeds"
          ],
          "operations": [
            {
              "operation": "DEL",
              "trigger": "Clear the cached tenant effective plan after the risky close flow is started",
              "implementation": "cachehandler.Get().Delete(constant.GetTenantEffectivePlanCacheName, tenantID)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/tenants/:tenant_id/tenant_risk_close/actions/cancel": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant path binding succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "tenant_close_records",
              "trigger": "Load the active close record before moving it into CANCELING state",
              "conditions": [
                "getTenantIDFromURI(c) succeeded"
              ],
              "implementation": "TenantCloseModel.CancelTenantClose(tenantID) -> GetTenantCloseInfo(tenantID)"
            },
            {
              "operation": "UPDATE",
              "table": "tenant_close_records",
              "trigger": "Mark the running close record CANCELING so the background close processor will execute cancel action flow",
              "conditions": [
                "close record status not in {DONE, CANCELED}"
              ],
              "implementation": "TenantCloseModel.CancelTenantClose(tenantID)"
            }
          ]
        },
        "redis": {
          "conditions": [
            "Always after CancelTenantClose(...) succeeds"
          ],
          "operations": [
            {
              "operation": "DEL",
              "trigger": "Clear the cached tenant effective plan after risky close cancellation is requested",
              "implementation": "cachehandler.Get().Delete(constant.GetTenantEffectivePlanCacheName, tenantID)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/closing/reasons": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Always"
          ],
          "operations": [
            {
              "operation": "SELECT DISTINCT",
              "table": "tenant_close_policies",
              "trigger": "List all configured close reasons by scanning distinct policy reasons",
              "implementation": "TenantCloseModel.ListCloseReasons()"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/closing/reasons/:reason/policies": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant/reason path binding succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "tenant_credit_risk_levels",
              "trigger": "Resolve the tenant's credit-risk level before choosing the reason-specific close policy",
              "conditions": [
                "getCloseQueryFromURI(c) succeeded"
              ],
              "implementation": "TenantCloseModel.GetTenantClosePolicyByTenantID(query.TenantID, query.Reason) -> CreditRiskLevelModel.GetTenantCreditRiskLevel(query.TenantID)"
            },
            {
              "operation": "SELECT",
              "table": "credit_risk_levels",
              "trigger": "Load the resolved credit-risk level row",
              "conditions": [
                "tenant credit-risk level resolved successfully"
              ],
              "implementation": "CreditRiskLevelModel.GetCreditRiskLevel(creditRiskLevelID)"
            },
            {
              "operation": "SELECT",
              "table": "tenant_close_policies",
              "trigger": "Read all policies for the given reason, then choose the global or matching credit-risk-level entry",
              "conditions": [
                "credit risk level lookup succeeded"
              ],
              "implementation": "TenantCloseModel.GetTenantClosePolicy(reason, level.CreditRiskLevelID)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/tenants/:tenant_id/closing/reasons/:reason/actions/run": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant/reason path binding succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "tenant_close_records",
              "trigger": "Check for an existing close record before starting a new close flow for the requested reason",
              "conditions": [
                "getCloseQueryFromURI(c) succeeded"
              ],
              "implementation": "TenantCloseModel.RunTenantClose(query.TenantID, query.Reason) -> GetTenantCloseInfo(query.TenantID)"
            },
            {
              "operation": "DELETE",
              "table": "tenant_close_records",
              "trigger": "Delete a previous DONE or CANCELED close record before starting a fresh close flow",
              "conditions": [
                "existing close record status in {DONE, CANCELED}"
              ],
              "implementation": "TenantCloseModel.DeleteTenantCloseRecord(query.TenantID)"
            },
            {
              "operation": "SELECT",
              "table": "tenant_credit_risk_levels",
              "trigger": "Resolve the tenant's credit-risk level before selecting the reason-specific close policy",
              "conditions": [
                "either no prior close record existed or stale record cleanup succeeded"
              ],
              "implementation": "TenantCloseModel.GetTenantClosePolicyByTenantID(query.TenantID, query.Reason) -> CreditRiskLevelModel.GetTenantCreditRiskLevel(query.TenantID)"
            },
            {
              "operation": "SELECT",
              "table": "tenant_close_policies",
              "trigger": "Load the close policy that will seed the new close record",
              "conditions": [
                "tenant credit-risk level resolved successfully"
              ],
              "implementation": "TenantCloseModel.GetTenantClosePolicyByTenantID(query.TenantID, query.Reason)"
            },
            {
              "operation": "INSERT",
              "table": "tenant_close_records",
              "trigger": "Create the RUNNING close record; actual cleanup/email/support-plan actions are deferred to the background close processor",
              "conditions": [
                "policy lookup succeeded"
              ],
              "implementation": "TenantCloseModel.RunTenantClose(query.TenantID, query.Reason)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/tenants/:tenant_id/closing/actions/cancel": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant path binding succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "tenant_close_records",
              "trigger": "Load the active close record before moving it into CANCELING state",
              "conditions": [
                "getTenantIDFromURI(c) succeeded"
              ],
              "implementation": "TenantCloseModel.CancelTenantClose(tenantID) -> GetTenantCloseInfo(tenantID)"
            },
            {
              "operation": "UPDATE",
              "table": "tenant_close_records",
              "trigger": "Mark the running close record CANCELING so the background close processor will execute cancel action flow",
              "conditions": [
                "close record status not in {DONE, CANCELED}"
              ],
              "implementation": "TenantCloseModel.CancelTenantClose(tenantID)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/closing": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant path binding succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "tenant_close_records",
              "trigger": "Load the tenant's current close record if one exists",
              "conditions": [
                "getTenantIDFromURI(c) succeeded"
              ],
              "implementation": "TenantCloseModel.GetTenantCloseInfo(tenantID)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/plans": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant path binding succeeds when the effective-plan cache misses"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "tenant_plans",
              "trigger": "Load dev-tier, POC, and on-demand plan rows in order to assemble the tenant effective-plan view",
              "conditions": [
                "cachehandler.Get().Get(GetTenantEffectivePlanCacheName, tenantID) missed"
              ],
              "implementation": "TenantPlanModel.getTenantEffectivePlan(...) -> GetTenantDevTierPlan(...) + GetTenantPOCPlanInfo(...) + GetTenantOnDemandPlanInfo(...)"
            },
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the active billing config used by on-demand plan and effective discount / credits summary lookup",
              "conditions": [
                "cachehandler GetTenantEffectivePlan missed"
              ],
              "implementation": "TenantPlanModel.getTenantBillingConfigID(tenantID)"
            },
            {
              "operation": "SELECT",
              "table": "discounts",
              "trigger": "Read the tenant's active on-demand discount for the resolved billing config",
              "conditions": [
                "billing config resolution succeeded"
              ],
              "implementation": "discount.Model.GetTenantOnDemandDiscount(tenantID, billingConfigID)"
            },
            {
              "operation": "SELECT",
              "table": "credits_packages",
              "trigger": "Read the tenant credits summary used to populate POC remaining credits",
              "conditions": [
                "billing config resolution succeeded"
              ],
              "implementation": "marketing.CreditsPackageModel.GetTenantCreditsSummary(tenantID, billingConfigID)"
            },
            {
              "operation": "SELECT",
              "table": "tenant_close_records",
              "trigger": "Check whether a running/done close flow should override the effective plan to CLOSING",
              "conditions": [
                "cachehandler GetTenantEffectivePlan missed"
              ],
              "implementation": "creditriskcontrol.TenantCloseModel.GetTenantCloseInfo(tenantID)"
            }
          ]
        },
        "redis": {
          "conditions": [
            "Always around effective-plan cache lookups"
          ],
          "operations": [
            {
              "operation": "GET",
              "trigger": "Try the effective-plan cache before rebuilding plan info from DB",
              "implementation": "cachehandler.Get().Get(constant.GetTenantEffectivePlanCacheName, &planInfo, tenantID)"
            },
            {
              "operation": "SET",
              "trigger": "Cache the rebuilt effective-plan view after DB assembly completes",
              "conditions": [
                "effective plan rebuilt successfully"
              ],
              "implementation": "cachehandler.Get().Set(constant.GetTenantEffectivePlanCacheName, res, tenantID)"
            }
          ]
        }
      },
      "services": [
        {
          "name": "account-service",
          "target_interface": "AccountAPIService.GetOrgByID",
          "operation_type": "grpc_unary",
          "target_repo": "tidbcloud/account",
          "conditions": [
            "Only when the effective plan is POC and the API must decide whether to downgrade that POC plan to DevTier for non-internal tenants after the cutoff"
          ],
          "operations": [
            {
              "operation": "gRPC GetOrgByID",
              "trigger": "Load tenant kind metadata before applying the POC-after-no-payable downgrade rule in the HTTP response",
              "conditions": [
                "result.EffectivePlan == POC"
              ],
              "implementation": "centralhandler.GetCentralHandler().GetTenant(tenantID)"
            }
          ]
        }
      ]
    },
    "HTTP PUT /api/v1/billing/tenants/:tenant_id/plans/dev_tier/notify_dev_tier_cluster_created": {
      "infrastructure": {},
      "services": [
        {
          "name": "eventbus",
          "target_interface": "PublishEvent",
          "operation_type": "publish",
          "conditions": [
            "Always after tenant path binding succeeds"
          ],
          "operations": [
            {
              "operation": "PUBLISH EVENT",
              "trigger": "Publish the dev-tier-cluster-created event so downstream dev-tier plan handlers can prepare/enable the plan asynchronously",
              "conditions": [
                "getTenantIDFromURI(c) succeeded"
              ],
              "implementation": "eventbushandler.Get().PublishEvent(plan.DevTierClusterCreatedEventType, &eventbushandler.Event{EventData: forms.TenantID{TenantID: tenantID}})"
            }
          ]
        }
      ]
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/budgets": {
      "infrastructure": {
        "mysql": {
          "conditions": ["Always"],
          "operations": [
            {"operation": "SELECT", "table": "budgets", "trigger": "Get budgets"}
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/tenants/:tenant_id/budgets": {
      "infrastructure": {
        "mysql": {
          "conditions": ["Always"],
          "operations": [
            {"operation": "INSERT", "table": "budgets", "trigger": "Create budget"}
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/marketplace/azure/token": {
      "infrastructure": {},
      "services": [
        {
          "name": "azure-marketplace-api",
          "target_interface": "POST /oauth2/v2.0/token",
          "operation_type": "http_post",
          "conditions": ["AZUREPaymentEnable == true"],
          "operations": [{"operation": "HTTP GetToken", "trigger": "Get Azure marketplace token"}]
        }
      ]
    },
    "HTTP POST /api/v1/billing/marketplace/tenants/:tenant_id/azure/subscriptions/:subscription_id": {
      "infrastructure": {
        "mysql": {
          "conditions": ["Always"],
          "operations": [
            {"operation": "SELECT", "table": "payment_methods", "trigger": "Get Azure payment method"},
            {"operation": "UPDATE", "table": "payment_methods", "trigger": "Update payment code"}
          ]
        }
      },
      "services": [
        {
          "name": "azure-marketplace-api",
          "target_interface": "GET /api/saas/subscriptions/:id",
          "operation_type": "http_get",
          "conditions": ["AZUREPaymentEnable == true"],
          "operations": [{"operation": "HTTP GetSubscription", "trigger": "Get Azure subscription"}]
        },
        {
          "name": "azure-marketplace-api",
          "target_interface": "POST /api/saas/subscriptions/:id/activate",
          "operation_type": "http_post",
          "conditions": ["AZUREPaymentEnable == true"],
          "operations": [{"operation": "HTTP ActivateSubscription", "trigger": "Activate Azure subscription"}]
        },
        {
          "name": "azure-marketplace-api",
          "target_interface": "POST /api/saas/subscriptions/:id/cancel",
          "operation_type": "http_post",
          "conditions": ["AZUREPaymentEnable == true", "old subscription exists"],
          "operations": [{"operation": "HTTP CancelSubscription", "trigger": "Cancel old Azure subscription"}]
        }
      ]
    },
    "HTTP POST /api/v1/billing/orgs/:tenant_id/measures": {
      "infrastructure": {
        "mysql": {
          "conditions": ["Always"],
          "operations": [
            {"operation": "INSERT", "table": "measures", "trigger": "Insert usage measures"},
            {"operation": "SELECT", "table": "packages", "trigger": "Get package info"},
            {"operation": "SELECT", "table": "units", "trigger": "Get unit info"},
            {"operation": "SELECT", "table": "billing_configs", "trigger": "Get billing config"}
          ]
        },
        "sqs": {
          "conditions": ["EnableQueueMeasure == true"],
          "operations": [
            {"operation": "RECEIVE", "trigger": "Receive measures from SQS queue"}
          ]
        }
      },
      "services": [
        {
          "name": "tidb-mgmt-svc",
          "target_interface": "ClusterService.GetCluster",
          "operation_type": "grpc_unary",
          "conditions": ["EnableUseMgmtGetClusterInfo == true"],
          "operations": [{"operation": "gRPC GetCluster", "trigger": "Get cluster info for measures"}]
        }
      ]
    },
    "HTTP GET /v1beta1/partners/partnerConfigs": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after partner OpenAPI middleware succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "partner_configs",
              "trigger": "Fetch the partner-level partnerConfigs row; return defaults when no row exists",
              "conditions": [
                "RemoveApiKeyHeaderMiddleware completed",
                "auth.GinGetIdentityInfoInterceptor populated authInfo.OrgID",
                "auth.GinPermissionCheckInterceptor authorized GET /v1beta1/partners/partnerConfigs"
              ],
              "implementation": "PartnerConfigsAPI.GetPartnerConfigs() -> partnerConfigModel.GetPartnerConfigs(uint(authInfo.OrgID))"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP PATCH /v1beta1/partners/partnerConfigs": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after partner OpenAPI middleware succeeds and request JSON binds successfully"
          ],
          "operations": [
            {
              "operation": "INSERT",
              "table": "partner_configs",
              "trigger": "Create the partner-level partnerConfigs row when it does not exist yet",
              "conditions": [
                "c.ShouldBindJSON(&forms.PartnerConfigs{}) succeeded"
              ],
              "implementation": "partnerConfigModel.UpdatePartnerConfigs() -> ent.Create(db.GetDB().Clauses(clause.Insert{Modifier: \"IGNORE\"}))"
            },
            {
              "operation": "UPDATE",
              "table": "partner_configs",
              "trigger": "Persist EnableBillsView onto the partner-level row",
              "conditions": [
                "Insert-or-ignore returned without error"
              ],
              "implementation": "entity.NewPartnerConfigsQuerySet(db.GetDB()).PartnerIDEq(partnerID).CustomerIDEq(0).GetUpdater().SetEnableCustomerBills(configs.EnableBillsView).Update()"
            },
            {
              "operation": "SELECT",
              "table": "partner_configs",
              "trigger": "Re-read the effective partner configs after update",
              "conditions": [
                "Partner config update succeeded"
              ],
              "implementation": "partnerConfigModel.UpdatePartnerConfigs() -> partnerConfigModel.GetPartnerConfigs(partnerID)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /v1beta1/partners/customers/:customerId/partnerConfigs": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after partner OpenAPI middleware succeeds and the customer belongs to the partner"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "partner_configs",
              "trigger": "Return the partner defaults currently used for the requested customer",
              "conditions": [
                "getCustomerIDFromUri(...) succeeded"
              ],
              "implementation": "PartnerConfigsAPI.GetCustomerPartnerConfigs() -> partnerConfigModel.GetCustomerPartnerConfigs(partnerID, customerID) -> partnerConfigModel.GetPartnerConfigs(partnerID)"
            }
          ]
        }
      },
      "services": [
        {
          "name": "account-svc",
          "target_interface": "AccountAPIService.ListPartnerCustomers",
          "operation_type": "grpc_unary",
          "conditions": [
            "Always before reading customer partner configs"
          ],
          "operations": [
            {
              "operation": "gRPC ListPartnerCustomers",
              "trigger": "Verify that the requested customer is managed by the authenticated partner org",
              "conditions": [
                "auth.GinGetIdentityInfoInterceptor populated authInfo.OrgID",
                "customerId path parameter is present"
              ],
              "implementation": "getCustomerIDFromUri(...) -> centralhandler.GetCentralHandler().IsPartnersCustomer(partnerID, customerID) -> account.ListPartnerCustomers(PartnerIds=[partnerID], PartnerCustomerIds=[customerID])"
            }
          ]
        }
      ]
    },
    "HTTP PATCH /v1beta1/partners/customers/:customerId/partnerConfigs": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after partner OpenAPI middleware succeeds, the customer belongs to the partner, and request JSON binds successfully"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "partner_configs",
              "trigger": "Return the partner defaults after validating the customer-scoped request",
              "conditions": [
                "getCustomerIDFromUri(...) succeeded",
                "c.ShouldBindJSON(&forms.PartnerConfigs{}) succeeded"
              ],
              "implementation": "PartnerConfigsAPI.UpdateCustomerPartnerConfigs() -> partnerConfigModel.UpdateCustomerPartnerConfigs(partnerID, customerID, &input) -> partnerConfigModel.GetPartnerConfigs(partnerID)"
            }
          ]
        }
      },
      "services": [
        {
          "name": "account-svc",
          "target_interface": "AccountAPIService.ListPartnerCustomers",
          "operation_type": "grpc_unary",
          "conditions": [
            "Always before accepting the customer-scoped update"
          ],
          "operations": [
            {
              "operation": "gRPC ListPartnerCustomers",
              "trigger": "Verify that the requested customer is managed by the authenticated partner org before returning the effective configs",
              "conditions": [
                "auth.GinGetIdentityInfoInterceptor populated authInfo.OrgID",
                "customerId path parameter is present"
              ],
              "implementation": "getCustomerIDFromUri(...) -> centralhandler.GetCentralHandler().IsPartnersCustomer(partnerID, customerID) -> account.ListPartnerCustomers(PartnerIds=[partnerID], PartnerCustomerIds=[customerID])"
            }
          ]
        }
      ]
    },
    "HTTP GET /v1beta1/partners/billingProfile": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after partner OpenAPI middleware succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the active billing config for the authenticated partner org",
              "conditions": [
                "auth.GinGetIdentityInfoInterceptor populated authInfo.OrgID"
              ],
              "implementation": "getBillingCfgFromAuth(c) -> billingconfig.BillingConfigModel.GetActiveBillingConfig(uint(authInfo.OrgID))"
            },
            {
              "operation": "SELECT",
              "table": "billing_information",
              "trigger": "Fetch the partner billing profile for the active billing config tenant",
              "conditions": [
                "getBillingCfgFromAuth(c) returned billingCfgStruct.TenantID"
              ],
              "implementation": "paymentsub.BillingInformationModel.GetBillingInfo(tenantID) -> getBillingInfo(tenantID)"
            },
            {
              "operation": "SELECT",
              "table": "tax_rates",
              "trigger": "Hydrate tax-rate details when the stored billing profile references a tax rate",
              "conditions": [
                "billing_information.TaxRateID != \"\"",
                "EnableTaxCalculation == true"
              ],
              "implementation": "BillingInfoFromEntityWithTaxRate(...) -> TaxModel.GetTaxRate(billingInfoEntity.TaxRateID)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP PATCH /v1beta1/partners/billingProfile": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after partner OpenAPI middleware succeeds and request JSON binds successfully"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the active billing config for the authenticated partner org before updating the billing profile",
              "conditions": [
                "auth.GinGetIdentityInfoInterceptor populated authInfo.OrgID"
              ],
              "implementation": "getBillingCfgFromAuth(c) -> billingconfig.BillingConfigModel.GetActiveBillingConfig(uint(authInfo.OrgID))"
            },
            {
              "operation": "INSERT",
              "table": "billing_information",
              "trigger": "Create the billing_information row on first write",
              "conditions": [
                "paymentsub.BillingInformationModel.createBillingInfo(..., updateExists=true) is called"
              ],
              "implementation": "entity.BillingInformation{TenantID: tenantID}.Create(db.GetDB().Clauses(clause.Insert{Modifier: \"IGNORE\"}))"
            },
            {
              "operation": "SELECT",
              "table": "country_code_company_map",
              "trigger": "Resolve the company key used by the supplied billing country code",
              "conditions": [
                "CompanyKey needs to be derived from billing profile country code"
              ],
              "implementation": "companyKeyFromCountryCode(countryCode)"
            },
            {
              "operation": "SELECT",
              "table": "billing_companies",
              "trigger": "Resolve billing company metadata and payment subcode before validating tax settings",
              "conditions": [
                "companyKeyFromCountryCode(...) succeeded"
              ],
              "implementation": "BillingInformationModel.GetBillingCompany(companyKey)"
            },
            {
              "operation": "SELECT",
              "table": "billing_information",
              "trigger": "Lock and inspect the existing billing profile before updating it",
              "conditions": [
                "The create-or-ignore step completed"
              ],
              "implementation": "entity.NewBillingInformationQuerySet(tx.Clauses(clause.Locking{Strength: \"UPDATE\"})).TenantIDEq(tenantID).One(&billingInfo)"
            },
            {
              "operation": "UPDATE",
              "table": "billing_information",
              "trigger": "Persist the normalized partner billing profile",
              "conditions": [
                "Validation passed inside createBillingInfo(...)"
              ],
              "implementation": "entity.NewBillingInformationQuerySet(tx).TenantIDEq(tenantID).GetUpdater().SetCompanyName(...).SetBillingEmail(...).SetCountryCode(...).SetState(...).SetCity(...).SetLine1(...).SetLine2(...).SetPostalCode(...).SetTaxID(...).SetTaxIDType(...).SetCustomInputCountryName(...).SetTaxIDCountryCode(...).Update()"
            },
            {
              "operation": "SELECT",
              "table": "payment_methods",
              "trigger": "Resolve or create the Stripe payment method used for billing-info sync",
              "conditions": [
                "EnableTaxCalculation == true"
              ],
              "implementation": "BillingInformationModel.UpdateStripeBillingInformation(...) -> PaymentModel.GetPaymentMethodWithPaymentTypeCurrentBillingConfig(...); fallback PaymentModel.CreateDefaultStripePaymentForBillingInformation(...)"
            },
            {
              "operation": "UPDATE",
              "table": "tenant_billing_companies",
              "trigger": "Update the tenant-to-company binding derived from the billing country code",
              "conditions": [
                "companyKeyFromCountryCode(...) succeeded"
              ],
              "implementation": "BillingInformationModel.UpdateTenantBillingCompany(tenantID, &forms.TenantBillingCompany{CompanyKey: companyKey})"
            },
            {
              "operation": "SELECT",
              "table": "billing_information",
              "trigger": "Return the latest billing profile after persistence completes",
              "conditions": [
                "Billing profile persistence completed"
              ],
              "implementation": "BillingInformationModel.CreateOrUpdateBillingInfo(...) -> BillingInformationModel.getBillingInfo(tenantID)"
            }
          ]
        }
      },
      "services": [
        {
          "name": "account-svc",
          "target_interface": "AccountAPIService.GetOrgByID",
          "operation_type": "grpc_unary",
          "conditions": [
            "Only when EnableTaxCalculation == true"
          ],
          "operations": [
            {
              "operation": "gRPC GetOrgByID",
              "trigger": "Fetch the tenant email when the submitted billing profile omits BillingEmail during Stripe sync",
              "conditions": [
                "EnableTaxCalculation == true",
                "input.BillingEmail == \"\""
              ],
              "implementation": "BillingInformationModel.UpdateStripeBillingInformation(...) -> centralhandler.GetCentralHandler().GetTenant(tenantID) -> account.GetOrgByID(IsBrief=true)"
            }
          ]
        },
        {
          "name": "stripe-api",
          "target_interface": "POST /v1/customers/{customer}/billing_info",
          "operation_type": "http_post",
          "conditions": [
            "Only when EnableTaxCalculation == true"
          ],
          "operations": [
            {
              "operation": "HTTP UpdateCustomerBillingInfo",
              "trigger": "Propagate the updated billing profile to Stripe after the database transaction succeeds",
              "conditions": [
                "EnableTaxCalculation == true",
                "paymenthandler.GetStripeProvider() succeeded"
              ],
              "implementation": "BillingInformationModel.UpdateStripeBillingInformation(...) -> sh.UpdateCustomerBillingInfo(payment.PaymentCode, info)"
            }
          ]
        }
      ]
    },
    "HTTP GET /v1beta1/partners/discounts": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after partner OpenAPI middleware succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the active billing config before deciding whether to list direct discounts or managing-customer discounts",
              "conditions": [
                "auth.GinGetIdentityInfoInterceptor populated authInfo.OrgID"
              ],
              "implementation": "getBillingCfgFromAuth(c) -> billingconfig.BillingConfigModel.GetActiveBillingConfig(uint(authInfo.OrgID))"
            },
            {
              "operation": "SELECT",
              "table": "discounts",
              "trigger": "List tenant-bound discounts for MSP and resale-partner orgs",
              "conditions": [
                "billingCfgStruct.Type in {MSP, ResalePartner}"
              ],
              "implementation": "discount.Model.ListDiscountsConsoleView(billingCfgStruct.TenantID, billingCfgStruct.BillingConfigID) -> ListTenantDiscounts(...)"
            },
            {
              "operation": "SELECT",
              "table": "discounts",
              "trigger": "List discounts across managed billing configs for marketplace-reseller and direct-customer orgs",
              "conditions": [
                "billingCfgStruct.Type in {MarketplaceReseller, DirectCustomer}"
              ],
              "implementation": "billingconfig.BillingConfigModel.GetManagingBillingConfigs(billingCfgStruct.TenantID) + discount.Model.ListDiscountsConsoleView(billingCfgStruct.TenantID, bcfg.BillingConfigID)"
            },
            {
              "operation": "SELECT",
              "table": "unit_filters",
              "trigger": "Load unit-filter metadata used to render discount service names in console/openapi view",
              "conditions": [
                "ListDiscountsConsoleView(...) loaded discount rows"
              ],
              "implementation": "ListTenantDiscounts / ListGlobalActiveDiscounts -> entity.NewDiscountQuerySet(db.GetDB().Preload(clause.Associations))"
            }
          ]
        },
        "redis": {
          "conditions": [
            "Only when global active discounts are included in the response"
          ],
          "operations": [
            {
              "operation": "GET",
              "trigger": "Reuse cached global active discounts when merging them into the partner discount list",
              "conditions": [
                "ListDiscountsConsoleView(...) reached ListGlobalActiveDiscounts()"
              ],
              "implementation": "discount.Model.ListGlobalActiveDiscounts() -> ListTenantActiveDiscounts(...) -> cachehandler.Get().Get(\"ListTenantActiveDiscounts\", ...)"
            },
            {
              "operation": "SET",
              "trigger": "Cache global active discount entities after the DB lookup succeeds",
              "conditions": [
                "ListTenantActiveDiscounts(...) queried active discount entities from MySQL"
              ],
              "implementation": "cachehandler.Get().Set(\"ListTenantActiveDiscounts\", &discountEntities, tenantID, billingConfigID)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /v1beta1/partners/payments": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after partner OpenAPI middleware succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the active billing config for the authenticated org before looking up its active payment method",
              "conditions": [
                "auth.GinGetIdentityInfoInterceptor populated authInfo.OrgID"
              ],
              "implementation": "getBillingCfgFromAuth(c) -> billingconfig.BillingConfigModel.GetActiveBillingConfig(uint(authInfo.OrgID))"
            },
            {
              "operation": "SELECT",
              "table": "payment_methods",
              "trigger": "Read the active payment method rendered as partner openapi payment summary",
              "conditions": [
                "billingCfgStruct.TenantID and billingCfgStruct.BillingConfigID resolved successfully"
              ],
              "implementation": "paymentModel.GetActivePaymentMethod(billingCfgStruct.TenantID, billingCfgStruct.BillingConfigID)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /v1beta1/partners/publicSupportPlans": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after partner OpenAPI middleware succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "support_plans",
              "trigger": "List support plans that are marked public for partner self-service selection",
              "conditions": [
                "ListAllPublicSupportPlanForOpenAPI(...) was reached"
              ],
              "implementation": "marketing.SupportPlanModel.ListPublicSupportPlan()"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /v1beta1/partners/boundSupportPlans": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after partner OpenAPI middleware succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the active billing config before reading the active payment method and support plan",
              "conditions": [
                "auth.GinGetIdentityInfoInterceptor populated authInfo.OrgID"
              ],
              "implementation": "getBillingCfgFromAuth(c) -> billingconfig.BillingConfigModel.GetActiveBillingConfig(uint(authInfo.OrgID))"
            },
            {
              "operation": "SELECT",
              "table": "payment_methods",
              "trigger": "Check whether the organization is billed through MSP delegation before resolving the active support plan",
              "conditions": [
                "billingCfgStruct.TenantID and billingCfgStruct.BillingConfigID resolved successfully"
              ],
              "implementation": "paymentModel.GetActivePaymentMethod(billingCfgStruct.TenantID, billingCfgStruct.BillingConfigID)"
            },
            {
              "operation": "SELECT",
              "table": "binded_support_plans",
              "trigger": "Read the currently active support plan either from the org itself or from the delegated MSP org",
              "conditions": [
                "payment method lookup succeeded or returned ObjectNotExists"
              ],
              "implementation": "marketing.SupportPlanModel.GetTenantActiveBindedPlan(targetTenantID)"
            },
            {
              "operation": "SELECT",
              "table": "support_plans",
              "trigger": "Hydrate support-plan attributes referenced by the active tenant binding",
              "conditions": [
                "GetTenantActiveBindedPlan(targetTenantID) returned a persisted support-plan binding"
              ],
              "implementation": "marketing.SupportPlanModel.GetTenantActiveBindedPlan(...)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /v1beta1/partners/bills/:billedMonth": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after partner OpenAPI middleware succeeds and billedMonth is within the allowed query window"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the active billing config for the authenticated partner org before deciding the partner billing traversal mode",
              "conditions": [
                "auth.GinGetIdentityInfoInterceptor populated authInfo.OrgID"
              ],
              "implementation": "getBillingCfgFromAuth(c) -> billingconfig.BillingConfigModel.GetActiveBillingConfig(uint(authInfo.OrgID))"
            },
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Expand marketplace reseller or direct-customer partners into their managed billing configs",
              "conditions": [
                "billingCfgStruct.Type in {MarketplaceReseller, DirectCustomer}"
              ],
              "implementation": "billingconfig.BillingConfigModel.GetManagingBillingConfigs(billingCfgStruct.TenantID)"
            },
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Expand the Alicloud managing org into all managed customer billing configs",
              "conditions": [
                "billingCfgStruct.Type == Alicloud",
                "billingCfgStruct.TenantID == AlicloudManagingOrgID"
              ],
              "implementation": "listAliCustomerTenantIDsAndBillingConfigIDs(managerID) -> billingconfig.BillingConfigModel.ListAlicloudCustomerBillingConfigs()"
            },
            {
              "operation": "SELECT",
              "table": "user_unit_costs",
              "trigger": "Query the monthly partner bill across one or many billing configs",
              "conditions": [
                "Partner billing traversal resolved tenantIDs and billingConfigIDs"
              ],
              "implementation": "CostExplorerModel.CalculatePartnerOpenAPIMonthlyCostWithCache(...) -> GetMonthlyCostWithCacheWithMultiBillingConfigsWithCache(...) -> queryCost(...) / GetMonthlyCostWithCacheWithMultiBillingConfigs(...)"
            }
          ]
        },
        "redis": {
          "conditions": [
            "Always around the partner monthly bill query"
          ],
          "operations": [
            {
              "operation": "GET",
              "trigger": "Try the cached aggregated partner monthly bill before querying cost rows",
              "conditions": [
                "CalculatePartnerOpenAPIMonthlyCostWithCache(...) is reached"
              ],
              "implementation": "GetMonthlyCostWithCacheWithMultiBillingConfigsWithCache(...) -> cachehandler.Get().Get(\"GetMonthlyCostWithCacheWithMultiBillingConfigs\", ...)"
            },
            {
              "operation": "SET",
              "trigger": "Cache the aggregated partner monthly bill after query and formatting succeed",
              "conditions": [
                "GetMonthlyCostWithCacheWithMultiBillingConfigs(...) succeeded"
              ],
              "implementation": "GetMonthlyCostWithCacheWithMultiBillingConfigsWithCache(...) -> cachehandler.Get().Set(\"GetMonthlyCostWithCacheWithMultiBillingConfigs\", ...)"
            }
          ]
        }
      },
      "services": [
        {
          "name": "account-svc",
          "target_interface": "AccountAPIService.GetOrgByID",
          "operation_type": "grpc_unary",
          "conditions": [
            "Only when partner summary-by-customer needs customer names from central rather than treating tenant IDs as the customer key"
          ],
          "operations": [
            {
              "operation": "gRPC GetOrgByID",
              "trigger": "Resolve customer org names while formatting SummaryByCustomer for non-Alicloud partner bills",
              "conditions": [
                "tenantIDAsCustomer == false",
                "A distinct MSP customer label was found in the aggregated cost result"
              ],
              "implementation": "CostExplorerModel.toPartnerBillsExplorer(...) -> GetSummaryByCustomerFromCosts(..., tenantIDAsCustomer=false) -> appendCustomer(...) -> centralhandler.GetCentralHandler().GetTenant(customerID) -> account.GetOrgByID(IsBrief=true)"
            }
          ]
        }
      ]
    },
    "HTTP GET /v1beta1/partners/billsDetails/:billedMonth": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after partner OpenAPI middleware succeeds and billedMonth parses successfully"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the active billing config for the authenticated partner org before deciding the detailed partner-billing traversal mode",
              "conditions": [
                "auth.GinGetIdentityInfoInterceptor populated authInfo.OrgID"
              ],
              "implementation": "getBillingCfgFromAuth(c) -> billingconfig.BillingConfigModel.GetActiveBillingConfig(uint(authInfo.OrgID))"
            },
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Expand marketplace reseller or direct-customer partners into their managed billing configs before querying detailed usage rows",
              "conditions": [
                "billingCfgStruct.Type in {MarketplaceReseller, DirectCustomer}"
              ],
              "implementation": "billingconfig.BillingConfigModel.GetManagingBillingConfigs(billingCfgStruct.TenantID)"
            },
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Expand the Alicloud managing org into all managed customer billing configs before querying detailed usage rows",
              "conditions": [
                "billingCfgStruct.Type == Alicloud",
                "billingCfgStruct.TenantID == AlicloudManagingOrgID"
              ],
              "implementation": "listAliCustomerTenantIDsAndBillingConfigIDs(managerID) -> billingconfig.BillingConfigModel.ListAlicloudCustomerBillingConfigs()"
            },
            {
              "operation": "SELECT",
              "table": "units",
              "trigger": "Load unit metadata needed to translate grouped usage rows into partner bill details",
              "conditions": [
                "CostExplorerModel.GetPartnerBillsDetails(...) was reached"
              ],
              "implementation": "billing.UnitModel.GetAllUnits()"
            },
            {
              "operation": "SELECT",
              "table": "user_unit_costs",
              "trigger": "Query grouped usage rows across one or many billing configs to build partner bill details",
              "conditions": [
                "Partner detailed billing traversal resolved tenantIDs and billingConfigIDs"
              ],
              "implementation": "CostExplorerModel.GetPartnerBillsDetails(...) -> getCostsSliceWithMultiBillingConfigs(tenantIDs, billingConfigIDs, year, month, nil, 0)"
            }
          ]
        },
        "redis": {
          "conditions": [
            "Always around partner detailed bill lookups"
          ],
          "operations": [
            {
              "operation": "GET",
              "trigger": "Try the cached partner bill details before recomputing grouped usage rows",
              "conditions": [
                "GetPartnerBillsDetailsWithCache(...) is reached"
              ],
              "implementation": "cachehandler.Get().Get(\"GetPartnerBillsDetails\", ret, array.JoinUnitSlice(tenantIDs, \"|\"), array.JoinUnitSlice(billingConfigIDs, \"|\"), year, month)"
            },
            {
              "operation": "SET",
              "trigger": "Cache the computed partner bill details after grouped usage queries and formatting succeed",
              "conditions": [
                "GetPartnerBillsDetails(...) succeeded"
              ],
              "implementation": "cachehandler.Get().Set(\"GetPartnerBillsDetails\", ret, array.JoinUnitSlice(tenantIDs, \"|\"), array.JoinUnitSlice(billingConfigIDs, \"|\"), year, month)"
            }
          ]
        }
      },
      "services": [
        {
          "name": "account-svc",
          "target_interface": "AccountAPIService.GetOrgByID",
          "operation_type": "grpc_unary",
          "conditions": [
            "Only when detailed partner bill rows should display customer org names rather than tenant IDs"
          ],
          "operations": [
            {
              "operation": "gRPC GetOrgByID",
              "trigger": "Resolve customer org names while materializing detailed partner bill rows",
              "conditions": [
                "tenantIDAsCustomer == false",
                "customerIDStr != \"\" in PartnerBillsDetailsFromUnitCosts(...)"
              ],
              "implementation": "PartnerBillsDetailsFromUnitCosts(...) -> centralhandler.GetCentralHandler().GetTenant(customerID) -> account.GetOrgByID(IsBrief=true)"
            }
          ]
        }
      ]
    },
    "HTTP GET /v1beta1/partners/billsCostExplorerArgs": {
      "infrastructure": {
        "redis": {
          "conditions": [
            "Always around the partner trends-args lookup"
          ],
          "operations": [
            {
              "operation": "GET",
              "trigger": "Try the cached partner trends args before enumerating clusters, projects, providers, services, and customers",
              "conditions": [
                "GetPartnerTrendsArgs(...) reached cachehandler.Get().Get(\"GetPartnerTrendsArgs\", ...)"
              ],
              "implementation": "cachehandler.Get().Get(\"GetPartnerTrendsArgs\", &ret, tenantID)"
            },
            {
              "operation": "SET",
              "trigger": "Cache the assembled partner trends args after all enumerations succeed",
              "conditions": [
                "clusters, projects, providers, services, and customers were all collected successfully"
              ],
              "implementation": "cachehandler.Get().Set(\"GetPartnerTrendsArgs\", &ret, tenantID)"
            }
          ]
        }
      },
      "services": [
        {
          "name": "infra-svc",
          "target_interface": "CoreService.ListClusters",
          "operation_type": "grpc_unary",
          "conditions": [
            "Only when EnableUseMgmtGetClusterInfo == false"
          ],
          "operations": [
            {
              "operation": "gRPC ListClusters",
              "trigger": "Enumerate partner-visible clusters for the trends-args response",
              "conditions": [
                "EnableUseMgmtGetClusterInfo == false"
              ],
              "implementation": "costexplorer.GetCostExplorerClusters(tenantID) -> infrahandler.Get().ListClusters(tenantID)"
            }
          ]
        },
        {
          "name": "tidb-mgmt-svc",
          "target_interface": "ClusterService.GetAllClustersByTenantID",
          "operation_type": "grpc_unary",
          "conditions": [
            "Only when EnableUseMgmtGetClusterInfo == true"
          ],
          "operations": [
            {
              "operation": "gRPC GetAllClustersByTenantID",
              "trigger": "Enumerate partner-visible clusters for the trends-args response via tidb-management-service",
              "conditions": [
                "EnableUseMgmtGetClusterInfo == true"
              ],
              "implementation": "costexplorer.GetCostExplorerClusters(tenantID) -> tidbmgmtsvchandler.Get().GetAllClustersByTenantID(context.Background(), uint64(tenantID))"
            }
          ]
        },
        {
          "name": "account-svc",
          "target_interface": "AccountAPIService.ListProjects",
          "operation_type": "grpc_unary",
          "conditions": [
            "Always while assembling partner trends args"
          ],
          "operations": [
            {
              "operation": "gRPC ListProjects",
              "trigger": "Enumerate projects for the partner trends-args response",
              "conditions": [
                "billingCfgStruct.TenantID resolved from auth context"
              ],
              "implementation": "costexplorer.GetCostExplorerProjects(tenantID) -> centralhandler.GetCentralHandler().ListProjects(tenantID, true)"
            }
          ]
        },
        {
          "name": "account-svc",
          "target_interface": "AccountAPIService.ListPartnerCustomers",
          "operation_type": "grpc_unary",
          "conditions": [
            "Always while assembling partner trends args"
          ],
          "operations": [
            {
              "operation": "gRPC ListPartnerCustomers",
              "trigger": "Enumerate managed partner customers for the partner trends-args response",
              "conditions": [
                "billingCfgStruct.TenantID resolved from auth context"
              ],
              "implementation": "costexplorer.GetCostExplorerCustomers(tenantID) -> centralhandler.GetCentralHandler().ListPartnerCustomers(tenantID)"
            }
          ]
        }
      ]
    },
    "HTTP POST /v1beta1/partners/billsCostExplorer": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after partner OpenAPI middleware succeeds, the OpenAPI trends body binds successfully, and tenant control checks pass"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the active billing config before deciding whether to query one billing config, managed billing configs, or Alicloud managed tenants",
              "conditions": [
                "auth.GinGetIdentityInfoInterceptor populated authInfo.OrgID"
              ],
              "implementation": "getBillingCfgFromAuth(c) -> billingconfig.BillingConfigModel.GetActiveBillingConfig(uint(authInfo.OrgID))"
            },
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Expand marketplace reseller or direct-customer partners into their managed billing configs before trends aggregation",
              "conditions": [
                "billingCfgStruct.Type in {MarketplaceReseller, DirectCustomer}"
              ],
              "implementation": "billingconfig.BillingConfigModel.GetManagingBillingConfigs(billingCfgStruct.TenantID)"
            },
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Expand the Alicloud managing org into all managed customer billing configs before trends aggregation",
              "conditions": [
                "billingCfgStruct.Type == Alicloud",
                "billingCfgStruct.TenantID == AlicloudManagingOrgID"
              ],
              "implementation": "listAliCustomerTenantIDsAndBillingConfigIDs(managerID) -> billingconfig.BillingConfigModel.ListAlicloudCustomerBillingConfigs()"
            },
            {
              "operation": "SELECT",
              "table": "user_unit_costs",
              "trigger": "Run the partner cost-explorer SQL over one or many tenant/billing-config combinations",
              "conditions": [
                "parseTrendsQuery(c, tenantID, true) succeeded",
                "Partner traversal resolved tenantIDs and billingConfigIDs"
              ],
              "implementation": "costexplorer.CostTrendsWithMultiTenantsMultiBillingConfigs(tenantIDs, billingConfigIDs, query) -> queryBreakdownDetails(...) -> db.GetReadOnlyDB().Raw(sql, params).Scan(&dbOutput)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /v1beta1/partners/invoicedBills/:billedMonth": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after partner OpenAPI middleware succeeds and billedMonth parses successfully"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the active billing config and partner query scope before filtering by invoice sent date",
              "conditions": [
                "auth.GinGetIdentityInfoInterceptor populated authInfo.OrgID"
              ],
              "implementation": "getBillingCfgFromAuth(c) + costExplorerOpenAPI.getPartnerQueryArgs(...)"
            },
            {
              "operation": "SELECT",
              "table": "invoices",
              "trigger": "List sent invoices in the requested month for the resolved tenantIDs and billingConfigIDs",
              "conditions": [
                "getPartnerQueryArgs(...) resolved tenantIDs and billingConfigIDs"
              ],
              "implementation": "InvoicedCostExplorerModel.GetInvoicesBySentDateRange(tenantIDs, billingConfigIDs, year, month)"
            },
            {
              "operation": "SELECT",
              "table": "user_unit_costs",
              "trigger": "Aggregate cost rows constrained by the invoice IDs sent during the requested month",
              "conditions": [
                "GetInvoicesBySentDateRange(...) returned invoice IDs"
              ],
              "implementation": "InvoicedCostExplorerModel.CalculatePartnerOpenAPIMonthlyCostBySentDateWithCache(...) -> CostExplorerModel.CalculateCostV2MultiTenantsWithCache(..., CostExplorerQueryV2{InvoiceIDs: invoiceIDs})"
            }
          ]
        }
      },
      "services": [
        {
          "name": "account-svc",
          "target_interface": "AccountAPIService.GetOrgByID",
          "operation_type": "grpc_unary",
          "conditions": [
            "Only when tenantIDAsCustomer == false and summary-by-customer needs customer names"
          ],
          "operations": [
            {
              "operation": "gRPC GetOrgByID",
              "trigger": "Resolve customer org names while formatting the invoiced partner bill summary-by-customer",
              "conditions": [
                "tenantIDAsCustomer == false",
                "A distinct MSP customer label was found in the aggregated invoice-date cost result"
              ],
              "implementation": "CostExplorerModel.toPartnerBillsExplorer(...) -> GetSummaryByCustomerFromCosts(..., tenantIDAsCustomer=false) -> appendCustomer(...) -> centralhandler.GetCentralHandler().GetTenant(customerID) -> account.GetOrgByID(IsBrief=true)"
            }
          ]
        }
      ]
    },
    "HTTP GET /v1beta1/partners/invoicedBillsDetails/:billedMonth": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after partner OpenAPI middleware succeeds and billedMonth parses successfully"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the active billing config and partner query scope before filtering detailed invoice rows by sent month",
              "conditions": [
                "auth.GinGetIdentityInfoInterceptor populated authInfo.OrgID"
              ],
              "implementation": "getBillingCfgFromAuth(c) + costExplorerOpenAPI.getPartnerQueryArgs(...)"
            },
            {
              "operation": "SELECT",
              "table": "invoices",
              "trigger": "List sent invoices in the requested month before querying grouped usage details",
              "conditions": [
                "getPartnerQueryArgs(...) resolved tenantIDs and billingConfigIDs"
              ],
              "implementation": "InvoicedCostExplorerModel.GetInvoicesBySentDateRange(tenantIDs, billingConfigIDs, year, month)"
            },
            {
              "operation": "SELECT",
              "table": "user_unit_costs",
              "trigger": "Query grouped usage detail rows constrained by invoice IDs sent during the requested month",
              "conditions": [
                "GetInvoicesBySentDateRange(...) returned invoice IDs"
              ],
              "implementation": "InvoicedCostExplorerModel.GetPartnerBillsDetailsBySentDate(...) -> getCostsSliceWithMultiBillingConfigsByInvoiceIDs(...)"
            }
          ]
        },
        "redis": {
          "conditions": [
            "Always around invoiced partner bill details lookups"
          ],
          "operations": [
            {
              "operation": "GET",
              "trigger": "Try the cached partner invoiced bill details before recomputing them",
              "conditions": [
                "GetPartnerBillsDetailsBySentDateWithCache(...) is reached"
              ],
              "implementation": "cachehandler.Get().Get(\"GetPartnerBillsDetailsBySentDate\", ret, array.JoinUnitSlice(tenantIDs, \"|\"), array.JoinUnitSlice(billingConfigIDs, \"|\"), year, month)"
            },
            {
              "operation": "SET",
              "trigger": "Cache the computed partner invoiced bill details after the grouped query succeeds",
              "conditions": [
                "GetPartnerBillsDetailsBySentDate(...) succeeded"
              ],
              "implementation": "cachehandler.Get().Set(\"GetPartnerBillsDetailsBySentDate\", ret, array.JoinUnitSlice(tenantIDs, \"|\"), array.JoinUnitSlice(billingConfigIDs, \"|\"), year, month)"
            }
          ]
        }
      },
      "services": [
        {
          "name": "account-svc",
          "target_interface": "AccountAPIService.GetOrgByID",
          "operation_type": "grpc_unary",
          "conditions": [
            "Only when the detailed invoice result needs customer names instead of using tenant IDs as the customer label"
          ],
          "operations": [
            {
              "operation": "gRPC GetOrgByID",
              "trigger": "Resolve customer org names while materializing detailed partner invoiced bill rows",
              "conditions": [
                "tenantIDAsCustomer == false",
                "customerIDStr != \"\" in PartnerBillsDetailsFromUnitCostsWithInvoicedDate(...)"
              ],
              "implementation": "PartnerBillsDetailsFromUnitCostsWithInvoicedDate(...) -> centralhandler.GetCentralHandler().GetTenant(customerID) -> account.GetOrgByID(IsBrief=true)"
            }
          ]
        }
      ]
    },
    "HTTP GET /v1beta1/partners/budgets": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after partner OpenAPI middleware succeeds and the tenant/billing-config pair is not hidden by BillsInvisibleList"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the active billing config used to apply the BillsInvisibleList visibility gate",
              "conditions": [
                "auth.GinGetIdentityInfoInterceptor populated authInfo.OrgID"
              ],
              "implementation": "getBillingCfgFromAuth(c) -> billingconfig.BillingConfigModel.GetActiveBillingConfig(uint(authInfo.OrgID))"
            },
            {
              "operation": "SELECT",
              "table": "spend_limit_settings",
              "trigger": "List spend-limit settings that back openapi budgets for the authenticated org",
              "conditions": [
                "tenant/billingConfig pair not listed in BillsInvisibleList"
              ],
              "implementation": "spend_limit.SpendLimitModel.ListTenantSpendLimitSettings(billingCfgStruct.TenantID, false)"
            },
            {
              "operation": "SELECT",
              "table": "spend_limit_alert_thresholds",
              "trigger": "Load thresholds for each retained budget while converting spend-limit settings into budget views",
              "conditions": [
                "A spend_limit_setting survived free-quota and empty-biz-type filtering"
              ],
              "implementation": "SpendLimitModel.SpendingLimitToBudgetView(setting) -> ListTenantThresholds(...)"
            },
            {
              "operation": "SELECT",
              "table": "user_unit_costs",
              "trigger": "Compute current budget cost usage when hydrating each budget view",
              "conditions": [
                "SpendLimitModel.SpendingLimitToBudgetView(setting) was reached"
              ],
              "implementation": "SpendLimitModel.SpendLimitSettingWithCost(...) -> CostExplorerModel.GetMonthlyCost / GetProjectMonthlyCost / GetClusterMonthlyCost / GetCustomerMonthlyCost"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /v1beta1/partners/budgets/:budgetId": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after partner OpenAPI middleware succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the active billing config before loading the requested budget",
              "conditions": [
                "auth.GinGetIdentityInfoInterceptor populated authInfo.OrgID"
              ],
              "implementation": "getBillingCfgFromAuth(c) -> billingconfig.BillingConfigModel.GetActiveBillingConfig(uint(authInfo.OrgID))"
            },
            {
              "operation": "SELECT",
              "table": "spend_limit_settings",
              "trigger": "Load the requested budget's underlying spend-limit setting",
              "conditions": [
                "budgetId path parameter parsed successfully"
              ],
              "implementation": "spend_limit.SpendLimitModel.GetSpendLimitSetting(billingCfgStruct.TenantID, budgetID)"
            },
            {
              "operation": "SELECT",
              "table": "spend_limit_alert_thresholds",
              "trigger": "Load thresholds while converting the spend-limit setting into a budget view",
              "conditions": [
                "GetSpendLimitSetting(...) succeeded"
              ],
              "implementation": "SpendLimitModel.SpendingLimitToBudgetView(*spendingLimit) -> ListTenantThresholds(...)"
            },
            {
              "operation": "SELECT",
              "table": "user_unit_costs",
              "trigger": "Compute current budget cost usage for the requested budget",
              "conditions": [
                "SpendLimitModel.SpendingLimitToBudgetView(*spendingLimit) was reached"
              ],
              "implementation": "SpendLimitModel.SpendLimitSettingWithCost(...) -> CostExplorerModel.GetMonthlyCost / GetProjectMonthlyCost / GetClusterMonthlyCost / GetCustomerMonthlyCost"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /v1beta1/partners/budgets": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after partner OpenAPI middleware succeeds, partner type is MSP, and request JSON binds successfully"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the active billing config and verify that only MSP orgs can create openapi budgets",
              "conditions": [
                "auth.GinGetIdentityInfoInterceptor populated authInfo.OrgID"
              ],
              "implementation": "getBillingCfgFromAuth(c) -> billingconfig.BillingConfigModel.GetActiveBillingConfig(uint(authInfo.OrgID))"
            },
            {
              "operation": "INSERT",
              "table": "spend_limit_settings",
              "trigger": "Create the spend-limit setting that backs the new budget",
              "conditions": [
                "billingCfgStruct.Type == MSP",
                "budget threshold count is within [2, MaxBudgetThresholds]"
              ],
              "implementation": "spend_limit.SpendLimitModel.CreateSpendLimitSetting(billingCfgStruct.TenantID, &budget.SpendLimitSetting)"
            },
            {
              "operation": "INSERT",
              "table": "spend_limit_alert_thresholds",
              "trigger": "Create threshold rows for the newly created budget",
              "conditions": [
                "CreateSpendLimitSetting(...) succeeded"
              ],
              "implementation": "SpendLimitModel.CreateThresholds(setting.TenantID, setting.SpendLimitSettingID, budget.Thresholds)"
            },
            {
              "operation": "SELECT",
              "table": "spend_limit_settings",
              "trigger": "Re-read the created budget as a budget view after persistence succeeds",
              "conditions": [
                "CreateSpendLimitSetting(...) and CreateThresholds(...) succeeded"
              ],
              "implementation": "SpendLimitModel.SpendingLimitToBudgetView(*setting)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP PATCH /v1beta1/partners/budgets/:budgetId": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after partner OpenAPI middleware succeeds and request JSON binds successfully"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the active billing config before updating the requested budget",
              "conditions": [
                "auth.GinGetIdentityInfoInterceptor populated authInfo.OrgID"
              ],
              "implementation": "getBillingCfgFromAuth(c) -> billingconfig.BillingConfigModel.GetActiveBillingConfig(uint(authInfo.OrgID))"
            },
            {
              "operation": "SELECT",
              "table": "spend_limit_settings",
              "trigger": "Load and validate the existing spend-limit setting before applying mutations",
              "conditions": [
                "budgetId path parameter parsed successfully"
              ],
              "implementation": "spend_limit.SpendLimitModel.GetSpendLimitSetting(billingCfgStruct.TenantID, budgetID)"
            },
            {
              "operation": "UPDATE",
              "table": "spend_limit_alert_thresholds",
              "trigger": "Replace threshold rows when the PATCH body includes thresholds",
              "conditions": [
                "len(params.Thresholds) != 0"
              ],
              "implementation": "SpendLimitModel.UpdateThresholds(billingCfgStruct.TenantID, budgetID, params.Thresholds)"
            },
            {
              "operation": "UPDATE",
              "table": "spend_limit_settings",
              "trigger": "Persist mutable budget fields such as name, range, limit, and biz data",
              "conditions": [
                "spendingLimit.BizType == Normal"
              ],
              "implementation": "SpendLimitModel.UpdateSpendLimitSettings(billingCfgStruct.TenantID, budgetID, spendingLimit)"
            },
            {
              "operation": "SELECT",
              "table": "spend_limit_settings",
              "trigger": "Re-read the updated budget as openapi view after persistence succeeds",
              "conditions": [
                "UpdateSpendLimitSettings(...) succeeded"
              ],
              "implementation": "SpendLimitModel.SpendingLimitToBudgetView(*settings)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP DELETE /v1beta1/partners/budgets/:budgetId": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after partner OpenAPI middleware succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the active billing config before deleting the requested budget",
              "conditions": [
                "auth.GinGetIdentityInfoInterceptor populated authInfo.OrgID"
              ],
              "implementation": "getBillingCfgFromAuth(c) -> billingconfig.BillingConfigModel.GetActiveBillingConfig(uint(authInfo.OrgID))"
            },
            {
              "operation": "SELECT",
              "table": "spend_limit_settings",
              "trigger": "Load the existing budget and validate its biz type before deletion",
              "conditions": [
                "budgetId path parameter parsed successfully"
              ],
              "implementation": "spend_limit.SpendLimitModel.GetSpendLimitSetting(billingCfgStruct.TenantID, budgetID)"
            },
            {
              "operation": "UPDATE",
              "table": "spend_limit_settings",
              "trigger": "Mark the spend-limit setting deprecated and clear its biz-unique key before deletion",
              "conditions": [
                "spendingLimit.BizType == Normal"
              ],
              "implementation": "SpendLimitModel.DeleteSpendLimitSetting(...) -> query.GetUpdater().SetStatus(Deprecated).SetBizUniqueKey(nil).Update()"
            },
            {
              "operation": "DELETE",
              "table": "spend_limit_settings",
              "trigger": "Delete the spend-limit setting after the deprecation transition and biz hooks complete",
              "conditions": [
                "DeleteSpendLimitSetting transaction reached query.Delete()"
              ],
              "implementation": "SpendLimitModel.DeleteSpendLimitSetting(...) -> query.Delete()"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/mspCustomerBills/:billedMonth/mspCustomers/:mspCustomerId": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only when billedMonth is within the allowed range and the MSP customer/payment validation succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the active billing config for the requested MSP customer tenant",
              "conditions": [
                "c.ShouldBindUri(&MspMonthlyCostURI{}) succeeded"
              ],
              "implementation": "billingconfig.BillingConfigModel.GetActiveBillingConfigID(query.MspCustomerId)"
            },
            {
              "operation": "SELECT",
              "table": "payment_methods",
              "trigger": "Validate that the requested customer is billed as an MSP customer of the tenant in the path",
              "conditions": [
                "GetActiveBillingConfigID(query.MspCustomerId) succeeded"
              ],
              "implementation": "paymentModel.GetActivePaymentMethod(query.MspCustomerId, billingConfigID)"
            },
            {
              "operation": "SELECT",
              "table": "user_unit_costs",
              "trigger": "Query the customer monthly cost rows that back the MSP customer bill",
              "conditions": [
                "paymentMethod.PaymentType == MSP",
                "paymentMethod.PaymentCode == strconv.FormatUint(uint64(query.TenantID), 10)"
              ],
              "implementation": "CostExplorerModel.CalculateMspCustomerOpenAPIMonthlyCost(...) -> queryCost([]uint{tenantID}, []uint{billingConfigID}, queryParam)"
            }
          ]
        },
        "redis": {
          "conditions": [
            "Always around the monthly MSP customer bill query"
          ],
          "operations": [
            {
              "operation": "GET",
              "trigger": "Try the cached MSP customer monthly bill before querying cost rows",
              "conditions": [
                "BillsExplorerByMspCustomerOpenAPI(...) reached CalculateMspCustomerOpenAPIMonthlyCostWithCache(...)"
              ],
              "implementation": "cachehandler.Get().Get(\"CalculateMspCustomerOpenAPIMonthlyCostWithCache\", ret, tenantID, billedMonth.String())"
            },
            {
              "operation": "SET",
              "trigger": "Cache the computed MSP customer monthly bill after cost aggregation succeeds",
              "conditions": [
                "CalculateMspCustomerOpenAPIMonthlyCost(...) succeeded"
              ],
              "implementation": "cachehandler.Get().Set(\"CalculateMspCustomerOpenAPIMonthlyCostWithCache\", ret, tenantID, billedMonth.String())"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /v1beta1/msp/tenants/:tenant_id/bills/:billedMonth": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only when the request is normalized into the tenant-scoped path and billedMonth is within the allowed range"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Verify that the tenant is an MSP before returning the aggregated MSP monthly bill",
              "conditions": [
                "c.ShouldBindUri(&MspMonthlyCostURI{}) succeeded"
              ],
              "implementation": "billingconfig.BillingConfigModel.IsMspWithCache(query.TenantID)"
            },
            {
              "operation": "SELECT",
              "table": "user_unit_costs",
              "trigger": "Query the tenant monthly cost rows used to assemble the MSP bill and summary-by-customer breakdown",
              "conditions": [
                "IsMspWithCache(query.TenantID) returned true"
              ],
              "implementation": "CostExplorerModel.CalculateMspOpenAPIMonthlyCost(...) -> queryCost([]uint{tenantID}, nil, queryParam)"
            }
          ]
        },
        "redis": {
          "conditions": [
            "Always around the monthly MSP bill query"
          ],
          "operations": [
            {
              "operation": "GET",
              "trigger": "Try the cached MSP monthly bill before querying cost rows",
              "conditions": [
                "MspBillsExplorerOpenAPI(...) reached CalculateMspOpenAPIMonthlyCostWithCache(...)"
              ],
              "implementation": "cachehandler.Get().Get(\"CalculateMspOpenAPIMonthlyCostWithCache\", ret, tenantID, billedMonth.String())"
            },
            {
              "operation": "SET",
              "trigger": "Cache the computed MSP monthly bill after aggregation succeeds",
              "conditions": [
                "CalculateMspOpenAPIMonthlyCost(...) succeeded"
              ],
              "implementation": "cachehandler.Get().Set(\"CalculateMspOpenAPIMonthlyCost\", ret, tenantID, billedMonth.String())"
            }
          ]
        }
      },
      "services": [
        {
          "name": "account-svc",
          "target_interface": "AccountAPIService.GetOpenAPIAccess",
          "operation_type": "grpc_unary",
          "conditions": [
            "Only when the request originally arrived through /v1beta1/msp/* without an embedded /tenants/{tenant_id} segment"
          ],
          "operations": [
            {
              "operation": "gRPC GetOpenAPIAccess",
              "trigger": "Resolve the tenant ID from the OpenAPI public key before OpenAPIPathNormalize rewrites /v1beta1/msp/bills/:billedMonth into the tenant-scoped route",
              "conditions": [
                "OpenAPIPathNormalize(router) handled the request",
                "X-Auth-Type == openapi",
                "request path did not already contain /tenants/"
              ],
              "implementation": "middleware.OpenAPIPathNormalize(...) -> centralhandler.GetCentralHandler().GetTenantIdByOpenAPIAccess(apiKey) -> account.GetOpenAPIAccess(PublicKey=apiKey)"
            }
          ]
        }
      ]
    },
    "HTTP GET /v1beta1/msp/tenants/:tenant_id/discounts": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only when the request already contains /tenants/{tenant_id} and billing-config resolution succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the active billing config for the tenant-scoped MSP OpenAPI request",
              "conditions": [
                "c.ShouldBindUri(&BillingCfgStruct{}) succeeded"
              ],
              "implementation": "getBillingCfgFromURI(c) -> billingconfig.BillingConfigModel.GetActiveBillingConfig(billingCfgStruct.TenantID)"
            },
            {
              "operation": "SELECT",
              "table": "discounts",
              "trigger": "List tenant-bound discounts rendered as MSP OpenAPI discounts",
              "conditions": [
                "getBillingCfgFromURI(c) resolved billingCfgStruct.TenantID and billingCfgStruct.BillingConfigID"
              ],
              "implementation": "discount.Model.ListDiscountsConsoleView(billingCfgStruct.TenantID, billingCfgStruct.BillingConfigID) -> ListTenantDiscounts(...)"
            },
            {
              "operation": "SELECT",
              "table": "unit_filters",
              "trigger": "Load unit-filter metadata used to render MSP discount service names",
              "conditions": [
                "ListDiscountsConsoleView(...) loaded discount rows"
              ],
              "implementation": "ListTenantDiscounts / ListGlobalActiveDiscounts -> entity.NewDiscountQuerySet(db.GetDB().Preload(clause.Associations))"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /v1beta1/msp/discounts": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after OpenAPIPathNormalize rewrites the bare /v1beta1/msp/discounts request into the tenant-scoped route and billing-config resolution succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the active billing config after path normalization injects the tenant segment",
              "conditions": [
                "OpenAPIPathNormalize(router) rewrote the request to /v1beta1/msp/tenants/{tenant_id}/discounts"
              ],
              "implementation": "getBillingCfgFromURI(c) -> billingconfig.BillingConfigModel.GetActiveBillingConfig(billingCfgStruct.TenantID)"
            },
            {
              "operation": "SELECT",
              "table": "discounts",
              "trigger": "List tenant-bound discounts rendered as MSP OpenAPI discounts",
              "conditions": [
                "OpenAPIPathNormalize(router) succeeded",
                "getBillingCfgFromURI(c) resolved billingCfgStruct.TenantID and billingCfgStruct.BillingConfigID"
              ],
              "implementation": "API.ListMspDiscounts(...) -> discount.Model.ListDiscountsConsoleView(billingCfgStruct.TenantID, billingCfgStruct.BillingConfigID) -> ListTenantDiscounts(...)"
            },
            {
              "operation": "SELECT",
              "table": "unit_filters",
              "trigger": "Load unit-filter metadata used to render MSP discount service names",
              "conditions": [
                "ListDiscountsConsoleView(...) loaded discount rows"
              ],
              "implementation": "ListTenantDiscounts / ListGlobalActiveDiscounts -> entity.NewDiscountQuerySet(db.GetDB().Preload(clause.Associations))"
            }
          ]
        }
      },
      "services": [
        {
          "name": "account-svc",
          "target_interface": "AccountAPIService.GetOpenAPIAccess",
          "operation_type": "grpc_unary",
          "conditions": [
            "Only when the request originally arrived through /v1beta1/msp/discounts without an embedded /tenants/{tenant_id} segment"
          ],
          "operations": [
            {
              "operation": "gRPC GetOpenAPIAccess",
              "trigger": "Resolve the tenant ID from the OpenAPI public key before OpenAPIPathNormalize rewrites the bare MSP discounts route",
              "conditions": [
                "OpenAPIPathNormalize(router) handled the request",
                "X-Auth-Type == openapi",
                "request path did not already contain /tenants/"
              ],
              "implementation": "middleware.OpenAPIPathNormalize(...) -> centralhandler.GetCentralHandler().GetTenantIdByOpenAPIAccess(apiKey) -> account.GetOpenAPIAccess(PublicKey=apiKey)"
            }
          ]
        }
      ]
    },
    "HTTP GET /v1beta1/msp/tenants/:tenant_id/credits": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only when the request already contains /tenants/{tenant_id} and billing-config resolution succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the active billing config for the tenant-scoped MSP credits request",
              "conditions": [
                "c.ShouldBindUri(&BillingCfgStruct{}) succeeded"
              ],
              "implementation": "getBillingCfgFromURI(c) -> billingconfig.BillingConfigModel.GetActiveBillingConfig(billingCfgStruct.TenantID)"
            },
            {
              "operation": "SELECT",
              "table": "credits_packages",
              "trigger": "List credit packages bound to the tenant billing config for the MSP OpenAPI response",
              "conditions": [
                "getBillingCfgFromURI(c) resolved billingCfgStruct.TenantID and billingCfgStruct.BillingConfigID"
              ],
              "implementation": "marketing.CreditsPackageModel.ListTenantCreditsPackages(billingCfgStruct.TenantID, billingCfgStruct.BillingConfigID)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /v1beta1/partners/swaggerDoc": {
      "infrastructure": {},
      "services": [
        {
          "name": "account-admin-api",
          "target_interface": "GET /api/v1/admin/uploaded/{path}",
          "operation_type": "http_get",
          "conditions": [
            "Only after partner OpenAPI middleware succeeds"
          ],
          "operations": [
            {
              "operation": "HTTP GET",
              "trigger": "Download the partner swagger document from the central uploaded-file endpoint",
              "conditions": [
                "config.Get().GetString(config.S3FileTCPNSwagger) is non-empty",
                "centralEnabled() == true"
              ],
              "implementation": "API.SwaggerDocOpenAPI() -> centralhandler.GetCentralHandler().DownloadFile(config.Get().GetString(config.S3FileTCPNSwagger)) -> getClient().RequestRaw(\"GET\", fmt.Sprintf(\"/uploaded/%s\", path), nil, nil)"
            }
          ]
        }
      ]
    },
    "HTTP GET /v1beta1/partners/userManualDoc": {
      "infrastructure": {},
      "services": [
        {
          "name": "account-admin-api",
          "target_interface": "GET /api/v1/admin/uploaded/{path}",
          "operation_type": "http_get",
          "conditions": [
            "Only after partner OpenAPI middleware succeeds"
          ],
          "operations": [
            {
              "operation": "HTTP GET",
              "trigger": "Download the partner user manual PDF from the central uploaded-file endpoint",
              "conditions": [
                "config.Get().GetString(config.S3FileTCPNUserManual) is non-empty",
                "centralEnabled() == true"
              ],
              "implementation": "API.UserManualOpenAPI() -> centralhandler.GetCentralHandler().DownloadFile(config.Get().GetString(config.S3FileTCPNUserManual)) -> getClient().RequestRaw(\"GET\", fmt.Sprintf(\"/uploaded/%s\", path), nil, nil)"
            }
          ]
        }
      ]
    },
    "HTTP GET /v1beta1/partners/credits": {
      "infrastructure": {
        "mysql": {
          "conditions": ["Always"],
          "operations": [
            {"operation": "SELECT", "table": "credits_packages", "trigger": "Query credits"},
            {"operation": "SELECT", "table": "partner_configs", "trigger": "Get partner config"}
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/payments/active": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant and billing-config resolution succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the active billing config used to look up the current active payment method",
              "conditions": [
                "c.ShouldBindUri(&BillingCfgStruct{}) succeeded"
              ],
              "implementation": "getBillingCfgFromURI(c)"
            },
            {
              "operation": "SELECT",
              "table": "payment_methods",
              "trigger": "Load the active payment method or decide to synthesize the default Stripe placeholder when no record exists",
              "conditions": [
                "getBillingCfgFromURI(c) resolved billingCfgStruct.TenantID and billingCfgStruct.BillingConfigID"
              ],
              "implementation": "paymentModel.GetActivePaymentMethod(billingCfgStruct.TenantID, billingCfgStruct.BillingConfigID)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/payments/types": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant and billing-config resolution succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the active billing config before checking MSP payment mode and enumerating stored payment methods",
              "conditions": [
                "c.ShouldBindUri(&BillingCfgStruct{}) succeeded"
              ],
              "implementation": "getBillingCfgFromURI(c)"
            },
            {
              "operation": "SELECT",
              "table": "payment_methods",
              "trigger": "Check whether the tenant is an MSP customer and load existing payment-method rows to derive payable payment types",
              "conditions": [
                "getBillingCfgFromURI(c) resolved billingCfgStruct.TenantID and billingCfgStruct.BillingConfigID"
              ],
              "implementation": "paymentModel.IsMspPayment(...) + paymentModel.ListPaymentMethods(billingCfgStruct.TenantID, billingCfgStruct.BillingConfigID)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP PUT /api/v1/billing/tenants/:tenant_id/payments/stripe/setup_intent/confirm": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant and billing-config resolution succeeds and a Stripe payment method is already provisioned"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the billing config used to select the tenant Stripe customer",
              "conditions": [
                "getTenantIDFromURI(c) succeeded"
              ],
              "implementation": "getBillingCfgFromURI(c)"
            },
            {
              "operation": "SELECT",
              "table": "payment_methods",
              "trigger": "Load the Stripe payment method and customer code needed to inspect attached cards",
              "conditions": [
                "getBillingCfgFromURI(c) resolved billingCfgStruct.BillingConfigID"
              ],
              "implementation": "getStripeProvider(tenantID, billingCfgStruct.BillingConfigID) -> paymentModel.GetPaymentMethodWithPaymentType(tenantID, billingConfigID, STRIPE)"
            },
            {
              "operation": "UPDATE",
              "table": "payment_methods",
              "trigger": "Sync the payable bit for the billing config after Stripe cards are visible",
              "conditions": [
                "handler.ListPaymentMethods(code) succeeded"
              ],
              "implementation": "paymentModel.SyncPayableByBillingConfigID(tenantID, billingCfgStruct.BillingConfigID)"
            },
            {
              "operation": "UPDATE",
              "table": "tenant_plans",
              "trigger": "Enable the tenant ondemand plan once card binding makes the billing config payable",
              "conditions": [
                "SyncPayableByBillingConfigID(...) succeeded"
              ],
              "implementation": "plan.TenantPlanModel.EnableTenantOnDemandPlanByBillingConfigID(tenantID, billingCfgStruct.BillingConfigID)"
            }
          ]
        }
      },
      "services": [
        {
          "name": "stripe-api",
          "target_interface": "GET /v1/payment_methods",
          "operation_type": "http_get",
          "conditions": [
            "Only when Stripe payment handling is enabled and the tenant has a Stripe payment method"
          ],
          "operations": [
            {
              "operation": "HTTP ListPaymentMethods",
              "trigger": "Inspect Stripe cards attached to the customer after setup intent confirmation",
              "conditions": [
                "getStripeProvider(...) succeeded"
              ],
              "implementation": "handler.ListPaymentMethods(code)"
            }
          ]
        },
        {
          "name": "stripe-api",
          "target_interface": "POST /v1/customers/:id",
          "operation_type": "http_post",
          "conditions": [
            "Only when exactly one Stripe card is attached after setup intent confirmation"
          ],
          "operations": [
            {
              "operation": "HTTP UpdateCustomer",
              "trigger": "Set the lone attached card as the default payment method",
              "conditions": [
                "len(methods) == 1"
              ],
              "implementation": "handler.SetPaymentMethodDefault(code, methods[0].ID) -> stripe.Customers.Update(userCode, InvoiceSettings.DefaultPaymentMethod=methodId)"
            }
          ]
        }
      ]
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/payments/stripe/customer": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant and billing-config resolution succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the billing config used to locate the tenant Stripe customer",
              "conditions": [
                "getTenantIDFromURI(c) succeeded"
              ],
              "implementation": "getBillingCfgFromURI(c)"
            },
            {
              "operation": "SELECT",
              "table": "payment_methods",
              "trigger": "Load the Stripe payment method and customer code used to fetch Stripe customer metadata",
              "conditions": [
                "getBillingCfgFromURI(c) resolved billingCfgStruct.BillingConfigID"
              ],
              "implementation": "getStripeProvider(tenantID, billingCfgStruct.BillingConfigID) -> paymentModel.GetPaymentMethodWithPaymentType(tenantID, billingConfigID, STRIPE)"
            }
          ]
        }
      },
      "services": [
        {
          "name": "stripe-api",
          "target_interface": "GET /v1/customers/:id",
          "operation_type": "http_get",
          "conditions": [
            "Only when Stripe payment handling is enabled and the tenant has a Stripe payment method"
          ],
          "operations": [
            {
              "operation": "HTTP GetCustomer",
              "trigger": "Fetch Stripe customer metadata and default card information",
              "conditions": [
                "getStripeProvider(...) succeeded"
              ],
              "implementation": "handler.GetCustomerInfo(code) -> stripe.Customers.Get(userCode, nil)"
            }
          ]
        }
      ]
    },
    "HTTP PUT /api/v1/billing/tenants/:tenant_id/payments/stripe/payment_methods/:payment_method_id/default": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant and billing-config resolution succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the billing config used to locate the tenant Stripe customer",
              "conditions": [
                "getTenantAndMethodFromURI(c) succeeded"
              ],
              "implementation": "getBillingCfgFromURI(c)"
            },
            {
              "operation": "SELECT",
              "table": "payment_methods",
              "trigger": "Load the Stripe payment method and customer code before updating the default payment method",
              "conditions": [
                "getBillingCfgFromURI(c) resolved billingCfgStruct.BillingConfigID"
              ],
              "implementation": "getStripeProvider(tenantID, billingCfgStruct.BillingConfigID) -> paymentModel.GetPaymentMethodWithPaymentType(tenantID, billingConfigID, STRIPE)"
            }
          ]
        }
      },
      "services": [
        {
          "name": "stripe-api",
          "target_interface": "GET /v1/payment_methods/:id",
          "operation_type": "http_get",
          "conditions": [
            "Only when Stripe payment handling is enabled"
          ],
          "operations": [
            {
              "operation": "HTTP GetPaymentMethod",
              "trigger": "Validate that the selected payment method belongs to the tenant Stripe customer before promoting it to default",
              "conditions": [
                "getStripeProvider(...) succeeded"
              ],
              "implementation": "handler.SetPaymentMethodDefault(code, methodID) -> handler.GetCustomerPaymentMethod(userCode, methodId)"
            }
          ]
        },
        {
          "name": "stripe-api",
          "target_interface": "POST /v1/customers/:id",
          "operation_type": "http_post",
          "conditions": [
            "Only when the selected payment method belongs to the tenant Stripe customer"
          ],
          "operations": [
            {
              "operation": "HTTP UpdateCustomer",
              "trigger": "Set the selected Stripe card as the customer's default payment method",
              "conditions": [
                "GetCustomerPaymentMethod(...) succeeded"
              ],
              "implementation": "stripe.Customers.Update(userCode, InvoiceSettings.DefaultPaymentMethod=methodId)"
            }
          ]
        }
      ]
    },
    "HTTP PUT /api/v1/billing/tenants/:tenant_id/payments/stripe/payment_methods/:payment_method_id/validate": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant and billing-config resolution succeeds and credit-card validation is enabled for the tenant"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the billing config used to locate the tenant Stripe customer",
              "conditions": [
                "c.ShouldBindUri(&TenantPaymentStruct{}) succeeded"
              ],
              "implementation": "getBillingCfgFromURI(c)"
            },
            {
              "operation": "SELECT",
              "table": "payment_methods",
              "trigger": "Load the Stripe payment method and customer code before card validation",
              "conditions": [
                "getBillingCfgFromURI(c) resolved billingCfgStruct.BillingConfigID"
              ],
              "implementation": "getStripeProvider(tenantID, billingConfigID) -> paymentModel.GetPaymentMethodWithPaymentType(tenantID, billingConfigID, STRIPE)"
            },
            {
              "operation": "SELECT",
              "table": "billing_companies",
              "trigger": "Check whether stored billing information is complete enough to skip Stripe-address validation",
              "conditions": [
                "EnableTaxCalculation == true",
                "IsCreditCardValidationRequired(tenantID) == true"
              ],
              "implementation": "paymentsub.BillingInformationModel.BillingInfoIsNotEmpty(tenantID)"
            },
            {
              "operation": "INSERT",
              "table": "credit_card_validate_refund_records",
              "trigger": "Create the async refund record when Stripe accepted the validation payment intent",
              "conditions": [
                "Init3DSPaymentIntent(...) returned a non-nil paymentIntent"
              ],
              "implementation": "CreditCardVerifyModel.CreateRefundRecord(entity.CreditCardValidateCancelStatus_Init, tenantID, paymentIntent.ID, decimal.NewFromInt(100))"
            }
          ]
        }
      },
      "services": [
        {
          "name": "account-svc",
          "target_interface": "AccountAPIService.GetOrgByID",
          "operation_type": "grpc_unary",
          "conditions": [
            "Only when credit-card validation is enabled for the tenant and compliance checks must inspect tenant kind/email"
          ],
          "operations": [
            {
              "operation": "gRPC GetOrgByID",
              "trigger": "Load tenant profile for internal-user and restricted-domain compliance checks",
              "conditions": [
                "IsCreditCardValidationRequired(tenantID) == true"
              ],
              "implementation": "CreditCardVerifyModel.ComplianceCheck(tenantID) -> centralhandler.GetCentralHandler().GetTenant(tenantID) -> account.GetOrgByID(IsBrief=false)"
            }
          ]
        },
        {
          "name": "stripe-api",
          "target_interface": "GET /v1/payment_methods/:id",
          "operation_type": "http_get",
          "conditions": [
            "Only when credit-card validation remains enabled after compliance checks"
          ],
          "operations": [
            {
              "operation": "HTTP GetPaymentMethod",
              "trigger": "Load the Stripe payment method and card brand/details before validation",
              "conditions": [
                "getStripeProvider(...) succeeded"
              ],
              "implementation": "stripeHandler.GetPaymentMethod(paymentMethodID)"
            }
          ]
        },
        {
          "name": "stripe-api",
          "target_interface": "POST /v1/payment_intents",
          "operation_type": "http_post",
          "conditions": [
            "Only when the payment method is a supported card brand and address validation passes when tax validation is enabled"
          ],
          "operations": [
            {
              "operation": "HTTP CreatePaymentIntent",
              "trigger": "Create the 100-cent validation payment intent used for 3DS / card verification",
              "conditions": [
                "methodInfo.Card != nil",
                "isSupportedCardBrand(methodInfo.Card.Brand) == true"
              ],
              "implementation": "stripeHandler.Init3DSPaymentIntent(decimal.NewFromInt(100), paymentMethodID, customerID)"
            }
          ]
        }
      ]
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/invoices/:invoice_id": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant, billing-config, and invoice path binding all succeed"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the billing config used to scope the tenant invoice lookup",
              "conditions": [
                "c.ShouldBindUri(&BillingCfgStruct{}) succeeded"
              ],
              "implementation": "getBillingCfgFromURI(c)"
            },
            {
              "operation": "SELECT",
              "table": "invoices",
              "trigger": "Load the requested tenant invoice entity before hydrating costs and tax metadata",
              "conditions": [
                "getInvoiceURIParams(c) succeeded"
              ],
              "implementation": "invoiceModel.GetTenantInvoice(billingCfgStruct.TenantID, billingCfgStruct.BillingConfigID, invoiceURI.InvoiceID)"
            },
            {
              "operation": "SELECT",
              "table": "user_unit_costs",
              "trigger": "Hydrate detailed invoice costs for non-commitment and non-subordinated invoices",
              "conditions": [
                "invoiceFromEntityWithCosts(...) handled an invoice whose type is neither COMMITMENT nor SUBORDINATED"
              ],
              "implementation": "invoiceFromEntityWithCosts(...) -> CostExplorerModel.GetInvoiceCosts(invoiceEntity.TenantID, invoiceEntity.BindedBillingConfigID, invoiceEntity.ID, false)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP PUT /api/v1/billing/tenants/:tenant_id/invoices/:invoice_id/send": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant, billing-config, and invoice path binding all succeed"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the billing config used to scope the tenant invoice lookup and payment attempt",
              "conditions": [
                "c.ShouldBindUri(&BillingCfgStruct{}) succeeded"
              ],
              "implementation": "getBillingCfgFromURI(c)"
            },
            {
              "operation": "SELECT",
              "table": "invoices",
              "trigger": "Load the target invoice and re-read it during the send flow",
              "conditions": [
                "getInvoiceURIParams(c) succeeded"
              ],
              "implementation": "invoiceModel.SendInvoice(...) -> GetTenantInvoice(...) + sendInvoice(invoiceID) -> GetInvoice(invoiceID)"
            },
            {
              "operation": "SELECT",
              "table": "payment_methods",
              "trigger": "Resolve the active payment method and invoiceable flag before paying the invoice",
              "conditions": [
                "invoice status allows sendInvoice(...) to proceed"
              ],
              "implementation": "paymentsub.PaymentModel.BillingConfigInvoiceable(info.TenantID, *info.BindedBillingConfigID) + paymentsub.PaymentModel.Pay(tenantID, billingConfigID, *info)"
            },
            {
              "operation": "UPDATE",
              "table": "invoices",
              "trigger": "Persist sent-date, payment method, payment type/code, channel loss, and final status after provider payment succeeds",
              "conditions": [
                "PaymentModel.Pay(...) returned paid invoices"
              ],
              "implementation": "InvoiceModel.UpdateSentInvoices(result)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP PUT /api/v1/billing/tenants/:tenant_id/invoices/:invoice_id/suspend": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after invoice path binding succeeds and the invoice is still in GENERATED status"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "invoices",
              "trigger": "Load the invoice to validate that only generated invoices can be suspended",
              "conditions": [
                "getInvoiceURIParams(c) succeeded"
              ],
              "implementation": "invoiceModel.SuspendInvoice(invoiceURI.InvoiceID) -> GetInvoice(invoiceID)"
            },
            {
              "operation": "INSERT",
              "table": "audit_records",
              "trigger": "Persist the suspend-invoice audit record inside the suspension transaction",
              "conditions": [
                "info.Status == GENERATED"
              ],
              "implementation": "entity.AuditRecord{Action: SuspendInvoice, ...}.Create(tx)"
            },
            {
              "operation": "UPDATE",
              "table": "invoices",
              "trigger": "Mark the invoice suspended inside the suspension transaction",
              "conditions": [
                "info.Status == GENERATED"
              ],
              "implementation": "entity.NewInvoiceQuerySet(db.GetDB()).IDEq(invoiceID).GetUpdater().SetStatus(SUSPENDED).Update()"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/tenants/:tenant_id/invoices/:invoice_id/resend": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after invoice path binding succeeds and the tenant ID matches the invoice owner"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "invoices",
              "trigger": "Load the invoice before resetting its status back to CONFIRMED",
              "conditions": [
                "getInvoiceURIParams(c) succeeded"
              ],
              "implementation": "invoiceModel.ReSendInvoice(invoiceURI.TenantID, invoiceURI.InvoiceID) -> GetInvoice(invoiceID)"
            },
            {
              "operation": "UPDATE",
              "table": "invoices",
              "trigger": "Reset the invoice status to CONFIRMED so later send flows can retry delivery",
              "conditions": [
                "tenantID == invoice.TenantID"
              ],
              "implementation": "entity.NewInvoiceQuerySet(db.GetDB()).TenantIDEq(tenantID).IDEq(invoiceID).GetUpdater().SetStatus(CONFIRMED).Update()"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP DELETE /api/v1/billing/tenants/:tenant_id/invoices/:invoice_id": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after invoice path binding succeeds and the invoice has not already been sent or paid"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "invoices",
              "trigger": "Load the invoice and validate that sent/paid invoices cannot be deleted",
              "conditions": [
                "getInvoiceURIParams(c) succeeded"
              ],
              "implementation": "invoiceModel.DeleteInvoice(invoiceURI.InvoiceID) -> GetInvoice(invoiceID)"
            },
            {
              "operation": "UPDATE",
              "table": "measures",
              "trigger": "Unbind invoice references from costs before deleting the invoice row",
              "conditions": [
                "invoice.Status not in {SENT, PAID}"
              ],
              "implementation": "billing.MeasureModel.CostsUnBindInvoice(invoice.TenantID, invoiceID)"
            },
            {
              "operation": "DELETE",
              "table": "invoices",
              "trigger": "Delete the invoice row after invoice-cost unbinding succeeds",
              "conditions": [
                "CostsUnBindInvoice(...) succeeded"
              ],
              "implementation": "entity.NewInvoiceQuerySet(db.GetDB()).IDEq(invoiceID).TenantIDEq(tenantID).Delete()"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/credits_summary": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant and billing-config resolution succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the billing config used to scope the tenant credit summary",
              "conditions": [
                "c.ShouldBindUri(&BillingCfgStruct{}) succeeded"
              ],
              "implementation": "getBillingCfgFromURI(c)"
            },
            {
              "operation": "SELECT",
              "table": "credits_packages",
              "trigger": "Aggregate the tenant's credit package summary for the resolved billing config",
              "conditions": [
                "getBillingCfgFromURI(c) resolved billingCfgStruct.TenantID and billingCfgStruct.BillingConfigID"
              ],
              "implementation": "marketing.CreditsPackageModel.GetTenantCreditsSummary(billingCfgStruct.TenantID, billingCfgStruct.BillingConfigID)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/tenants/:tenant_id/credits/:credit_id": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant and credit path binding succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "credits_packages",
              "trigger": "Load the requested credit package details for the tenant",
              "conditions": [
                "credit_id path parameter parsed successfully"
              ],
              "implementation": "marketing.CreditsPackageModel.GetCreditsPackage(creditIDStruct.CreditID)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/tenants/:tenant_id/credits/:credit_id/actions/reclaim": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant and credit path binding succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "credits_packages",
              "trigger": "Load the credit package before reclaiming it",
              "conditions": [
                "credit_id path parameter parsed successfully"
              ],
              "implementation": "marketing.CreditsPackageModel.GetCreditsPackage(creditIDStruct.CreditID)"
            },
            {
              "operation": "UPDATE",
              "table": "credits_packages",
              "trigger": "Mark the credit package reclaimed and closed",
              "conditions": [
                "GetCreditsPackage(...) succeeded"
              ],
              "implementation": "marketing.CreditsPackageModel.CloseCreditsPackage(creditIDStruct.CreditID, entity.CreditsPackageClosedReason_Reclaimed)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/contracts/:contract_id": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant and contract path binding succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "contracts",
              "trigger": "Load the requested contract for the tenant",
              "conditions": [
                "contract_id path parameter parsed successfully"
              ],
              "implementation": "billing.ContractModel.GetContract(contractURIArgs.TenantID, contractURIArgs.ContractID)"
            }
          ]
        },
        "s3": {
          "conditions": [
            "Only when the returned contract references an uploaded file"
          ],
          "operations": [
            {
              "operation": "GET",
              "trigger": "Fetch the contract attachment linked from the stored contract metadata",
              "conditions": [
                "GetContract(...) returned a contract with file metadata"
              ]
            }
          ]
        }
      },
      "services": []
    },
    "HTTP PUT /api/v1/billing/tenants/:tenant_id/contracts/:contract_id": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant and contract path binding succeeds and the request body binds successfully"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "contracts",
              "trigger": "Load the existing contract before applying field updates",
              "conditions": [
                "contract_id path parameter parsed successfully"
              ],
              "implementation": "billing.ContractModel.UpdateContract(contractURIArgs.TenantID, contractURIArgs.ContractID, contract)"
            },
            {
              "operation": "UPDATE",
              "table": "contracts",
              "trigger": "Persist the updated contract fields",
              "conditions": [
                "ShouldBindJSON(contract) succeeded"
              ],
              "implementation": "billing.ContractModel.UpdateContract(contractURIArgs.TenantID, contractURIArgs.ContractID, contract)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/tenants/:tenant_id/contracts/:contract_id/actions/:action": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant, contract, and action path binding succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "contracts",
              "trigger": "Load the contract and validate the admin action against current contract state",
              "conditions": [
                "action in {create, submit, cancel, delete, terminate}"
              ],
              "implementation": "billing.ContractModel.OperateContractByAdmin(operateArgs.TenantID, &contractAction)"
            },
            {
              "operation": "UPDATE",
              "table": "contracts",
              "trigger": "Persist the admin action's contract state transition",
              "conditions": [
                "OperateContractByAdmin(...) accepted the requested action"
              ],
              "implementation": "billing.ContractModel.OperateContractByAdmin(operateArgs.TenantID, &contractAction)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/tenants/:tenant_id/billing_info/sync_on_card_binding": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant path binding succeeds and the billing-info request body validates"
          ],
          "operations": [
            {
              "operation": "INSERT",
              "table": "billing_companies",
              "trigger": "Create the default tenant billing profile on the first successful card-binding sync",
              "conditions": [
                "No default billing info exists for the tenant"
              ],
              "implementation": "paymentsub.BillingInformationModel.CreateDefaultBillingInfo(tenantID, info)"
            },
            {
              "operation": "UPDATE",
              "table": "billing_companies",
              "trigger": "Update the tenant's default billing profile from the card-binding payload when one already exists",
              "conditions": [
                "A default billing info row already exists for the tenant"
              ],
              "implementation": "paymentsub.BillingInformationModel.CreateDefaultBillingInfo(tenantID, info)"
            },
            {
              "operation": "SELECT",
              "table": "billing_companies",
              "trigger": "Re-read the tenant billing profile after sync",
              "conditions": [
                "CreateDefaultBillingInfo(...) finished"
              ],
              "implementation": "paymentsub.BillingInformationModel.GetBillingInfo(tenantID)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP PUT /api/v1/billing/support_plan/:support_plan_id": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after support_plan_id path binding succeeds and the request body binds successfully"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "support_plans",
              "trigger": "Load the support plan before enforcing that only public plans can be updated here",
              "conditions": [
                "support_plan_id path parameter parsed successfully"
              ],
              "implementation": "marketing.SupportPlanModel.GetSupportPlan(supportPlanURIStruct.SupportPlanID)"
            },
            {
              "operation": "UPDATE",
              "table": "support_plans",
              "trigger": "Persist updates to the public support plan",
              "conditions": [
                "info.Public == true"
              ],
              "implementation": "marketing.SupportPlanModel.UpdateSupportPlan(supportPlanURIStruct.SupportPlanID, input)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/budgets/:budget_id": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant and budget path binding succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "spend_limit_settings",
              "trigger": "Load the requested spend-limit setting that backs the budget",
              "conditions": [
                "budget_id path parameter parsed successfully"
              ],
              "implementation": "spend_limit.SpendLimitModel.GetSpendLimitSetting(query.TenantID, query.BudgetID)"
            },
            {
              "operation": "SELECT",
              "table": "spend_limit_alert_thresholds",
              "trigger": "Load thresholds when converting the spend-limit setting into a budget view",
              "conditions": [
                "GetSpendLimitSetting(...) succeeded"
              ],
              "implementation": "SpendLimitModel.SpendingLimitToBudgetView(*setting)"
            },
            {
              "operation": "SELECT",
              "table": "user_unit_costs",
              "trigger": "Hydrate current budget cost usage while rendering the budget view",
              "conditions": [
                "The spend-limit setting is not a free-quota-only budget"
              ],
              "implementation": "SpendLimitModel.SpendLimitSettingWithCost(...) -> CostExplorerModel.GetMonthlyCost / GetProjectMonthlyCost / GetClusterMonthlyCost / GetCustomerMonthlyCost"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP PUT /api/v1/billing/tenants/:tenant_id/budgets/:budget_id": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant and budget path binding succeeds and the request body binds successfully"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "spend_limit_settings",
              "trigger": "Load the existing spend-limit setting before applying mutable budget updates",
              "conditions": [
                "budget_id path parameter parsed successfully"
              ],
              "implementation": "spend_limit.SpendLimitModel.GetSpendLimitSetting(query.TenantID, query.BudgetID)"
            },
            {
              "operation": "UPDATE",
              "table": "spend_limit_alert_thresholds",
              "trigger": "Replace thresholds when the update payload carries a non-empty threshold list",
              "conditions": [
                "len(params.Thresholds) != 0"
              ],
              "implementation": "SpendLimitModel.UpdateThresholds(query.TenantID, query.BudgetID, params.Thresholds)"
            },
            {
              "operation": "UPDATE",
              "table": "spend_limit_settings",
              "trigger": "Persist mutable fields such as name, limit, range, and biz data",
              "conditions": [
                "spendingLimit.BizType == Normal"
              ],
              "implementation": "SpendLimitModel.UpdateSpendLimitSettings(query.TenantID, query.BudgetID, spendingLimit)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP DELETE /api/v1/billing/tenants/:tenant_id/budgets/:budget_id": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant and budget path binding succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "spend_limit_settings",
              "trigger": "Load the spend-limit setting before validating that only normal budgets can be deleted here",
              "conditions": [
                "budget_id path parameter parsed successfully"
              ],
              "implementation": "spend_limit.SpendLimitModel.GetSpendLimitSetting(query.TenantID, query.BudgetID)"
            },
            {
              "operation": "UPDATE",
              "table": "spend_limit_settings",
              "trigger": "Deprecate and clear the biz-unique key before deleting the budget backing row",
              "conditions": [
                "spendingLimit.BizType == Normal"
              ],
              "implementation": "SpendLimitModel.DeleteSpendLimitSetting(query.TenantID, query.BudgetID)"
            },
            {
              "operation": "DELETE",
              "table": "spend_limit_settings",
              "trigger": "Delete the budget backing row after the deprecation transition succeeds",
              "conditions": [
                "DeleteSpendLimitSetting(...) reached query.Delete()"
              ],
              "implementation": "SpendLimitModel.DeleteSpendLimitSetting(query.TenantID, query.BudgetID)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/tenants/:tenant_id/budgets/:budget_id/thresholds": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant and budget path binding succeeds and the threshold payload validates"
          ],
          "operations": [
            {
              "operation": "INSERT",
              "table": "spend_limit_alert_thresholds",
              "trigger": "Create a new threshold row under the target budget",
              "conditions": [
                "ShouldBindJSON(threshold) succeeded"
              ],
              "implementation": "SpendLimitModel.CreateTenantSpendingLimitThreshold(query.TenantID, query.BudgetID, threshold)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP DELETE /api/v1/billing/tenants/:tenant_id/budgets/:budget_id/thresholds/:threshold_id": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant, budget, and threshold path binding succeeds"
          ],
          "operations": [
            {
              "operation": "DELETE",
              "table": "spend_limit_alert_thresholds",
              "trigger": "Delete the selected threshold row from the target budget",
              "conditions": [
                "threshold_id path parameter parsed successfully"
              ],
              "implementation": "SpendLimitModel.DeleteTenantThreshold(query.TenantID, query.BudgetID, query.ThresholdID)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/costexplorer/enabled": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant and billing-config resolution succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the billing config and inspect its partner-managed type before deciding whether bills view is enabled",
              "conditions": [
                "c.ShouldBindUri(&BillingCfgStruct{}) succeeded"
              ],
              "implementation": "getBillingCfgFromURI(c) + isBillsEnabled(tenantID, billingConfigID) -> billingconfig.BillingConfigModel.GetBillingConfig(billingConfigID)"
            },
            {
              "operation": "SELECT",
              "table": "partner_configs",
              "trigger": "Load partner-customer visibility flags for MSP/resale managed customers",
              "conditions": [
                "billingConfigs.Type in {MSPCustomer, ResaleCustomer, MarketplaceResellerManagedCustomer}"
              ],
              "implementation": "partner.Configs.GetCustomerPartnerConfigs(partnerID, billingConfigs.TenantID)"
            }
          ]
        }
      },
      "services": [
        {
          "name": "account-svc",
          "target_interface": "AccountAPIService.GetOrgByID",
          "operation_type": "grpc_unary",
          "conditions": [
            "Only when partnerID must be derived from the tenant profile of an MSP/resale customer"
          ],
          "operations": [
            {
              "operation": "gRPC GetOrgByID",
              "trigger": "Load tenant metadata so isBillsEnabled can derive partner ownership from ThirdPartyAccountCode",
              "conditions": [
                "billingConfigs.Type in {MSPCustomer, ResaleCustomer}"
              ],
              "implementation": "centralhandler.GetCentralHandler().GetTenant(tenantID) -> account.GetOrgByID(IsBrief=false)"
            }
          ]
        }
      ]
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/costexplorer/monthly_cost/year/:year/month/:month": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant/year/month binding succeeds, bills visibility checks pass, and the tenant is not hidden by MonthlyBillsInvisibleList"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the billing config and bill-visibility gates before reading monthly cost data",
              "conditions": [
                "c.ShouldBindUri(&MonthlyCostURI{}) succeeded"
              ],
              "implementation": "getBillingCfgFromURI(c) + isBillsEnabled(billingCfgStruct.TenantID, billingCfgStruct.BillingConfigID)"
            },
            {
              "operation": "SELECT",
              "table": "user_unit_costs",
              "trigger": "Load the requested month's aggregated cost result, choosing the big-customer or normal cache path",
              "conditions": [
                "MonthlyBillsInvisibleList did not hide the tenant/billingConfig pair"
              ],
              "implementation": "CostExplorerModel.GetMonthlyCostFromCache(...) or GetMonthlyCostWithCache(...)"
            },
            {
              "operation": "SELECT",
              "table": "invoices",
              "trigger": "Check whether the previous month's monthly invoice has already been generated",
              "conditions": [
                "Monthly cost query succeeded"
              ],
              "implementation": "payment.InvoiceModel.GetMonthlyInvoice(tenantID, billingCfgStruct.BillingConfigID, lastMonthDate)"
            }
          ]
        },
        "redis": {
          "conditions": [
            "Always around monthly cost cache lookups"
          ],
          "operations": [
            {
              "operation": "GET",
              "trigger": "Try the appropriate monthly cost cache before recomputing from DB",
              "conditions": [
                "isBigCustomer chooses GetMonthlyCostFromCache(...) or GetMonthlyCostWithCache(...)"
              ],
              "implementation": "cachehandler.Get().Get(\"GetMonthlyCostFromCache\", ...) / cachehandler.Get().Get(\"GetMonthlyCostWithCache\", ...)"
            },
            {
              "operation": "SET",
              "trigger": "Cache the monthly cost result after DB aggregation succeeds",
              "conditions": [
                "GetMonthlyCostFromCache(...) or GetMonthlyCostWithCache(...) missed and recomputed"
              ],
              "implementation": "cachehandler.Get().SetWithTimeOut(...) / cachehandler.Get().Set(...)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/costexplorer/bills_details/year/:year/month/:month": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant/year/month binding succeeds, BillsInvisibleList does not hide the tenant, and bills visibility checks pass"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the billing config and bill-visibility gate before querying bill details",
              "conditions": [
                "c.ShouldBindUri(&MonthlyCostURI{}) succeeded"
              ],
              "implementation": "getBillingConfigIDFromURI(c) + isBillsEnabled(input.TenantID, billingConfigID)"
            },
            {
              "operation": "SELECT",
              "table": "user_unit_costs",
              "trigger": "Load grouped daily usage details for the requested month",
              "conditions": [
                "Bills visibility checks passed"
              ],
              "implementation": "CostExplorerModel.GetBillsDetailsWithCache(tenantID, billingConfigID, input.Year, input.Month)"
            }
          ]
        },
        "redis": {
          "conditions": [
            "Always around bill-details cache lookups"
          ],
          "operations": [
            {
              "operation": "GET",
              "trigger": "Try the cached detailed bill rows before recomputing them",
              "conditions": [
                "GetBillsDetailsWithCache(...) is reached"
              ],
              "implementation": "cachehandler.Get().Get(\"GetBillsDetailsWithCache\", ...)"
            },
            {
              "operation": "SET",
              "trigger": "Cache the detailed bill rows after DB aggregation succeeds",
              "conditions": [
                "GetBillsDetails(...) succeeded"
              ],
              "implementation": "cachehandler.Get().Set(\"GetBillsDetailsWithCache\", ...)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/tenants/:tenant_id/costexplorer/trends/csv": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant and billing-config resolution succeeds, bills visibility checks pass, and parseTrendsQuery validates the requested date range"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the billing config and bill-visibility gates before running the trends CSV query",
              "conditions": [
                "getBillingCfgFromURI(c) succeeded"
              ],
              "implementation": "getBillingCfgFromURI(c) + isBillsEnabled(tenantID, billingConfigID)"
            },
            {
              "operation": "SELECT",
              "table": "user_unit_costs",
              "trigger": "Run the trends aggregation that backs the CSV export",
              "conditions": [
                "parseTrendsQuery(c, tenantID, false) succeeded"
              ],
              "implementation": "costexplorer.CostTrendsCSV(tenantID, billingConfigID, query)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/tenants/:tenant_id/costexplorer/monthly_cost/year/:year/month/:month/export": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant/year/month binding succeeds and bills visibility checks pass"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the billing config and visibility gates before exporting monthly cost CSV",
              "conditions": [
                "c.ShouldBindUri(&MonthlyCostURI{}) succeeded"
              ],
              "implementation": "getBillingConfigIDFromURI(c) + isBillsEnabled(tenantID, billingConfigID)"
            },
            {
              "operation": "SELECT",
              "table": "user_unit_costs",
              "trigger": "Load the monthly aggregated cost result used to build the export CSV",
              "conditions": [
                "Bills visibility checks passed"
              ],
              "implementation": "CostExplorerModel.GetMonthlyCostWithCache(tenantID, billingConfigID, input.Year, input.Month)"
            }
          ]
        },
        "redis": {
          "conditions": [
            "Always around monthly-cost export cache lookups"
          ],
          "operations": [
            {
              "operation": "GET",
              "trigger": "Reuse the cached monthly cost result for the export path",
              "conditions": [
                "GetMonthlyCostWithCache(...) is reached"
              ],
              "implementation": "cachehandler.Get().Get(\"GetMonthlyCostWithCache\", ...)"
            },
            {
              "operation": "SET",
              "trigger": "Cache the monthly cost result after DB aggregation succeeds",
              "conditions": [
                "GetMonthlyCost(...) succeeded"
              ],
              "implementation": "cachehandler.Get().Set(\"GetMonthlyCostWithCache\", ...)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/tenants/:tenant_id/costexplorer/monthly_bills/year/:year/month/:month/export": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant/year/month binding succeeds, BillsInvisibleList does not hide the tenant, and bills visibility checks pass"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the billing config and bill-visibility gates before exporting monthly bill details",
              "conditions": [
                "c.ShouldBindUri(&MonthlyCostURI{}) succeeded"
              ],
              "implementation": "getBillingConfigIDFromURI(c) + isBillsEnabled(tenantID, billingConfigID)"
            },
            {
              "operation": "SELECT",
              "table": "user_unit_costs",
              "trigger": "Load export-grade usage detail rows for the requested month",
              "conditions": [
                "Bills visibility checks passed"
              ],
              "implementation": "CostExplorerModel.GetExportBillsDetailsWithCache(tenantID, billingConfigID, input.Year, input.Month)"
            }
          ]
        },
        "redis": {
          "conditions": [
            "Always around export-bills-detail cache lookups"
          ],
          "operations": [
            {
              "operation": "GET",
              "trigger": "Reuse cached export bill details before recomputing them",
              "conditions": [
                "GetExportBillsDetailsWithCache(...) is reached"
              ],
              "implementation": "cachehandler.Get().Get(\"GetBillsDetailsWithCache\", ...) / export-details cache path"
            }
          ]
        }
      },
      "services": [
        {
          "name": "account-svc",
          "target_interface": "AccountAPIService.GetOrgByID",
          "operation_type": "grpc_unary",
          "conditions": [
            "Always after bill visibility checks pass"
          ],
          "operations": [
            {
              "operation": "gRPC GetOrgByID",
              "trigger": "Load tenant display name for the bill-export CSV header",
              "conditions": [
                "tenantID resolved from path"
              ],
              "implementation": "centralhandler.GetCentralHandler().GetTenant(tenantID) -> account.GetOrgByID(IsBrief=false)"
            }
          ]
        }
      ]
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/costexplorer/monthly_usage/app/:app_name/apps/:app_id/year/:year/month/:month": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant/app/year/month path binding succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "user_unit_costs",
              "trigger": "Load internal usage rows for the specified app and aggregate them into per-usage buckets",
              "conditions": [
                "GetMonthlyAppUsageWithCache(...) missed"
              ],
              "implementation": "UsageExplorerModel.GetMonthlyAppUsage(...) -> db.GetDB().Raw(sqlQuery, params).Find(&allCosts)"
            }
          ]
        },
        "redis": {
          "conditions": [
            "Always around monthly app-usage cache lookups"
          ],
          "operations": [
            {
              "operation": "GET",
              "trigger": "Reuse cached app usage for the same tenant/app/month tuple",
              "conditions": [
                "GetMonthlyAppUsageWithCache(...) is reached"
              ],
              "implementation": "cachehandler.Get().Get(\"GetMonthlyAppUsageWithCache\", ...)"
            },
            {
              "operation": "SET",
              "trigger": "Cache the aggregated app usage after DB aggregation succeeds",
              "conditions": [
                "GetMonthlyAppUsage(...) succeeded"
              ],
              "implementation": "cachehandler.Get().Set(\"GetMonthlyAppUsageWithCache\", ...)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/costexplorer/monthly_usage/dataapi/apps/:app_id/year/:year/month/:month": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant/app/year/month path binding succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "user_unit_costs",
              "trigger": "Load internal DataAPI usage rows for the specified app and aggregate request/network usage",
              "conditions": [
                "GetMonthlyAppUsageWithCache(...) missed"
              ],
              "implementation": "UsageExplorerModel.GetMonthlyAppUsage(...) -> db.GetDB().Raw(sqlQuery, params).Find(&allCosts)"
            }
          ]
        },
        "redis": {
          "conditions": [
            "Always around monthly DataAPI usage cache lookups"
          ],
          "operations": [
            {
              "operation": "GET",
              "trigger": "Reuse cached DataAPI usage for the same tenant/app/month tuple",
              "conditions": [
                "GetMonthlyAppUsageWithCache(...) is reached"
              ],
              "implementation": "cachehandler.Get().Get(\"GetMonthlyAppUsageWithCache\", ...)"
            },
            {
              "operation": "SET",
              "trigger": "Cache the aggregated DataAPI usage after DB aggregation succeeds",
              "conditions": [
                "GetMonthlyAppUsage(...) succeeded"
              ],
              "implementation": "cachehandler.Get().Set(\"GetMonthlyAppUsageWithCache\", ...)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/marketplace/azure/subscriptions/:payment_code": {
      "infrastructure": {},
      "services": [
        {
          "name": "azure-marketplace-api",
          "target_interface": "GET /subscriptions",
          "operation_type": "http_get",
          "conditions": [
            "Only after payment_code path binding succeeds and the Azure marketplace handler initializes successfully"
          ],
          "operations": [
            {
              "operation": "HTTP ListSubscriptions",
              "trigger": "List Azure marketplace subscriptions filtered by the provided payment code",
              "conditions": [
                "cloudmarketplacehandler.GetMarketplaceHandler().GetMarketplace(AZURE) succeeded"
              ],
              "implementation": "handler.GetSubscriptionsByAzureSubscriptionID(paymentCode.PaymentCode, false)"
            }
          ]
        }
      ]
    },
    "HTTP DELETE /api/v1/billing/marketplace/tenants/:tenant_id/azure/subscriptions/:subscription_id": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant and subscription path binding succeeds and the existing Azure payment method matches the subscription ID in the path"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "payment_methods",
              "trigger": "Load the tenant Azure payment method and verify that the request is canceling the currently bound subscription",
              "conditions": [
                "getBillingConfigIDFromURI(c) resolved billingConfigID"
              ],
              "implementation": "paymentModel.GetPaymentMethodWithPaymentType(subscriptionStruct.TenantID, billingConfigID, entity.PaymentType_AZURE)"
            }
          ]
        }
      },
      "services": [
        {
          "name": "azure-marketplace-api",
          "target_interface": "DELETE /subscriptions/{subscriptionId}",
          "operation_type": "http_delete",
          "conditions": [
            "Only when oldPaymentMethod.PaymentCode == subscriptionStruct.SubscriptionId"
          ],
          "operations": [
            {
              "operation": "HTTP CancelSubscription",
              "trigger": "Cancel the currently bound Azure marketplace subscription",
              "conditions": [
                "payment method verification succeeded"
              ],
              "implementation": "handler.CancelSubscription(subscriptionStruct.SubscriptionId)"
            }
          ]
        }
      ]
    },
    "HTTP GET /api/v1/unc/tenants/:tenant_id/notifications/:query_type/page/:page/page_size/:page_size": {
      "infrastructure": {},
      "services": [
        {
          "name": "novu-api",
          "target_interface": "POST /v1/subscribers/bulk",
          "operation_type": "http_post",
          "conditions": [
            "Always before querying the subscriber feed"
          ],
          "operations": [
            {
              "operation": "HTTP CreateSubscribers",
              "trigger": "Ensure the tenant-user subscriber exists before querying Novu feed endpoints",
              "conditions": [
                "subscriberID derived from tenant_id and current user ID"
              ],
              "implementation": "novuhandler.Get().CreateSubscribers([]map[string]string{{\"subscriberId\": subscriberID}})"
            }
          ]
        },
        {
          "name": "novu-api",
          "target_interface": "GET /v1/subscribers/{subscriberId}/notifications/feed",
          "operation_type": "http_get",
          "conditions": [
            "Always after subscriber bootstrap"
          ],
          "operations": [
            {
              "operation": "HTTP GetNotificationsFeed",
              "trigger": "Fetch the current user's in-app notification feed page from Novu",
              "conditions": [
                "request.Page converted to zero-based offset",
                "request.QueryType optionally sets seen=true/false"
              ],
              "implementation": "novuhandler.Get().GetSubscriberInAppNotifications(request) -> GetClient().Get(path, input, &resp)"
            }
          ]
        },
        {
          "name": "novu-api",
          "target_interface": "GET /v1/subscribers/{subscriberId}/notifications/unseen",
          "operation_type": "http_get",
          "conditions": [
            "Always after feed retrieval when the total count must be returned to the client"
          ],
          "operations": [
            {
              "operation": "HTTP GetNotificationsCount",
              "trigger": "Fetch seen/unseen counters to fill the notification count in the response",
              "conditions": [
                "GetSubscriberInAppNotifications(...) reached GetNotificationsCount(...)"
              ],
              "implementation": "NovuHandlerImpl.GetNotificationsCount(subscriberID, request.QueryType)"
            }
          ]
        }
      ]
    },
    "HTTP GET /api/v1/unc/tenants/:tenant_id/notifications/notification_id/:notification_id": {
      "infrastructure": {},
      "services": [
        {
          "name": "novu-api",
          "target_interface": "GET /v1/subscribers/{subscriberId}/notifications/feed",
          "operation_type": "http_get",
          "conditions": [
            "Always after tenant and notification path binding succeeds"
          ],
          "operations": [
            {
              "operation": "HTTP GetNotificationsFeed",
              "trigger": "Scan paged Novu feed results until the requested notification ID is found or feed exhaustion proves it absent",
              "conditions": [
                "subscriberID derived from tenant_id and current user ID"
              ],
              "implementation": "novuhandler.Get().GetSubscriberInAppNotificationByID(request) -> repeated GetClient().Get(path, {page, limit}, &resp)"
            }
          ]
        }
      ]
    },
    "HTTP POST /api/v1/unc/tenants/:tenant_id/notifications/:type/notification_id/:notification_id": {
      "infrastructure": {},
      "services": [
        {
          "name": "novu-api",
          "target_interface": "POST /v1/subscribers/{subscriberId}/messages/markAs",
          "operation_type": "http_post",
          "conditions": [
            "Only when the request targets a specific notification rather than the all/all shortcut"
          ],
          "operations": [
            {
              "operation": "HTTP MarkAsSeen",
              "trigger": "Mark the specified Novu message seen for the current tenant-user subscriber",
              "conditions": [
                "request.Type != \"all\" or request.NotificationID != \"all\""
              ],
              "implementation": "novuhandler.Get().MarkMessagesAsSeen(request) -> GetClient().Request(\"POST\", \"/v1/subscribers/{subscriberId}/messages/markAs\", nil, input, nil)"
            }
          ]
        },
        {
          "name": "novu-api",
          "target_interface": "POST /v1/subscribers/{subscriberId}/messages/mark-all",
          "operation_type": "http_post",
          "conditions": [
            "Only when the request uses the all/all shortcut"
          ],
          "operations": [
            {
              "operation": "HTTP MarkAllSeen",
              "trigger": "Mark all Novu messages seen for the current tenant-user subscriber",
              "conditions": [
                "request.Type == \"all\"",
                "request.NotificationID == \"all\""
              ],
              "implementation": "novuhandler.Get().MarkMessagesAsSeen(request) -> GetClient().Request(\"POST\", \"/v1/subscribers/{subscriberId}/messages/mark-all\", nil, {markAs:\"seen\"}, nil)"
            }
          ]
        }
      ]
    },
    "HTTP POST /api/v1/unc/tenants/:tenant_id/notifications/notification_id/:notification_id": {
      "infrastructure": {},
      "services": []
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/billing_config_id/:billing_config_id/costexplorer/args": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Always"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "user_unit_costs",
              "trigger": "Query distinct values for args"
            }
          ]
        },
        "redis": {
          "conditions": [
            "EnableCache == true"
          ],
          "operations": [
            {
              "operation": "GET",
              "trigger": "Cache lookup for args"
            },
            {
              "operation": "SET",
              "trigger": "Cache args"
            }
          ]
        }
      },
      "services": [
        {
          "name": "account-svc",
          "target_interface": "AccountAPIService.ListProjects",
          "operation_type": "grpc_unary",
          "conditions": [
            "DBaaSCentralEnable == true"
          ],
          "operations": [
            {
              "operation": "gRPC ListProjects",
              "trigger": "Get project list for args"
            }
          ]
        },
        {
          "name": "infra-svc",
          "target_interface": "CoreService.ListClusters",
          "operation_type": "grpc_unary",
          "conditions": [
            "Always"
          ],
          "operations": [
            {
              "operation": "gRPC ListClusters",
              "trigger": "Get cluster list for args"
            }
          ]
        }
      ]
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/billing_config_id/:billing_config_id/costexplorer/enabled": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant and billing-config resolution succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the billing config and inspect its partner-managed type before deciding whether bills view is enabled",
              "conditions": [
                "c.ShouldBindUri(&BillingCfgStruct{}) succeeded"
              ],
              "implementation": "getBillingCfgFromURI(c) + isBillsEnabled(tenantID, billingConfigID) -> billingconfig.BillingConfigModel.GetBillingConfig(billingConfigID)"
            },
            {
              "operation": "SELECT",
              "table": "partner_configs",
              "trigger": "Load partner-customer visibility flags for MSP/resale managed customers",
              "conditions": [
                "billingConfigs.Type in {MSPCustomer, ResaleCustomer, MarketplaceResellerManagedCustomer}"
              ],
              "implementation": "partner.Configs.GetCustomerPartnerConfigs(partnerID, billingConfigs.TenantID)"
            }
          ]
        }
      },
      "services": [
        {
          "name": "account-svc",
          "target_interface": "AccountAPIService.GetOrgByID",
          "operation_type": "grpc_unary",
          "conditions": [
            "Only when partnerID must be derived from the tenant profile of an MSP/resale customer"
          ],
          "operations": [
            {
              "operation": "gRPC GetOrgByID",
              "trigger": "Load tenant metadata so isBillsEnabled can derive partner ownership from ThirdPartyAccountCode",
              "conditions": [
                "billingConfigs.Type in {MSPCustomer, ResaleCustomer}"
              ],
              "implementation": "centralhandler.GetCentralHandler().GetTenant(tenantID) -> account.GetOrgByID(IsBrief=false)"
            }
          ]
        }
      ]
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/billing_config_id/:billing_config_id/costexplorer/monthly_cost/year/:year/month/:month": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant/year/month binding succeeds, bills visibility checks pass, and the tenant is not hidden by MonthlyBillsInvisibleList"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the billing config and bill-visibility gates before reading monthly cost data",
              "conditions": [
                "c.ShouldBindUri(&MonthlyCostURI{}) succeeded"
              ],
              "implementation": "getBillingCfgFromURI(c) + isBillsEnabled(billingCfgStruct.TenantID, billingCfgStruct.BillingConfigID)"
            },
            {
              "operation": "SELECT",
              "table": "user_unit_costs",
              "trigger": "Load the requested month's aggregated cost result, choosing the big-customer or normal cache path",
              "conditions": [
                "MonthlyBillsInvisibleList did not hide the tenant/billingConfig pair"
              ],
              "implementation": "CostExplorerModel.GetMonthlyCostFromCache(...) or GetMonthlyCostWithCache(...)"
            },
            {
              "operation": "SELECT",
              "table": "invoices",
              "trigger": "Check whether the previous month's monthly invoice has already been generated",
              "conditions": [
                "Monthly cost query succeeded"
              ],
              "implementation": "payment.InvoiceModel.GetMonthlyInvoice(tenantID, billingCfgStruct.BillingConfigID, lastMonthDate)"
            }
          ]
        },
        "redis": {
          "conditions": [
            "Always around monthly cost cache lookups"
          ],
          "operations": [
            {
              "operation": "GET",
              "trigger": "Try the appropriate monthly cost cache before recomputing from DB",
              "conditions": [
                "isBigCustomer chooses GetMonthlyCostFromCache(...) or GetMonthlyCostWithCache(...)"
              ],
              "implementation": "cachehandler.Get().Get(\"GetMonthlyCostFromCache\", ...) / cachehandler.Get().Get(\"GetMonthlyCostWithCache\", ...)"
            },
            {
              "operation": "SET",
              "trigger": "Cache the monthly cost result after DB aggregation succeeds",
              "conditions": [
                "GetMonthlyCostFromCache(...) or GetMonthlyCostWithCache(...) missed and recomputed"
              ],
              "implementation": "cachehandler.Get().SetWithTimeOut(...) / cachehandler.Get().Set(...)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/billing_config_id/:billing_config_id/costexplorer/bills_details/year/:year/month/:month": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant/year/month binding succeeds, BillsInvisibleList does not hide the tenant, and bills visibility checks pass"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the billing config and bill-visibility gate before querying bill details",
              "conditions": [
                "c.ShouldBindUri(&MonthlyCostURI{}) succeeded"
              ],
              "implementation": "getBillingConfigIDFromURI(c) + isBillsEnabled(input.TenantID, billingConfigID)"
            },
            {
              "operation": "SELECT",
              "table": "user_unit_costs",
              "trigger": "Load grouped daily usage details for the requested month",
              "conditions": [
                "Bills visibility checks passed"
              ],
              "implementation": "CostExplorerModel.GetBillsDetailsWithCache(tenantID, billingConfigID, input.Year, input.Month)"
            }
          ]
        },
        "redis": {
          "conditions": [
            "Always around bill-details cache lookups"
          ],
          "operations": [
            {
              "operation": "GET",
              "trigger": "Try the cached detailed bill rows before recomputing them",
              "conditions": [
                "GetBillsDetailsWithCache(...) is reached"
              ],
              "implementation": "cachehandler.Get().Get(\"GetBillsDetailsWithCache\", ...)"
            },
            {
              "operation": "SET",
              "trigger": "Cache the detailed bill rows after DB aggregation succeeds",
              "conditions": [
                "GetBillsDetails(...) succeeded"
              ],
              "implementation": "cachehandler.Get().Set(\"GetBillsDetailsWithCache\", ...)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/tenants/:tenant_id/billing_config_id/:billing_config_id/costexplorer": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Always"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "user_unit_costs",
              "trigger": "Query billing costs from database"
            },
            {
              "operation": "SELECT",
              "table": "invoices",
              "trigger": "Get invoice data"
            },
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Get billing configuration"
            },
            {
              "operation": "SELECT",
              "table": "tenant_plans",
              "trigger": "Get tenant plan info"
            },
            {
              "operation": "SELECT",
              "table": "credits_packages",
              "trigger": "Calculate credits"
            }
          ]
        },
        "redis": {
          "conditions": [
            "EnableCache == true"
          ],
          "operations": [
            {
              "operation": "GET",
              "trigger": "Cache lookup for cost explorer results"
            },
            {
              "operation": "SET",
              "trigger": "Cache cost explorer results"
            }
          ]
        }
      },
      "services": [
        {
          "name": "account-svc",
          "target_interface": "AccountAPIService.GetOrgByID",
          "operation_type": "grpc_unary",
          "conditions": [
            "DBaaSCentralEnable == true"
          ],
          "operations": [
            {
              "operation": "gRPC GetOrgByID",
              "trigger": "Get tenant info for bills"
            }
          ]
        },
        {
          "name": "account-svc",
          "target_interface": "AccountAPIService.ListProjects",
          "operation_type": "grpc_unary",
          "conditions": [
            "DBaaSCentralEnable == true"
          ],
          "operations": [
            {
              "operation": "gRPC ListProjects",
              "trigger": "Get project list for cost breakdown"
            }
          ]
        },
        {
          "name": "infra-svc",
          "target_interface": "CoreService.ListClusters",
          "operation_type": "grpc_unary",
          "conditions": [
            "breakdown by cluster"
          ],
          "operations": [
            {
              "operation": "gRPC ListClusters",
              "trigger": "Get cluster list for cost breakdown"
            }
          ]
        }
      ]
    },
    "HTTP POST /api/v1/billing/tenants/:tenant_id/billing_config_id/:billing_config_id/costexplorer/trends": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Always"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "user_unit_costs",
              "trigger": "Query billing costs from database"
            },
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Get billing configuration"
            }
          ]
        },
        "redis": {
          "conditions": [
            "EnableCache == true"
          ],
          "operations": [
            {
              "operation": "GET",
              "trigger": "Cache lookup for trends results"
            },
            {
              "operation": "SET",
              "trigger": "Cache trends results"
            }
          ]
        }
      },
      "services": [
        {
          "name": "account-svc",
          "target_interface": "AccountAPIService.GetOrgByID",
          "operation_type": "grpc_unary",
          "conditions": [
            "DBaaSCentralEnable == true"
          ],
          "operations": [
            {
              "operation": "gRPC GetOrgByID",
              "trigger": "Get tenant info"
            }
          ]
        },
        {
          "name": "account-svc",
          "target_interface": "AccountAPIService.ListProjects",
          "operation_type": "grpc_unary",
          "conditions": [
            "breakdown by project"
          ],
          "operations": [
            {
              "operation": "gRPC ListProjects",
              "trigger": "Get project list"
            }
          ]
        },
        {
          "name": "account-svc",
          "target_interface": "AccountAPIService.ListPartnerCustomers",
          "operation_type": "grpc_unary",
          "conditions": [
            "breakdown by customer"
          ],
          "operations": [
            {
              "operation": "gRPC ListPartnerCustomers",
              "trigger": "Get partner customers"
            }
          ]
        },
        {
          "name": "infra-svc",
          "target_interface": "CoreService.ListClusters",
          "operation_type": "grpc_unary",
          "conditions": [
            "breakdown by cluster"
          ],
          "operations": [
            {
              "operation": "gRPC ListClusters",
              "trigger": "Get cluster list"
            }
          ]
        }
      ]
    },
    "HTTP POST /api/v1/billing/tenants/:tenant_id/billing_config_id/:billing_config_id/costexplorer/trends/csv": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant and billing-config resolution succeeds, bills visibility checks pass, and parseTrendsQuery validates the requested date range"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the billing config and bill-visibility gates before running the trends CSV query",
              "conditions": [
                "getBillingCfgFromURI(c) succeeded"
              ],
              "implementation": "getBillingCfgFromURI(c) + isBillsEnabled(tenantID, billingConfigID)"
            },
            {
              "operation": "SELECT",
              "table": "user_unit_costs",
              "trigger": "Run the trends aggregation that backs the CSV export",
              "conditions": [
                "parseTrendsQuery(c, tenantID, false) succeeded"
              ],
              "implementation": "costexplorer.CostTrendsCSV(tenantID, billingConfigID, query)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/tenants/:tenant_id/billing_config_id/:billing_config_id/costexplorer/monthly_cost/year/:year/month/:month/export": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant/year/month binding succeeds and bills visibility checks pass"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the billing config and visibility gates before exporting monthly cost CSV",
              "conditions": [
                "c.ShouldBindUri(&MonthlyCostURI{}) succeeded"
              ],
              "implementation": "getBillingConfigIDFromURI(c) + isBillsEnabled(tenantID, billingConfigID)"
            },
            {
              "operation": "SELECT",
              "table": "user_unit_costs",
              "trigger": "Load the monthly aggregated cost result used to build the export CSV",
              "conditions": [
                "Bills visibility checks passed"
              ],
              "implementation": "CostExplorerModel.GetMonthlyCostWithCache(tenantID, billingConfigID, input.Year, input.Month)"
            }
          ]
        },
        "redis": {
          "conditions": [
            "Always around monthly-cost export cache lookups"
          ],
          "operations": [
            {
              "operation": "GET",
              "trigger": "Reuse the cached monthly cost result for the export path",
              "conditions": [
                "GetMonthlyCostWithCache(...) is reached"
              ],
              "implementation": "cachehandler.Get().Get(\"GetMonthlyCostWithCache\", ...)"
            },
            {
              "operation": "SET",
              "trigger": "Cache the monthly cost result after DB aggregation succeeds",
              "conditions": [
                "GetMonthlyCost(...) succeeded"
              ],
              "implementation": "cachehandler.Get().Set(\"GetMonthlyCostWithCache\", ...)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/tenants/:tenant_id/billing_config_id/:billing_config_id/costexplorer/monthly_bills/year/:year/month/:month/export": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant/year/month binding succeeds, BillsInvisibleList does not hide the tenant, and bills visibility checks pass"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the billing config and bill-visibility gates before exporting monthly bill details",
              "conditions": [
                "c.ShouldBindUri(&MonthlyCostURI{}) succeeded"
              ],
              "implementation": "getBillingConfigIDFromURI(c) + isBillsEnabled(tenantID, billingConfigID)"
            },
            {
              "operation": "SELECT",
              "table": "user_unit_costs",
              "trigger": "Load export-grade usage detail rows for the requested month",
              "conditions": [
                "Bills visibility checks passed"
              ],
              "implementation": "CostExplorerModel.GetExportBillsDetailsWithCache(tenantID, billingConfigID, input.Year, input.Month)"
            }
          ]
        },
        "redis": {
          "conditions": [
            "Always around export-bills-detail cache lookups"
          ],
          "operations": [
            {
              "operation": "GET",
              "trigger": "Reuse cached export bill details before recomputing them",
              "conditions": [
                "GetExportBillsDetailsWithCache(...) is reached"
              ],
              "implementation": "cachehandler.Get().Get(\"GetBillsDetailsWithCache\", ...) / export-details cache path"
            }
          ]
        }
      },
      "services": [
        {
          "name": "account-svc",
          "target_interface": "AccountAPIService.GetOrgByID",
          "operation_type": "grpc_unary",
          "conditions": [
            "Always after bill visibility checks pass"
          ],
          "operations": [
            {
              "operation": "gRPC GetOrgByID",
              "trigger": "Load tenant display name for the bill-export CSV header",
              "conditions": [
                "tenantID resolved from path"
              ],
              "implementation": "centralhandler.GetCentralHandler().GetTenant(tenantID) -> account.GetOrgByID(IsBrief=false)"
            }
          ]
        }
      ]
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/billing_config_id/:billing_config_id/payments": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Always"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "payment_methods",
              "trigger": "Query payment methods"
            }
          ]
        }
      },
      "services": [
        {
          "name": "account-svc",
          "target_interface": "AccountAPIService.GetOrgByID",
          "operation_type": "grpc_unary",
          "conditions": [
            "DBaaSCentralEnable == true"
          ],
          "operations": [
            {
              "operation": "gRPC GetOrgByID",
              "trigger": "Get tenant info"
            }
          ]
        }
      ]
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/billing_config_id/:billing_config_id/payments/active": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant and billing-config resolution succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the active billing config used to look up the current active payment method",
              "conditions": [
                "c.ShouldBindUri(&BillingCfgStruct{}) succeeded"
              ],
              "implementation": "getBillingCfgFromURI(c)"
            },
            {
              "operation": "SELECT",
              "table": "payment_methods",
              "trigger": "Load the active payment method or decide to synthesize the default Stripe placeholder when no record exists",
              "conditions": [
                "getBillingCfgFromURI(c) resolved billingCfgStruct.TenantID and billingCfgStruct.BillingConfigID"
              ],
              "implementation": "paymentModel.GetActivePaymentMethod(billingCfgStruct.TenantID, billingCfgStruct.BillingConfigID)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/billing_config_id/:billing_config_id/payments/types": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant and billing-config resolution succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the active billing config before checking MSP payment mode and enumerating stored payment methods",
              "conditions": [
                "c.ShouldBindUri(&BillingCfgStruct{}) succeeded"
              ],
              "implementation": "getBillingCfgFromURI(c)"
            },
            {
              "operation": "SELECT",
              "table": "payment_methods",
              "trigger": "Check whether the tenant is an MSP customer and load existing payment-method rows to derive payable payment types",
              "conditions": [
                "getBillingCfgFromURI(c) resolved billingCfgStruct.TenantID and billingCfgStruct.BillingConfigID"
              ],
              "implementation": "paymentModel.IsMspPayment(...) + paymentModel.ListPaymentMethods(billingCfgStruct.TenantID, billingCfgStruct.BillingConfigID)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/tenants/:tenant_id/billing_config_id/:billing_config_id/payments/setup/:payment_type": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Always"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "payment_methods",
              "trigger": "Check existing payment methods"
            },
            {
              "operation": "INSERT",
              "table": "payment_methods",
              "trigger": "Create payment method"
            },
            {
              "operation": "UPDATE",
              "table": "payment_methods",
              "trigger": "Update payment method status"
            }
          ]
        }
      },
      "services": [
        {
          "name": "account-svc",
          "target_interface": "AccountAPIService.GetOrgByID",
          "operation_type": "grpc_unary",
          "conditions": [
            "DBaaSCentralEnable == true"
          ],
          "operations": [
            {
              "operation": "gRPC GetOrgByID",
              "trigger": "Get tenant info"
            }
          ]
        }
      ]
    },
    "HTTP POST /api/v1/billing/tenants/:tenant_id/billing_config_id/:billing_config_id/payments/stripe/setup_intent": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Always"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "payment_methods",
              "trigger": "Get Stripe payment info"
            },
            {
              "operation": "UPDATE",
              "table": "payment_methods",
              "trigger": "Update payable status"
            },
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Get billing config"
            }
          ]
        }
      },
      "services": [
        {
          "name": "stripe-api",
          "target_interface": "POST /v1/setup_intents",
          "operation_type": "http_post",
          "conditions": [
            "StripePaymentEnable == true"
          ],
          "operations": [
            {
              "operation": "HTTP SetupIntent",
              "trigger": "Create Stripe setup intent"
            }
          ]
        },
        {
          "name": "stripe-api",
          "target_interface": "POST /v1/customers",
          "operation_type": "http_post",
          "conditions": [
            "StripePaymentEnable == true",
            "customer not exists"
          ],
          "operations": [
            {
              "operation": "HTTP CreateCustomer",
              "trigger": "Create Stripe customer"
            }
          ]
        }
      ]
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/billing_config_id/:billing_config_id/payments/stripe/invoices": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Always"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "payment_methods",
              "trigger": "Get Stripe payment info"
            },
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Get billing config"
            }
          ]
        },
        "redis": {
          "conditions": [
            "EnableCache == true"
          ],
          "operations": [
            {
              "operation": "GET",
              "trigger": "Get cached Stripe invoices"
            },
            {
              "operation": "SET",
              "trigger": "Cache Stripe invoices"
            }
          ]
        }
      },
      "services": [
        {
          "name": "stripe-api",
          "target_interface": "GET /v1/invoices",
          "operation_type": "http_get",
          "conditions": [
            "StripePaymentEnable == true"
          ],
          "operations": [
            {
              "operation": "HTTP ListInvoices",
              "trigger": "List Stripe invoices"
            }
          ]
        }
      ]
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/billing_config_id/:billing_config_id/payments/stripe/invoices/:invoice_id": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant, billing-config, and invoice path binding succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the explicit billing config that owns the Stripe payment method used for invoice lookup",
              "conditions": [
                "getTenantAndInvoiceFromURI(c) succeeded"
              ],
              "implementation": "getTenantAndInvoiceFromURI(c) -> getBillingCfgFromURI(c)"
            },
            {
              "operation": "SELECT",
              "table": "payment_methods",
              "trigger": "Load the active Stripe payment method and customer code before calling Stripe invoice detail APIs",
              "conditions": [
                "getTenantAndInvoiceFromURI(c) resolved billingCfgStruct.BillingConfigID"
              ],
              "implementation": "getStripeProvider(billingCfgStruct.TenantID, billingCfgStruct.BillingConfigID) -> paymentModel.GetPaymentMethodWithPaymentType(tenantID, billingConfigID, STRIPE)"
            }
          ]
        }
      },
      "services": [
        {
          "name": "stripe-api",
          "target_interface": "GET /v1/invoices/:invoice_id",
          "operation_type": "http_get",
          "conditions": [
            "Only when Stripe payment handling is enabled and the tenant has a Stripe payment method"
          ],
          "operations": [
            {
              "operation": "HTTP GetInvoice",
              "trigger": "Fetch the target Stripe invoice and reject cross-customer access by validating inv.Customer.ID == userCode",
              "conditions": [
                "getStripeProvider(...) succeeded"
              ],
              "implementation": "handler.GetStripeInvoice(code, stripeVoiceID) -> stripe.Invoices.Get(invoiceID, nil)"
            }
          ]
        },
        {
          "name": "stripe-api",
          "target_interface": "GET /v1/payment_intents/:payment_intent_id",
          "operation_type": "http_get",
          "conditions": [
            "Only when the fetched Stripe invoice carries a non-nil PaymentIntent"
          ],
          "operations": [
            {
              "operation": "HTTP GetPaymentIntent",
              "trigger": "Hydrate payment-intent status and client secret for the invoice detail response",
              "conditions": [
                "inv.PaymentIntent != nil"
              ],
              "implementation": "handler.GetStripeInvoice(...) -> stripe.PaymentIntents.Get(inv.PaymentIntent.ID, nil)"
            }
          ]
        }
      ]
    },
    "HTTP POST /api/v1/billing/tenants/:tenant_id/billing_config_id/:billing_config_id/payments/stripe/invoices/:invoice_id/payment_required_notification": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant, billing-config, and invoice path binding succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the explicit billing config that owns the Stripe payment method used for invoice lookup",
              "conditions": [
                "getTenantAndInvoiceFromURI(c) succeeded"
              ],
              "implementation": "getTenantAndInvoiceFromURI(c) -> getBillingCfgFromURI(c)"
            },
            {
              "operation": "SELECT",
              "table": "payment_methods",
              "trigger": "Load the active Stripe payment method and customer code before fetching the invoice that needs payment-required notification",
              "conditions": [
                "getTenantAndInvoiceFromURI(c) resolved billingCfgStruct.BillingConfigID"
              ],
              "implementation": "getStripeProvider(billingCfgStruct.TenantID, billingCfgStruct.BillingConfigID) -> paymentModel.GetPaymentMethodWithPaymentType(tenantID, billingConfigID, STRIPE)"
            }
          ]
        }
      },
      "services": [
        {
          "name": "stripe-api",
          "target_interface": "GET /v1/invoices/:invoice_id",
          "operation_type": "http_get",
          "conditions": [
            "Only when Stripe payment handling is enabled and the tenant has a Stripe payment method"
          ],
          "operations": [
            {
              "operation": "HTTP GetInvoice",
              "trigger": "Fetch the Stripe invoice so the notification payload can be derived from its billing month",
              "conditions": [
                "getStripeProvider(...) succeeded"
              ],
              "implementation": "handler.GetStripeInvoice(code, stripeVoiceID) -> stripe.Invoices.Get(invoiceID, nil)"
            }
          ]
        },
        {
          "name": "novu-api",
          "target_interface": "POST /v1/events/trigger/bulk",
          "operation_type": "http_post",
          "conditions": [
            "Only when InAPPNotificationEnable == true"
          ],
          "operations": [
            {
              "operation": "HTTP BulkTriggerEvent",
              "trigger": "Send the in-app payment-action-required notification to org-owner and billing-admin users",
              "conditions": [
                "payload.invoiceMonth derived from result.StartDate"
              ],
              "implementation": "uncutils.SendInAppNotification(billingCfgStruct.TenantID, PaymentActionRequired, payload) -> novuhandler.Get().BulkTriggerEvent(...)"
            }
          ]
        },
        {
          "name": "account-svc",
          "target_interface": "SendEmailByLabels",
          "operation_type": "grpc",
          "conditions": [
            "Always after Stripe invoice lookup succeeds"
          ],
          "operations": [
            {
              "operation": "GRPC SendEmailByLabels",
              "trigger": "Send the payment-required email once to org owner and billing admins using a dedupe key derived from invoice ID and tenant ID",
              "conditions": [
                "payload.invoiceMonth derived from result.StartDate"
              ],
              "implementation": "centralhandler.GetCentralHandler().SendTenantEmailWithLabelOnce(...) -> account.SendEmailByLabels(...)"
            }
          ]
        }
      ]
    },
    "HTTP PUT /api/v1/billing/tenants/:tenant_id/billing_config_id/:billing_config_id/payments/stripe/payment_methods/:payment_method_id/validate": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant and billing-config resolution succeeds and credit-card validation is enabled for the tenant"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the billing config used to locate the tenant Stripe customer",
              "conditions": [
                "c.ShouldBindUri(&TenantPaymentStruct{}) succeeded"
              ],
              "implementation": "getBillingCfgFromURI(c)"
            },
            {
              "operation": "SELECT",
              "table": "payment_methods",
              "trigger": "Load the Stripe payment method and customer code before card validation",
              "conditions": [
                "getBillingCfgFromURI(c) resolved billingCfgStruct.BillingConfigID"
              ],
              "implementation": "getStripeProvider(tenantID, billingConfigID) -> paymentModel.GetPaymentMethodWithPaymentType(tenantID, billingConfigID, STRIPE)"
            },
            {
              "operation": "SELECT",
              "table": "billing_companies",
              "trigger": "Check whether stored billing information is complete enough to skip Stripe-address validation",
              "conditions": [
                "EnableTaxCalculation == true",
                "IsCreditCardValidationRequired(tenantID) == true"
              ],
              "implementation": "paymentsub.BillingInformationModel.BillingInfoIsNotEmpty(tenantID)"
            },
            {
              "operation": "INSERT",
              "table": "credit_card_validate_refund_records",
              "trigger": "Create the async refund record when Stripe accepted the validation payment intent",
              "conditions": [
                "Init3DSPaymentIntent(...) returned a non-nil paymentIntent"
              ],
              "implementation": "CreditCardVerifyModel.CreateRefundRecord(entity.CreditCardValidateCancelStatus_Init, tenantID, paymentIntent.ID, decimal.NewFromInt(100))"
            }
          ]
        }
      },
      "services": [
        {
          "name": "account-svc",
          "target_interface": "AccountAPIService.GetOrgByID",
          "operation_type": "grpc_unary",
          "conditions": [
            "Only when credit-card validation is enabled for the tenant and compliance checks must inspect tenant kind/email"
          ],
          "operations": [
            {
              "operation": "gRPC GetOrgByID",
              "trigger": "Load tenant profile for internal-user and restricted-domain compliance checks",
              "conditions": [
                "IsCreditCardValidationRequired(tenantID) == true"
              ],
              "implementation": "CreditCardVerifyModel.ComplianceCheck(tenantID) -> centralhandler.GetCentralHandler().GetTenant(tenantID) -> account.GetOrgByID(IsBrief=false)"
            }
          ]
        },
        {
          "name": "stripe-api",
          "target_interface": "GET /v1/payment_methods/:id",
          "operation_type": "http_get",
          "conditions": [
            "Only when credit-card validation remains enabled after compliance checks"
          ],
          "operations": [
            {
              "operation": "HTTP GetPaymentMethod",
              "trigger": "Load the Stripe payment method and card brand/details before validation",
              "conditions": [
                "getStripeProvider(...) succeeded"
              ],
              "implementation": "stripeHandler.GetPaymentMethod(paymentMethodID)"
            }
          ]
        },
        {
          "name": "stripe-api",
          "target_interface": "POST /v1/payment_intents",
          "operation_type": "http_post",
          "conditions": [
            "Only when the payment method is a supported card brand and address validation passes when tax validation is enabled"
          ],
          "operations": [
            {
              "operation": "HTTP CreatePaymentIntent",
              "trigger": "Create the 100-cent validation payment intent used for 3DS / card verification",
              "conditions": [
                "methodInfo.Card != nil",
                "isSupportedCardBrand(methodInfo.Card.Brand) == true"
              ],
              "implementation": "stripeHandler.Init3DSPaymentIntent(decimal.NewFromInt(100), paymentMethodID, customerID)"
            }
          ]
        }
      ]
    },
    "HTTP PUT /api/v1/billing/tenants/:tenant_id/billing_config_id/:billing_config_id/payments/stripe/setup_intent/confirm": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant and billing-config resolution succeeds and a Stripe payment method is already provisioned"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the billing config used to select the tenant Stripe customer",
              "conditions": [
                "getTenantIDFromURI(c) succeeded"
              ],
              "implementation": "getBillingCfgFromURI(c)"
            },
            {
              "operation": "SELECT",
              "table": "payment_methods",
              "trigger": "Load the Stripe payment method and customer code needed to inspect attached cards",
              "conditions": [
                "getBillingCfgFromURI(c) resolved billingCfgStruct.BillingConfigID"
              ],
              "implementation": "getStripeProvider(tenantID, billingCfgStruct.BillingConfigID) -> paymentModel.GetPaymentMethodWithPaymentType(tenantID, billingConfigID, STRIPE)"
            },
            {
              "operation": "UPDATE",
              "table": "payment_methods",
              "trigger": "Sync the payable bit for the billing config after Stripe cards are visible",
              "conditions": [
                "handler.ListPaymentMethods(code) succeeded"
              ],
              "implementation": "paymentModel.SyncPayableByBillingConfigID(tenantID, billingCfgStruct.BillingConfigID)"
            },
            {
              "operation": "UPDATE",
              "table": "tenant_plans",
              "trigger": "Enable the tenant ondemand plan once card binding makes the billing config payable",
              "conditions": [
                "SyncPayableByBillingConfigID(...) succeeded"
              ],
              "implementation": "plan.TenantPlanModel.EnableTenantOnDemandPlanByBillingConfigID(tenantID, billingCfgStruct.BillingConfigID)"
            }
          ]
        }
      },
      "services": [
        {
          "name": "stripe-api",
          "target_interface": "GET /v1/payment_methods",
          "operation_type": "http_get",
          "conditions": [
            "Only when Stripe payment handling is enabled and the tenant has a Stripe payment method"
          ],
          "operations": [
            {
              "operation": "HTTP ListPaymentMethods",
              "trigger": "Inspect Stripe cards attached to the customer after setup intent confirmation",
              "conditions": [
                "getStripeProvider(...) succeeded"
              ],
              "implementation": "handler.ListPaymentMethods(code)"
            }
          ]
        },
        {
          "name": "stripe-api",
          "target_interface": "POST /v1/customers/:id",
          "operation_type": "http_post",
          "conditions": [
            "Only when exactly one Stripe card is attached after setup intent confirmation"
          ],
          "operations": [
            {
              "operation": "HTTP UpdateCustomer",
              "trigger": "Set the lone attached card as the default payment method",
              "conditions": [
                "len(methods) == 1"
              ],
              "implementation": "handler.SetPaymentMethodDefault(code, methods[0].ID) -> stripe.Customers.Update(userCode, InvoiceSettings.DefaultPaymentMethod=methodId)"
            }
          ]
        }
      ]
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/billing_config_id/:billing_config_id/payments/stripe/customer": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant and billing-config resolution succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the billing config used to locate the tenant Stripe customer",
              "conditions": [
                "getTenantIDFromURI(c) succeeded"
              ],
              "implementation": "getBillingCfgFromURI(c)"
            },
            {
              "operation": "SELECT",
              "table": "payment_methods",
              "trigger": "Load the Stripe payment method and customer code used to fetch Stripe customer metadata",
              "conditions": [
                "getBillingCfgFromURI(c) resolved billingCfgStruct.BillingConfigID"
              ],
              "implementation": "getStripeProvider(tenantID, billingCfgStruct.BillingConfigID) -> paymentModel.GetPaymentMethodWithPaymentType(tenantID, billingConfigID, STRIPE)"
            }
          ]
        }
      },
      "services": [
        {
          "name": "stripe-api",
          "target_interface": "GET /v1/customers/:id",
          "operation_type": "http_get",
          "conditions": [
            "Only when Stripe payment handling is enabled and the tenant has a Stripe payment method"
          ],
          "operations": [
            {
              "operation": "HTTP GetCustomer",
              "trigger": "Fetch Stripe customer metadata and default card information",
              "conditions": [
                "getStripeProvider(...) succeeded"
              ],
              "implementation": "handler.GetCustomerInfo(code) -> stripe.Customers.Get(userCode, nil)"
            }
          ]
        }
      ]
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/billing_config_id/:billing_config_id/payments/stripe/payment_methods": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Always"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "payment_methods",
              "trigger": "Get Stripe payment info"
            }
          ]
        }
      },
      "services": [
        {
          "name": "stripe-api",
          "target_interface": "GET /v1/payment_methods",
          "operation_type": "http_get",
          "conditions": [
            "StripePaymentEnable == true"
          ],
          "operations": [
            {
              "operation": "HTTP ListPaymentMethods",
              "trigger": "List payment methods"
            }
          ]
        }
      ]
    },
    "HTTP PUT /api/v1/billing/tenants/:tenant_id/billing_config_id/:billing_config_id/payments/stripe/payment_methods/:payment_method_id": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Always"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "payment_methods",
              "trigger": "Get Stripe payment info"
            }
          ]
        }
      },
      "services": [
        {
          "name": "stripe-api",
          "target_interface": "POST /v1/payment_methods/:id",
          "operation_type": "http_post",
          "conditions": [
            "StripePaymentEnable == true"
          ],
          "operations": [
            {
              "operation": "HTTP UpdatePaymentMethod",
              "trigger": "Update payment method"
            }
          ]
        }
      ]
    },
    "HTTP DELETE /api/v1/billing/tenants/:tenant_id/billing_config_id/:billing_config_id/payments/stripe/payment_methods/:payment_method_id": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Always"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "payment_methods",
              "trigger": "Get Stripe payment info"
            },
            {
              "operation": "DELETE",
              "table": "payment_methods",
              "trigger": "Delete payment method"
            }
          ]
        }
      },
      "services": [
        {
          "name": "stripe-api",
          "target_interface": "DELETE /v1/payment_methods/:id",
          "operation_type": "http_delete",
          "conditions": [
            "StripePaymentEnable == true"
          ],
          "operations": [
            {
              "operation": "HTTP DetachPaymentMethod",
              "trigger": "Detach payment method from customer"
            }
          ]
        }
      ]
    },
    "HTTP PUT /api/v1/billing/tenants/:tenant_id/billing_config_id/:billing_config_id/payments/stripe/payment_methods/:payment_method_id/default": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant and billing-config resolution succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the billing config used to locate the tenant Stripe customer",
              "conditions": [
                "getTenantAndMethodFromURI(c) succeeded"
              ],
              "implementation": "getBillingCfgFromURI(c)"
            },
            {
              "operation": "SELECT",
              "table": "payment_methods",
              "trigger": "Load the Stripe payment method and customer code before updating the default payment method",
              "conditions": [
                "getBillingCfgFromURI(c) resolved billingCfgStruct.BillingConfigID"
              ],
              "implementation": "getStripeProvider(tenantID, billingCfgStruct.BillingConfigID) -> paymentModel.GetPaymentMethodWithPaymentType(tenantID, billingConfigID, STRIPE)"
            }
          ]
        }
      },
      "services": [
        {
          "name": "stripe-api",
          "target_interface": "GET /v1/payment_methods/:id",
          "operation_type": "http_get",
          "conditions": [
            "Only when Stripe payment handling is enabled"
          ],
          "operations": [
            {
              "operation": "HTTP GetPaymentMethod",
              "trigger": "Validate that the selected payment method belongs to the tenant Stripe customer before promoting it to default",
              "conditions": [
                "getStripeProvider(...) succeeded"
              ],
              "implementation": "handler.SetPaymentMethodDefault(code, methodID) -> handler.GetCustomerPaymentMethod(userCode, methodId)"
            }
          ]
        },
        {
          "name": "stripe-api",
          "target_interface": "POST /v1/customers/:id",
          "operation_type": "http_post",
          "conditions": [
            "Only when the selected payment method belongs to the tenant Stripe customer"
          ],
          "operations": [
            {
              "operation": "HTTP UpdateCustomer",
              "trigger": "Set the selected Stripe card as the customer's default payment method",
              "conditions": [
                "GetCustomerPaymentMethod(...) succeeded"
              ],
              "implementation": "stripe.Customers.Update(userCode, InvoiceSettings.DefaultPaymentMethod=methodId)"
            }
          ]
        }
      ]
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/billing_config_id/:billing_config_id/invoices": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Always"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "invoices",
              "trigger": "Query invoices"
            },
            {
              "operation": "SELECT",
              "table": "invoice_items",
              "trigger": "Get invoice items"
            },
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Get billing config"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/billing_config_id/:billing_config_id/invoices/:invoice_id": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant, billing-config, and invoice path binding all succeed"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the billing config used to scope the tenant invoice lookup",
              "conditions": [
                "c.ShouldBindUri(&BillingCfgStruct{}) succeeded"
              ],
              "implementation": "getBillingCfgFromURI(c)"
            },
            {
              "operation": "SELECT",
              "table": "invoices",
              "trigger": "Load the requested tenant invoice entity before hydrating costs and tax metadata",
              "conditions": [
                "getInvoiceURIParams(c) succeeded"
              ],
              "implementation": "invoiceModel.GetTenantInvoice(billingCfgStruct.TenantID, billingCfgStruct.BillingConfigID, invoiceURI.InvoiceID)"
            },
            {
              "operation": "SELECT",
              "table": "user_unit_costs",
              "trigger": "Hydrate detailed invoice costs for non-commitment and non-subordinated invoices",
              "conditions": [
                "invoiceFromEntityWithCosts(...) handled an invoice whose type is neither COMMITMENT nor SUBORDINATED"
              ],
              "implementation": "invoiceFromEntityWithCosts(...) -> CostExplorerModel.GetInvoiceCosts(invoiceEntity.TenantID, invoiceEntity.BindedBillingConfigID, invoiceEntity.ID, false)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP PUT /api/v1/billing/tenants/:tenant_id/billing_config_id/:billing_config_id/invoices/:invoice_id/confirm": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Always"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "invoices",
              "trigger": "Get invoice"
            },
            {
              "operation": "UPDATE",
              "table": "invoices",
              "trigger": "Update invoice status"
            }
          ]
        }
      },
      "services": [
        {
          "name": "stripe-api",
          "target_interface": "POST /v1/invoices/:id/pay",
          "operation_type": "http_post",
          "conditions": [
            "payment type == STRIPE"
          ],
          "operations": [
            {
              "operation": "HTTP PayInvoice",
              "trigger": "Pay Stripe invoice"
            }
          ]
        }
      ]
    },
    "HTTP PUT /api/v1/billing/tenants/:tenant_id/billing_config_id/:billing_config_id/invoices/:invoice_id/send": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant, billing-config, and invoice path binding all succeed"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the billing config used to scope the tenant invoice lookup and payment attempt",
              "conditions": [
                "c.ShouldBindUri(&BillingCfgStruct{}) succeeded"
              ],
              "implementation": "getBillingCfgFromURI(c)"
            },
            {
              "operation": "SELECT",
              "table": "invoices",
              "trigger": "Load the target invoice and re-read it during the send flow",
              "conditions": [
                "getInvoiceURIParams(c) succeeded"
              ],
              "implementation": "invoiceModel.SendInvoice(...) -> GetTenantInvoice(...) + sendInvoice(invoiceID) -> GetInvoice(invoiceID)"
            },
            {
              "operation": "SELECT",
              "table": "payment_methods",
              "trigger": "Resolve the active payment method and invoiceable flag before paying the invoice",
              "conditions": [
                "invoice status allows sendInvoice(...) to proceed"
              ],
              "implementation": "paymentsub.PaymentModel.BillingConfigInvoiceable(info.TenantID, *info.BindedBillingConfigID) + paymentsub.PaymentModel.Pay(tenantID, billingConfigID, *info)"
            },
            {
              "operation": "UPDATE",
              "table": "invoices",
              "trigger": "Persist sent-date, payment method, payment type/code, channel loss, and final status after provider payment succeeds",
              "conditions": [
                "PaymentModel.Pay(...) returned paid invoices"
              ],
              "implementation": "InvoiceModel.UpdateSentInvoices(result)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP PUT /api/v1/billing/tenants/:tenant_id/billing_config_id/:billing_config_id/invoices/:invoice_id/suspend": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after invoice path binding succeeds and the invoice is still in GENERATED status"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "invoices",
              "trigger": "Load the invoice to validate that only generated invoices can be suspended",
              "conditions": [
                "getInvoiceURIParams(c) succeeded"
              ],
              "implementation": "invoiceModel.SuspendInvoice(invoiceURI.InvoiceID) -> GetInvoice(invoiceID)"
            },
            {
              "operation": "INSERT",
              "table": "audit_records",
              "trigger": "Persist the suspend-invoice audit record inside the suspension transaction",
              "conditions": [
                "info.Status == GENERATED"
              ],
              "implementation": "entity.AuditRecord{Action: SuspendInvoice, ...}.Create(tx)"
            },
            {
              "operation": "UPDATE",
              "table": "invoices",
              "trigger": "Mark the invoice suspended inside the suspension transaction",
              "conditions": [
                "info.Status == GENERATED"
              ],
              "implementation": "entity.NewInvoiceQuerySet(db.GetDB()).IDEq(invoiceID).GetUpdater().SetStatus(SUSPENDED).Update()"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/tenants/:tenant_id/billing_config_id/:billing_config_id/invoices": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Always"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Get billing config"
            },
            {
              "operation": "SELECT",
              "table": "payment_methods",
              "trigger": "Get payment method"
            },
            {
              "operation": "INSERT",
              "table": "invoices",
              "trigger": "Create invoice"
            },
            {
              "operation": "INSERT",
              "table": "invoice_items",
              "trigger": "Create invoice items"
            }
          ]
        },
        "s3": {
          "conditions": [
            "EnablePutARTableToS3 == true"
          ],
          "operations": [
            {
              "operation": "PUT",
              "trigger": "Upload AR table to S3"
            }
          ]
        }
      },
      "services": [
        {
          "name": "stripe-api",
          "target_interface": "POST /v1/invoices",
          "operation_type": "http_post",
          "conditions": [
            "payment type == STRIPE"
          ],
          "operations": [
            {
              "operation": "HTTP CreateInvoice",
              "trigger": "Create Stripe invoice"
            }
          ]
        }
      ]
    },
    "HTTP POST /api/v1/billing/tenants/:tenant_id/billing_config_id/:billing_config_id/invoices/:invoice_id/resend": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after invoice path binding succeeds and the tenant ID matches the invoice owner"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "invoices",
              "trigger": "Load the invoice before resetting its status back to CONFIRMED",
              "conditions": [
                "getInvoiceURIParams(c) succeeded"
              ],
              "implementation": "invoiceModel.ReSendInvoice(invoiceURI.TenantID, invoiceURI.InvoiceID) -> GetInvoice(invoiceID)"
            },
            {
              "operation": "UPDATE",
              "table": "invoices",
              "trigger": "Reset the invoice status to CONFIRMED so later send flows can retry delivery",
              "conditions": [
                "tenantID == invoice.TenantID"
              ],
              "implementation": "entity.NewInvoiceQuerySet(db.GetDB()).TenantIDEq(tenantID).IDEq(invoiceID).GetUpdater().SetStatus(CONFIRMED).Update()"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP DELETE /api/v1/billing/tenants/:tenant_id/billing_config_id/:billing_config_id/invoices/:invoice_id": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after invoice path binding succeeds and the invoice has not already been sent or paid"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "invoices",
              "trigger": "Load the invoice and validate that sent/paid invoices cannot be deleted",
              "conditions": [
                "getInvoiceURIParams(c) succeeded"
              ],
              "implementation": "invoiceModel.DeleteInvoice(invoiceURI.InvoiceID) -> GetInvoice(invoiceID)"
            },
            {
              "operation": "UPDATE",
              "table": "measures",
              "trigger": "Unbind invoice references from costs before deleting the invoice row",
              "conditions": [
                "invoice.Status not in {SENT, PAID}"
              ],
              "implementation": "billing.MeasureModel.CostsUnBindInvoice(invoice.TenantID, invoiceID)"
            },
            {
              "operation": "DELETE",
              "table": "invoices",
              "trigger": "Delete the invoice row after invoice-cost unbinding succeeds",
              "conditions": [
                "CostsUnBindInvoice(...) succeeded"
              ],
              "implementation": "entity.NewInvoiceQuerySet(db.GetDB()).IDEq(invoiceID).TenantIDEq(tenantID).Delete()"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/billing_config_id/:billing_config_id/credits": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Always"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "credits_packages",
              "trigger": "Query credits"
            },
            {
              "operation": "SELECT",
              "table": "unit_filters",
              "trigger": "Get unit filter info"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/billing_config_id/:billing_config_id/credits_summary": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant and billing-config resolution succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the billing config used to scope the tenant credit summary",
              "conditions": [
                "c.ShouldBindUri(&BillingCfgStruct{}) succeeded"
              ],
              "implementation": "getBillingCfgFromURI(c)"
            },
            {
              "operation": "SELECT",
              "table": "credits_packages",
              "trigger": "Aggregate the tenant's credit package summary for the resolved billing config",
              "conditions": [
                "getBillingCfgFromURI(c) resolved billingCfgStruct.TenantID and billingCfgStruct.BillingConfigID"
              ],
              "implementation": "marketing.CreditsPackageModel.GetTenantCreditsSummary(billingCfgStruct.TenantID, billingCfgStruct.BillingConfigID)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/tenants/:tenant_id/billing_config_id/:billing_config_id/credits": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Always"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "credits_packages",
              "trigger": "Check existing credits"
            },
            {
              "operation": "INSERT",
              "table": "credits_packages",
              "trigger": "Create credits package"
            },
            {
              "operation": "SELECT",
              "table": "unit_filters",
              "trigger": "Get unit filter info"
            }
          ]
        }
      },
      "services": [
        {
          "name": "account-svc",
          "target_interface": "AccountAPIService.GetOrgByID",
          "operation_type": "grpc_unary",
          "conditions": [
            "DBaaSCentralEnable == true"
          ],
          "operations": [
            {
              "operation": "gRPC GetOrgByID",
              "trigger": "Get tenant info"
            }
          ]
        }
      ]
    },
    "HTTP POST /api/v1/billing/tenants/:tenant_id/billing_config_id/:billing_config_id/credits/:credit_id": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant and credit path binding succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "credits_packages",
              "trigger": "Load the requested credit package details for the tenant",
              "conditions": [
                "credit_id path parameter parsed successfully"
              ],
              "implementation": "marketing.CreditsPackageModel.GetCreditsPackage(creditIDStruct.CreditID)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/tenants/:tenant_id/billing_config_id/:billing_config_id/credits/:credit_id/actions/reclaim": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant and credit path binding succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "credits_packages",
              "trigger": "Load the credit package before reclaiming it",
              "conditions": [
                "credit_id path parameter parsed successfully"
              ],
              "implementation": "marketing.CreditsPackageModel.GetCreditsPackage(creditIDStruct.CreditID)"
            },
            {
              "operation": "UPDATE",
              "table": "credits_packages",
              "trigger": "Mark the credit package reclaimed and closed",
              "conditions": [
                "GetCreditsPackage(...) succeeded"
              ],
              "implementation": "marketing.CreditsPackageModel.CloseCreditsPackage(creditIDStruct.CreditID, entity.CreditsPackageClosedReason_Reclaimed)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/billing_config_id/:billing_config_id/contracts": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Always"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "contracts",
              "trigger": "Query contracts"
            }
          ]
        },
        "s3": {
          "conditions": [
            "contract file exists"
          ],
          "operations": [
            {
              "operation": "GET",
              "trigger": "Download contract file"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/billing_config_id/:billing_config_id/contracts/:contract_id": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant and contract path binding succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "contracts",
              "trigger": "Load the requested contract for the tenant",
              "conditions": [
                "contract_id path parameter parsed successfully"
              ],
              "implementation": "billing.ContractModel.GetContract(contractURIArgs.TenantID, contractURIArgs.ContractID)"
            }
          ]
        },
        "s3": {
          "conditions": [
            "Only when the returned contract references an uploaded file"
          ],
          "operations": [
            {
              "operation": "GET",
              "trigger": "Fetch the contract attachment linked from the stored contract metadata",
              "conditions": [
                "GetContract(...) returned a contract with file metadata"
              ]
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/tenants/:tenant_id/billing_config_id/:billing_config_id/contracts": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Always"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "contracts",
              "trigger": "Check existing contracts"
            },
            {
              "operation": "INSERT",
              "table": "contracts",
              "trigger": "Create contract"
            }
          ]
        },
        "s3": {
          "conditions": [
            "contract file uploaded"
          ],
          "operations": [
            {
              "operation": "PUT",
              "trigger": "Upload contract file"
            }
          ]
        }
      },
      "services": [
        {
          "name": "account-svc",
          "target_interface": "AccountAPIService.DownloadFile",
          "operation_type": "grpc_unary",
          "conditions": [
            "DBaaSCentralEnable == true",
            "central file exists"
          ],
          "operations": [
            {
              "operation": "gRPC DownloadFile",
              "trigger": "Download contract from central"
            }
          ]
        }
      ]
    },
    "HTTP PUT /api/v1/billing/tenants/:tenant_id/billing_config_id/:billing_config_id/contracts/:contract_id": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant and contract path binding succeeds and the request body binds successfully"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "contracts",
              "trigger": "Load the existing contract before applying field updates",
              "conditions": [
                "contract_id path parameter parsed successfully"
              ],
              "implementation": "billing.ContractModel.UpdateContract(contractURIArgs.TenantID, contractURIArgs.ContractID, contract)"
            },
            {
              "operation": "UPDATE",
              "table": "contracts",
              "trigger": "Persist the updated contract fields",
              "conditions": [
                "ShouldBindJSON(contract) succeeded"
              ],
              "implementation": "billing.ContractModel.UpdateContract(contractURIArgs.TenantID, contractURIArgs.ContractID, contract)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/tenants/:tenant_id/billing_config_id/:billing_config_id/contracts/:contract_id/actions/:action": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant, contract, and action path binding succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "contracts",
              "trigger": "Load the contract and validate the admin action against current contract state",
              "conditions": [
                "action in {create, submit, cancel, delete, terminate}"
              ],
              "implementation": "billing.ContractModel.OperateContractByAdmin(operateArgs.TenantID, &contractAction)"
            },
            {
              "operation": "UPDATE",
              "table": "contracts",
              "trigger": "Persist the admin action's contract state transition",
              "conditions": [
                "OperateContractByAdmin(...) accepted the requested action"
              ],
              "implementation": "billing.ContractModel.OperateContractByAdmin(operateArgs.TenantID, &contractAction)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /version": {
      "infrastructure": {},
      "services": []
    },
    "HTTP GET /api/v1/billing/payments_payable/tenant_ids": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Always"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "payment_methods",
              "trigger": "List tenant IDs whose active payment methods are currently payable",
              "implementation": "paymentModel.GetAllPayableTenantIDs()"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP PUT /api/v1/billing/tenants/:tenant_id/billing_config_id/:billing_config_id/payments/:payment_type/invoiceable": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant, billing_config_id, and payment_type binding succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "payment_methods",
              "trigger": "Load the targeted payment method before toggling its invoiceable flag",
              "conditions": [
                "c.ShouldBindUri(&paymentQueryStruct{}) succeeded"
              ],
              "implementation": "paymentModel.GetPaymentMethodWithPaymentType(paymentQuery.TenantID, paymentQuery.BillingConfigID, paymentQuery.PaymentType)"
            },
            {
              "operation": "UPDATE",
              "table": "payment_methods",
              "trigger": "Mark the selected payment method invoiceable",
              "conditions": [
                "GetPaymentMethodWithPaymentType(...) succeeded"
              ],
              "implementation": "paymentModel.UpdatePaymentInvoiceable(paymentMethod.PaymentMethodID)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP PUT /api/v1/billing/tenants/:tenant_id/billing_config_id/:billing_config_id/payments/:payment_type/code": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant, billing_config_id, payment_type, and request-body binding succeed"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "payment_methods",
              "trigger": "Load the targeted payment method and ensure invoiceable payments cannot mutate codes",
              "conditions": [
                "c.ShouldBindUri(&paymentQueryStruct{}) succeeded"
              ],
              "implementation": "paymentModel.GetPaymentMethodWithPaymentType(paymentQuery.TenantID, paymentQuery.BillingConfigID, paymentQuery.PaymentType)"
            },
            {
              "operation": "UPDATE",
              "table": "payment_methods",
              "trigger": "Persist the new payment code and optional payment sub-code",
              "conditions": [
                "paymentMethod.Invoiceable == false"
              ],
              "implementation": "paymentModel.UpdatePaymentCode(paymentQuery.TenantID, paymentMethod.PaymentMethodID, body.PaymentCode, body.PaymentSubCode)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/tenants/:tenant_id/commitment_invoices": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant and billing-config resolution succeeds and the request body binds successfully"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the active billing config that will own the commitment invoice",
              "conditions": [
                "getBillingCfgFromURI(c) succeeded"
              ],
              "implementation": "getBillingCfgFromURI(c)"
            },
            {
              "operation": "SELECT",
              "table": "payment_methods",
              "trigger": "Validate the optional payment code against the tenant's current active payment method",
              "conditions": [
                "createInvoiceReq.PaymentCode != nil"
              ],
              "implementation": "paymentsub.PaymentModel.GetActivePaymentMethod(billingCfgStruct.TenantID, billingCfgStruct.BillingConfigID)"
            },
            {
              "operation": "INSERT",
              "table": "invoices",
              "trigger": "Create the commitment invoice row for the resolved billing config",
              "conditions": [
                "payment-code validation passed or was skipped"
              ],
              "implementation": "invoiceModel.CreateCommitmentInvoice(billingCfgStruct.TenantID, createInvoiceReq)"
            },
            {
              "operation": "INSERT",
              "table": "invoice_items",
              "trigger": "Persist the commitment invoice line items produced by commitment-invoice creation",
              "conditions": [
                "CreateCommitmentInvoice(...) succeeded"
              ],
              "implementation": "invoiceModel.CreateCommitmentInvoice(...)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/tenants/:tenant_id/billing_config_id/:billing_config_id/commitment_invoices": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant and billing-config resolution succeeds and the request body binds successfully"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the explicit billing config that will own the commitment invoice",
              "conditions": [
                "getBillingCfgFromURI(c) succeeded"
              ],
              "implementation": "getBillingCfgFromURI(c)"
            },
            {
              "operation": "SELECT",
              "table": "payment_methods",
              "trigger": "Validate the optional payment code against the active payment method of the explicit billing config",
              "conditions": [
                "createInvoiceReq.PaymentCode != nil"
              ],
              "implementation": "paymentsub.PaymentModel.GetActivePaymentMethod(billingCfgStruct.TenantID, billingCfgStruct.BillingConfigID)"
            },
            {
              "operation": "INSERT",
              "table": "invoices",
              "trigger": "Create the commitment invoice row for the explicit billing config",
              "conditions": [
                "payment-code validation passed or was skipped"
              ],
              "implementation": "invoiceModel.CreateCommitmentInvoice(billingCfgStruct.TenantID, createInvoiceReq)"
            },
            {
              "operation": "INSERT",
              "table": "invoice_items",
              "trigger": "Persist the commitment invoice line items produced by commitment-invoice creation",
              "conditions": [
                "CreateCommitmentInvoice(...) succeeded"
              ],
              "implementation": "invoiceModel.CreateCommitmentInvoice(...)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/opened_credits/tenant_ids": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Always"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "credits_packages",
              "trigger": "List tenant IDs that still have opened credit packages",
              "implementation": "marketing.CreditsPackageModel.GetAllCreditsOpenedTenantIDs()"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/users/contracts": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant and billing-config resolution succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the active billing config whose user-visible contracts should be listed",
              "conditions": [
                "getBillingCfgFromURI(c) succeeded"
              ],
              "implementation": "getBillingCfgFromURI(c)"
            },
            {
              "operation": "SELECT",
              "table": "contracts",
              "trigger": "List contracts visible to end users for the resolved billing config",
              "conditions": [
                "pagination.GetPagination(c) succeeded"
              ],
              "implementation": "contractModel.ListUserViewContracts(billingCfgStruct.TenantID, billingCfgStruct.BillingConfigID, p)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/users/contracts/:contract_id": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant, contract, and billing-config resolution succeed"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the active billing config whose user-visible contract view is being requested",
              "conditions": [
                "getBillingConfigIDFromURI(c) succeeded"
              ],
              "implementation": "getBillingConfigIDFromURI(c)"
            },
            {
              "operation": "SELECT",
              "table": "contracts",
              "trigger": "Load the user-visible contract projection scoped by tenant, billing config, and contract ID",
              "conditions": [
                "getContractURIParams(c) succeeded"
              ],
              "implementation": "contractModel.GetUserViewContract(contractURIArgs.TenantID, billingConfigID, contractURIArgs.ContractID)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/tenants/:tenant_id/users/contracts/:contract_id/actions/:action": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant, contract, and action path binding succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "contracts",
              "trigger": "Load the contract before applying the user action and again while building the audit-log payload",
              "conditions": [
                "c.ShouldBindUri(&ContractOperationURIStruct{}) succeeded"
              ],
              "implementation": "contractModel.OperateContractByUser(operateArgs.TenantID, &contractAction) + contractModel.GetContract(operateArgs.TenantID, operateArgs.ContractID)"
            },
            {
              "operation": "UPDATE",
              "table": "contracts",
              "trigger": "Persist the user contract state transition such as accept or reject",
              "conditions": [
                "OperateContractByUser(...) accepted the requested action"
              ],
              "implementation": "contractModel.OperateContractByUser(operateArgs.TenantID, &contractAction)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/billing_config_id/:billing_config_id/users/contracts": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant and billing-config resolution succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the explicit billing config whose user-visible contracts should be listed",
              "conditions": [
                "getBillingCfgFromURI(c) succeeded"
              ],
              "implementation": "getBillingCfgFromURI(c)"
            },
            {
              "operation": "SELECT",
              "table": "contracts",
              "trigger": "List contracts visible to end users for the explicit billing config",
              "conditions": [
                "pagination.GetPagination(c) succeeded"
              ],
              "implementation": "contractModel.ListUserViewContracts(billingCfgStruct.TenantID, billingCfgStruct.BillingConfigID, p)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/billing_config_id/:billing_config_id/users/contracts/:contract_id": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant, contract, and billing-config resolution succeed"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the explicit billing config whose user-visible contract view is being requested",
              "conditions": [
                "getBillingConfigIDFromURI(c) succeeded"
              ],
              "implementation": "getBillingConfigIDFromURI(c)"
            },
            {
              "operation": "SELECT",
              "table": "contracts",
              "trigger": "Load the user-visible contract projection scoped by tenant, explicit billing config, and contract ID",
              "conditions": [
                "getContractURIParams(c) succeeded"
              ],
              "implementation": "contractModel.GetUserViewContract(contractURIArgs.TenantID, billingConfigID, contractURIArgs.ContractID)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/tenants/:tenant_id/billing_config_id/:billing_config_id/users/contracts/:contract_id/actions/:action": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant, contract, and action path binding succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "contracts",
              "trigger": "Load the contract before applying the user action and again while building the audit-log payload",
              "conditions": [
                "c.ShouldBindUri(&ContractOperationURIStruct{}) succeeded"
              ],
              "implementation": "contractModel.OperateContractByUser(operateArgs.TenantID, &contractAction) + contractModel.GetContract(operateArgs.TenantID, operateArgs.ContractID)"
            },
            {
              "operation": "UPDATE",
              "table": "contracts",
              "trigger": "Persist the user contract state transition such as accept or reject",
              "conditions": [
                "OperateContractByUser(...) accepted the requested action"
              ],
              "implementation": "contractModel.OperateContractByUser(operateArgs.TenantID, &contractAction)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/billing_company": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant_id path parsing succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "tenant_billing_companies",
              "trigger": "Load the tenant-specific billing company binding",
              "conditions": [
                "getTenantIDFromURI(c) succeeded"
              ],
              "implementation": "paymentsub.BillingInformationModel.GetTenantBillingCompany(tenantID)"
            },
            {
              "operation": "SELECT",
              "table": "billing_companies",
              "trigger": "Hydrate the billing company metadata referenced by the tenant-company binding",
              "conditions": [
                "GetTenantBillingCompany(...) succeeded"
              ],
              "implementation": "paymentsub.BillingInformationModel.GetTenantBillingCompany(tenantID)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP PUT /api/v1/billing/tenants/:tenant_id/billing_company": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant_id path parsing and request-body binding succeed"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_companies",
              "trigger": "Validate the requested billing company key before rebinding the tenant",
              "conditions": [
                "ShouldBindJSON(company) succeeded"
              ],
              "implementation": "paymentsub.BillingInformationModel.UpdateTenantBillingCompany(tenantID, company)"
            },
            {
              "operation": "INSERT",
              "table": "tenant_billing_companies",
              "trigger": "Create or update the tenant-to-company binding",
              "conditions": [
                "UpdateTenantBillingCompany(...) entered its transaction"
              ],
              "implementation": "paymentsub.BillingInformationModel.UpdateTenantBillingCompany(tenantID, company)"
            },
            {
              "operation": "UPDATE",
              "table": "tenant_billing_companies",
              "trigger": "Persist the new tenant billing-company binding",
              "conditions": [
                "UpdateTenantBillingCompany(...) entered its transaction"
              ],
              "implementation": "paymentsub.BillingInformationModel.UpdateTenantBillingCompany(tenantID, company)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/billing_configs": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant_id path parsing succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "List every billing config bound to the tenant",
              "conditions": [
                "getTenantIDFromURI(c) succeeded"
              ],
              "implementation": "BillingConfigModel.GetTenantIDAllBillingConfigID(tenantID)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/billing_configs/managed_tenants/:tenant_id": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant_id path parsing succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Find the billing config that manages the target tenant",
              "conditions": [
                "getTenantIDFromURI(c) succeeded"
              ],
              "implementation": "BillingConfigModel.GetBillingConfigByManagedTenantID(tenantID)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/tenants/:tenant_id/cppo_billing_config": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after request-body binding succeeds"
          ],
          "operations": [
            {
              "operation": "INSERT",
              "table": "support_plans",
              "trigger": "Create the optional private support plan embedded in the CPPO config request",
              "conditions": [
                "request.SupportPlanInfo != nil"
              ],
              "implementation": "marketing.SupportPlanModel.CreateSupportPlan(&request.SupportPlanInfo.SupportPlan)"
            },
            {
              "operation": "INSERT",
              "table": "billing_configs",
              "trigger": "Create the customer and reseller billing-config pair for the marketplace reseller relationship",
              "conditions": [
                "request validated successfully"
              ],
              "implementation": "BillingConfigModel.CreateMarketplaceResellerBillingConfig(request.MarketplaceResellerBillingConfig)"
            },
            {
              "operation": "INSERT",
              "table": "payment_methods",
              "trigger": "Create and activate the customer and reseller marketplace transfer payment methods",
              "conditions": [
                "CreateMarketplaceResellerBillingConfig(...) succeeded"
              ],
              "implementation": "paymentModel.CreatePaymentMethodAndActive(request.TenantID, ...) + paymentModel.CreatePaymentMethodAndActive(request.ResellerId, ...)"
            },
            {
              "operation": "INSERT",
              "table": "discounts",
              "trigger": "Create reseller discounts scoped to the new payment billing config",
              "conditions": [
                "request.Discounts is not empty"
              ],
              "implementation": "discountModel.CreateDiscount(request.ResellerId, &d)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/tenants/:tenant_id/mcpo_billing_config": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after request-body binding succeeds"
          ],
          "operations": [
            {
              "operation": "INSERT",
              "table": "support_plans",
              "trigger": "Create the optional private support plan embedded in the MCPO config request",
              "conditions": [
                "request.SupportPlanInfo != nil"
              ],
              "implementation": "marketing.SupportPlanModel.CreateSupportPlan(&request.SupportPlanInfo.SupportPlan)"
            },
            {
              "operation": "INSERT",
              "table": "billing_configs",
              "trigger": "Create the customer and reseller billing-config pair for the marketplace reseller relationship",
              "conditions": [
                "request validated successfully"
              ],
              "implementation": "BillingConfigModel.CreateMarketplaceResellerBillingConfig(request.MarketplaceResellerBillingConfig)"
            },
            {
              "operation": "INSERT",
              "table": "payment_methods",
              "trigger": "Create and activate the customer and reseller marketplace transfer payment methods",
              "conditions": [
                "CreateMarketplaceResellerBillingConfig(...) succeeded"
              ],
              "implementation": "paymentModel.CreatePaymentMethodAndActive(request.TenantID, ...) + paymentModel.CreatePaymentMethodAndActive(request.ResellerId, ...)"
            },
            {
              "operation": "INSERT",
              "table": "discounts",
              "trigger": "Create reseller discounts scoped to the new payment billing config",
              "conditions": [
                "request.Discounts is not empty"
              ],
              "implementation": "discountModel.CreateDiscount(request.ResellerId, &d)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/tenants/:tenant_id/billing_action_check": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant_id path parsing and request-body binding succeed"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the tenant's active billing config before running provider/payable/closing checks",
              "conditions": [
                "control.Model.BillingActionCheck(tenantID, &action) reached GetActiveBillingConfigID"
              ],
              "implementation": "billingconfig.BillingConfigModel.GetActiveBillingConfigID(tenantID)"
            },
            {
              "operation": "SELECT",
              "table": "payment_methods",
              "trigger": "Inspect the active payment method to derive provider restrictions and payability",
              "conditions": [
                "billing config exists for tenant"
              ],
              "implementation": "paymentsub.PaymentModel.GetActivePaymentMethod(tenantID, billingConfigID)"
            },
            {
              "operation": "SELECT",
              "table": "tenant_plans",
              "trigger": "Inspect the tenant's effective plan to enforce closing/org-payability restrictions",
              "conditions": [
                "action requires non-view billability checks"
              ],
              "implementation": "plan.TenantPlanModel.GetTenantEffectivePlan(tenantID)"
            }
          ]
        }
      },
      "services": [
        {
          "name": "account-svc",
          "target_interface": "AccountAPIService.GetOrgByID",
          "operation_type": "grpc_unary",
          "conditions": [
            "Only when provider checks must fall back to the tenant's third-party account metadata or POC/internal-user checks"
          ],
          "operations": [
            {
              "operation": "gRPC GetOrgByID",
              "trigger": "Load tenant metadata for third-party-provider and POC/internal-user checks",
              "conditions": [
                "EnableThirdPartyProviderFromAccountCheck == true or tenant plan is POC"
              ],
              "implementation": "centralhandler.GetCentralHandler().GetTenant(tenantID)"
            }
          ]
        }
      ]
    },
    "HTTP POST /api/v1/billing/tenants/:tenant_id/billing_action_check/_batch": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant_id path parsing and batch request-body binding succeed"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the tenant's active billing config before running provider/payable/closing checks for each requested action",
              "conditions": [
                "control.Model.BillingActionCheck(...) is reached for each batch item"
              ],
              "implementation": "billingconfig.BillingConfigModel.GetActiveBillingConfigID(tenantID)"
            },
            {
              "operation": "SELECT",
              "table": "payment_methods",
              "trigger": "Inspect the active payment method to derive provider restrictions and payability for each batch item",
              "conditions": [
                "billing config exists for tenant"
              ],
              "implementation": "paymentsub.PaymentModel.GetActivePaymentMethod(tenantID, billingConfigID)"
            },
            {
              "operation": "SELECT",
              "table": "tenant_plans",
              "trigger": "Inspect the tenant's effective plan to enforce closing/org-payability restrictions for each batch item",
              "conditions": [
                "batch item requires non-view billability checks"
              ],
              "implementation": "plan.TenantPlanModel.GetTenantEffectivePlan(tenantID)"
            }
          ]
        }
      },
      "services": [
        {
          "name": "account-svc",
          "target_interface": "AccountAPIService.GetOrgByID",
          "operation_type": "grpc_unary",
          "conditions": [
            "Only when provider checks must fall back to the tenant's third-party account metadata or POC/internal-user checks"
          ],
          "operations": [
            {
              "operation": "gRPC GetOrgByID",
              "trigger": "Load tenant metadata for third-party-provider and POC/internal-user checks across the batch",
              "conditions": [
                "EnableThirdPartyProviderFromAccountCheck == true or tenant plan is POC"
              ],
              "implementation": "centralhandler.GetCentralHandler().GetTenant(tenantID)"
            }
          ]
        }
      ]
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/plans/ondemand/discounts": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant and billing-config resolution succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the billing config whose bound on-demand discount should be returned",
              "conditions": [
                "c.ShouldBindUri(&BillingCfgStruct{}) succeeded"
              ],
              "implementation": "getBillingCfgFromURI(c)"
            },
            {
              "operation": "SELECT",
              "table": "discounts",
              "trigger": "List tenant discounts for the resolved billing config and return the newest bound on-demand discount or NoDiscount",
              "conditions": [
                "getBillingCfgFromURI(c) resolved billingCfgStruct.TenantID and billingCfgStruct.BillingConfigID"
              ],
              "implementation": "discount.Model.GetTenantOnDemandDiscount(...) -> ListTenantDiscounts(tenantID, billingConfigID)"
            },
            {
              "operation": "SELECT",
              "table": "unit_filters",
              "trigger": "Hydrate unit-filter associations while materializing the newest bound on-demand discount row",
              "conditions": [
                "ListTenantDiscounts(...) found persisted discount rows"
              ],
              "implementation": "entity.NewDiscountQuerySet(db.GetDB().Preload(clause.Associations)).TenantIDEq(...).BindedBillingConfigIDEq(...).All(&discountEntities)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP PUT /api/v1/billing/tenants/:tenant_id/plans/ondemand/discounts": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant and billing-config resolution succeeds, request JSON binds successfully, and the active payment method is not MSP"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the billing config whose bound on-demand discount should be mutated",
              "conditions": [
                "c.ShouldBindUri(&BillingCfgStruct{}) succeeded"
              ],
              "implementation": "getBillingCfgFromURI(c)"
            },
            {
              "operation": "SELECT",
              "table": "payment_methods",
              "trigger": "Reject MSP-customer billing configs because they are not allowed to manage on-demand discounts directly",
              "conditions": [
                "ShouldBindJSON(&forms.Discount{}) succeeded"
              ],
              "implementation": "paymentModel.IsMspPayment(billingCfgStruct.TenantID, billingCfgStruct.BillingConfigID) -> GetActivePaymentMethod(...)"
            },
            {
              "operation": "SELECT",
              "table": "unit_filters",
              "trigger": "Load the default discount unit filters used to seed the singleton bound-discount row when it does not exist yet",
              "conditions": [
                "IsMspPayment(...) returned false"
              ],
              "implementation": "discount.Model.SetDiscount(...) -> db.GetDB().Model(&entity.UnitFilter{}).Where(\"name in (?)\", DefaultDiscountUnitFilters).Find(&unitFilters)"
            },
            {
              "operation": "INSERT",
              "table": "discounts",
              "trigger": "Insert the singleton bound-discount row with OldDiscountUniqueMark if the tenant has never bound an on-demand discount before",
              "conditions": [
                "IsMspPayment(...) returned false"
              ],
              "implementation": "discount.Model.SetDiscount(...) -> db.GetDB().Clauses(clause.Insert{Modifier:\"IGNORE\"}).Create(&discountEntity)"
            },
            {
              "operation": "SELECT",
              "table": "discounts",
              "trigger": "Reload the singleton bound-discount row before applying the new discount value",
              "conditions": [
                "Insert IGNORE completed"
              ],
              "implementation": "entity.NewDiscountQuerySet(db.GetDB()).OldDiscountUniqueMarkEq(changeInfo.ChangerTenantID).TenantIDEq(changeInfo.ChangerTenantID).One(&discountEntity)"
            },
            {
              "operation": "INSERT",
              "table": "discount_versions",
              "trigger": "Persist the version row that snapshots the updated bound-discount value",
              "conditions": [
                "discount.Model.UpdateDiscount(...) transaction started"
              ],
              "implementation": "discount.Model.CreateDiscountVersion(tx, tenantID, info)"
            },
            {
              "operation": "INSERT",
              "table": "audit_records",
              "trigger": "Persist the bound-discount audit record inside the update transaction",
              "conditions": [
                "CreateDiscountVersion(...) succeeded"
              ],
              "implementation": "discount.Model.CreateDiscountChangeAuditLog(tx, tenantID, info)"
            },
            {
              "operation": "UPDATE",
              "table": "discounts",
              "trigger": "Store the new bound-discount value and version on the singleton discount row",
              "conditions": [
                "ValidateDiscountReq(info) succeeded"
              ],
              "implementation": "entity.NewDiscountQuerySet(tx).IDEq(discountID).GetUpdater().SetVersion(version).SetValue(value).Update()"
            },
            {
              "operation": "SELECT",
              "table": "discounts",
              "trigger": "Re-read the updated bound-discount row after the transaction persists the new value",
              "conditions": [
                "discount update succeeded"
              ],
              "implementation": "discount.Model.GetDiscountWithTx(tx, tenantID, discountID)"
            }
          ]
        },
        "redis": {
          "conditions": [
            "Only when the tenant has active-discount cache entries for the affected billing config"
          ],
          "operations": [
            {
              "operation": "DEL",
              "trigger": "Invalidate the active-discount cache for the affected tenant/billing-config pair after the update completes",
              "conditions": [
                "discount.Model.UpdateDiscount(...) committed successfully"
              ],
              "implementation": "cachehandler.Get().Delete(\"ListTenantActiveDiscounts\", tenantID, ret.BindedBillingConfigID)"
            }
          ]
        }
      },
      "services": [
        {
          "name": "account-svc",
          "target_interface": "AccountAPIService.GetOrgByID",
          "operation_type": "grpc_unary",
          "conditions": [
            "Only when the updated bound-discount row remains active and in-app discount notifications are enabled"
          ],
          "operations": [
            {
              "operation": "gRPC GetOrgByID",
              "trigger": "Load tenant metadata so the bound-discount notification can include org name",
              "conditions": [
                "discount.Model.sendDiscountChangeNotificationIfNeed(...) did not early-return on inactive or tenant_id == 0"
              ],
              "implementation": "centralhandler.GetCentralHandler().GetTenant(targetDiscount.TenantID) -> account.GetOrgByID(IsBrief=true)"
            }
          ]
        },
        {
          "name": "novu-api",
          "target_interface": "POST /v1/events/trigger/bulk",
          "operation_type": "http_post",
          "conditions": [
            "Only when InAPPNotificationEnable == true and the updated bound-discount row remains active"
          ],
          "operations": [
            {
              "operation": "HTTP BulkTriggerEvent",
              "trigger": "Notify org users that the tenant discount changed after the on-demand discount update committed",
              "conditions": [
                "discount.Model.sendDiscountChangeNotificationIfNeed(...) selected the update notification path"
              ],
              "implementation": "uncutils.SendInAppNotification(...) -> novuhandler.Get().BulkTriggerEvent(...)"
            }
          ]
        }
      ]
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/plans/ondemand/effective-discounts": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant and billing-config resolution succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the billing config before running the aliased effective-discounts handler",
              "conditions": [
                "c.ShouldBindUri(&BillingCfgStruct{}) succeeded"
              ],
              "implementation": "GetTenantEffectiveDiscount(c) -> GetTenantDiscount(c) -> getBillingCfgFromURI(c)"
            },
            {
              "operation": "SELECT",
              "table": "discounts",
              "trigger": "Return the same newest tenant-bound on-demand discount that GetTenantDiscount would return",
              "conditions": [
                "GetTenantEffectiveDiscount(...) reuses GetTenantDiscount(...) instead of ListEffectiveDiscounts(...)"
              ],
              "implementation": "discount.Model.GetTenantOnDemandDiscount(...) -> ListTenantDiscounts(tenantID, billingConfigID)"
            },
            {
              "operation": "SELECT",
              "table": "unit_filters",
              "trigger": "Hydrate unit-filter associations for the aliased GetTenantDiscount path",
              "conditions": [
                "ListTenantDiscounts(...) found persisted discount rows"
              ],
              "implementation": "entity.NewDiscountQuerySet(db.GetDB().Preload(clause.Associations)).TenantIDEq(...).BindedBillingConfigIDEq(...).All(&discountEntities)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/billing_config_id/:billing_config_id/plans/ondemand/discounts": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant and explicit billing_config_id resolution succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Load and tenant-check the explicit billing config before reading its bound on-demand discount",
              "conditions": [
                "c.ShouldBindUri(&BillingCfgStruct{}) succeeded"
              ],
              "implementation": "getBillingCfgFromURI(c) -> billingconfig.BillingConfigModel.GetBillingConfig(billing_config_id)"
            },
            {
              "operation": "SELECT",
              "table": "discounts",
              "trigger": "List tenant discounts for the explicit billing config and return the newest bound on-demand discount or NoDiscount",
              "conditions": [
                "ret.TenantID == billingCfgStruct.TenantID"
              ],
              "implementation": "discount.Model.GetTenantOnDemandDiscount(...) -> ListTenantDiscounts(tenantID, billingConfigID)"
            },
            {
              "operation": "SELECT",
              "table": "unit_filters",
              "trigger": "Hydrate unit-filter associations while materializing the bound discount for the explicit billing config",
              "conditions": [
                "ListTenantDiscounts(...) found persisted discount rows"
              ],
              "implementation": "entity.NewDiscountQuerySet(db.GetDB().Preload(clause.Associations)).TenantIDEq(...).BindedBillingConfigIDEq(...).All(&discountEntities)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP PUT /api/v1/billing/tenants/:tenant_id/billing_config_id/:billing_config_id/plans/ondemand/discounts": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant and explicit billing_config_id resolution succeeds, request JSON binds successfully, and the active payment method is not MSP"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Load and tenant-check the explicit billing config before mutating its bound on-demand discount",
              "conditions": [
                "c.ShouldBindUri(&BillingCfgStruct{}) succeeded"
              ],
              "implementation": "getBillingCfgFromURI(c) -> billingconfig.BillingConfigModel.GetBillingConfig(billing_config_id)"
            },
            {
              "operation": "SELECT",
              "table": "payment_methods",
              "trigger": "Reject MSP-customer billing configs because they are not allowed to manage on-demand discounts directly",
              "conditions": [
                "ret.TenantID == billingCfgStruct.TenantID",
                "ShouldBindJSON(&forms.Discount{}) succeeded"
              ],
              "implementation": "paymentModel.IsMspPayment(billingCfgStruct.TenantID, billingCfgStruct.BillingConfigID) -> GetActivePaymentMethod(...)"
            },
            {
              "operation": "SELECT",
              "table": "unit_filters",
              "trigger": "Load the default discount unit filters used to seed the singleton bound-discount row when it does not exist yet",
              "conditions": [
                "IsMspPayment(...) returned false"
              ],
              "implementation": "discount.Model.SetDiscount(...) -> db.GetDB().Model(&entity.UnitFilter{}).Where(\"name in (?)\", DefaultDiscountUnitFilters).Find(&unitFilters)"
            },
            {
              "operation": "INSERT",
              "table": "discounts",
              "trigger": "Insert the singleton bound-discount row for the explicit billing config if the tenant has never bound one before",
              "conditions": [
                "IsMspPayment(...) returned false"
              ],
              "implementation": "discount.Model.SetDiscount(...) -> db.GetDB().Clauses(clause.Insert{Modifier:\"IGNORE\"}).Create(&discountEntity)"
            },
            {
              "operation": "SELECT",
              "table": "discounts",
              "trigger": "Reload the singleton bound-discount row before applying the new discount value",
              "conditions": [
                "Insert IGNORE completed"
              ],
              "implementation": "entity.NewDiscountQuerySet(db.GetDB()).OldDiscountUniqueMarkEq(changeInfo.ChangerTenantID).TenantIDEq(changeInfo.ChangerTenantID).One(&discountEntity)"
            },
            {
              "operation": "INSERT",
              "table": "discount_versions",
              "trigger": "Persist the version row that snapshots the updated bound-discount value",
              "conditions": [
                "discount.Model.UpdateDiscount(...) transaction started"
              ],
              "implementation": "discount.Model.CreateDiscountVersion(tx, tenantID, info)"
            },
            {
              "operation": "INSERT",
              "table": "audit_records",
              "trigger": "Persist the bound-discount audit record inside the update transaction",
              "conditions": [
                "CreateDiscountVersion(...) succeeded"
              ],
              "implementation": "discount.Model.CreateDiscountChangeAuditLog(tx, tenantID, info)"
            },
            {
              "operation": "UPDATE",
              "table": "discounts",
              "trigger": "Store the new bound-discount value and version on the singleton discount row",
              "conditions": [
                "ValidateDiscountReq(info) succeeded"
              ],
              "implementation": "entity.NewDiscountQuerySet(tx).IDEq(discountID).GetUpdater().SetVersion(version).SetValue(value).Update()"
            },
            {
              "operation": "SELECT",
              "table": "discounts",
              "trigger": "Re-read the updated bound-discount row after the transaction persists the new value",
              "conditions": [
                "discount update succeeded"
              ],
              "implementation": "discount.Model.GetDiscountWithTx(tx, tenantID, discountID)"
            }
          ]
        },
        "redis": {
          "conditions": [
            "Only when the tenant has active-discount cache entries for the affected billing config"
          ],
          "operations": [
            {
              "operation": "DEL",
              "trigger": "Invalidate the active-discount cache for the affected tenant/billing-config pair after the update completes",
              "conditions": [
                "discount.Model.UpdateDiscount(...) committed successfully"
              ],
              "implementation": "cachehandler.Get().Delete(\"ListTenantActiveDiscounts\", tenantID, ret.BindedBillingConfigID)"
            }
          ]
        }
      },
      "services": [
        {
          "name": "account-svc",
          "target_interface": "AccountAPIService.GetOrgByID",
          "operation_type": "grpc_unary",
          "conditions": [
            "Only when the updated bound-discount row remains active and in-app discount notifications are enabled"
          ],
          "operations": [
            {
              "operation": "gRPC GetOrgByID",
              "trigger": "Load tenant metadata so the bound-discount notification can include org name",
              "conditions": [
                "discount.Model.sendDiscountChangeNotificationIfNeed(...) did not early-return on inactive or tenant_id == 0"
              ],
              "implementation": "centralhandler.GetCentralHandler().GetTenant(targetDiscount.TenantID) -> account.GetOrgByID(IsBrief=true)"
            }
          ]
        },
        {
          "name": "novu-api",
          "target_interface": "POST /v1/events/trigger/bulk",
          "operation_type": "http_post",
          "conditions": [
            "Only when InAPPNotificationEnable == true and the updated bound-discount row remains active"
          ],
          "operations": [
            {
              "operation": "HTTP BulkTriggerEvent",
              "trigger": "Notify org users that the tenant discount changed after the on-demand discount update committed",
              "conditions": [
                "discount.Model.sendDiscountChangeNotificationIfNeed(...) selected the update notification path"
              ],
              "implementation": "uncutils.SendInAppNotification(...) -> novuhandler.Get().BulkTriggerEvent(...)"
            }
          ]
        }
      ]
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/billing_config_id/:billing_config_id/plans/ondemand/effective-discounts": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant and explicit billing_config_id resolution succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Load and tenant-check the explicit billing config before running the aliased effective-discounts handler",
              "conditions": [
                "c.ShouldBindUri(&BillingCfgStruct{}) succeeded"
              ],
              "implementation": "GetTenantEffectiveDiscount(c) -> GetTenantDiscount(c) -> getBillingCfgFromURI(c) -> billingconfig.BillingConfigModel.GetBillingConfig(billing_config_id)"
            },
            {
              "operation": "SELECT",
              "table": "discounts",
              "trigger": "Return the same newest tenant-bound on-demand discount that GetTenantDiscount would return for the explicit billing config",
              "conditions": [
                "GetTenantEffectiveDiscount(...) reuses GetTenantDiscount(...) instead of ListEffectiveDiscounts(...)"
              ],
              "implementation": "discount.Model.GetTenantOnDemandDiscount(...) -> ListTenantDiscounts(tenantID, billingConfigID)"
            },
            {
              "operation": "SELECT",
              "table": "unit_filters",
              "trigger": "Hydrate unit-filter associations for the aliased GetTenantDiscount path",
              "conditions": [
                "ListTenantDiscounts(...) found persisted discount rows"
              ],
              "implementation": "entity.NewDiscountQuerySet(db.GetDB().Preload(clause.Associations)).TenantIDEq(...).BindedBillingConfigIDEq(...).All(&discountEntities)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/discounts": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant and billing-config resolution succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the billing config whose tenant discount history should be listed",
              "conditions": [
                "c.ShouldBindUri(&BillingCfgStruct{}) succeeded"
              ],
              "implementation": "getBillingCfgFromURI(c)"
            },
            {
              "operation": "SELECT",
              "table": "discounts",
              "trigger": "List all discount rows bound to the resolved tenant/billing-config pair",
              "conditions": [
                "getBillingCfgFromURI(c) resolved billingCfgStruct.TenantID and billingCfgStruct.BillingConfigID"
              ],
              "implementation": "discount.Model.ListTenantDiscounts(billingCfgStruct.TenantID, billingCfgStruct.BillingConfigID)"
            },
            {
              "operation": "SELECT",
              "table": "unit_filters",
              "trigger": "Hydrate unit-filter associations for each discount row returned in the history list",
              "conditions": [
                "ListTenantDiscounts(...) reached the preload query"
              ],
              "implementation": "entity.NewDiscountQuerySet(db.GetDB().Preload(clause.Associations)).TenantIDEq(...).BindedBillingConfigIDEq(...).All(&discountEntities)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/users/discounts": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant and billing-config resolution succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the billing config whose console-view discounts should be listed",
              "conditions": [
                "c.ShouldBindUri(&BillingCfgStruct{}) succeeded"
              ],
              "implementation": "getBillingCfgFromURI(c)"
            },
            {
              "operation": "SELECT",
              "table": "discounts",
              "trigger": "List tenant-bound discounts and merge active global discounts before returning the console-view payload",
              "conditions": [
                "getBillingCfgFromURI(c) resolved billingCfgStruct.TenantID and billingCfgStruct.BillingConfigID"
              ],
              "implementation": "discount.Model.ListDiscountsConsoleView(...) -> ListTenantDiscounts(...) + ListGlobalActiveDiscounts()"
            },
            {
              "operation": "SELECT",
              "table": "unit_filters",
              "trigger": "Hydrate unit-filter associations for tenant and global discount rows that survive console-view filtering",
              "conditions": [
                "ListDiscountsConsoleView(...) loaded discount rows"
              ],
              "implementation": "ListTenantDiscounts / ListGlobalActiveDiscounts -> entity.NewDiscountQuerySet(db.GetDB().Preload(clause.Associations))"
            }
          ]
        },
        "redis": {
          "conditions": [
            "Only when global active discounts are included in the console-view payload"
          ],
          "operations": [
            {
              "operation": "GET",
              "trigger": "Reuse cached global active discount entities when merging them into the tenant console-view list",
              "conditions": [
                "ListDiscountsConsoleView(...) reached ListGlobalActiveDiscounts()"
              ],
              "implementation": "discount.Model.ListGlobalActiveDiscounts() -> ListTenantActiveDiscounts(...) -> cachehandler.Get().Get(\"ListTenantActiveDiscounts\", ...)"
            },
            {
              "operation": "SET",
              "trigger": "Cache global active discount entities after the DB lookup succeeds",
              "conditions": [
                "ListTenantActiveDiscounts(...) queried active discount entities from MySQL"
              ],
              "implementation": "cachehandler.Get().Set(\"ListTenantActiveDiscounts\", &discountEntities, tenantID, billingConfigID)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/tenants/:tenant_id/discounts": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after request JSON binds successfully, tenant and billing-config resolution succeeds, and the active payment method is not MSP"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the billing config that the new tenant discount should bind to",
              "conditions": [
                "ShouldBindJSON(&forms.Discount{}) succeeded"
              ],
              "implementation": "getBillingCfgFromURI(c)"
            },
            {
              "operation": "SELECT",
              "table": "payment_methods",
              "trigger": "Reject MSP-customer billing configs because they are not allowed to create discounts directly",
              "conditions": [
                "getBillingCfgFromURI(c) resolved billingCfgStruct.TenantID and billingCfgStruct.BillingConfigID"
              ],
              "implementation": "paymentModel.IsMspPayment(billingCfgStruct.TenantID, billingCfgStruct.BillingConfigID) -> GetActivePaymentMethod(...)"
            },
            {
              "operation": "SELECT",
              "table": "unit_filters",
              "trigger": "Resolve copy arguments before optionally cloning unit-filter rows for the new discount",
              "conditions": [
                "IsMspPayment(...) returned false"
              ],
              "implementation": "unit_filter.Model.GetCopyArgs(&d.CopyUnitFilterArgs)"
            },
            {
              "operation": "INSERT",
              "table": "unit_filters",
              "trigger": "Create copied unit-filter rows when the request asks to duplicate filters from an existing source",
              "conditions": [
                "copyArgs != nil"
              ],
              "implementation": "unit_filter.Model.CreateCopiedUnitFilters(d.UnitFilters, copyArgs)"
            },
            {
              "operation": "INSERT",
              "table": "discount_versions",
              "trigger": "Persist the initial version row for the newly created discount",
              "conditions": [
                "ValidateDiscountReq(info) succeeded"
              ],
              "implementation": "discount.Model.CreateDiscountVersion(tx, tenantID, info)"
            },
            {
              "operation": "INSERT",
              "table": "audit_records",
              "trigger": "Persist the discount-change audit record inside the create transaction",
              "conditions": [
                "CreateDiscountVersion(...) succeeded"
              ],
              "implementation": "discount.Model.CreateDiscountChangeAuditLog(tx, tenantID, info)"
            },
            {
              "operation": "INSERT",
              "table": "discounts",
              "trigger": "Create the new tenant discount row bound to the resolved billing config",
              "conditions": [
                "ValidateDiscountReq(info) succeeded"
              ],
              "implementation": "discount.Model.CreateDiscountWithTx(...) -> ent.Create(tx)"
            },
            {
              "operation": "SELECT",
              "table": "discounts",
              "trigger": "Re-read the newly created discount row after persistence succeeds",
              "conditions": [
                "ent.Create(tx) succeeded"
              ],
              "implementation": "discount.Model.GetDiscountWithTx(tx, tenantID, ent.ID)"
            }
          ]
        },
        "redis": {
          "conditions": [
            "Only when the tenant has active-discount cache entries for the affected billing config"
          ],
          "operations": [
            {
              "operation": "DEL",
              "trigger": "Invalidate the active-discount cache for the affected tenant/billing-config pair after creation completes",
              "conditions": [
                "discount.Model.CreateDiscount(...) committed successfully"
              ],
              "implementation": "cachehandler.Get().Delete(\"ListTenantActiveDiscounts\", tenantID, *info.BindedBillingConfigID)"
            }
          ]
        }
      },
      "services": [
        {
          "name": "account-svc",
          "target_interface": "AccountAPIService.GetOrgByID",
          "operation_type": "grpc_unary",
          "conditions": [
            "Only when the created discount targets a non-zero tenant and in-app discount notifications are enabled"
          ],
          "operations": [
            {
              "operation": "gRPC GetOrgByID",
              "trigger": "Load tenant metadata so the created-discount notification can include org name",
              "conditions": [
                "discount.Model.sendDiscountChangeNotificationIfNeed(...) did not early-return on tenant_id == 0"
              ],
              "implementation": "centralhandler.GetCentralHandler().GetTenant(targetDiscount.TenantID) -> account.GetOrgByID(IsBrief=true)"
            }
          ]
        },
        {
          "name": "novu-api",
          "target_interface": "POST /v1/events/trigger/bulk",
          "operation_type": "http_post",
          "conditions": [
            "Only when InAPPNotificationEnable == true and the created discount targets a non-zero tenant"
          ],
          "operations": [
            {
              "operation": "HTTP BulkTriggerEvent",
              "trigger": "Notify org users that a new tenant discount was created",
              "conditions": [
                "discount.Model.sendDiscountChangeNotificationIfNeed(...) selected the create notification path"
              ],
              "implementation": "uncutils.SendInAppNotification(...) -> novuhandler.Get().BulkTriggerEvent(...)"
            }
          ]
        }
      ]
    },
    "HTTP PUT /api/v1/billing/tenants/:tenant_id/discounts/:discount_id": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant and discount path binding succeeds and request JSON binds successfully"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "discounts",
              "trigger": "Load the tenant discount row before validating and updating its value",
              "conditions": [
                "getDiscountQueryFromURI(c) and getTenantIDFromURI(c) both succeeded"
              ],
              "implementation": "discount.Model.UpdateDiscount(...) -> GetDiscountWithTx(tx, tenantID, discountID)"
            },
            {
              "operation": "INSERT",
              "table": "discount_versions",
              "trigger": "Persist the version row that snapshots the updated discount value",
              "conditions": [
                "ValidateDiscountReq(info) succeeded"
              ],
              "implementation": "discount.Model.CreateDiscountVersion(tx, tenantID, info)"
            },
            {
              "operation": "INSERT",
              "table": "audit_records",
              "trigger": "Persist the discount-change audit record inside the update transaction",
              "conditions": [
                "CreateDiscountVersion(...) succeeded"
              ],
              "implementation": "discount.Model.CreateDiscountChangeAuditLog(tx, tenantID, info)"
            },
            {
              "operation": "UPDATE",
              "table": "discounts",
              "trigger": "Store the new discount value and version on the existing tenant discount row",
              "conditions": [
                "ValidateDiscountReq(info) succeeded"
              ],
              "implementation": "entity.NewDiscountQuerySet(tx).IDEq(discountID).GetUpdater().SetVersion(version).SetValue(value).Update()"
            },
            {
              "operation": "SELECT",
              "table": "discounts",
              "trigger": "Re-read the updated tenant discount after the transaction persists the new value",
              "conditions": [
                "discount update succeeded"
              ],
              "implementation": "discount.Model.GetDiscountWithTx(tx, tenantID, discountID)"
            }
          ]
        },
        "redis": {
          "conditions": [
            "Only when the affected discount row belongs to a billing-config pair with cached active discounts"
          ],
          "operations": [
            {
              "operation": "DEL",
              "trigger": "Invalidate the active-discount cache for the billing config bound to the updated discount row",
              "conditions": [
                "discount.Model.UpdateDiscount(...) committed successfully"
              ],
              "implementation": "cachehandler.Get().Delete(\"ListTenantActiveDiscounts\", tenantID, ret.BindedBillingConfigID)"
            }
          ]
        }
      },
      "services": [
        {
          "name": "account-svc",
          "target_interface": "AccountAPIService.GetOrgByID",
          "operation_type": "grpc_unary",
          "conditions": [
            "Only when the updated discount remains active and in-app discount notifications are enabled"
          ],
          "operations": [
            {
              "operation": "gRPC GetOrgByID",
              "trigger": "Load tenant metadata so the updated-discount notification can include org name",
              "conditions": [
                "discount.Model.sendDiscountChangeNotificationIfNeed(...) did not early-return on inactive or tenant_id == 0"
              ],
              "implementation": "centralhandler.GetCentralHandler().GetTenant(targetDiscount.TenantID) -> account.GetOrgByID(IsBrief=true)"
            }
          ]
        },
        {
          "name": "novu-api",
          "target_interface": "POST /v1/events/trigger/bulk",
          "operation_type": "http_post",
          "conditions": [
            "Only when InAPPNotificationEnable == true and the updated discount remains active"
          ],
          "operations": [
            {
              "operation": "HTTP BulkTriggerEvent",
              "trigger": "Notify org users that a tenant discount changed after the update committed",
              "conditions": [
                "discount.Model.sendDiscountChangeNotificationIfNeed(...) selected the update notification path"
              ],
              "implementation": "uncutils.SendInAppNotification(...) -> novuhandler.Get().BulkTriggerEvent(...)"
            }
          ]
        }
      ]
    },
    "HTTP DELETE /api/v1/billing/tenants/:tenant_id/discounts/:discount_id": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant and discount path binding succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "discounts",
              "trigger": "Load the tenant discount row before reclaiming it",
              "conditions": [
                "getDiscountQueryFromURI(c) succeeded",
                "q.TenantID != 0"
              ],
              "implementation": "discount.Model.DeleteDiscount(...) -> GetDiscountWithTx(tx, tenantID, discountID)"
            },
            {
              "operation": "UPDATE",
              "table": "discounts",
              "trigger": "Mark the discount reclaimed and set closed_at on the existing discount row",
              "conditions": [
                "GetDiscountWithTx(...) succeeded"
              ],
              "implementation": "entity.NewDiscountQuerySet(tx).IDEq(discountID).TenantIDEq(tenantID).GetUpdater().SetStatus(Reclaimed).SetClosedAt(&now).UpdateNum()"
            }
          ]
        },
        "redis": {
          "conditions": [
            "Only when the affected discount row belongs to a billing-config pair with cached active discounts"
          ],
          "operations": [
            {
              "operation": "DEL",
              "trigger": "Invalidate the active-discount cache for the billing config bound to the reclaimed discount row",
              "conditions": [
                "DeleteDiscountWithTx(...) succeeded"
              ],
              "implementation": "cachehandler.Get().Delete(\"ListTenantActiveDiscounts\", tenantID, discount.BindedBillingConfigID)"
            }
          ]
        }
      },
      "services": [
        {
          "name": "account-svc",
          "target_interface": "AccountAPIService.GetOrgByID",
          "operation_type": "grpc_unary",
          "conditions": [
            "Only when the reclaimed discount was still active and in-app discount notifications are enabled"
          ],
          "operations": [
            {
              "operation": "gRPC GetOrgByID",
              "trigger": "Load tenant metadata so the reclaimed-discount notification can include org name",
              "conditions": [
                "discount.Model.sendDiscountChangeNotificationIfNeed(...) did not early-return on inactive or tenant_id == 0"
              ],
              "implementation": "centralhandler.GetCentralHandler().GetTenant(targetDiscount.TenantID) -> account.GetOrgByID(IsBrief=true)"
            }
          ]
        },
        {
          "name": "novu-api",
          "target_interface": "POST /v1/events/trigger/bulk",
          "operation_type": "http_post",
          "conditions": [
            "Only when InAPPNotificationEnable == true and the reclaimed discount was still active"
          ],
          "operations": [
            {
              "operation": "HTTP BulkTriggerEvent",
              "trigger": "Notify org users that a tenant discount was reclaimed",
              "conditions": [
                "discount.Model.sendDiscountChangeNotificationIfNeed(...) selected the reclaim notification path"
              ],
              "implementation": "uncutils.SendInAppNotification(...) -> novuhandler.Get().BulkTriggerEvent(...)"
            }
          ]
        }
      ]
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/billing_config_id/:billing_config_id/discounts": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant and explicit billing_config_id resolution succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Load and tenant-check the explicit billing config before listing its discount history",
              "conditions": [
                "c.ShouldBindUri(&BillingCfgStruct{}) succeeded"
              ],
              "implementation": "getBillingCfgFromURI(c) -> billingconfig.BillingConfigModel.GetBillingConfig(billing_config_id)"
            },
            {
              "operation": "SELECT",
              "table": "discounts",
              "trigger": "List all discount rows bound to the explicit tenant/billing-config pair",
              "conditions": [
                "ret.TenantID == billingCfgStruct.TenantID"
              ],
              "implementation": "discount.Model.ListTenantDiscounts(billingCfgStruct.TenantID, billingCfgStruct.BillingConfigID)"
            },
            {
              "operation": "SELECT",
              "table": "unit_filters",
              "trigger": "Hydrate unit-filter associations for each discount row returned in the history list",
              "conditions": [
                "ListTenantDiscounts(...) reached the preload query"
              ],
              "implementation": "entity.NewDiscountQuerySet(db.GetDB().Preload(clause.Associations)).TenantIDEq(...).BindedBillingConfigIDEq(...).All(&discountEntities)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/billing_config_id/:billing_config_id/users/discounts": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant and explicit billing_config_id resolution succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Load and tenant-check the explicit billing config before listing its console-view discounts",
              "conditions": [
                "c.ShouldBindUri(&BillingCfgStruct{}) succeeded"
              ],
              "implementation": "getBillingCfgFromURI(c) -> billingconfig.BillingConfigModel.GetBillingConfig(billing_config_id)"
            },
            {
              "operation": "SELECT",
              "table": "discounts",
              "trigger": "List tenant-bound discounts and merge active global discounts before returning the console-view payload",
              "conditions": [
                "ret.TenantID == billingCfgStruct.TenantID"
              ],
              "implementation": "discount.Model.ListDiscountsConsoleView(...) -> ListTenantDiscounts(...) + ListGlobalActiveDiscounts()"
            },
            {
              "operation": "SELECT",
              "table": "unit_filters",
              "trigger": "Hydrate unit-filter associations for tenant and global discount rows that survive console-view filtering",
              "conditions": [
                "ListDiscountsConsoleView(...) loaded discount rows"
              ],
              "implementation": "ListTenantDiscounts / ListGlobalActiveDiscounts -> entity.NewDiscountQuerySet(db.GetDB().Preload(clause.Associations))"
            }
          ]
        },
        "redis": {
          "conditions": [
            "Only when global active discounts are included in the console-view payload"
          ],
          "operations": [
            {
              "operation": "GET",
              "trigger": "Reuse cached global active discount entities when merging them into the tenant console-view list",
              "conditions": [
                "ListDiscountsConsoleView(...) reached ListGlobalActiveDiscounts()"
              ],
              "implementation": "discount.Model.ListGlobalActiveDiscounts() -> ListTenantActiveDiscounts(...) -> cachehandler.Get().Get(\"ListTenantActiveDiscounts\", ...)"
            },
            {
              "operation": "SET",
              "trigger": "Cache global active discount entities after the DB lookup succeeds",
              "conditions": [
                "ListTenantActiveDiscounts(...) queried active discount entities from MySQL"
              ],
              "implementation": "cachehandler.Get().Set(\"ListTenantActiveDiscounts\", &discountEntities, tenantID, billingConfigID)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/tenants/:tenant_id/billing_config_id/:billing_config_id/discounts": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after request JSON binds successfully, tenant and explicit billing_config_id resolution succeeds, and the active payment method is not MSP"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Load and tenant-check the explicit billing config that the new tenant discount should bind to",
              "conditions": [
                "ShouldBindJSON(&forms.Discount{}) succeeded"
              ],
              "implementation": "getBillingCfgFromURI(c) -> billingconfig.BillingConfigModel.GetBillingConfig(billing_config_id)"
            },
            {
              "operation": "SELECT",
              "table": "payment_methods",
              "trigger": "Reject MSP-customer billing configs because they are not allowed to create discounts directly",
              "conditions": [
                "ret.TenantID == billingCfgStruct.TenantID"
              ],
              "implementation": "paymentModel.IsMspPayment(billingCfgStruct.TenantID, billingCfgStruct.BillingConfigID) -> GetActivePaymentMethod(...)"
            },
            {
              "operation": "SELECT",
              "table": "unit_filters",
              "trigger": "Resolve copy arguments before optionally cloning unit-filter rows for the new discount",
              "conditions": [
                "IsMspPayment(...) returned false"
              ],
              "implementation": "unit_filter.Model.GetCopyArgs(&d.CopyUnitFilterArgs)"
            },
            {
              "operation": "INSERT",
              "table": "unit_filters",
              "trigger": "Create copied unit-filter rows when the request asks to duplicate filters from an existing source",
              "conditions": [
                "copyArgs != nil"
              ],
              "implementation": "unit_filter.Model.CreateCopiedUnitFilters(d.UnitFilters, copyArgs)"
            },
            {
              "operation": "INSERT",
              "table": "discount_versions",
              "trigger": "Persist the initial version row for the newly created discount",
              "conditions": [
                "ValidateDiscountReq(info) succeeded"
              ],
              "implementation": "discount.Model.CreateDiscountVersion(tx, tenantID, info)"
            },
            {
              "operation": "INSERT",
              "table": "audit_records",
              "trigger": "Persist the discount-change audit record inside the create transaction",
              "conditions": [
                "CreateDiscountVersion(...) succeeded"
              ],
              "implementation": "discount.Model.CreateDiscountChangeAuditLog(tx, tenantID, info)"
            },
            {
              "operation": "INSERT",
              "table": "discounts",
              "trigger": "Create the new tenant discount row bound to the explicit billing config",
              "conditions": [
                "ValidateDiscountReq(info) succeeded"
              ],
              "implementation": "discount.Model.CreateDiscountWithTx(...) -> ent.Create(tx)"
            },
            {
              "operation": "SELECT",
              "table": "discounts",
              "trigger": "Re-read the newly created discount row after persistence succeeds",
              "conditions": [
                "ent.Create(tx) succeeded"
              ],
              "implementation": "discount.Model.GetDiscountWithTx(tx, tenantID, ent.ID)"
            }
          ]
        },
        "redis": {
          "conditions": [
            "Only when the tenant has active-discount cache entries for the affected billing config"
          ],
          "operations": [
            {
              "operation": "DEL",
              "trigger": "Invalidate the active-discount cache for the affected tenant/billing-config pair after creation completes",
              "conditions": [
                "discount.Model.CreateDiscount(...) committed successfully"
              ],
              "implementation": "cachehandler.Get().Delete(\"ListTenantActiveDiscounts\", tenantID, *info.BindedBillingConfigID)"
            }
          ]
        }
      },
      "services": [
        {
          "name": "account-svc",
          "target_interface": "AccountAPIService.GetOrgByID",
          "operation_type": "grpc_unary",
          "conditions": [
            "Only when the created discount targets a non-zero tenant and in-app discount notifications are enabled"
          ],
          "operations": [
            {
              "operation": "gRPC GetOrgByID",
              "trigger": "Load tenant metadata so the created-discount notification can include org name",
              "conditions": [
                "discount.Model.sendDiscountChangeNotificationIfNeed(...) did not early-return on tenant_id == 0"
              ],
              "implementation": "centralhandler.GetCentralHandler().GetTenant(targetDiscount.TenantID) -> account.GetOrgByID(IsBrief=true)"
            }
          ]
        },
        {
          "name": "novu-api",
          "target_interface": "POST /v1/events/trigger/bulk",
          "operation_type": "http_post",
          "conditions": [
            "Only when InAPPNotificationEnable == true and the created discount targets a non-zero tenant"
          ],
          "operations": [
            {
              "operation": "HTTP BulkTriggerEvent",
              "trigger": "Notify org users that a new tenant discount was created",
              "conditions": [
                "discount.Model.sendDiscountChangeNotificationIfNeed(...) selected the create notification path"
              ],
              "implementation": "uncutils.SendInAppNotification(...) -> novuhandler.Get().BulkTriggerEvent(...)"
            }
          ]
        }
      ]
    },
    "HTTP PUT /api/v1/billing/tenants/:tenant_id/billing_config_id/:billing_config_id/discounts/:discount_id": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant and discount path binding succeeds and request JSON binds successfully; the explicit billing_config_id is present in the route but the update path itself only reuses tenantID + discountID"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "discounts",
              "trigger": "Load the tenant discount row before validating and updating its value",
              "conditions": [
                "getDiscountQueryFromURI(c) and getTenantIDFromURI(c) both succeeded"
              ],
              "implementation": "discount.Model.UpdateDiscount(...) -> GetDiscountWithTx(tx, tenantID, discountID)"
            },
            {
              "operation": "INSERT",
              "table": "discount_versions",
              "trigger": "Persist the version row that snapshots the updated discount value",
              "conditions": [
                "ValidateDiscountReq(info) succeeded"
              ],
              "implementation": "discount.Model.CreateDiscountVersion(tx, tenantID, info)"
            },
            {
              "operation": "INSERT",
              "table": "audit_records",
              "trigger": "Persist the discount-change audit record inside the update transaction",
              "conditions": [
                "CreateDiscountVersion(...) succeeded"
              ],
              "implementation": "discount.Model.CreateDiscountChangeAuditLog(tx, tenantID, info)"
            },
            {
              "operation": "UPDATE",
              "table": "discounts",
              "trigger": "Store the new discount value and version on the existing tenant discount row",
              "conditions": [
                "ValidateDiscountReq(info) succeeded"
              ],
              "implementation": "entity.NewDiscountQuerySet(tx).IDEq(discountID).GetUpdater().SetVersion(version).SetValue(value).Update()"
            },
            {
              "operation": "SELECT",
              "table": "discounts",
              "trigger": "Re-read the updated tenant discount after the transaction persists the new value",
              "conditions": [
                "discount update succeeded"
              ],
              "implementation": "discount.Model.GetDiscountWithTx(tx, tenantID, discountID)"
            }
          ]
        },
        "redis": {
          "conditions": [
            "Only when the affected discount row belongs to a billing-config pair with cached active discounts"
          ],
          "operations": [
            {
              "operation": "DEL",
              "trigger": "Invalidate the active-discount cache for the billing config bound to the updated discount row",
              "conditions": [
                "discount.Model.UpdateDiscount(...) committed successfully"
              ],
              "implementation": "cachehandler.Get().Delete(\"ListTenantActiveDiscounts\", tenantID, ret.BindedBillingConfigID)"
            }
          ]
        }
      },
      "services": [
        {
          "name": "account-svc",
          "target_interface": "AccountAPIService.GetOrgByID",
          "operation_type": "grpc_unary",
          "conditions": [
            "Only when the updated discount remains active and in-app discount notifications are enabled"
          ],
          "operations": [
            {
              "operation": "gRPC GetOrgByID",
              "trigger": "Load tenant metadata so the updated-discount notification can include org name",
              "conditions": [
                "discount.Model.sendDiscountChangeNotificationIfNeed(...) did not early-return on inactive or tenant_id == 0"
              ],
              "implementation": "centralhandler.GetCentralHandler().GetTenant(targetDiscount.TenantID) -> account.GetOrgByID(IsBrief=true)"
            }
          ]
        },
        {
          "name": "novu-api",
          "target_interface": "POST /v1/events/trigger/bulk",
          "operation_type": "http_post",
          "conditions": [
            "Only when InAPPNotificationEnable == true and the updated discount remains active"
          ],
          "operations": [
            {
              "operation": "HTTP BulkTriggerEvent",
              "trigger": "Notify org users that a tenant discount changed after the update committed",
              "conditions": [
                "discount.Model.sendDiscountChangeNotificationIfNeed(...) selected the update notification path"
              ],
              "implementation": "uncutils.SendInAppNotification(...) -> novuhandler.Get().BulkTriggerEvent(...)"
            }
          ]
        }
      ]
    },
    "HTTP DELETE /api/v1/billing/tenants/:tenant_id/billing_config_id/:billing_config_id/discounts/:discount_id": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant and discount path binding succeeds; the explicit billing_config_id is present in the route but the delete path itself only reuses tenantID + discountID"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "discounts",
              "trigger": "Load the tenant discount row before reclaiming it",
              "conditions": [
                "getDiscountQueryFromURI(c) succeeded",
                "q.TenantID != 0"
              ],
              "implementation": "discount.Model.DeleteDiscount(...) -> GetDiscountWithTx(tx, tenantID, discountID)"
            },
            {
              "operation": "UPDATE",
              "table": "discounts",
              "trigger": "Mark the discount reclaimed and set closed_at on the existing discount row",
              "conditions": [
                "GetDiscountWithTx(...) succeeded"
              ],
              "implementation": "entity.NewDiscountQuerySet(tx).IDEq(discountID).TenantIDEq(tenantID).GetUpdater().SetStatus(Reclaimed).SetClosedAt(&now).UpdateNum()"
            }
          ]
        },
        "redis": {
          "conditions": [
            "Only when the affected discount row belongs to a billing-config pair with cached active discounts"
          ],
          "operations": [
            {
              "operation": "DEL",
              "trigger": "Invalidate the active-discount cache for the billing config bound to the reclaimed discount row",
              "conditions": [
                "DeleteDiscountWithTx(...) succeeded"
              ],
              "implementation": "cachehandler.Get().Delete(\"ListTenantActiveDiscounts\", tenantID, discount.BindedBillingConfigID)"
            }
          ]
        }
      },
      "services": [
        {
          "name": "account-svc",
          "target_interface": "AccountAPIService.GetOrgByID",
          "operation_type": "grpc_unary",
          "conditions": [
            "Only when the reclaimed discount was still active and in-app discount notifications are enabled"
          ],
          "operations": [
            {
              "operation": "gRPC GetOrgByID",
              "trigger": "Load tenant metadata so the reclaimed-discount notification can include org name",
              "conditions": [
                "discount.Model.sendDiscountChangeNotificationIfNeed(...) did not early-return on inactive or tenant_id == 0"
              ],
              "implementation": "centralhandler.GetCentralHandler().GetTenant(targetDiscount.TenantID) -> account.GetOrgByID(IsBrief=true)"
            }
          ]
        },
        {
          "name": "novu-api",
          "target_interface": "POST /v1/events/trigger/bulk",
          "operation_type": "http_post",
          "conditions": [
            "Only when InAPPNotificationEnable == true and the reclaimed discount was still active"
          ],
          "operations": [
            {
              "operation": "HTTP BulkTriggerEvent",
              "trigger": "Notify org users that a tenant discount was reclaimed",
              "conditions": [
                "discount.Model.sendDiscountChangeNotificationIfNeed(...) selected the reclaim notification path"
              ],
              "implementation": "uncutils.SendInAppNotification(...) -> novuhandler.Get().BulkTriggerEvent(...)"
            }
          ]
        }
      ]
    },
    "HTTP GET /api/v1/billing/plans/ondemand/global-discounts": {
      "infrastructure": {},
      "services": []
    },
    "HTTP GET /api/v1/billing/global-discounts": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Always"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "discounts",
              "trigger": "List all global discount rows owned by tenant_id 0",
              "conditions": [
                "handler reached discountModel.ListGlobalDiscounts()"
              ],
              "implementation": "discount.Model.ListGlobalDiscounts() -> ListTenantDiscounts(0, 0)"
            },
            {
              "operation": "SELECT",
              "table": "unit_filters",
              "trigger": "Hydrate unit-filter associations for each persisted global discount row",
              "conditions": [
                "ListTenantDiscounts(0, 0) reached the preload query"
              ],
              "implementation": "entity.NewDiscountQuerySet(db.GetDB().Preload(clause.Associations)).TenantIDEq(0).BindedBillingConfigIDEq(0).All(&discountEntities)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/global-discounts": {
      "infrastructure": {},
      "services": []
    },
    "HTTP PUT /api/v1/billing/global-discounts/:discount_id": {
      "infrastructure": {},
      "services": []
    },
    "HTTP DELETE /api/v1/billing/global-discounts/:discount_id": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after discount_id path binding succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "discounts",
              "trigger": "Load the global discount row before reclaiming it",
              "conditions": [
                "getDiscountQueryFromURI(c) succeeded"
              ],
              "implementation": "discount.Model.DeleteDiscount(0, q.DiscountID) -> GetDiscountWithTx(tx, 0, discountID)"
            },
            {
              "operation": "UPDATE",
              "table": "discounts",
              "trigger": "Mark the global discount reclaimed and set closed_at on the existing discount row",
              "conditions": [
                "GetDiscountWithTx(...) succeeded"
              ],
              "implementation": "entity.NewDiscountQuerySet(tx).IDEq(discountID).TenantIDEq(0).GetUpdater().SetStatus(Reclaimed).SetClosedAt(&now).UpdateNum()"
            }
          ]
        },
        "redis": {
          "conditions": [
            "Only when the global active-discount cache was previously populated"
          ],
          "operations": [
            {
              "operation": "DEL",
              "trigger": "Invalidate the global active-discount cache after reclaiming the global discount",
              "conditions": [
                "DeleteDiscountWithTx(...) succeeded"
              ],
              "implementation": "cachehandler.Get().Delete(\"ListTenantActiveDiscounts\", 0, discount.BindedBillingConfigID)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/tenants/:tenant_id/internal/costexplorer": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant path binding succeeds and the internal cost-explorer request body binds successfully"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "user_unit_costs",
              "trigger": "Run the grouped internal or external cost-explorer aggregation over the tenant's usage rows",
              "conditions": [
                "CalculateCostWithCache(...) reached CalculateCostV2MultiTenantsWithCache(...)"
              ],
              "implementation": "costexplorer.CostExplorerModel.CalculateCostWithCache(tenantID, 0, query) -> CalculateCostV2MultiTenantsWithCache(...) -> queryCost(...)"
            }
          ]
        },
        "redis": {
          "conditions": [
            "Only when the internal query can be normalized into the V2 cache key shape"
          ],
          "operations": [
            {
              "operation": "GET",
              "trigger": "Reuse the cached internal cost-explorer result before requerying grouped cost rows",
              "conditions": [
                "buildCalculateCostCacheArgs(...) accepted the transformed CostExplorerQueryV2 arguments"
              ],
              "implementation": "cachehandler.Get().Get(\"CalculateCostV2WithCache\", ret, cacheArgs...)"
            },
            {
              "operation": "SET",
              "trigger": "Cache the transformed internal cost-explorer result after grouped cost aggregation succeeds",
              "conditions": [
                "buildCalculateCostCacheArgs(...) accepted the transformed CostExplorerQueryV2 arguments",
                "CalculateCostV2MultiTenants(...) succeeded"
              ],
              "implementation": "cachehandler.Get().Set(\"CalculateCostV2WithCache\", ret, cacheArgs...)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/tenants/:tenant_id/internal/costexplorer/v2": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant path binding succeeds and the V2 internal cost-explorer request body binds successfully"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "user_unit_costs",
              "trigger": "Run the grouped internal/external cost-explorer aggregation over the tenant's usage rows",
              "conditions": [
                "CalculateCostV2WithCache(...) reached CalculateCostV2MultiTenants(...)"
              ],
              "implementation": "costexplorer.CostExplorerModel.CalculateCostV2WithCache(tenantID, nil, query) -> CalculateCostV2MultiTenants(...) -> queryCost(...)"
            }
          ]
        },
        "redis": {
          "conditions": [
            "Only when buildCalculateCostCacheArgs(...) accepts the submitted label set"
          ],
          "operations": [
            {
              "operation": "GET",
              "trigger": "Reuse the cached V2 internal cost-explorer result before requerying grouped cost rows",
              "conditions": [
                "buildCalculateCostCacheArgs(...) returned canCache == true"
              ],
              "implementation": "cachehandler.Get().Get(\"CalculateCostV2WithCache\", ret, cacheArgs...)"
            },
            {
              "operation": "SET",
              "trigger": "Cache the V2 internal cost-explorer result after grouped cost aggregation succeeds",
              "conditions": [
                "buildCalculateCostCacheArgs(...) returned canCache == true",
                "CalculateCostV2MultiTenants(...) succeeded"
              ],
              "implementation": "cachehandler.Get().Set(\"CalculateCostV2WithCache\", ret, cacheArgs...)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/packages": {
      "infrastructure": {},
      "services": []
    },
    "HTTP GET /api/v1/billing/packages/:package_id": {
      "infrastructure": {},
      "services": []
    },
    "HTTP POST /api/v1/billing/packages": {
      "infrastructure": {},
      "services": []
    },
    "HTTP PUT /api/v1/billing/packages/:package_id": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after package_id path binding succeeds and the request body can be read and unmarshaled"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "units",
              "trigger": "Load the unit catalog used to validate package unit pricing and later sync changed SKU prices",
              "conditions": [
                "ShouldBindUri(&PackageIDStruct{}) succeeded"
              ],
              "implementation": "billing.PackageModel.UpdatePackage(...) -> billing.UnitModel.GetAllUnits()"
            },
            {
              "operation": "SELECT",
              "table": "packages",
              "trigger": "Load the existing package row inside the update transaction before appending a new version",
              "conditions": [
                "packageContentFromForm(...) succeeded"
              ],
              "implementation": "entity.NewPackageQuerySet(tx).IDEq(packageID).One(packageEntity)"
            },
            {
              "operation": "INSERT",
              "table": "package_versions",
              "trigger": "Create the next immutable package version row for the updated package content",
              "conditions": [
                "existing package row loaded successfully"
              ],
              "implementation": "packageVersion.Create(tx)"
            },
            {
              "operation": "UPDATE",
              "table": "packages",
              "trigger": "Persist the latest-version pointer and package content onto the live package row",
              "conditions": [
                "packageVersion.Create(tx) succeeded"
              ],
              "implementation": "tx.Model(packageEntity).Select(\"*\").Omit(\"created_at, deleted_at\").Updates(packageEntity)"
            },
            {
              "operation": "UPDATE",
              "table": "units",
              "trigger": "Propagate changed package unit prices back into SKU unit pricing when the package delta changes unit prices",
              "conditions": [
                "UpdatePackage(...) transaction committed successfully",
                "updatePrice(...) found differing unit prices"
              ],
              "implementation": "updateSKUFromPackage(units, packageInfo) -> billing.UnitModel.UpdateUnitPrice(modifyUnit)"
            }
          ]
        },
        "redis": {
          "conditions": [
            "Only when package caching is enabled"
          ],
          "operations": [
            {
              "operation": "DEL",
              "trigger": "Invalidate the package cache and package-version cache after the package update commits",
              "conditions": [
                "EnableCache == true",
                "UpdatePackage(...) transaction committed successfully"
              ],
              "implementation": "billing.PackageModel.deletePackageCache(packageID) -> cachehandler.Get().Delete(\"GetPackage\", packageID) + Delete(\"GetPackageVersionCache\", packageID)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP PATCH /api/v1/billing/packages/:package_id": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after package_id path binding succeeds, APISwitchUpdateUnit == true, and the request body can be read twice for full and partial decoding"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "packages",
              "trigger": "Load the existing package before PartialMerge overlays the patch payload onto the stored package shape",
              "conditions": [
                "APISwitchUpdateUnit == true"
              ],
              "implementation": "packageModel.GetPackage(packageID)"
            },
            {
              "operation": "SELECT",
              "table": "units",
              "trigger": "Load the unit catalog used to validate the merged package content and later sync changed SKU prices",
              "conditions": [
                "PartialMerge(dest, packageInfo, mapInput) completed"
              ],
              "implementation": "billing.PackageModel.UpdatePackage(...) -> billing.UnitModel.GetAllUnits()"
            },
            {
              "operation": "INSERT",
              "table": "package_versions",
              "trigger": "Create the next immutable package version row for the patched package content",
              "conditions": [
                "packageContentFromForm(...) succeeded"
              ],
              "implementation": "billing.PackageModel.UpdatePackage(...) -> packageVersion.Create(tx)"
            },
            {
              "operation": "UPDATE",
              "table": "packages",
              "trigger": "Persist the patched package content and latest-version pointer onto the live package row",
              "conditions": [
                "packageVersion.Create(tx) succeeded"
              ],
              "implementation": "billing.PackageModel.UpdatePackage(...) -> tx.Model(packageEntity).Select(\"*\").Omit(\"created_at, deleted_at\").Updates(packageEntity)"
            },
            {
              "operation": "UPDATE",
              "table": "units",
              "trigger": "Propagate changed package unit prices back into SKU unit pricing when the patch changes unit prices",
              "conditions": [
                "UpdatePackage(...) transaction committed successfully",
                "updatePrice(...) found differing unit prices"
              ],
              "implementation": "updateSKUFromPackage(units, dest) -> billing.UnitModel.UpdateUnitPrice(modifyUnit)"
            }
          ]
        },
        "redis": {
          "conditions": [
            "Only when package caching is enabled"
          ],
          "operations": [
            {
              "operation": "GET",
              "trigger": "Reuse the cached package before applying the partial merge if the package cache is warm",
              "conditions": [
                "EnableCache == true",
                "packageModel.GetPackage(packageID) reached getPackageCache(packageID)"
              ],
              "implementation": "billing.PackageModel.getPackageCache(packageID) -> cachehandler.Get().Get(\"GetPackage\", result, packageID)"
            },
            {
              "operation": "DEL",
              "trigger": "Invalidate the package cache and package-version cache after the patch commits",
              "conditions": [
                "EnableCache == true",
                "UpdatePackage(...) transaction committed successfully"
              ],
              "implementation": "billing.PackageModel.deletePackageCache(packageID) -> cachehandler.Get().Delete(\"GetPackage\", packageID) + Delete(\"GetPackageVersionCache\", packageID)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP DELETE /api/v1/billing/packages/:package_id": {
      "infrastructure": {},
      "services": []
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/binded_packages": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant path binding succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "binded_packages",
              "trigger": "List active binded-package rows for the tenant",
              "conditions": [
                "c.ShouldBindUri(&BindedPackageURI{}) succeeded"
              ],
              "implementation": "billing.BindedPackageModel.GetAllTenantBindedPackage(tenantID)"
            },
            {
              "operation": "SELECT",
              "table": "packages",
              "trigger": "Hydrate package associations for each active binded package returned to the caller",
              "conditions": [
                "GetAllTenantBindedPackage(...) reached the preload query"
              ],
              "implementation": "entity.NewBindedPackageQuerySet(db.GetDB().Preload(clause.Associations)).TenantIDEq(tenantID).ActiveEq(Active).All(&entities)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/binded_packages/:binded_package_id": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant and binded_package_id path binding succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "binded_packages",
              "trigger": "Load the requested binded package row",
              "conditions": [
                "c.ShouldBindUri(&BindedPackageURI{}) succeeded"
              ],
              "implementation": "billing.BindedPackageModel.GetBindedPackage(binded_package_id)"
            },
            {
              "operation": "SELECT",
              "table": "packages",
              "trigger": "Hydrate package associations for the selected binded package",
              "conditions": [
                "GetBindedPackage(...) reached the preload query"
              ],
              "implementation": "entity.NewBindedPackageQuerySet(db.GetDB().Preload(clause.Associations)).IDEq(binded_package_id).One(bindedPackage)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/binded_packages/:binded_package_id/charge_credits": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant and binded_package_id path binding succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "credits_charge_records",
              "trigger": "List manual credit-charge records for the selected binded package",
              "conditions": [
                "c.ShouldBindUri(&BindedPackageURI{}) succeeded"
              ],
              "implementation": "billing.BindedPackageModel.GetChargeCreditsHistory(binded_package_id)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/tenants/:tenant_id/binded_packages": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant path binding succeeds and the binded-package request body binds successfully"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the active billing config before binding the package to the tenant",
              "conditions": [
                "c.ShouldBindUri(&BindedPackageURI{}) succeeded",
                "ShouldBindJSON(&forms.BindedPackageInfo{}) succeeded"
              ],
              "implementation": "billing.BindedPackageModel.BindPackage(tenantID, packageID) -> billingconfig.BillingConfigModel.GetActiveBillingConfigID(tenantID)"
            },
            {
              "operation": "INSERT",
              "table": "binded_packages",
              "trigger": "Create the new active binded-package row for the tenant and resolved billing config",
              "conditions": [
                "GetActiveBillingConfigID(tenantID) succeeded"
              ],
              "implementation": "billing.BindedPackageModel.BindPackageExtraWithTx(tx, tenantID, bindedPackageInfo) -> bindedPackage.Create(tx)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/tenants/:tenant_id/binded_packages/:binded_package_id/charge_credits": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant and binded_package_id path binding succeeds and the charge-credits request body binds successfully"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "binded_packages",
              "trigger": "Load the binded package and reject credit charging when it is no longer active",
              "conditions": [
                "c.ShouldBindUri(&BindedPackageURI{}) succeeded",
                "ShouldBindJSON(&forms.CreditsChargeInfo{}) succeeded"
              ],
              "implementation": "billing.BindedPackageModel.ChargeCredits(...) -> GetBindedPackage(bindedPackageID)"
            },
            {
              "operation": "INSERT",
              "table": "credits_charge_records",
              "trigger": "Persist the manual credit charge record inside the charging transaction",
              "conditions": [
                "bindedPackageInfo.Active == Active"
              ],
              "implementation": "recordEntity.Create(tx)"
            },
            {
              "operation": "UPDATE",
              "table": "binded_packages",
              "trigger": "Increase remaining_credits on the binded package after the charge record is created",
              "conditions": [
                "recordEntity.Create(tx) succeeded"
              ],
              "implementation": "tx.Model(&entity.BindedPackage{}).Where(\"id = ?\", recordEntity.BindedPackageID).Update(\"remaining_credits\", gorm.Expr(\"remaining_credits + ?\", recordEntity.ChargeCount))"
            },
            {
              "operation": "SELECT",
              "table": "binded_packages",
              "trigger": "Re-read the binded package after the credit charge commits",
              "conditions": [
                "remaining_credits update affected exactly one row"
              ],
              "implementation": "billing.BindedPackageModel.GetBindedPackage(bindedPackageID)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP DELETE /api/v1/billing/tenants/:tenant_id/binded_packages/:binded_package_id": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant and binded_package_id path binding succeeds"
          ],
          "operations": [
            {
              "operation": "UPDATE",
              "table": "binded_packages",
              "trigger": "Close the binded package by writing closed_date when it has not already been closed",
              "conditions": [
                "c.ShouldBindUri(&BindedPackageURI{}) succeeded"
              ],
              "implementation": "billing.BindedPackageModel.UnbindPackageWithTx(tx, binded_package_id) -> entity.NewBindedPackageQuerySet(tx).IDEq(binded_package_id).ClosedDateIsNull().GetUpdater().SetClosedDate(&now).Update()"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/billing_config_id/:billing_config_id/binded_packages": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant path binding succeeds; the explicit billing_config_id is present in the route but the list handler itself still reuses the tenant-wide binded-package query"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "binded_packages",
              "trigger": "List active binded-package rows for the tenant even though the scoped billing_config_id is not consumed by the current handler body",
              "conditions": [
                "c.ShouldBindUri(&BindedPackageURI{}) succeeded"
              ],
              "implementation": "API.ListUserBindedPackage(...) -> billing.BindedPackageModel.GetAllTenantBindedPackage(tenantID)"
            },
            {
              "operation": "SELECT",
              "table": "packages",
              "trigger": "Hydrate package associations for each active binded package returned to the caller",
              "conditions": [
                "GetAllTenantBindedPackage(...) reached the preload query"
              ],
              "implementation": "entity.NewBindedPackageQuerySet(db.GetDB().Preload(clause.Associations)).TenantIDEq(tenantID).ActiveEq(Active).All(&entities)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/fx_rates": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after base/target query parsing succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "invoice_applied_fx",
              "trigger": "Load the newest FX rate row for the requested base/target currency pair",
              "conditions": [
                "c.ShouldBindQuery(&query) succeeded"
              ],
              "implementation": "paymentsub.FXRateModel.GetInvoiceAppliedFX(base, target) -> entity.NewInvoiceAppliedFXQuerySet(db.GetDB()).BaseEq(...).TargetEq(...).OrderDescByDate().OrderDescByCreatedAt().One(&ent)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/fx_rates": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after the FX payload binds successfully"
          ],
          "operations": [
            {
              "operation": "INSERT",
              "table": "invoice_applied_fx",
              "trigger": "Create a new invoice-applied FX row for the submitted base/target/date/value tuple",
              "conditions": [
                "c.ShouldBindJSON(&forms.InvoiceAppliedFXRate{}) succeeded"
              ],
              "implementation": "paymentsub.FXRateModel.CreateInvoiceAppliedFX(&in) -> ent.Create(db.GetDB())"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/recharge_plans": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Always"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "recharge_credits_plans",
              "trigger": "List recharge plans created from the web source",
              "conditions": [
                "handler reached marketing.RechargeCreditsModel.ListWebRechargePlans()"
              ],
              "implementation": "marketing.RechargeCreditsModel.ListWebRechargePlans() -> listRechargePlans(Source=Web)"
            },
            {
              "operation": "SELECT",
              "table": "unit_filters",
              "trigger": "Hydrate unit-filter associations for each returned recharge plan",
              "conditions": [
                "listRechargePlans(Source=Web) reached the preload query"
              ],
              "implementation": "entity.NewRechargeCreditsPlanQuerySet(db.GetDB().Preload(clause.Associations)).SourceEq(Web).All(&entities)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/recharge_plans/:recharge_plan_id": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after recharge_plan_id path binding succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "recharge_credits_plans",
              "trigger": "Load the requested recharge plan row",
              "conditions": [
                "getRechargePlanIDFromURI(c) succeeded"
              ],
              "implementation": "marketing.RechargeCreditsModel.GetRechargePlan(planID) -> GetRechargePlanWithTx(db.GetDB(), planID)"
            },
            {
              "operation": "SELECT",
              "table": "unit_filters",
              "trigger": "Hydrate unit-filter associations for the requested recharge plan",
              "conditions": [
                "GetRechargePlanWithTx(...) reached the preload query"
              ],
              "implementation": "entity.NewRechargeCreditsPlanQuerySet(tx.Preload(clause.Associations)).IDEq(planID).One(&e)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/recharge_plans": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after the recharge-plan payload binds successfully and query.Value > 0"
          ],
          "operations": [
            {
              "operation": "INSERT",
              "table": "recharge_credits_plans",
              "trigger": "Create a new web-source recharge plan with fixed 2099 expiration and source=Web",
              "conditions": [
                "query.Value > 0"
              ],
              "implementation": "marketing.RechargeCreditsModel.CreateRechargePlan(query) -> CreateRechargePlanWithTx(db.GetDB(), query) -> e.Create(tx)"
            },
            {
              "operation": "INSERT",
              "table": "unit_filters",
              "trigger": "Persist unit-filter associations attached to the new recharge plan",
              "conditions": [
                "query.UnitFilters not empty"
              ],
              "implementation": "CreateRechargePlanWithTx(...) -> transformer.UnitFiltersEntitiesFromUnitFilterSlimForm(req.UnitFilters)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP PATCH /api/v1/billing/recharge_plans/:recharge_plan_id": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after recharge_plan_id path binding succeeds, the recharge-plan payload binds successfully, and query.Value > 0"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "recharge_credits_plans",
              "trigger": "Load the recharge plan before updating its value",
              "conditions": [
                "getRechargePlanIDFromURI(c) succeeded"
              ],
              "implementation": "marketing.RechargeCreditsModel.UpdateRechargePlanValue(planID, query.Value) -> GetRechargePlan(planID)"
            },
            {
              "operation": "UPDATE",
              "table": "recharge_credits_plans",
              "trigger": "Persist the new recharge-plan value",
              "conditions": [
                "GetRechargePlan(planID) succeeded",
                "query.Value > 0"
              ],
              "implementation": "entity.NewRechargeCreditsPlanQuerySet(db.GetDB()).IDEq(planID).GetUpdater().SetValue(value).Update()"
            },
            {
              "operation": "SELECT",
              "table": "recharge_credits_plans",
              "trigger": "Re-read the recharge plan after the value update succeeds",
              "conditions": [
                "SetValue(value).Update() succeeded"
              ],
              "implementation": "marketing.RechargeCreditsModel.GetRechargePlan(planID)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP DELETE /api/v1/billing/recharge_plans/:recharge_plan_id": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after recharge_plan_id path binding succeeds"
          ],
          "operations": [
            {
              "operation": "UPDATE",
              "table": "recharge_credits_plans",
              "trigger": "Close the recharge plan by filling closed_at when it is still open",
              "conditions": [
                "getRechargePlanIDFromURI(c) succeeded"
              ],
              "implementation": "marketing.RechargeCreditsModel.DisableRechargePlanWithTx(tx, planID) -> entity.NewRechargeCreditsPlanQuerySet(tx).IDEq(planID).ClosedAtIsNull().GetUpdater().SetClosedAt(now).Update()"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/recharge_plans/:tenant_recharge_plan_id": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant_id and tenant_recharge_plan_id path binding succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "tenant_recharge_credits_plans",
              "trigger": "Load the tenant recharge plan row",
              "conditions": [
                "getTenantRechargePlanIDFromURI(c) succeeded"
              ],
              "implementation": "marketing.RechargeCreditsModel.GetTenantRechargePlan(query.TenantRechargePlanID) -> GetTenantRechargePlanWithTx(db.GetDB(), query.TenantRechargePlanID)"
            },
            {
              "operation": "SELECT",
              "table": "unit_filters",
              "trigger": "Hydrate unit-filter associations for the selected tenant recharge plan",
              "conditions": [
                "GetTenantRechargePlanWithTx(...) reached the preload query"
              ],
              "implementation": "entity.NewTenantRechargeCreditsPlanQuerySet(tx.Preload(clause.Associations)).IDEq(tenantPlanID).One(&e)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP DELETE /api/v1/billing/tenants/:tenant_id/recharge_plans/:tenant_recharge_plan_id": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant and tenant_recharge_plan_id path binding succeeds, and the current implementation's tenant check compares result.TenantID against tenant_recharge_plan_id rather than tenant_id"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "tenant_recharge_credits_plans",
              "trigger": "Load the tenant recharge plan before disabling it",
              "conditions": [
                "getTenantRechargePlanIDFromURI(c) succeeded"
              ],
              "implementation": "RechargePlanAPI.GetTenantRechargePlan(c) -> marketing.RechargeCreditsModel.GetTenantRechargePlan(query.TenantRechargePlanID)"
            },
            {
              "operation": "UPDATE",
              "table": "tenant_recharge_credits_plans",
              "trigger": "Close the tenant recharge plan by filling closed_at and deleted_unique_key_mark when it is still open",
              "conditions": [
                "GetTenantRechargePlan(c) returned a plan",
                "current code path passed result.TenantID != query.TenantRechargePlanID guard"
              ],
              "implementation": "marketing.RechargeCreditsModel.DisableTenantRechargePlan(planID) -> DisableTenantRechargePlanWithTx(db.GetDB(), planID) -> entity.NewTenantRechargeCreditsPlanQuerySet(tx).IDEq(planID).ClosedAtIsNull().GetUpdater().SetClosedAt(now).SetDeletedUniqueKeyMark(uuid.NewString()).Update()"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/units": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after optional group_id query parsing succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "units",
              "trigger": "List all units when group_id is absent or zero",
              "conditions": [
                "uriForm.GroupID == 0"
              ],
              "implementation": "billing.UnitModel.GetAllUnits()"
            },
            {
              "operation": "SELECT",
              "table": "units",
              "trigger": "List units scoped to the requested sku group when group_id > 0",
              "conditions": [
                "uriForm.GroupID > 0"
              ],
              "implementation": "billing.UnitModel.ListUnitsByGroupID(uriForm.GroupID)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/units/:unit_key": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after unit_key path binding succeeds and the GetUnit cache misses"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "units",
              "trigger": "Load the requested unit row by unit_key",
              "conditions": [
                "cachehandler.Get().Get(\"GetUnit\", result, unitKey) missed"
              ],
              "implementation": "billing.UnitModel.GetUnit(unitKey) -> entity.NewUnitQuerySet(db.GetDB()).UnitKeyEq(unitKey).One(unit)"
            }
          ]
        },
        "redis": {
          "conditions": [
            "Always around GetUnit cache lookups"
          ],
          "operations": [
            {
              "operation": "GET",
              "trigger": "Reuse cached unit metadata before requerying the unit row",
              "conditions": [
                "billing.UnitModel.GetUnit(unitKey) is reached"
              ],
              "implementation": "cachehandler.Get().Get(\"GetUnit\", result, unitKey)"
            },
            {
              "operation": "SET",
              "trigger": "Cache unit metadata after the DB lookup succeeds",
              "conditions": [
                "UnitKeyEq(unitKey).One(unit) succeeded"
              ],
              "implementation": "cachehandler.Get().Set(\"GetUnit\", result, unitKey)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/units": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after the unit payload binds successfully and validator.ValidateStruct(unitform) succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "units",
              "trigger": "Check whether the submitted unit_key already exists before deciding create vs update",
              "conditions": [
                "validator.ValidateStruct(unitform) succeeded"
              ],
              "implementation": "billing.UnitModel.CreateAndUpdateUnit(unitform) -> entity.NewUnitQuerySet(db.GetDB()).UnitKeyEq(unitInfo.UnitKey).One(unitFromDb)"
            },
            {
              "operation": "INSERT",
              "table": "units",
              "trigger": "Create the new unit row when the submitted unit_key does not exist yet",
              "conditions": [
                "CreateAndUpdateUnit(...) detected isUpdate == false"
              ],
              "implementation": "unit.Create(db.GetDB())"
            },
            {
              "operation": "UPDATE",
              "table": "units",
              "trigger": "Update the existing unit row and bump its version when the submitted unit_key already exists",
              "conditions": [
                "CreateAndUpdateUnit(...) detected isUpdate == true"
              ],
              "implementation": "db.GetDB().Model(unitFromDb).Where(\"unit_key\", unitFromDb.UnitKey).Updates(unit)"
            },
            {
              "operation": "INSERT",
              "table": "version_skus",
              "trigger": "Persist the pre-update unit snapshot before the updated unit row overwrites it",
              "conditions": [
                "CreateAndUpdateUnit(...) detected isUpdate == true",
                "unit update transaction succeeded"
              ],
              "implementation": "versionSku.Create(tx)"
            }
          ]
        },
        "redis": {
          "conditions": [
            "Only when a cached GetUnit entry exists for the submitted unit_key"
          ],
          "operations": [
            {
              "operation": "DEL",
              "trigger": "Invalidate the GetUnit cache after the create or update completes",
              "conditions": [
                "CreateAndUpdateUnit(...) completed"
              ],
              "implementation": "cachehandler.Get().Delete(\"GetUnit\", unitInfo.UnitKey)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP PUT /api/v1/billing/units/:unit_key": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after unit_key path binding succeeds, the unit payload binds successfully, and validator.ValidateStruct(unitform) succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "units",
              "trigger": "Check whether the requested unit exists before overwriting its description/provider/category/region fields",
              "conditions": [
                "validator.ValidateStruct(unitform) succeeded"
              ],
              "implementation": "billing.UnitModel.CreateAndUpdateUnit(unitform) -> entity.NewUnitQuerySet(db.GetDB()).UnitKeyEq(unitInfo.UnitKey).One(unitFromDb)"
            },
            {
              "operation": "UPDATE",
              "table": "units",
              "trigger": "Overwrite the existing unit row and bump its version using the CreateAndUpdateUnit path",
              "conditions": [
                "CreateAndUpdateUnit(...) detected isUpdate == true"
              ],
              "implementation": "db.GetDB().Model(unitFromDb).Where(\"unit_key\", unitFromDb.UnitKey).Updates(unit)"
            },
            {
              "operation": "INSERT",
              "table": "version_skus",
              "trigger": "Persist the pre-update unit snapshot before the updated unit row overwrites it",
              "conditions": [
                "CreateAndUpdateUnit(...) detected isUpdate == true",
                "unit update transaction succeeded"
              ],
              "implementation": "versionSku.Create(tx)"
            }
          ]
        },
        "redis": {
          "conditions": [
            "Only when a cached GetUnit entry exists for the submitted unit_key"
          ],
          "operations": [
            {
              "operation": "DEL",
              "trigger": "Invalidate the GetUnit cache after the update completes",
              "conditions": [
                "CreateAndUpdateUnit(...) completed"
              ],
              "implementation": "cachehandler.Get().Delete(\"GetUnit\", unitInfo.UnitKey)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP DELETE /api/v1/billing/units/:unit_key": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after unit_key path binding succeeds"
          ],
          "operations": [
            {
              "operation": "DELETE",
              "table": "units",
              "trigger": "Delete the requested unit row by unit_key",
              "conditions": [
                "c.ShouldBindUri(&UnitURIForm{}) succeeded"
              ],
              "implementation": "billing.UnitModel.DeleteUnit(unitKey) -> entity.NewUnitQuerySet(db.GetDB()).UnitKeyEq(unitKey).Delete()"
            }
          ]
        },
        "redis": {
          "conditions": [
            "Only when a cached GetUnit entry exists for the deleted unit_key"
          ],
          "operations": [
            {
              "operation": "DEL",
              "trigger": "Invalidate the GetUnit cache after the delete completes",
              "conditions": [
                "DeleteUnit(unitKey) succeeded"
              ],
              "implementation": "cachehandler.Get().Delete(\"GetUnit\", unitKey)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/units/_create_by_group": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after the UnitByGroup payload binds successfully"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "sku_groups",
              "trigger": "Load the sku group used to derive unit_key and price from the submitted group input",
              "conditions": [
                "c.ShouldBindJSON(&forms.UnitByGroup{}) succeeded"
              ],
              "implementation": "billing.UnitModel.CreateUnitByGroup(unitByGroup, false) -> billing.SKUGroupModel.GetSKUGroup(unitByGroup.GroupID)"
            },
            {
              "operation": "SELECT",
              "table": "units",
              "trigger": "Reject duplicate unit_key creation when the generated unit already exists",
              "conditions": [
                "GetUnitKeyByGroupWithInput(...) succeeded",
                "dryrun == false"
              ],
              "implementation": "entity.NewUnitQuerySet(db.GetDB()).UnitKeyEq(unitKey).One(unitFromDb)"
            },
            {
              "operation": "INSERT",
              "table": "units",
              "trigger": "Create the generated unit when the unit key does not already exist",
              "conditions": [
                "dryrun == false",
                "generated unit key was not found"
              ],
              "implementation": "unit.Create(db.GetDB())"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/units/_create_by_group/dryrun": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after the UnitByGroup payload binds successfully"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "sku_groups",
              "trigger": "Load the sku group used to derive the unit_key and price preview",
              "conditions": [
                "c.ShouldBindJSON(&forms.UnitByGroup{}) succeeded"
              ],
              "implementation": "billing.UnitModel.CreateUnitByGroup(unitByGroup, true) -> billing.SKUGroupModel.GetSKUGroup(unitByGroup.GroupID)"
            },
            {
              "operation": "SELECT",
              "table": "units",
              "trigger": "Check whether the generated unit key already exists even though dryrun mode avoids writing the row",
              "conditions": [
                "GetUnitKeyByGroupWithInput(...) succeeded"
              ],
              "implementation": "entity.NewUnitQuerySet(db.GetDB()).UnitKeyEq(unitKey).One(unitFromDb)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/units/_bulk": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after the bulk unit payload binds successfully and APISwitchUpdateUnit == true"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "units",
              "trigger": "Check each submitted unit key before deciding create vs update for every batch item",
              "conditions": [
                "validator.ValidateStruct(&unitInfo) succeeded for the batch item"
              ],
              "implementation": "billing.UnitModel.CreateAndUpdateUnitFromCoreSVC(&unitInfo) -> entity.NewUnitQuerySet(db.GetDB()).UnitKeyEq(unitInfo.UnitKey).One(unitFromDb)"
            },
            {
              "operation": "INSERT",
              "table": "units",
              "trigger": "Create any submitted unit keys that do not already exist",
              "conditions": [
                "CreateAndUpdateUnitFromCoreSVC(...) detected isUpdate == false"
              ],
              "implementation": "unit.Create(db.GetDB())"
            },
            {
              "operation": "UPDATE",
              "table": "units",
              "trigger": "Update description/category/provider/region for existing unit keys whose core-svc payload differs",
              "conditions": [
                "CreateAndUpdateUnitFromCoreSVC(...) detected isUpdate == true",
                "incoming fields differ from the DB row"
              ],
              "implementation": "unit.Update(db.GetDB(), Description, Category, Provider, Region)"
            }
          ]
        },
        "redis": {
          "conditions": [
            "Only when a cached GetUnit entry exists for a batch item's unit_key"
          ],
          "operations": [
            {
              "operation": "DEL",
              "trigger": "Invalidate the GetUnit cache for each batch item whose create/update path completes",
              "conditions": [
                "CreateAndUpdateUnitFromCoreSVC(&unitInfo) completed"
              ],
              "implementation": "cachehandler.Get().Delete(\"GetUnit\", unitInfo.UnitKey)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/units/network/:provider/:region": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after provider and region path binding succeeds and provider is one of aws/azure/gcp"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "units",
              "trigger": "Check each generated network-traffic unit key before deciding create vs update across the provider's fixed category set",
              "conditions": [
                "provider in {aws, azure, gcp}"
              ],
              "implementation": "billing.UnitModel.AddRegionNetWorkUnit(provider, region) -> CreateUnit(...) -> CreateAndUpdateUnit(...) -> entity.NewUnitQuerySet(db.GetDB()).UnitKeyEq(unitInfo.UnitKey).One(unitFromDb)"
            },
            {
              "operation": "INSERT",
              "table": "units",
              "trigger": "Create generated network-traffic unit rows that do not already exist",
              "conditions": [
                "CreateAndUpdateUnit(...) detected isUpdate == false"
              ],
              "implementation": "unit.Create(db.GetDB())"
            },
            {
              "operation": "UPDATE",
              "table": "units",
              "trigger": "Refresh generated network-traffic unit rows when they already exist",
              "conditions": [
                "CreateAndUpdateUnit(...) detected isUpdate == true"
              ],
              "implementation": "db.GetDB().Model(unitFromDb).Where(\"unit_key\", unitFromDb.UnitKey).Updates(unit)"
            },
            {
              "operation": "INSERT",
              "table": "version_skus",
              "trigger": "Persist the pre-update unit snapshot when an existing generated network unit is refreshed",
              "conditions": [
                "CreateAndUpdateUnit(...) detected isUpdate == true",
                "unit update transaction succeeded"
              ],
              "implementation": "versionSku.Create(tx)"
            }
          ]
        },
        "redis": {
          "conditions": [
            "Only when a cached GetUnit entry exists for one of the generated network unit keys"
          ],
          "operations": [
            {
              "operation": "DEL",
              "trigger": "Invalidate the GetUnit cache for every generated network unit key after create/update completes",
              "conditions": [
                "CreateAndUpdateUnit(...) completed for a generated network unit key"
              ],
              "implementation": "cachehandler.Get().Delete(\"GetUnit\", unitInfo.UnitKey)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/unit_filters": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Always"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "unit_filters",
              "trigger": "List external unit filters and build the filter tree rooted at the synthetic root node",
              "conditions": [
                "handler reached unit_filter.Model.GetUnitFilterTree()"
              ],
              "implementation": "unit_filter.Model.GetUnitFilterTree() -> ListExternalUnitFilters() -> ListUnitFilters(Internal=false)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/credit_types": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Always"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "unit_filters",
              "trigger": "List external credit-type rows through the same tree builder used by /unit_filters",
              "conditions": [
                "handler reached unit_filter.Model.GetUnitFilterTree()"
              ],
              "implementation": "unit_filter.Model.GetUnitFilterTree() -> ListExternalUnitFilters() -> ListUnitFilters(Internal=false)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/unit_filters/quick_selections/:target": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after target path binding succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "unit_filter_selections",
              "trigger": "Load quick-selection rows for the requested target",
              "conditions": [
                "c.ShouldBindUri(&targetQuery) succeeded"
              ],
              "implementation": "unit_filter.Model.GetUnitFilterQuickSelection(target) -> entity.NewUnitFilterSelectionQuerySet(db.GetDB()).TargetEq(target).All(&selections)"
            },
            {
              "operation": "SELECT",
              "table": "unit_filters",
              "trigger": "Load the unit-filter rows referenced by the quick-selection entries",
              "conditions": [
                "len(selections) != 0"
              ],
              "implementation": "entity.NewUnitFilterQuerySet(db.GetDB()).IDIn(targetIDs...).All(&entList)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/sku_groups": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Always"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "sku_groups",
              "trigger": "List all sku group rows",
              "conditions": [
                "handler reached billing.SKUGroupModel.GetSKUGroupList()"
              ],
              "implementation": "entity.NewSKUGroupsQuerySet(db.GetDB()).All(&groupEntityList)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/sku_groups/:group_id": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after group_id path binding succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "sku_groups",
              "trigger": "Load the requested sku group row",
              "conditions": [
                "c.ShouldBindUri(&GroupIDURIForm{}) succeeded"
              ],
              "implementation": "billing.SKUGroupModel.GetSKUGroup(groupID) -> entity.NewSKUGroupsQuerySet(db.GetDB()).IDEq(groupID).One(groupEntity)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/sku_groups/category": {
      "infrastructure": {},
      "services": []
    },
    "HTTP POST /api/v1/billing/sku_groups": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after the SKUGroup payload binds successfully and the unit-key pattern passes isValidPattern"
          ],
          "operations": [
            {
              "operation": "INSERT",
              "table": "sku_groups",
              "trigger": "Create the new sku group row",
              "conditions": [
                "isValidPattern(group.UnitKeyPattern) returned true"
              ],
              "implementation": "billing.SKUGroupModel.CreateGroup(group) -> groupEntity.Create(db.GetDB())"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP PUT /api/v1/billing/sku_groups/:group_id": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after group_id path binding succeeds and the SKUGroup payload binds successfully"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "sku_groups",
              "trigger": "Load the existing sku group row before applying mutations",
              "conditions": [
                "c.ShouldBindUri(&GroupIDURIForm{}) succeeded"
              ],
              "implementation": "billing.SKUGroupModel.GetSKUGroup(groupID)"
            },
            {
              "operation": "UPDATE",
              "table": "sku_groups",
              "trigger": "Persist the updated unit-key pattern, naming, category, pricing, and measure-unit fields",
              "conditions": [
                "GetSKUGroup(groupID) succeeded"
              ],
              "implementation": "groupEntity.Update(db.GetDB(), UnitKeyPattern, Name, Category, PriceType, PriceFormula, PriceFormula, MeasureUnit)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP DELETE /api/v1/billing/sku_groups/:group_id": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after group_id path binding succeeds"
          ],
          "operations": [
            {
              "operation": "DELETE",
              "table": "sku_groups",
              "trigger": "Delete the requested sku group row",
              "conditions": [
                "c.ShouldBindUri(&GroupIDURIForm{}) succeeded"
              ],
              "implementation": "billing.SKUGroupModel.DeleteSKUGroup(groupID) -> entity.NewSKUGroupsQuerySet(db.GetDB()).IDEq(groupID).Delete()"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/switch/card/validate/is_allowed": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only when the route reaches credit-card validation switch evaluation after URI binding succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_information",
              "trigger": "This endpoint does not read billing tables directly, but any later card-validation flow it gates may skip address/tax validation only if billing information already exists",
              "conditions": [
                "Downstream callers proceed past this switch endpoint and later run CreditCardVerifyModel.creditCardAddressValidate(...)"
              ],
              "implementation": "CreditCardVerifyModel.IsCreditCardValidationRequired(tenantID) only returns a config decision; the eventual gated flow may later call paymentsub.BillingInformationModel.BillingInfoIsNotEmpty(tenantID)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/switch/card/validation/required": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only when the route reaches credit-card validation switch evaluation after URI binding succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_information",
              "trigger": "This alias endpoint shares the same switch implementation as /switch/card/validate/is_allowed and gates the later card-validation path",
              "conditions": [
                "Downstream callers proceed past this switch endpoint and later run CreditCardVerifyModel.creditCardAddressValidate(...)"
              ],
              "implementation": "CreditCardVerifyModel.IsCreditCardValidationRequired(tenantID) only returns a config decision; the eventual gated flow may later call paymentsub.BillingInformationModel.BillingInfoIsNotEmpty(tenantID)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/tenants/:tenant_id/measures": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only when HTTPMeasuresToQueue == false and the request body was accepted",
            "Writes are skipped when the request is queue-only or cost == 0 with MeasureDisableSuccessResponse handling"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve which billing config applies at the measure timestamp before pricing the usage",
              "conditions": [
                "c.ShouldBindJSON(costForm) succeeded",
                "HTTPMeasuresToQueue == false"
              ],
              "implementation": "MeasureModel.GetBillingConfigIDByTimeStamp(tenantID, costs, false) -> billingconfig.BillingConfigModel.GetUseBillingConfigIDByTimeStampWithCache(...)"
            },
            {
              "operation": "SELECT",
              "table": "units",
              "trigger": "Load the priced unit definition before validating and pricing the raw usage",
              "conditions": [
                "MeasureModel.CostUnits(...) continued into buildRawUnitCost(...)"
              ],
              "implementation": "MeasureModel.buildRawUnitCost(...) -> UnitModel.GetUnit(costs.Unit)"
            },
            {
              "operation": "SELECT",
              "table": "binded_packages",
              "trigger": "Resolve effective tenant packages before computing credits-vs-invoice consumption",
              "conditions": [
                "MeasureModel.ListBindedPackages(...) reached tenant package lookup"
              ],
              "implementation": "BindedPackageModel.GetAllTenantBindedPackage(tenantID)"
            },
            {
              "operation": "SELECT",
              "table": "discounts",
              "trigger": "Resolve the effective discount chain before finalizing the priced raw usage",
              "conditions": [
                "MeasureModel.GetUseDiscount(...) reached discount resolution"
              ],
              "implementation": "discount.Model.ListEffectiveDiscounts(costEntity.TenantID, costEntity.BindedBillingConfigID)"
            },
            {
              "operation": "INSERT/UPDATE",
              "table": "raw_user_unit_costs",
              "trigger": "Persist the raw cost row before merge/copy processing",
              "conditions": [
                "dryrun == false",
                "MeasureModel.procRawUnitCost(...) reached initRawUnitCost(...) or status update branches"
              ],
              "implementation": "MeasureModel.initRawUnitCost(...) / MeasureModel.costUserRawUnitCost(...) / entity.NewRawUserUnitCostQuerySet(...).GetUpdater()"
            },
            {
              "operation": "INSERT/UPDATE",
              "table": "user_unit_costs",
              "trigger": "Create or merge the final billable usage row after raw-cost processing succeeds",
              "conditions": [
                "dryrun == false",
                "costEntity.Status == done",
                "costEntity.Cost != 0"
              ],
              "implementation": "MeasureModel.copyRawUnitCost(...) or MeasureModel.mergeRawUnitCost(...)"
            }
          ]
        },
        "sqs": {
          "conditions": [
            "Only when HTTPMeasuresToQueue == true",
            "Only when costForm.Cost > 0"
          ],
          "operations": [
            {
              "operation": "SEND",
              "queue": "configurable (MeasureSender queue target)",
              "trigger": "Enqueue the measure instead of pricing it inline",
              "conditions": [
                "config.Get().GetBool(config.HTTPMeasuresToQueue) == true",
                "costForm.Cost > 0"
              ],
              "implementation": "sqsmeasurehandler.GetMeasureSender().SendMeasure(tenantID, costForm)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/tenants/:tenant_id/measures/dryrun": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after the request body was accepted",
            "Dryrun resolves pricing state but does not persist usage rows"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the billing config that would apply to the submitted measure timestamp",
              "conditions": [
                "c.ShouldBindJSON(costForm) succeeded"
              ],
              "implementation": "MeasureModel.GetBillingConfigIDByTimeStamp(tenantID, costs, true)"
            },
            {
              "operation": "SELECT",
              "table": "units",
              "trigger": "Load the unit metadata needed for dryrun pricing",
              "conditions": [
                "MeasureModel.CostUnitsDryrun(...) continued into buildRawUnitCost(...)"
              ],
              "implementation": "MeasureModel.buildRawUnitCost(...) -> UnitModel.GetUnit(costs.Unit)"
            },
            {
              "operation": "SELECT",
              "table": "binded_packages",
              "trigger": "Resolve package matches that would be used if the measure were billed for real",
              "conditions": [
                "MeasureModel.ListBindedPackages(...) reached tenant package lookup"
              ],
              "implementation": "BindedPackageModel.GetAllTenantBindedPackage(tenantID)"
            },
            {
              "operation": "SELECT",
              "table": "discounts",
              "trigger": "Resolve the discount that would be applied during dryrun pricing",
              "conditions": [
                "MeasureModel.GetUseDiscount(...) reached discount lookup"
              ],
              "implementation": "discount.Model.ListEffectiveDiscounts(costEntity.TenantID, costEntity.BindedBillingConfigID)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/subscriptions": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant_id URI binding succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "subscriptions",
              "trigger": "List all subscription rows for the tenant ordered by creation time descending",
              "conditions": [
                "getTenantIDFromURI(c) succeeded"
              ],
              "implementation": "SubscriptionModel.ListSubscriptions(tenantID)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/submited_subscriptions": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant_id URI binding succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "subscriptions",
              "trigger": "List only submitted/non-draft subscription rows for the tenant",
              "conditions": [
                "getTenantIDFromURI(c) succeeded"
              ],
              "implementation": "SubscriptionModel.ListSubmitedSubscriptions(tenantID) -> entity.NewSubscriptionQuerySet(...).StatusNotIn(entity.SubscriptionStatus_DRAFT)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/subscriptions/:subscription_id": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after subscription_id URI binding succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "subscriptions",
              "trigger": "Load the requested subscription row by primary key",
              "conditions": [
                "c.ShouldBindUri(subscriptionURIStruct) succeeded"
              ],
              "implementation": "SubscriptionModel.GetSubscription(subscriptionURIStruct.SubscriptionID)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/tenants/:tenant_id/subscriptions": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant_id URI binding and JSON body binding both succeed"
          ],
          "operations": [
            {
              "operation": "INSERT",
              "table": "subscriptions",
              "trigger": "Create a new draft subscription row for the tenant",
              "conditions": [
                "c.ShouldBindJSON(subscription) succeeded"
              ],
              "implementation": "SubscriptionModel.CreateSubscription(tenantID, subscription)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP PUT /api/v1/billing/tenants/:tenant_id/subscriptions/:subscription_id": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after URI and JSON binding both succeed"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "subscriptions",
              "trigger": "Load the current subscription row to reject updates on accepted subscriptions",
              "conditions": [
                "c.ShouldBindUri(subscriptionURIStruct) succeeded"
              ],
              "implementation": "SubscriptionModel.UpdateSubscription(...) -> SubscriptionModel.GetSubscription(subscriptionID)"
            },
            {
              "operation": "UPDATE",
              "table": "subscriptions",
              "trigger": "Reset the subscription to draft and replace file/email fields",
              "conditions": [
                "Current subscription.Status != accepted"
              ],
              "implementation": "entity.NewSubscriptionQuerySet(db.GetDB()).IDEq(subscriptionID).GetUpdater().SetContractEmail(...).SetStatus(draft).SetFilePath(...).Update()"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/tenants/:tenant_id/subscriptions/:subscription_id/actions/reject": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after URI and JSON binding both succeed"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "subscriptions",
              "trigger": "Load the current subscription state before enforcing the pending-only reject rule",
              "conditions": [
                "c.ShouldBindUri(subscriptionURIStruct) succeeded"
              ],
              "implementation": "SubscriptionModel.RejectSubscription(...) -> SubscriptionModel.GetSubscription(subscriptionID)"
            },
            {
              "operation": "UPDATE",
              "table": "subscriptions",
              "trigger": "Mark the subscription rejected and persist rejection actor/time",
              "conditions": [
                "Current subscription.Status == pending"
              ],
              "implementation": "entity.NewSubscriptionQuerySet(db.GetDB()).IDEq(subscriptionID).GetUpdater().SetStatus(rejected).SetRejectedDate(...).SetRejectedUser(...).Update()"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/tenants/:tenant_id/subscriptions/:subscription_id/actions/accept": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after URI and JSON binding both succeed"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "subscriptions",
              "trigger": "Load the current subscription state before enforcing the pending-only accept rule",
              "conditions": [
                "c.ShouldBindUri(subscriptionURIStruct) succeeded"
              ],
              "implementation": "SubscriptionModel.AcceptSubscription(...) -> SubscriptionModel.GetSubscription(subscriptionID)"
            },
            {
              "operation": "UPDATE",
              "table": "subscriptions",
              "trigger": "Mark the subscription accepted and persist accepted actor/time",
              "conditions": [
                "Current subscription.Status == pending"
              ],
              "implementation": "entity.NewSubscriptionQuerySet(db.GetDB()).IDEq(subscriptionID).GetUpdater().SetStatus(accepted).SetAcceptedDate(...).SetAcceptedUser(...).Update()"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/tenants/:tenant_id/subscriptions/:subscription_id/actions/suspend": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after subscription_id URI binding succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "subscriptions",
              "trigger": "Load the current subscription state before enforcing the accepted-only suspend rule",
              "conditions": [
                "c.ShouldBindUri(subscriptionURIStruct) succeeded"
              ],
              "implementation": "SubscriptionModel.SuspendSubscription(...) -> SubscriptionModel.GetSubscription(subscriptionID)"
            },
            {
              "operation": "UPDATE",
              "table": "subscriptions",
              "trigger": "Mark the subscription suspended",
              "conditions": [
                "Current subscription.Status == accepted"
              ],
              "implementation": "entity.NewSubscriptionQuerySet(db.GetDB()).IDEq(subscriptionID).GetUpdater().SetStatus(suspended).Update()"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/tenants/:tenant_id/subscriptions/:subscription_id/actions/submit": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after subscription_id URI binding succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "subscriptions",
              "trigger": "Load the current subscription state before enforcing the draft-only submit rule",
              "conditions": [
                "c.ShouldBindUri(subscriptionURIStruct) succeeded"
              ],
              "implementation": "SubscriptionModel.SubmitSubscription(...) -> SubscriptionModel.GetSubscription(subscriptionID)"
            },
            {
              "operation": "UPDATE",
              "table": "subscriptions",
              "trigger": "Move the subscription from draft to pending",
              "conditions": [
                "Current subscription.Status == draft"
              ],
              "implementation": "entity.NewSubscriptionQuerySet(db.GetDB()).IDEq(subscriptionID).GetUpdater().SetStatus(pending).Update()"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/tenants/:tenant_id/tax_rates": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant_id URI binding succeeds",
            "Write path only runs when the newly calculated tax rate differs from the existing stored one"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_information",
              "trigger": "Load tenant billing profile before calculating a fresh tax rate",
              "conditions": [
                "EnableTaxCalculation == true"
              ],
              "implementation": "paymentsub.TaxModel.RetrieveAndUpdateTenantTaxRate(tenantID) -> BillingInformationModel.GetBillingInfo(tenantID)"
            },
            {
              "operation": "SELECT",
              "table": "tenant_billing_companies",
              "trigger": "Resolve which billing company and payment sub-code should drive tax calculation",
              "conditions": [
                "EnableTaxCalculation == true"
              ],
              "implementation": "BillingInformationModel.GetTenantBillingCompany(tenantID)"
            },
            {
              "operation": "SELECT",
              "table": "billing_companies",
              "trigger": "Load the billing company record that decides designated-address tax calculation vs tenant billing-profile tax calculation",
              "conditions": [
                "BillingInformationModel.GetTenantBillingCompany(...) succeeded"
              ],
              "implementation": "BillingInformationModel.GetBillingCompany(tenantCompany.CompanyKey)"
            },
            {
              "operation": "UPDATE",
              "table": "billing_information",
              "trigger": "Persist the new Stripe tax rate ID after creating a changed tax rate",
              "conditions": [
                "EnableTaxCalculation == true",
                "TaxModel.MatchTaxRate(billingInfo.TaxRate, rate) == false"
              ],
              "implementation": "BillingInformationModel.UpdateTaxRate(tenantID, rate.StripeTaxRateID)"
            }
          ]
        }
      },
      "services": [
        {
          "name": "stripe-api",
          "target_interface": "POST /v1/tax/calculations, POST /v1/tax_rates, POST /v1/tax_rates/:id/deactivate",
          "operation_type": "https",
          "conditions": [
            "Only when EnableTaxCalculation == true"
          ],
          "operations": [
            {
              "operation": "HTTP CalculateTax",
              "trigger": "Calculate the tenant/company tax rate candidate from Stripe",
              "conditions": [
                "Billing information and billing company lookups succeeded"
              ],
              "implementation": "stripe provider CalculateTax(...) inside TaxModel.RetrieveAndUpdateTenantTaxRate(...)"
            },
            {
              "operation": "HTTP CreateTaxRate",
              "trigger": "Create the new Stripe tax rate when the calculated rate changed",
              "conditions": [
                "TaxModel.MatchTaxRate(old, new) == false"
              ],
              "implementation": "handler.CreateTaxRate(rate)"
            },
            {
              "operation": "HTTP InactiveTaxRate",
              "trigger": "Deactivate the old Stripe tax rate after replacing it",
              "conditions": [
                "billingInfo.TaxRate != nil",
                "TaxModel.MatchTaxRate(old, new) == false"
              ],
              "implementation": "TaxModel.InactiveTaxRate(billingInfo.TaxRate.StripeTaxRateID)"
            }
          ]
        }
      ]
    },
    "HTTP POST /api/v1/billing/migrate_tasks/:name": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after the task name was accepted and the async goroutine starts running",
            "Actual tables depend on query.Name"
          ],
          "operations": [
            {
              "operation": "INSERT/UPDATE",
              "table": "multiple billing tables (task-dependent)",
              "trigger": "Run the selected migration task asynchronously after returning OK to the caller",
              "conditions": [
                "query.Name matched one of the supported migrate tasks"
              ],
              "implementation": "go f() where f is one of MigrateModel.UpdateStripeEmail / ReCalculateMeasures / CreateReCalculateInvoices / MigrateSpendLimitRechargePlanID / CreateAllTenantIDBillingConfig / CreateAllTenantIDNovuSubscriber / SyncAllSupportPlanInfoToEventBus / SyncOnDemandOrgsToJSM"
            }
          ]
        }
      },
      "services": [
        {
          "name": "novu-api",
          "target_interface": "subscriber sync APIs",
          "operation_type": "https",
          "conditions": [
            "Only when query.Name == create_novu_subscribers"
          ],
          "operations": [
            {
              "operation": "HTTP CreateSubscribers",
              "trigger": "Backfill Novu subscribers for all tenants in the async migration task",
              "conditions": [
                "query.Name == create_novu_subscribers"
              ],
              "implementation": "MigrateModel.CreateAllTenantIDNovuSubscriber()"
            }
          ]
        },
        {
          "name": "eventbus",
          "target_interface": "support-plan sync event publishing",
          "operation_type": "event",
          "conditions": [
            "Only when query.Name == sync_binded_support_plans_to_eventbus"
          ],
          "operations": [
            {
              "operation": "Publish support-plan sync events",
              "trigger": "Backfill support-plan information into the event bus asynchronously",
              "conditions": [
                "query.Name == sync_binded_support_plans_to_eventbus"
              ],
              "implementation": "MigrateModel.SyncAllSupportPlanInfoToEventBus()"
            }
          ]
        }
      ]
    },
    "HTTP GET /api/v1/billing/sentry/validate": {
      "infrastructure": {},
      "services": []
    },
    "HTTP GET /api/v1/billing/auditlog": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after query binding and date-range validation both succeed"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "audit_records",
              "trigger": "List audit records filtered by time range plus optional tenant/operator/action filters",
              "conditions": [
                "query.PageSize <= 100",
                "query.EndDate is not before query.StartDate"
              ],
              "implementation": "AuditLogModel.GetAuditLog(query)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/billing_company": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Always after the handler is reached"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_companies",
              "trigger": "List all configured billing companies",
              "conditions": [
                "ListBillingCompany handler invoked"
              ],
              "implementation": "paymentsub.BillingInformationModel.ListBillingCompany()"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP PUT /api/v1/billing/events": {
      "infrastructure": {},
      "services": [
        {
          "name": "eventbus",
          "target_interface": "Publish(eventType, eventData)",
          "operation_type": "event",
          "conditions": [
            "Only when EnableEventbus == true"
          ],
          "operations": [
            {
              "operation": "PublishEvent",
              "trigger": "Publish the decoded event payload onto the shared Ti eventbus",
              "conditions": [
                "json.NewDecoder(c.Request.Body).Decode(event) succeeded"
              ],
              "implementation": "eventbushandler.Get().PublishEvent(event.EventType, event)"
            }
          ]
        }
      ]
    },
    "HTTP GET /api/v1/unc/tenants/:tenant_id/notifications/:query_type/page/:page/page_size/:page_size": {
      "infrastructure": {},
      "services": [
        {
          "name": "novu-api",
          "target_interface": "GET /v1/subscribers/:subscriberId/notifications/feed",
          "operation_type": "https",
          "conditions": [
            "Only after tenant/page/path binding succeeds",
            "The authenticated current user ID is used to derive subscriberId"
          ],
          "operations": [
            {
              "operation": "HTTP GET feed",
              "trigger": "Fetch the current user's in-app notification feed for the tenant/query_type/page window",
              "conditions": [
                "NotificationRequest URI binding succeeded"
              ],
              "implementation": "novuhandler.Get().GetSubscriberInAppNotifications(request) -> GET /v1/subscribers/{tenantID}_{userID}/notifications/feed"
            }
          ]
        }
      ]
    },
    "HTTP GET /api/v1/unc/tenants/:tenant_id/notifications/notification_id/:notification_id": {
      "infrastructure": {},
      "services": [
        {
          "name": "novu-api",
          "target_interface": "GET /v1/subscribers/:subscriberId/notifications/feed",
          "operation_type": "https",
          "conditions": [
            "Only after tenant_id and notification_id URI binding succeeds"
          ],
          "operations": [
            {
              "operation": "HTTP GET paged feed scan",
              "trigger": "Iterate the subscriber feed until the requested notification ID is found or pages are exhausted",
              "conditions": [
                "NotificationID URI binding succeeded"
              ],
              "implementation": "novuhandler.Get().GetSubscriberInAppNotificationByID(request)"
            }
          ]
        }
      ]
    },
    "HTTP POST /api/v1/unc/tenants/:tenant_id/notifications/:type/notification_id/:notification_id": {
      "infrastructure": {},
      "services": [
        {
          "name": "novu-api",
          "target_interface": "POST /v1/subscribers/:subscriberId/messages/mark-all or /markAs",
          "operation_type": "https",
          "conditions": [
            "Only after tenant/type/notification_id URI binding succeeds"
          ],
          "operations": [
            {
              "operation": "HTTP POST mark-all or markAs",
              "trigger": "Mark the caller's notification(s) as seen",
              "conditions": [
                "request.Type == all && request.NotificationID == all uses mark-all",
                "otherwise uses markAs for the single notification"
              ],
              "implementation": "novuhandler.Get().MarkMessagesAsSeen(request)"
            }
          ]
        }
      ]
    },
    "HTTP POST /api/v1/unc/tenants/:tenant_id/notifications/notification_id/:notification_id": {
      "infrastructure": {},
      "services": []
    },
    "HTTP GET /api/v1/unc/workflow/page/:page/page_size/:page_size": {
      "infrastructure": {},
      "services": [
        {
          "name": "novu-api",
          "target_interface": "GET /v1/workflows",
          "operation_type": "https",
          "conditions": [
            "Only after page and page_size URI binding succeeds"
          ],
          "operations": [
            {
              "operation": "HTTP GET workflows",
              "trigger": "List workflows from Novu and reshape them into billing's forms.WorkFlows response",
              "conditions": [
                "PageQuery URI binding succeeded"
              ],
              "implementation": "novuhandler.Get().GetWorkflows(page, pageSize)"
            }
          ]
        }
      ]
    },
    "HTTP GET /api/v1/unc/workflow/workflow_id/:workflow_id": {
      "infrastructure": {},
      "services": [
        {
          "name": "novu-api",
          "target_interface": "GET /v1/workflows/:workflowId, GET /v1/notification-groups/:id",
          "operation_type": "https",
          "conditions": [
            "Only after workflow_id URI binding succeeds"
          ],
          "operations": [
            {
              "operation": "HTTP GET workflow",
              "trigger": "Load the workflow definition from Novu",
              "conditions": [
                "WorkFlowStruct URI binding succeeded"
              ],
              "implementation": "novuhandler.Get().GetWorkflow(workflowID) -> GetWorkflowFromNovu(workflowID)"
            },
            {
              "operation": "HTTP GET notification group",
              "trigger": "Resolve the notification-group name referenced by the workflow",
              "conditions": [
                "GetWorkflowFromNovu(...) succeeded"
              ],
              "implementation": "GetNotificationGroupNameByID(novuData.Data.NotificationGroupId2)"
            }
          ]
        }
      ]
    },
    "HTTP POST /api/v1/unc/workflow": {
      "infrastructure": {},
      "services": [
        {
          "name": "novu-api",
          "target_interface": "GET /v1/notification-groups, POST /v1/workflows",
          "operation_type": "https",
          "conditions": [
            "Only after workflow JSON binding succeeds"
          ],
          "operations": [
            {
              "operation": "HTTP GET notification groups",
              "trigger": "Resolve the notification-group ID by name before creating the workflow",
              "conditions": [
                "flow.NotificationGroup is set"
              ],
              "implementation": "GetNotificationGroupIDByName(flow.NotificationGroup)"
            },
            {
              "operation": "HTTP POST workflow",
              "trigger": "Create the workflow in Novu",
              "conditions": [
                "CreateWorkflow payload assembly succeeded"
              ],
              "implementation": "novuhandler.Get().CreateWorkflow(flow) -> POST /v1/workflows"
            }
          ]
        }
      ]
    },
    "HTTP PUT /api/v1/unc/workflow": {
      "infrastructure": {},
      "services": [
        {
          "name": "novu-api",
          "target_interface": "GET /v1/workflows/:workflowId, optional GET /v1/notification-groups, PUT /v1/workflows/:workflowId",
          "operation_type": "https",
          "conditions": [
            "Only after workflow JSON binding succeeds"
          ],
          "operations": [
            {
              "operation": "HTTP GET workflow",
              "trigger": "Load the current workflow document before mutating it",
              "conditions": [
                "flow.WorkFlowID is present"
              ],
              "implementation": "novuhandler.Get().UpdateWorkflow(flow) -> GetWorkflowFromNovu(flow.WorkFlowID)"
            },
            {
              "operation": "HTTP GET notification groups",
              "trigger": "Resolve a new notification-group ID when the update payload changed the group name",
              "conditions": [
                "flow.NotificationGroup is non-empty"
              ],
              "implementation": "GetNotificationGroupIDByName(flow.NotificationGroup)"
            },
            {
              "operation": "HTTP PUT workflow",
              "trigger": "Persist the mutated workflow back to Novu",
              "conditions": [
                "Workflow fetch succeeded"
              ],
              "implementation": "PUT /v1/workflows/{flow.WorkFlowID}"
            }
          ]
        }
      ]
    },
    "HTTP DELETE /api/v1/unc/workflow": {
      "infrastructure": {},
      "services": [
        {
          "name": "novu-api",
          "target_interface": "DELETE /v1/workflows/:workflowId",
          "operation_type": "https",
          "conditions": [
            "Only after workflow JSON binding succeeds"
          ],
          "operations": [
            {
              "operation": "HTTP DELETE workflow",
              "trigger": "Delete the selected workflow in Novu",
              "conditions": [
                "flow.WorkFlowID is present in the request body"
              ],
              "implementation": "novuhandler.Get().DeleteWorkflow(flow)"
            }
          ]
        }
      ]
    },
    "HTTP POST /api/v1/unc/workflow/workflow_id/:workflow_id": {
      "infrastructure": {},
      "services": [
        {
          "name": "novu-api",
          "target_interface": "GET /v1/workflows/:workflowId, POST /v1/workflows",
          "operation_type": "https",
          "conditions": [
            "Only after workflow_id URI binding succeeds"
          ],
          "operations": [
            {
              "operation": "HTTP GET workflow",
              "trigger": "Load the source workflow that should be duplicated",
              "conditions": [
                "WorkFlowStruct URI binding succeeded"
              ],
              "implementation": "novuhandler.Get().DuplicateWorkflow(workflowID) -> GetWorkflowFromNovu(workflowID)"
            },
            {
              "operation": "HTTP POST workflow",
              "trigger": "Create a duplicated workflow document in Novu",
              "conditions": [
                "GetWorkflowFromNovu(...) succeeded"
              ],
              "implementation": "POST /v1/workflows with the fetched workflow document"
            }
          ]
        }
      ]
    },
    "HTTP POST /api/v1/unc/bulk_trigger": {
      "infrastructure": {},
      "services": [
        {
          "name": "novu-api",
          "target_interface": "GET workflow helpers + POST /v1/events/trigger/bulk",
          "operation_type": "https",
          "conditions": [
            "Only after trigger JSON binding succeeds"
          ],
          "operations": [
            {
              "operation": "HTTP POST bulk trigger",
              "trigger": "Send a bulk Novu trigger for the tenant/workflow/target selection",
              "conditions": [
                "trigger.ScopeType defaulting and send-now scheduling completed"
              ],
              "implementation": "novuhandler.Get().BulkTriggerEvent(trigger.TenantID, *trigger)"
            }
          ]
        }
      ]
    },
    "HTTP POST /api/v1/unc/broadcast_trigger": {
      "infrastructure": {},
      "services": [
        {
          "name": "novu-api",
          "target_interface": "POST /v1/events/trigger/broadcast",
          "operation_type": "https",
          "conditions": [
            "Only after trigger JSON binding succeeds",
            "Only when operatorAuth(trigger.Operator) == true",
            "Only when trigger.IsSendNow == false"
          ],
          "operations": [
            {
              "operation": "HTTP POST broadcast trigger",
              "trigger": "Broadcast the trigger to all matching Novu subscribers",
              "conditions": [
                "BroadcastTriggerEvent passed operatorAuth and prohibited send-now checks"
              ],
              "implementation": "novuhandler.Get().BroadcastTriggerEvent(*trigger)"
            }
          ]
        }
      ]
    },
    "HTTP GET /api/v1/unc/broadcast_trigger/:operator/auth": {
      "infrastructure": {},
      "services": []
    },
    "HTTP GET /api/v1/unc/notifications": {
      "infrastructure": {},
      "services": [
        {
          "name": "novu-api",
          "target_interface": "GET /v1/notifications",
          "operation_type": "https",
          "conditions": [
            "Only after query binding succeeds"
          ],
          "operations": [
            {
              "operation": "HTTP GET notifications",
              "trigger": "List workflow-trigger notifications for ops review",
              "conditions": [
                "NotificationQuery binding succeeded"
              ],
              "implementation": "novuhandler.Get().GetNotificationsByWorkflowID(*query)"
            }
          ]
        }
      ]
    },
    "HTTP GET /api/v1/unc/notifications/workflow_id/:workflow_id/summary": {
      "infrastructure": {},
      "services": [
        {
          "name": "novu-api",
          "target_interface": "GET /v1/notifications/graph/stats",
          "operation_type": "https",
          "conditions": [
            "Only after workflow_id URI binding succeeds"
          ],
          "operations": [
            {
              "operation": "HTTP GET notification graph stats",
              "trigger": "Fetch Novu graph statistics and filter them down to the requested workflow ID",
              "conditions": [
                "WorkFlowStruct URI binding succeeded"
              ],
              "implementation": "novuhandler.Get().GetNotificationsSummaryByWorkflowID(query.WorkflowID)"
            }
          ]
        }
      ]
    },
    "HTTP POST /api/v1/billing/tenants/:tenant_id/bulk_trigger": {
      "infrastructure": {},
      "services": [
        {
          "name": "novu-api",
          "target_interface": "GET workflow helpers + POST /v1/events/trigger/bulk",
          "operation_type": "https",
          "conditions": [
            "Only after tenant_id URI binding and trigger JSON binding both succeed",
            "Only when trigger.IsSendNow == true",
            "Only when len(trigger.TargetIDList) == 1"
          ],
          "operations": [
            {
              "operation": "HTTP POST bulk trigger",
              "trigger": "Trigger a tenant-scoped Novu event immediately for a single target",
              "conditions": [
                "BulkTriggerEventByAPI validation passed"
              ],
              "implementation": "novuhandler.Get().BulkTriggerEvent(tenantID, *trigger)"
            }
          ]
        }
      ]
    },
    "HTTP POST /api/v1/billing/ar_tables/trigger": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after year/month query binding succeeds",
            "The heavy work runs asynchronously in a goroutine after the HTTP response returns"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "invoices and related payment/billing tables",
              "trigger": "Generate the AR-table dataset for the requested month before rendering/uploading the CSV",
              "conditions": [
                "InitARTableTrigger(...) accepted the request and the background goroutine started"
              ],
              "implementation": "ARTableModel.GenerateARInitTable(date) -> ListInvoicingPayments(...) / costexplorer / billingconfig / paymentsub lookups"
            }
          ]
        },
        "s3": {
          "conditions": [
            "Only after GenerateARInitTable(...) and RenderARTable(...) both succeed in the background goroutine"
          ],
          "operations": [
            {
              "operation": "PUT",
              "bucket": "configurable (ARTablesS3Bucket)",
              "trigger": "Upload the generated AR table CSV to S3 under the generated key",
              "conditions": [
                "Background generation completed successfully"
              ],
              "implementation": "ARTableModel.PutARTableResultToS3(key, ret)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/ali_uid/:ali_uid/aliyun_subscription_record": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after ali_uid URI binding succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "aliyun_subscription_management",
              "trigger": "Load the latest active Aliyun subscription record for the given ali_uid",
              "conditions": [
                "AliUidStruct URI binding succeeded"
              ],
              "implementation": "AliyunSubscriptionMngt.GetActiveSubscriptionRecordByAliUid(aliUid) -> entity.NewAliyunSubscriptionManagementQuerySet(...).AliUidEq(...).IsSubscribedEq(true).OrderDescByCreatedAt().One(...)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/biz_id/:biz_id/aliyun_subscription_record": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after biz_id URI binding succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "aliyun_subscription_management",
              "trigger": "Load the Aliyun subscription record identified by biz_id",
              "conditions": [
                "BizIdStruct URI binding succeeded"
              ],
              "implementation": "AliyunSubscriptionMngt.GetSubscriptionRecordByBizId(bizId)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/aliyun_subscription_record": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after the request JSON binds successfully"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "aliyun_subscription_management",
              "trigger": "Check whether the biz_id already exists before choosing create vs reactivate",
              "conditions": [
                "ShouldBindJSON(subscriptionRecord) succeeded"
              ],
              "implementation": "AliyunSubscriptionMngt.CreateOrActiveSubscriptionRecord(record) -> entity.NewAliyunSubscriptionManagementQuerySet(...).BizIdEq(record.BizId).One(&entityRecord)"
            },
            {
              "operation": "INSERT/UPDATE",
              "table": "aliyun_subscription_management",
              "trigger": "Create a new Aliyun subscription row or reactivate an existing unsubscribed one",
              "conditions": [
                "No existing record found inserts a new row",
                "Existing record with IsSubscribed == false updates it back to true"
              ],
              "implementation": "entity.AliyunSubscriptionManagement.Create(db.GetDB()) or GetUpdater().SetIsSubscribed(true).Update()"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP PUT /api/v1/billing/biz_id/:biz_id/aliyun_subscription_record": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after biz_id URI binding succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "aliyun_subscription_management",
              "trigger": "Load the current Aliyun subscription row before deciding whether the unsubscribe is idempotent",
              "conditions": [
                "BizIdStruct URI binding succeeded"
              ],
              "implementation": "AliyunSubscriptionMngt.InActiveSubscriptionRecordWithBizId(bizId)"
            },
            {
              "operation": "UPDATE",
              "table": "aliyun_subscription_management",
              "trigger": "Mark the Aliyun subscription unsubscribed",
              "conditions": [
                "Current subscription.IsSubscribed == true"
              ],
              "implementation": "entity.NewAliyunSubscriptionManagementQuerySet(db.GetDB()).BizIdEq(bizId).GetUpdater().SetIsSubscribed(false).Update()"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/identifier_id/:customer_identifier/product_code/:product_code/aws_subscription_record": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after customer_identifier and product_code URI binding succeed"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "aws_subscription_management",
              "trigger": "Load the AWS subscription record for the customer/product pair",
              "conditions": [
                "AWSSubscriptionUriStruct URI binding succeeded"
              ],
              "implementation": "AWSSubscriptionMngt.GetSubscriptionRecord(productCode, customerIdentifier)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/aws_subscription_record": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after the request JSON binds successfully"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "aws_subscription_management",
              "trigger": "Check whether the customer/product record already exists before create vs reactivate/update",
              "conditions": [
                "ShouldBindJSON(subscriptionRecord) succeeded"
              ],
              "implementation": "AWSSubscriptionMngt.CreateOrActiveSubscriptionRecord(record) -> entity.NewAWSSubscriptionManagementQuerySet(...).CustomerIdentifierEq(...).ProductCodeEq(...).One(&entityRecord)"
            },
            {
              "operation": "INSERT/UPDATE",
              "table": "aws_subscription_management",
              "trigger": "Create the AWS subscription row or reactivate/update its subscribed/trial flags",
              "conditions": [
                "Missing row inserts a new record",
                "Existing row updates IsSubscribed and InTrial unless the request tries to downgrade non-trial back to free-trial"
              ],
              "implementation": "entity.AWSSubscriptionManagement.Create(db.GetDB()) or GetUpdater().SetIsSubscribed(true).SetInTrial(record.InTrial).Update()"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP PUT /api/v1/billing/identifier_id/:customer_identifier/product_code/:product_code/aws_subscription_record": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after customer_identifier and product_code URI binding succeed"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "aws_subscription_management",
              "trigger": "Load the current AWS subscription row before deciding whether unsubscribe is idempotent",
              "conditions": [
                "AWSSubscriptionUriStruct URI binding succeeded"
              ],
              "implementation": "AWSSubscriptionMngt.InActiveSubscriptionRecord(productCode, customerIdentifier)"
            },
            {
              "operation": "UPDATE",
              "table": "aws_subscription_management",
              "trigger": "Mark the AWS subscription unsubscribed",
              "conditions": [
                "Current subscription.IsSubscribed == true"
              ],
              "implementation": "entity.NewAWSSubscriptionManagementQuerySet(db.GetDB()).ProductCodeEq(productCode).CustomerIdentifierEq(customerIdentifier).GetUpdater().SetIsSubscribed(false).Update()"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/worker/run": {
      "infrastructure": {},
      "services": [
        {
          "name": "billing-workers",
          "target_interface": "worker action dispatch",
          "operation_type": "in_process_call",
          "conditions": [
            "Only after WorkerTaskAction JSON binding succeeds"
          ],
          "operations": [
            {
              "operation": "CALL",
              "trigger": "Dispatch the requested global maintenance worker in-process",
              "conditions": [
                "workerAction.Action matched a supported global action"
              ],
              "implementation": "api.WorkerRunAction() -> workers.SendSupportPlanMetering / MergeSmallCosts / RemoveUnusedCosts / RemoveUnusedRawCosts / MarkMergedCostsToRaw / ProgressTenantCreditRiskClose / POCSyncCredits / POCCleanup / POCCreditsEmailReminder / CreateInvoiceWorker / CheckAllSpendLimit / InactiveTimeoutDiscountWorker / InactiveTimeoutBindedPackagesWorker / SyncTenantPayableWorker / CreateCostQuotaInvoice / ReconciliationDailyWorker / ReconciliationMonthlyWorker / GenerateAWSDailyReportWorker"
            }
          ]
        }
      ]
    },
    "HTTP POST /api/v1/billing/worker/subtask/run": {
      "infrastructure": {},
      "services": [
        {
          "name": "billing-workers",
          "target_interface": "tenant-scoped worker action dispatch",
          "operation_type": "in_process_call",
          "conditions": [
            "Only after WorkerSubTaskAction JSON binding succeeds"
          ],
          "operations": [
            {
              "operation": "CALL",
              "trigger": "Dispatch the requested tenant-scoped maintenance worker in-process",
              "conditions": [
                "workerAction.Action matched a supported tenant-scoped action"
              ],
              "implementation": "api.RunWorkerSubTask() -> workers.SupportPlanWorkerByTenant / plan.TenantPlanModel.SyncPOCCreditsSalesforce / plan.TenantPlanModel.POCCleanup / plan.TenantPlanModel.SendPOCReminderEmail / workers.CreateInvoiceWorkerByTenant / workers.CheckSpendLimitByTenant / discount.Model.InactiveTimeoutDiscount / billing.BindedPackageModel.InactiveTimeoutBindedPackages / workers.RechargeByTenant / paymentModel.SyncPayable / workers.MergeSmallCosts / workers.RemoveUnusedCosts / workers.RemoveUnusedRawCosts / workers.MarkMergedCostsToRaw / workers.CreateCostQuotaInvoiceByTenant"
            }
          ]
        }
      ]
    },
    "HTTP POST /api/v1/billing/create_commodity": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after the Commodity payload binds successfully"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "commodities",
              "trigger": "Reject duplicate commodity_code and commodity_show_name rows before insert",
              "conditions": [
                "CreateCommodity handler invoked"
              ],
              "implementation": "managementcommodity.CommodityModel.validateCommodityInput(...)"
            },
            {
              "operation": "INSERT",
              "table": "commodities",
              "trigger": "Create the commodity row",
              "conditions": [
                "validateCommodityInput(...) returned nil"
              ],
              "implementation": "commodityEntity.Create(db.GetDB())"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP PUT /api/v1/billing/modify_commodity": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after the CommodityModify payload binds successfully"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "commodities",
              "trigger": "Load the target commodity row by modify_id",
              "conditions": [
                "commodityModifyForm.ModifyID > 0"
              ],
              "implementation": "db.GetDB().First(&commodityEntity, commodityModifyForm.ModifyID)"
            },
            {
              "operation": "UPDATE",
              "table": "commodities",
              "trigger": "Persist commodity show-name/type/owner changes",
              "conditions": [
                "The target commodity row exists"
              ],
              "implementation": "commodityEntity.Update(db.GetDB(), entity.CommodityDBSchema.CommodityShowName, entity.CommodityDBSchema.CommodityType, entity.CommodityDBSchema.Owner)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/add_commodity_dimension": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after the CommodityDimension payload binds successfully"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "commodity_dimensions",
              "trigger": "Reject duplicate dimension_code rows before insert",
              "conditions": [
                "AddCommodityDimension handler invoked"
              ],
              "implementation": "managementcommodity.CommodityDimensionsModel.validateCommodityDimensionInput(...)"
            },
            {
              "operation": "INSERT",
              "table": "commodity_dimensions",
              "trigger": "Create the commodity-dimension row",
              "conditions": [
                "validateCommodityDimensionInput(...) returned nil"
              ],
              "implementation": "dimensionEntity.Create(db.GetDB())"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP PUT /api/v1/billing/modify_commodity_dimension": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after the CommodityDimensionModify payload binds successfully"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "commodity_dimensions",
              "trigger": "Load the target commodity-dimension row by modify_id",
              "conditions": [
                "commodityDimensionModifyForm.ModifyID > 0"
              ],
              "implementation": "db.GetDB().First(&commodityDimensionEntity, commodityDimensionModifyForm.ModifyID)"
            },
            {
              "operation": "UPDATE",
              "table": "commodity_dimensions",
              "trigger": "Persist dimension_value plus dimension_show_name/dimension_code changes",
              "conditions": [
                "The target commodity-dimension row exists"
              ],
              "implementation": "db.GetDB().Model(commodityDimensionEntity).Update(\"dimension_value\", ...); commodityDimensionEntity.Update(...)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/add_commodity_edition": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after the CommodityEdition payload binds successfully"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "commodity_editions",
              "trigger": "Reject duplicate edition_code rows before insert",
              "conditions": [
                "AddCommodityEdition handler invoked"
              ],
              "implementation": "managementcommodity.CommodityEditionModel.validateCommodityEditionInput(...)"
            },
            {
              "operation": "INSERT",
              "table": "commodity_editions",
              "trigger": "Create the commodity-edition row",
              "conditions": [
                "validateCommodityEditionInput(...) returned nil"
              ],
              "implementation": "editionEntity.Create(db.GetDB())"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP PUT /api/v1/billing/modify_commodity_edition": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after the CommodityEditionModify payload binds successfully"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "commodity_editions",
              "trigger": "Load the target commodity-edition row by modify_id",
              "conditions": [
                "commodityEditionModifyForm.ModifyID > 0"
              ],
              "implementation": "db.GetDB().First(&commodityEditionEntity, commodityEditionModifyForm.ModifyID)"
            },
            {
              "operation": "UPDATE",
              "table": "commodity_editions",
              "trigger": "Persist edition_dimension_value plus edition_show_name/edition_code changes",
              "conditions": [
                "The target commodity-edition row exists"
              ],
              "implementation": "db.GetDB().Model(commodityEditionEntity).Update(\"edition_dimension_value\", ...); commodityEditionEntity.Update(...)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/add_sku_template": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after the SkuTemplate payload binds successfully"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "sku_templates",
              "trigger": "Reject duplicate edition_code rows before insert",
              "conditions": [
                "AddSkuTemplate handler invoked"
              ],
              "implementation": "managementcommodity.CommoditySkuTemplateModel.validateCommoditySkuTemplateInput(...)"
            },
            {
              "operation": "INSERT",
              "table": "sku_templates",
              "trigger": "Create the sku-template row",
              "conditions": [
                "validateCommoditySkuTemplateInput(...) returned nil"
              ],
              "implementation": "skuTemplateEntity.Create(db.GetDB())"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP PUT /api/v1/billing/modify_commodity_sku_template": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after the SkuTemplateModify payload binds successfully"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "sku_templates",
              "trigger": "Load the target sku-template row by modify_id",
              "conditions": [
                "skuTemplateModifyForm.ModifyID > 0"
              ],
              "implementation": "db.GetDB().First(&skuTemplate, skuTemplateModifyForm.ModifyID)"
            },
            {
              "operation": "UPDATE",
              "table": "sku_templates",
              "trigger": "Persist the replacement template payload",
              "conditions": [
                "len(skuTemplateModifyForm.SkuTemplate.Template) > 0"
              ],
              "implementation": "db.GetDB().Model(skuTemplate).Update(\"template\", entity.DimensionValue(...))"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/add_sku_list": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after the []SkuInfo payload binds successfully"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "units",
              "trigger": "Reject duplicate unit_key rows or duplicate keys inside the same request before insert",
              "conditions": [
                "len(skuListForm) > 0"
              ],
              "implementation": "entity.NewUnitQuerySet(db.GetDB()).UnitKeyIn(allUnitKey...).All(&checkEntity)"
            },
            {
              "operation": "INSERT",
              "table": "units",
              "trigger": "Batch-create the submitted SKU rows",
              "conditions": [
                "len(checkEntity) == 0",
                "len(allUnitKeyMap) == len(allUnitKey)"
              ],
              "implementation": "db.GetDB().Create(&allEntity)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP PUT /api/v1/billing/modify_sku_list": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after the SkuModify payload binds successfully"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "units",
              "trigger": "Load every submitted unit row before mutating it",
              "conditions": [
                "len(skuModifyForm.ModifyMap) > 0"
              ],
              "implementation": "entity.NewUnitQuerySet(db.GetDB()).UnitKeyIn(allUnitKey...).All(&allUnitEntity)"
            },
            {
              "operation": "UPDATE",
              "table": "units",
              "trigger": "Persist per-unit description/category/provider/region/price/measure-unit changes",
              "conditions": [
                "len(allUnitEntity) == len(allUnitKey)"
              ],
              "implementation": "unitEntity.Update(tx, entity.UnitDBSchema.Description, entity.UnitDBSchema.Category, entity.UnitDBSchema.Provider, entity.UnitDBSchema.Region, entity.UnitDBSchema.Price, entity.UnitDBSchema.MeasureUnit)"
            },
            {
              "operation": "INSERT",
              "table": "version_skus",
              "trigger": "Append a version snapshot row for each mutated SKU",
              "conditions": [
                "The transactional update loop reached versionSku.Create(tx)"
              ],
              "implementation": "versionSku.Create(tx)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/query_commodities": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after the CommodityQuery payload binds successfully"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "commodities",
              "trigger": "List commodities filtered by optional commodity_code, commodity_show_name, and owner fields",
              "conditions": [
                "QueryCommodities handler invoked"
              ],
              "implementation": "managementcommodity.CommodityModel.QueryCommodities(...)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/query_commodity_dimensions": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after the CommodityDimensionQuery payload binds successfully"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "commodity_dimensions",
              "trigger": "List filtered commodity-dimension rows plus shared rows",
              "conditions": [
                "QueryCommodityDimensions handler invoked"
              ],
              "implementation": "managementcommodity.CommodityDimensionsModel.QueryCommodityDimensions(...)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/query_commodity_editions": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after the CommodityEditionQuery payload binds successfully"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "commodity_editions",
              "trigger": "List commodity-edition rows filtered by optional commodity_code, edition_code, and edition_show_name fields",
              "conditions": [
                "QueryCommodityEditions handler invoked"
              ],
              "implementation": "managementcommodity.CommodityEditionModel.QueryCommodityEditions(...)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/query_commodity_sku_templates": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after the SkuTemplateQuery payload binds successfully"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "sku_templates",
              "trigger": "List sku-template rows filtered by optional commodity_code and edition_code",
              "conditions": [
                "QuerySkuTemplates handler invoked"
              ],
              "implementation": "managementcommodity.CommoditySkuTemplateModel.QueryCommoditySkuTemplate(...)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/query_sku_list": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after the SkuInfoQuery payload binds successfully"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "units",
              "trigger": "List SKU rows filtered by optional commodity_code, edition_code, unit_key, and sku_template_id",
              "conditions": [
                "QuerySkuList handler invoked"
              ],
              "implementation": "managementcommodity.CommoditySkuTemplateModel.QuerySkuList(...)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/providers/alicloud/costexplorer/monthly_bills/year/:year/month/:month/export": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after year/month URI binding succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "invoices",
              "trigger": "Load sent AliCloud invoices for the requested billing month",
              "conditions": [
                "input.Year and input.Month were parsed from the URI"
              ],
              "implementation": "invoiceModel.ListSentInvoicesByPaymentType(input.Year, input.Month, entity.PaymentType_AliCloud)"
            },
            {
              "operation": "SELECT",
              "table": "user_unit_costs and units",
              "trigger": "Build the exported usage-detail rows for the invoice-backed tenant/billing-config set",
              "conditions": [
                "ListSentInvoicesByPaymentType(...) succeeded"
              ],
              "implementation": "costexplorer.CostExplorerModel.GetExportBillsDetailsByTenant(tenantIDs, billingConfigs, input.Year, input.Month, invoiceIDs)"
            },
            {
              "operation": "SELECT",
              "table": "payment_methods",
              "trigger": "Backfill missing billing-config payment codes while composing the CSV",
              "conditions": [
                "billingConfigPaymentCodeMap does not contain usageDetail.BillingConfigID"
              ],
              "implementation": "paymentModel.GetPaymentMethodWithPaymentType(usageDetail.TenantID, usageDetail.BillingConfigID, entity.PaymentType_AliCloud)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /inner/billing/sku_groups": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Always"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "sku_groups",
              "trigger": "List all sku group rows for inner callers",
              "conditions": [
                "Inner GetSKUGroupList handler invoked"
              ],
              "implementation": "billing.SKUGroupModel.GetSKUGroupList()"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /inner/billing/units": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after optional group_id query parsing succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "units",
              "trigger": "List all units for inner callers when group_id is absent or zero",
              "conditions": [
                "uriForm.GroupID == 0"
              ],
              "implementation": "billing.UnitModel.GetAllUnits()"
            },
            {
              "operation": "SELECT",
              "table": "units",
              "trigger": "List units scoped to the requested sku group for inner callers",
              "conditions": [
                "uriForm.GroupID > 0"
              ],
              "implementation": "billing.UnitModel.ListUnitsByGroupID(uriForm.GroupID)"
            }
          ]
        }
      },
      "services": []
    }
  },
  "external_services": {
    "account-service": {
      "address": "account-provider-grpc:10000",
      "protocol": "grpc",
      "methods_used": [
        "GetOrgByID",
        "ListOrgs",
        "GetUserByID",
        "ListUsersByFilter",
        "SendEmail",
        "SendEmailByLabels",
        "GetProjectByID",
        "ListProjects",
        "DeleteOrgByID",
        "UpdateOrg",
        "ListPartnerCustomers",
        "ConfigFeatureFlagOrg",
        "ClearEmailUniqueID",
        "GetOpenAPIAccess"
      ]
    },
    "account-admin-api": {
      "address": "configurable (DBaaSCentralScheme://DBaaSCentralHost/api/v1/admin)",
      "protocol": "https",
      "auth": "Auth0 client-credential bearer token"
    },
    "infra-svc": {
      "address": "infra-svc-grpc:10000",
      "protocol": "grpc",
      "methods_used": ["ListClusters"]
    },
    "tidb-mgmt-svc": {
      "address": "tidb-mgmt-service.tidb-management-service:10001",
      "protocol": "grpc",
      "usage": "TiDB management service for cluster info"
    },
    "stripe-api": {
      "address": "https://api.stripe.com",
      "protocol": "https",
      "auth": "Bearer token"
    },
    "aws-marketplace-api": {
      "address": "https://marketplace.eu-west-1.amazonaws.com",
      "protocol": "https",
      "auth": "AWS Signature V4",
      "methods_used": ["BatchMeterUsage"]
    },
    "gcp-procurement-api": {
      "address": "https://cloudcommerceprocurement.googleapis.com",
      "protocol": "https",
      "auth": "OAuth2"
    },
    "azure-marketplace-api": {
      "address": "https://marketplaceapi.microsoft.com",
      "protocol": "https",
      "auth": "Bearer token"
    },
    "novu-api": {
      "address": "https://api.novu.co",
      "protocol": "https",
      "auth": "API key"
    },
    "aliyun-marketplace-api": {
      "address": "https://market.aliyuncs.com",
      "protocol": "https",
      "auth": "AccessKey"
    },
    "salesforce-api": {
      "address": "https://login.salesforce.com",
      "protocol": "https",
      "auth": "OAuth2",
      "conditions": ["EnableSalesforce == true"]
    },
    "novu-api": {
      "address": "configurable (NovuAPIHost)",
      "protocol": "https",
      "auth": "API Key"
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/switch/card/validate/is_allowed": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only when the route reaches credit-card validation switch evaluation after URI binding succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_information",
              "trigger": "This endpoint does not read billing tables directly, but any later card-validation flow it gates may skip address/tax validation only if billing information already exists",
              "conditions": [
                "Downstream callers proceed past this switch endpoint and later run CreditCardVerifyModel.creditCardAddressValidate(...)"
              ],
              "implementation": "CreditCardVerifyModel.IsCreditCardValidationRequired(tenantID) only returns a config decision; the eventual gated flow may later call paymentsub.BillingInformationModel.BillingInfoIsNotEmpty(tenantID)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/switch/card/validation/required": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only when the route reaches credit-card validation switch evaluation after URI binding succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_information",
              "trigger": "This alias endpoint shares the same switch implementation as /switch/card/validate/is_allowed and gates the later card-validation path",
              "conditions": [
                "Downstream callers proceed past this switch endpoint and later run CreditCardVerifyModel.creditCardAddressValidate(...)"
              ],
              "implementation": "CreditCardVerifyModel.IsCreditCardValidationRequired(tenantID) only returns a config decision; the eventual gated flow may later call paymentsub.BillingInformationModel.BillingInfoIsNotEmpty(tenantID)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/tenants/:tenant_id/measures": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only when HTTPMeasuresToQueue == false and the request body was accepted",
            "Writes are skipped when the request is queue-only or cost == 0 with MeasureDisableSuccessResponse handling"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve which billing config applies at the measure timestamp before pricing the usage",
              "conditions": [
                "c.ShouldBindJSON(costForm) succeeded",
                "HTTPMeasuresToQueue == false"
              ],
              "implementation": "MeasureModel.GetBillingConfigIDByTimeStamp(tenantID, costs, false) -> billingconfig.BillingConfigModel.GetUseBillingConfigIDByTimeStampWithCache(...)"
            },
            {
              "operation": "SELECT",
              "table": "units",
              "trigger": "Load the priced unit definition before validating and pricing the raw usage",
              "conditions": [
                "MeasureModel.CostUnits(...) continued into buildRawUnitCost(...)"
              ],
              "implementation": "MeasureModel.buildRawUnitCost(...) -> UnitModel.GetUnit(costs.Unit)"
            },
            {
              "operation": "SELECT",
              "table": "binded_packages",
              "trigger": "Resolve effective tenant packages before computing credits-vs-invoice consumption",
              "conditions": [
                "MeasureModel.ListBindedPackages(...) reached tenant package lookup"
              ],
              "implementation": "BindedPackageModel.GetAllTenantBindedPackage(tenantID)"
            },
            {
              "operation": "SELECT",
              "table": "discounts",
              "trigger": "Resolve the effective discount chain before finalizing the priced raw usage",
              "conditions": [
                "MeasureModel.GetUseDiscount(...) reached discount resolution"
              ],
              "implementation": "discount.Model.ListEffectiveDiscounts(costEntity.TenantID, costEntity.BindedBillingConfigID)"
            },
            {
              "operation": "INSERT/UPDATE",
              "table": "raw_user_unit_costs",
              "trigger": "Persist the raw cost row before merge/copy processing",
              "conditions": [
                "dryrun == false",
                "MeasureModel.procRawUnitCost(...) reached initRawUnitCost(...) or status update branches"
              ],
              "implementation": "MeasureModel.initRawUnitCost(...) / MeasureModel.costUserRawUnitCost(...) / entity.NewRawUserUnitCostQuerySet(...).GetUpdater()"
            },
            {
              "operation": "INSERT/UPDATE",
              "table": "user_unit_costs",
              "trigger": "Create or merge the final billable usage row after raw-cost processing succeeds",
              "conditions": [
                "dryrun == false",
                "costEntity.Status == done",
                "costEntity.Cost != 0"
              ],
              "implementation": "MeasureModel.copyRawUnitCost(...) or MeasureModel.mergeRawUnitCost(...)"
            }
          ]
        },
        "sqs": {
          "conditions": [
            "Only when HTTPMeasuresToQueue == true",
            "Only when costForm.Cost > 0"
          ],
          "operations": [
            {
              "operation": "SEND",
              "queue": "configurable (MeasureSender queue target)",
              "trigger": "Enqueue the measure instead of pricing it inline",
              "conditions": [
                "config.Get().GetBool(config.HTTPMeasuresToQueue) == true",
                "costForm.Cost > 0"
              ],
              "implementation": "sqsmeasurehandler.GetMeasureSender().SendMeasure(tenantID, costForm)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/tenants/:tenant_id/measures/dryrun": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after the request body was accepted",
            "Dryrun resolves pricing state but does not persist usage rows"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_configs",
              "trigger": "Resolve the billing config that would apply to the submitted measure timestamp",
              "conditions": [
                "c.ShouldBindJSON(costForm) succeeded"
              ],
              "implementation": "MeasureModel.GetBillingConfigIDByTimeStamp(tenantID, costs, true)"
            },
            {
              "operation": "SELECT",
              "table": "units",
              "trigger": "Load the unit metadata needed for dryrun pricing",
              "conditions": [
                "MeasureModel.CostUnitsDryrun(...) continued into buildRawUnitCost(...)"
              ],
              "implementation": "MeasureModel.buildRawUnitCost(...) -> UnitModel.GetUnit(costs.Unit)"
            },
            {
              "operation": "SELECT",
              "table": "binded_packages",
              "trigger": "Resolve package matches that would be used if the measure were billed for real",
              "conditions": [
                "MeasureModel.ListBindedPackages(...) reached tenant package lookup"
              ],
              "implementation": "BindedPackageModel.GetAllTenantBindedPackage(tenantID)"
            },
            {
              "operation": "SELECT",
              "table": "discounts",
              "trigger": "Resolve the discount that would be applied during dryrun pricing",
              "conditions": [
                "MeasureModel.GetUseDiscount(...) reached discount lookup"
              ],
              "implementation": "discount.Model.ListEffectiveDiscounts(costEntity.TenantID, costEntity.BindedBillingConfigID)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/subscriptions": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant_id URI binding succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "subscriptions",
              "trigger": "List all subscription rows for the tenant ordered by creation time descending",
              "conditions": [
                "getTenantIDFromURI(c) succeeded"
              ],
              "implementation": "SubscriptionModel.ListSubscriptions(tenantID)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/submited_subscriptions": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant_id URI binding succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "subscriptions",
              "trigger": "List only submitted/non-draft subscription rows for the tenant",
              "conditions": [
                "getTenantIDFromURI(c) succeeded"
              ],
              "implementation": "SubscriptionModel.ListSubmitedSubscriptions(tenantID) -> entity.NewSubscriptionQuerySet(...).StatusNotIn(entity.SubscriptionStatus_DRAFT)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/tenants/:tenant_id/subscriptions/:subscription_id": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after subscription_id URI binding succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "subscriptions",
              "trigger": "Load the requested subscription row by primary key",
              "conditions": [
                "c.ShouldBindUri(subscriptionURIStruct) succeeded"
              ],
              "implementation": "SubscriptionModel.GetSubscription(subscriptionURIStruct.SubscriptionID)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/tenants/:tenant_id/subscriptions": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant_id URI binding and JSON body binding both succeed"
          ],
          "operations": [
            {
              "operation": "INSERT",
              "table": "subscriptions",
              "trigger": "Create a new draft subscription row for the tenant",
              "conditions": [
                "c.ShouldBindJSON(subscription) succeeded"
              ],
              "implementation": "SubscriptionModel.CreateSubscription(tenantID, subscription)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP PUT /api/v1/billing/tenants/:tenant_id/subscriptions/:subscription_id": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after URI and JSON binding both succeed"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "subscriptions",
              "trigger": "Load the current subscription row to reject updates on accepted subscriptions",
              "conditions": [
                "c.ShouldBindUri(subscriptionURIStruct) succeeded"
              ],
              "implementation": "SubscriptionModel.UpdateSubscription(...) -> SubscriptionModel.GetSubscription(subscriptionID)"
            },
            {
              "operation": "UPDATE",
              "table": "subscriptions",
              "trigger": "Reset the subscription to draft and replace file/email fields",
              "conditions": [
                "Current subscription.Status != accepted"
              ],
              "implementation": "entity.NewSubscriptionQuerySet(db.GetDB()).IDEq(subscriptionID).GetUpdater().SetContractEmail(...).SetStatus(draft).SetFilePath(...).Update()"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/tenants/:tenant_id/subscriptions/:subscription_id/actions/reject": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after URI and JSON binding both succeed"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "subscriptions",
              "trigger": "Load the current subscription state before enforcing the pending-only reject rule",
              "conditions": [
                "c.ShouldBindUri(subscriptionURIStruct) succeeded"
              ],
              "implementation": "SubscriptionModel.RejectSubscription(...) -> SubscriptionModel.GetSubscription(subscriptionID)"
            },
            {
              "operation": "UPDATE",
              "table": "subscriptions",
              "trigger": "Mark the subscription rejected and persist rejection actor/time",
              "conditions": [
                "Current subscription.Status == pending"
              ],
              "implementation": "entity.NewSubscriptionQuerySet(db.GetDB()).IDEq(subscriptionID).GetUpdater().SetStatus(rejected).SetRejectedDate(...).SetRejectedUser(...).Update()"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/tenants/:tenant_id/subscriptions/:subscription_id/actions/accept": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after URI and JSON binding both succeed"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "subscriptions",
              "trigger": "Load the current subscription state before enforcing the pending-only accept rule",
              "conditions": [
                "c.ShouldBindUri(subscriptionURIStruct) succeeded"
              ],
              "implementation": "SubscriptionModel.AcceptSubscription(...) -> SubscriptionModel.GetSubscription(subscriptionID)"
            },
            {
              "operation": "UPDATE",
              "table": "subscriptions",
              "trigger": "Mark the subscription accepted and persist accepted actor/time",
              "conditions": [
                "Current subscription.Status == pending"
              ],
              "implementation": "entity.NewSubscriptionQuerySet(db.GetDB()).IDEq(subscriptionID).GetUpdater().SetStatus(accepted).SetAcceptedDate(...).SetAcceptedUser(...).Update()"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/tenants/:tenant_id/subscriptions/:subscription_id/actions/suspend": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after subscription_id URI binding succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "subscriptions",
              "trigger": "Load the current subscription state before enforcing the accepted-only suspend rule",
              "conditions": [
                "c.ShouldBindUri(subscriptionURIStruct) succeeded"
              ],
              "implementation": "SubscriptionModel.SuspendSubscription(...) -> SubscriptionModel.GetSubscription(subscriptionID)"
            },
            {
              "operation": "UPDATE",
              "table": "subscriptions",
              "trigger": "Mark the subscription suspended",
              "conditions": [
                "Current subscription.Status == accepted"
              ],
              "implementation": "entity.NewSubscriptionQuerySet(db.GetDB()).IDEq(subscriptionID).GetUpdater().SetStatus(suspended).Update()"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/tenants/:tenant_id/subscriptions/:subscription_id/actions/submit": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after subscription_id URI binding succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "subscriptions",
              "trigger": "Load the current subscription state before enforcing the draft-only submit rule",
              "conditions": [
                "c.ShouldBindUri(subscriptionURIStruct) succeeded"
              ],
              "implementation": "SubscriptionModel.SubmitSubscription(...) -> SubscriptionModel.GetSubscription(subscriptionID)"
            },
            {
              "operation": "UPDATE",
              "table": "subscriptions",
              "trigger": "Move the subscription from draft to pending",
              "conditions": [
                "Current subscription.Status == draft"
              ],
              "implementation": "entity.NewSubscriptionQuerySet(db.GetDB()).IDEq(subscriptionID).GetUpdater().SetStatus(pending).Update()"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/tenants/:tenant_id/tax_rates": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after tenant_id URI binding succeeds",
            "Write path only runs when the newly calculated tax rate differs from the existing stored one"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_information",
              "trigger": "Load tenant billing profile before calculating a fresh tax rate",
              "conditions": [
                "EnableTaxCalculation == true"
              ],
              "implementation": "paymentsub.TaxModel.RetrieveAndUpdateTenantTaxRate(tenantID) -> BillingInformationModel.GetBillingInfo(tenantID)"
            },
            {
              "operation": "SELECT",
              "table": "tenant_billing_companies",
              "trigger": "Resolve which billing company and payment sub-code should drive tax calculation",
              "conditions": [
                "EnableTaxCalculation == true"
              ],
              "implementation": "BillingInformationModel.GetTenantBillingCompany(tenantID)"
            },
            {
              "operation": "SELECT",
              "table": "billing_companies",
              "trigger": "Load the billing company record that decides designated-address tax calculation vs tenant billing-profile tax calculation",
              "conditions": [
                "BillingInformationModel.GetTenantBillingCompany(...) succeeded"
              ],
              "implementation": "BillingInformationModel.GetBillingCompany(tenantCompany.CompanyKey)"
            },
            {
              "operation": "UPDATE",
              "table": "billing_information",
              "trigger": "Persist the new Stripe tax rate ID after creating a changed tax rate",
              "conditions": [
                "EnableTaxCalculation == true",
                "TaxModel.MatchTaxRate(billingInfo.TaxRate, rate) == false"
              ],
              "implementation": "BillingInformationModel.UpdateTaxRate(tenantID, rate.StripeTaxRateID)"
            }
          ]
        }
      },
      "services": [
        {
          "name": "stripe-api",
          "target_interface": "POST /v1/tax/calculations, POST /v1/tax_rates, POST /v1/tax_rates/:id/deactivate",
          "operation_type": "https",
          "conditions": [
            "Only when EnableTaxCalculation == true"
          ],
          "operations": [
            {
              "operation": "HTTP CalculateTax",
              "trigger": "Calculate the tenant/company tax rate candidate from Stripe",
              "conditions": [
                "Billing information and billing company lookups succeeded"
              ],
              "implementation": "stripe provider CalculateTax(...) inside TaxModel.RetrieveAndUpdateTenantTaxRate(...)"
            },
            {
              "operation": "HTTP CreateTaxRate",
              "trigger": "Create the new Stripe tax rate when the calculated rate changed",
              "conditions": [
                "TaxModel.MatchTaxRate(old, new) == false"
              ],
              "implementation": "handler.CreateTaxRate(rate)"
            },
            {
              "operation": "HTTP InactiveTaxRate",
              "trigger": "Deactivate the old Stripe tax rate after replacing it",
              "conditions": [
                "billingInfo.TaxRate != nil",
                "TaxModel.MatchTaxRate(old, new) == false"
              ],
              "implementation": "TaxModel.InactiveTaxRate(billingInfo.TaxRate.StripeTaxRateID)"
            }
          ]
        }
      ]
    },
    "HTTP POST /api/v1/billing/migrate_tasks/:name": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after the task name was accepted and the async goroutine starts running",
            "Actual tables depend on query.Name"
          ],
          "operations": [
            {
              "operation": "INSERT/UPDATE",
              "table": "multiple billing tables (task-dependent)",
              "trigger": "Run the selected migration task asynchronously after returning OK to the caller",
              "conditions": [
                "query.Name matched one of the supported migrate tasks"
              ],
              "implementation": "go f() where f is one of MigrateModel.UpdateStripeEmail / ReCalculateMeasures / CreateReCalculateInvoices / MigrateSpendLimitRechargePlanID / CreateAllTenantIDBillingConfig / CreateAllTenantIDNovuSubscriber / SyncAllSupportPlanInfoToEventBus / SyncOnDemandOrgsToJSM"
            }
          ]
        }
      },
      "services": [
        {
          "name": "novu-api",
          "target_interface": "subscriber sync APIs",
          "operation_type": "https",
          "conditions": [
            "Only when query.Name == create_novu_subscribers"
          ],
          "operations": [
            {
              "operation": "HTTP CreateSubscribers",
              "trigger": "Backfill Novu subscribers for all tenants in the async migration task",
              "conditions": [
                "query.Name == create_novu_subscribers"
              ],
              "implementation": "MigrateModel.CreateAllTenantIDNovuSubscriber()"
            }
          ]
        },
        {
          "name": "eventbus",
          "target_interface": "support-plan sync event publishing",
          "operation_type": "event",
          "conditions": [
            "Only when query.Name == sync_binded_support_plans_to_eventbus"
          ],
          "operations": [
            {
              "operation": "Publish support-plan sync events",
              "trigger": "Backfill support-plan information into the event bus asynchronously",
              "conditions": [
                "query.Name == sync_binded_support_plans_to_eventbus"
              ],
              "implementation": "MigrateModel.SyncAllSupportPlanInfoToEventBus()"
            }
          ]
        }
      ]
    },
    "HTTP GET /api/v1/billing/sentry/validate": {
      "infrastructure": {},
      "services": []
    },
    "HTTP GET /api/v1/billing/auditlog": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after query binding and date-range validation both succeed"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "audit_records",
              "trigger": "List audit records filtered by time range plus optional tenant/operator/action filters",
              "conditions": [
                "query.PageSize <= 100",
                "query.EndDate is not before query.StartDate"
              ],
              "implementation": "AuditLogModel.GetAuditLog(query)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/billing_company": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Always after the handler is reached"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "billing_companies",
              "trigger": "List all configured billing companies",
              "conditions": [
                "ListBillingCompany handler invoked"
              ],
              "implementation": "paymentsub.BillingInformationModel.ListBillingCompany()"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP PUT /api/v1/billing/events": {
      "infrastructure": {},
      "services": [
        {
          "name": "eventbus",
          "target_interface": "Publish(eventType, eventData)",
          "operation_type": "event",
          "conditions": [
            "Only when EnableEventbus == true"
          ],
          "operations": [
            {
              "operation": "PublishEvent",
              "trigger": "Publish the decoded event payload onto the shared Ti eventbus",
              "conditions": [
                "json.NewDecoder(c.Request.Body).Decode(event) succeeded"
              ],
              "implementation": "eventbushandler.Get().PublishEvent(event.EventType, event)"
            }
          ]
        }
      ]
    },
    "HTTP POST /api/v1/billing/worker/run": {
      "infrastructure": {},
      "services": [
        {
          "name": "billing-workers",
          "target_interface": "worker action dispatch",
          "operation_type": "in_process_call",
          "conditions": [
            "Only after WorkerTaskAction JSON binding succeeds"
          ],
          "operations": [
            {
              "operation": "CALL",
              "trigger": "Run the global support-plan status and metering batch immediately",
              "conditions": [
                "workerAction.Action == \"support_plan_metering\""
              ],
              "implementation": "workers.SendSupportPlanMetering()"
            },
            {
              "operation": "CALL",
              "trigger": "Run the credits package close/open maintenance trio in-process",
              "conditions": [
                "workerAction.Action == \"credits\""
              ],
              "implementation": "workers.CloseExhaustedCreditsPackage(); workers.CloseExpiredCreditsPackage(); workers.OpenNeedOpenCreditsPackage()"
            },
            {
              "operation": "CALL",
              "trigger": "Execute the global merged-cost compaction pass",
              "conditions": [
                "workerAction.Action == \"merge_small_costs\""
              ],
              "implementation": "workers.MergeSmallCosts()"
            },
            {
              "operation": "CALL",
              "trigger": "Execute the global unused-cost cleanup pass",
              "conditions": [
                "workerAction.Action == \"remove_unused_costs\""
              ],
              "implementation": "workers.RemoveUnusedCosts()"
            },
            {
              "operation": "CALL",
              "trigger": "Execute the global unused-raw-cost cleanup pass",
              "conditions": [
                "workerAction.Action == \"remove_unused_raw_costs\""
              ],
              "implementation": "workers.RemoveUnusedRawCosts()"
            },
            {
              "operation": "CALL",
              "trigger": "Flip merged costs back to raw rows for the configured window",
              "conditions": [
                "workerAction.Action == \"mark_merged_costs_to_raw\""
              ],
              "implementation": "workers.MarkMergedCostsToRaw()"
            },
            {
              "operation": "CALL",
              "trigger": "Progress all tenant credit-risk close records",
              "conditions": [
                "workerAction.Action == \"credit_tenant_close\""
              ],
              "implementation": "workers.ProgressTenantCreditRiskClose()"
            },
            {
              "operation": "CALL",
              "trigger": "Run the global POC credits sync batch",
              "conditions": [
                "workerAction.Action == \"poc_sync_credits\""
              ],
              "implementation": "workers.POCSyncCredits()"
            },
            {
              "operation": "CALL",
              "trigger": "Run the global POC cleanup batch",
              "conditions": [
                "workerAction.Action == \"poc_cleanup\""
              ],
              "implementation": "workers.POCCleanup()"
            },
            {
              "operation": "CALL",
              "trigger": "Run the global POC reminder-email batch",
              "conditions": [
                "workerAction.Action == \"poc_credits_email_reminder\""
              ],
              "implementation": "workers.POCCreditsEmailReminder()"
            },
            {
              "operation": "CALL",
              "trigger": "Create invoices for all eligible tenants immediately",
              "conditions": [
                "workerAction.Action == \"invoice_worker\""
              ],
              "implementation": "workers.CreateInvoiceWorker()"
            },
            {
              "operation": "CALL",
              "trigger": "Run the global spend-limit enforcement sweep",
              "conditions": [
                "workerAction.Action == \"spend_limit\""
              ],
              "implementation": "workers.CheckAllSpendLimit()"
            },
            {
              "operation": "CALL",
              "trigger": "Expire inactive discounts globally",
              "conditions": [
                "workerAction.Action == \"inactive_timeout_discount\""
              ],
              "implementation": "workers.InactiveTimeoutDiscountWorker()"
            },
            {
              "operation": "CALL",
              "trigger": "Expire inactive binded packages globally",
              "conditions": [
                "workerAction.Action == \"inactive_timeout_binded_packages\""
              ],
              "implementation": "workers.InactiveTimeoutBindedPackagesWorker()"
            },
            {
              "operation": "CALL",
              "trigger": "Refresh payable status for all tenants",
              "conditions": [
                "workerAction.Action == \"sync_payable\""
              ],
              "implementation": "workers.SyncTenantPayableWorker()"
            },
            {
              "operation": "CALL",
              "trigger": "Generate cost-quota invoices globally",
              "conditions": [
                "workerAction.Action == \"cost_quota_invoice\""
              ],
              "implementation": "workers.CreateCostQuotaInvoice()"
            },
            {
              "operation": "CALL",
              "trigger": "Run the daily reconciliation batch",
              "conditions": [
                "workerAction.Action == \"reconciliation_daily\""
              ],
              "implementation": "workers.ReconciliationDailyWorker()"
            },
            {
              "operation": "CALL",
              "trigger": "Run the monthly reconciliation batch",
              "conditions": [
                "workerAction.Action == \"reconciliation_monthly\""
              ],
              "implementation": "workers.ReconciliationMonthlyWorker()"
            },
            {
              "operation": "CALL",
              "trigger": "Generate the AWS daily reconciliation report",
              "conditions": [
                "workerAction.Action == \"generate_aws_reconciliation_report\""
              ],
              "implementation": "workers.GenerateAWSDailyReportWorker()"
            }
          ]
        }
      ]
    },
    "HTTP POST /api/v1/billing/worker/subtask/run": {
      "infrastructure": {},
      "services": [
        {
          "name": "billing-workers",
          "target_interface": "tenant-scoped worker action dispatch",
          "operation_type": "in_process_call",
          "conditions": [
            "Only after WorkerSubTaskAction JSON binding succeeds"
          ],
          "operations": [
            {
              "operation": "CALL",
              "trigger": "Run the tenant-scoped support-plan sync + metering path immediately",
              "conditions": [
                "workerAction.Action == \"support_plan_metering\""
              ],
              "implementation": "workers.SupportPlanWorkerByTenant(workerAction.TenantID)"
            },
            {
              "operation": "CALL",
              "trigger": "Sync POC credits from Salesforce for the target tenant",
              "conditions": [
                "workerAction.Action == \"poc_sync_credits\""
              ],
              "implementation": "plan.TenantPlanModel.SyncPOCCreditsSalesforce(workerAction.TenantID)"
            },
            {
              "operation": "CALL",
              "trigger": "Run POC cleanup for the target tenant",
              "conditions": [
                "workerAction.Action == \"poc_cleanup\""
              ],
              "implementation": "plan.TenantPlanModel.POCCleanup(workerAction.TenantID)"
            },
            {
              "operation": "CALL",
              "trigger": "Send POC reminder email for the target tenant",
              "conditions": [
                "workerAction.Action == \"poc_credits_email_reminder\""
              ],
              "implementation": "plan.TenantPlanModel.SendPOCReminderEmail(workerAction.TenantID)"
            },
            {
              "operation": "CALL",
              "trigger": "Create invoices for the target tenant immediately",
              "conditions": [
                "workerAction.Action == \"invoice_worker\""
              ],
              "implementation": "workers.CreateInvoiceWorkerByTenant(workerAction.TenantID)"
            },
            {
              "operation": "CALL",
              "trigger": "Check spend limit for the target tenant",
              "conditions": [
                "workerAction.Action == \"spend_limit\""
              ],
              "implementation": "workers.CheckSpendLimitByTenant(workerAction.TenantID)"
            },
            {
              "operation": "CALL",
              "trigger": "Expire inactive discounts for the target tenant",
              "conditions": [
                "workerAction.Action == \"inactive_timeout_discount\""
              ],
              "implementation": "discount.Model.InactiveTimeoutDiscount(workerAction.TenantID)"
            },
            {
              "operation": "CALL",
              "trigger": "Expire inactive binded packages for the target tenant",
              "conditions": [
                "workerAction.Action == \"inactive_timeout_binded_packages\""
              ],
              "implementation": "billing.BindedPackageModel.InactiveTimeoutBindedPackages(workerAction.TenantID)"
            },
            {
              "operation": "CALL",
              "trigger": "Trigger tenant recharge flow immediately",
              "conditions": [
                "workerAction.Action == \"recharge\""
              ],
              "implementation": "workers.RechargeByTenant(workerAction.TenantID)"
            },
            {
              "operation": "CALL",
              "trigger": "Refresh payable status for the target tenant",
              "conditions": [
                "workerAction.Action == \"sync_payable\""
              ],
              "implementation": "paymentModel.SyncPayable(workerAction.TenantID)"
            },
            {
              "operation": "CALL",
              "trigger": "Merge small costs for the target tenant",
              "conditions": [
                "workerAction.Action == \"merge_small_costs\""
              ],
              "implementation": "workers.MergeSmallCosts(workerAction.TenantID)"
            },
            {
              "operation": "CALL",
              "trigger": "Remove unused costs for the target tenant",
              "conditions": [
                "workerAction.Action == \"remove_unused_costs\""
              ],
              "implementation": "workers.RemoveUnusedCosts(workerAction.TenantID)"
            },
            {
              "operation": "CALL",
              "trigger": "Remove unused raw costs for the target tenant",
              "conditions": [
                "workerAction.Action == \"remove_unused_raw_costs\""
              ],
              "implementation": "workers.RemoveUnusedRawCosts(workerAction.TenantID)"
            },
            {
              "operation": "CALL",
              "trigger": "Mark merged costs back to raw for the target tenant",
              "conditions": [
                "workerAction.Action == \"mark_merged_costs_to_raw\""
              ],
              "implementation": "workers.MarkMergedCostsToRaw(workerAction.TenantID)"
            },
            {
              "operation": "CALL",
              "trigger": "Generate cost-quota invoices for the target tenant",
              "conditions": [
                "workerAction.Action == \"cost_quota_invoice\""
              ],
              "implementation": "workers.CreateCostQuotaInvoiceByTenant(workerAction.TenantID)"
            }
          ]
        }
      ]
    },
    "HTTP POST /api/v1/billing/create_commodity": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after the Commodity payload binds successfully"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "commodities",
              "trigger": "Reject duplicate commodity_code rows before insert",
              "conditions": [
                "commodityForm.CommodityCode is non-empty"
              ],
              "implementation": "entity.NewCommodityQuerySet(db.GetDB()).CommodityCodeEq(commodityForm.CommodityCode).All(&checkEntity)"
            },
            {
              "operation": "SELECT",
              "table": "commodities",
              "trigger": "Reject duplicate commodity_show_name rows before insert",
              "conditions": [
                "No duplicate CommodityCode row was found"
              ],
              "implementation": "entity.NewCommodityQuerySet(db.GetDB()).CommodityShowNameEq(commodityForm.CommodityShowName).All(&checkEntity)"
            },
            {
              "operation": "INSERT",
              "table": "commodities",
              "trigger": "Create the commodity row",
              "conditions": [
                "validateCommodityInput(...) returned nil"
              ],
              "implementation": "commodityEntity.Create(db.GetDB())"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP PUT /api/v1/billing/modify_commodity": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after the CommodityModify payload binds successfully"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "commodities",
              "trigger": "Load the commodity row identified by modify_id before mutating it",
              "conditions": [
                "commodityModifyForm.ModifyID > 0"
              ],
              "implementation": "db.GetDB().First(&commodityEntity, commodityModifyForm.ModifyID)"
            },
            {
              "operation": "UPDATE",
              "table": "commodities",
              "trigger": "Persist commodity show-name/type/owner changes",
              "conditions": [
                "The target commodity row exists"
              ],
              "implementation": "commodityEntity.Update(db.GetDB(), entity.CommodityDBSchema.CommodityShowName, entity.CommodityDBSchema.CommodityType, entity.CommodityDBSchema.Owner)"
            },
            {
              "operation": "SELECT",
              "table": "commodities",
              "trigger": "Reload the updated commodity row for the response payload",
              "conditions": [
                "Update succeeded"
              ],
              "implementation": "db.GetDB().First(&commodityEntity, commodityModifyForm.ModifyID)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/add_commodity_dimension": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after the CommodityDimension payload binds successfully"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "commodity_dimensions",
              "trigger": "Reject duplicate dimension_code rows before insert",
              "conditions": [
                "dimensionForm.DimensionCode is non-empty"
              ],
              "implementation": "entity.NewCommodityDimensionQuerySet(db.GetDB()).DimensionCodeEq(dimensionForm.DimensionCode).All(&checkEntity)"
            },
            {
              "operation": "INSERT",
              "table": "commodity_dimensions",
              "trigger": "Create the commodity-dimension row",
              "conditions": [
                "validateCommodityDimensionInput(...) returned nil"
              ],
              "implementation": "dimensionEntity.Create(db.GetDB())"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP PUT /api/v1/billing/modify_commodity_dimension": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after the CommodityDimensionModify payload binds successfully"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "commodity_dimensions",
              "trigger": "Load the commodity-dimension row identified by modify_id before mutating it",
              "conditions": [
                "form.ModifyID > 0"
              ],
              "implementation": "db.GetDB().First(&commodityDimensionEntity, commodityDimensionModifyForm.ModifyID)"
            },
            {
              "operation": "UPDATE",
              "table": "commodity_dimensions",
              "trigger": "Persist dimension_value when the payload provides a replacement list",
              "conditions": [
                "len(commodityDimensionModifyForm.CommodityDimension.DimensionValue) > 0"
              ],
              "implementation": "db.GetDB().Model(commodityDimensionEntity).Update(\"dimension_value\", entity.DimensionValue(...))"
            },
            {
              "operation": "UPDATE",
              "table": "commodity_dimensions",
              "trigger": "Persist dimension_show_name and dimension_code changes",
              "conditions": [
                "The target commodity-dimension row exists"
              ],
              "implementation": "commodityDimensionEntity.Update(db.GetDB(), entity.CommodityDimensionDBSchema.DimensionShowName, entity.CommodityDimensionDBSchema.DimensionCode)"
            },
            {
              "operation": "SELECT",
              "table": "commodity_dimensions",
              "trigger": "Reload the updated commodity-dimension row for the response payload",
              "conditions": [
                "Update succeeded"
              ],
              "implementation": "db.GetDB().First(&commodityDimensionEntity, commodityDimensionModifyForm.ModifyID)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/add_commodity_edition": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after the CommodityEdition payload binds successfully"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "commodity_editions",
              "trigger": "Reject duplicate edition_code rows before insert",
              "conditions": [
                "editionForm.EditionCode is non-empty"
              ],
              "implementation": "entity.NewCommodityEditionQuerySet(db.GetDB()).EditionCodeEq(editionForm.EditionCode).All(&checkEntity)"
            },
            {
              "operation": "INSERT",
              "table": "commodity_editions",
              "trigger": "Create the commodity-edition row",
              "conditions": [
                "validateCommodityEditionInput(...) returned nil"
              ],
              "implementation": "editionEntity.Create(db.GetDB())"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP PUT /api/v1/billing/modify_commodity_edition": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after the CommodityEditionModify payload binds successfully"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "commodity_editions",
              "trigger": "Load the commodity-edition row identified by modify_id before mutating it",
              "conditions": [
                "form.ModifyID > 0"
              ],
              "implementation": "db.GetDB().First(&commodityEditionEntity, commodityEditionModifyForm.ModifyID)"
            },
            {
              "operation": "UPDATE",
              "table": "commodity_editions",
              "trigger": "Persist edition_dimension_value when the payload provides a replacement map",
              "conditions": [
                "len(commodityEditionModifyForm.CommodityEdition.EditionDimensionValue) > 0"
              ],
              "implementation": "db.GetDB().Model(commodityEditionEntity).Update(\"edition_dimension_value\", entity.EditionDimensionValue(...))"
            },
            {
              "operation": "UPDATE",
              "table": "commodity_editions",
              "trigger": "Persist edition_show_name and edition_code changes",
              "conditions": [
                "The target commodity-edition row exists"
              ],
              "implementation": "commodityEditionEntity.Update(db.GetDB(), entity.CommodityEditionDBSchema.EditionShowName, entity.CommodityEditionDBSchema.EditionCode)"
            },
            {
              "operation": "SELECT",
              "table": "commodity_editions",
              "trigger": "Reload the updated commodity-edition row for the response payload",
              "conditions": [
                "Update succeeded"
              ],
              "implementation": "db.GetDB().First(&commodityEditionEntity, commodityEditionModifyForm.ModifyID)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/add_sku_template": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after the SkuTemplate payload binds successfully"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "sku_templates",
              "trigger": "Reject duplicate edition_code rows before insert",
              "conditions": [
                "skuTemplateForm.EditionCode is non-empty"
              ],
              "implementation": "entity.NewSkuTemplateQuerySet(db.GetDB()).EditionCodeEq(skuTemplateForm.EditionCode).All(&checkEntity)"
            },
            {
              "operation": "INSERT",
              "table": "sku_templates",
              "trigger": "Create the sku-template row",
              "conditions": [
                "validateCommoditySkuTemplateInput(...) returned nil"
              ],
              "implementation": "skuTemplateEntity.Create(db.GetDB())"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP PUT /api/v1/billing/modify_commodity_sku_template": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after the SkuTemplateModify payload binds successfully"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "sku_templates",
              "trigger": "Load the sku-template row identified by modify_id before mutating it",
              "conditions": [
                "form.ModifyID > 0"
              ],
              "implementation": "db.GetDB().First(&skuTemplate, skuTemplateModifyForm.ModifyID)"
            },
            {
              "operation": "UPDATE",
              "table": "sku_templates",
              "trigger": "Persist the replacement template payload",
              "conditions": [
                "len(skuTemplateModifyForm.SkuTemplate.Template) > 0"
              ],
              "implementation": "db.GetDB().Model(skuTemplate).Update(\"template\", entity.DimensionValue(...))"
            },
            {
              "operation": "SELECT",
              "table": "sku_templates",
              "trigger": "Reload the updated sku-template row for the response payload",
              "conditions": [
                "The target sku-template row exists"
              ],
              "implementation": "db.GetDB().First(&skuTemplate, skuTemplateModifyForm.ModifyID)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/add_sku_list": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after the []SkuInfo payload binds successfully"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "units",
              "trigger": "Reject duplicate unit_key rows or duplicate keys inside the same request before insert",
              "conditions": [
                "len(skuListForm) > 0"
              ],
              "implementation": "entity.NewUnitQuerySet(db.GetDB()).UnitKeyIn(allUnitKey...).All(&checkEntity)"
            },
            {
              "operation": "INSERT",
              "table": "units",
              "trigger": "Batch-create the submitted SKU rows",
              "conditions": [
                "len(checkEntity) == 0",
                "len(allUnitKeyMap) == len(allUnitKey)"
              ],
              "implementation": "db.GetDB().Create(&allEntity)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP PUT /api/v1/billing/modify_sku_list": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after the SkuModify payload binds successfully"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "units",
              "trigger": "Load every submitted unit row before mutating it",
              "conditions": [
                "len(skuModifyForm.ModifyMap) > 0"
              ],
              "implementation": "entity.NewUnitQuerySet(db.GetDB()).UnitKeyIn(allUnitKey...).All(&allUnitEntity)"
            },
            {
              "operation": "UPDATE",
              "table": "units",
              "trigger": "Persist per-unit description/category/provider/region/price/measure-unit changes inside one transaction",
              "conditions": [
                "len(allUnitEntity) == len(allUnitKey)"
              ],
              "implementation": "unitEntity.Update(tx, entity.UnitDBSchema.Description, entity.UnitDBSchema.Category, entity.UnitDBSchema.Provider, entity.UnitDBSchema.Region, entity.UnitDBSchema.Price, entity.UnitDBSchema.MeasureUnit)"
            },
            {
              "operation": "INSERT",
              "table": "version_skus",
              "trigger": "Append a version snapshot row for each mutated SKU",
              "conditions": [
                "The transactional unit update loop reached versionSku.Create(tx)"
              ],
              "implementation": "versionSku.Create(tx)"
            },
            {
              "operation": "SELECT",
              "table": "units",
              "trigger": "Reload the mutated SKU rows for the response payload",
              "conditions": [
                "Transaction succeeded"
              ],
              "implementation": "entity.NewUnitQuerySet(db.GetDB()).UnitKeyIn(allUnitKey...).All(&allUnitEntity)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/query_commodities": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after the CommodityQuery payload binds successfully"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "commodities",
              "trigger": "List commodities filtered by optional commodity_code, commodity_show_name, and owner fields",
              "conditions": [
                "QueryCommodities handler invoked"
              ],
              "implementation": "entity.NewCommodityQuerySet(db.GetDB()).CommodityCodeEq(...).CommodityShowNameEq(...).OwnerEq(...).All(&allEntity)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/query_commodity_dimensions": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after the CommodityDimensionQuery payload binds successfully"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "commodity_dimensions",
              "trigger": "List commodity-dimension rows filtered by optional commodity_code, dimension_code, and dimension_show_name fields",
              "conditions": [
                "QueryCommodityDimensions handler invoked"
              ],
              "implementation": "entity.NewCommodityDimensionQuerySet(db.GetDB()).CommodityCodeEq(...).DimensionCodeEq(...).DimensionShowNameEq(...).All(&allEntity)"
            },
            {
              "operation": "SELECT",
              "table": "commodity_dimensions",
              "trigger": "Load every shared dimension row and append it to the result set",
              "conditions": [
                "The filtered query succeeded"
              ],
              "implementation": "entity.NewCommodityDimensionQuerySet(db.GetDB()).IsShareEq(true).All(&shareEntitySlice)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/query_commodity_editions": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after the CommodityEditionQuery payload binds successfully"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "commodity_editions",
              "trigger": "List commodity-edition rows filtered by optional commodity_code, edition_code, and edition_show_name fields",
              "conditions": [
                "QueryCommodityEditions handler invoked"
              ],
              "implementation": "entity.NewCommodityEditionQuerySet(db.GetDB()).CommodityCodeEq(...).EditionShowNameEq(...).All(&allEntity)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/query_commodity_sku_templates": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after the SkuTemplateQuery payload binds successfully"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "sku_templates",
              "trigger": "List sku-template rows filtered by optional commodity_code and edition_code",
              "conditions": [
                "QuerySkuTemplates handler invoked"
              ],
              "implementation": "entity.NewSkuTemplateQuerySet(db.GetDB()).CommodityCodeEq(...).EditionCodeEq(...).All(&allEntity)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /api/v1/billing/query_sku_list": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after the SkuInfoQuery payload binds successfully"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "units",
              "trigger": "List SKU rows filtered by optional commodity_code, edition_code, unit_key, and sku_template_id",
              "conditions": [
                "QuerySkuList handler invoked"
              ],
              "implementation": "entity.NewUnitQuerySet(db.GetDB()).CommodityCodeEq(...).EditionCodeEq(...).UnitKeyEq(...).SkuTemplateIDEq(...).All(&allEntity)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP POST /api/v1/billing/providers/alicloud/costexplorer/monthly_bills/year/:year/month/:month/export": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after year/month URI binding succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "invoices",
              "trigger": "Load sent AliCloud invoices for the requested billing month",
              "conditions": [
                "input.Year and input.Month were parsed from the URI"
              ],
              "implementation": "invoiceModel.ListSentInvoicesByPaymentType(input.Year, input.Month, entity.PaymentType_AliCloud)"
            },
            {
              "operation": "SELECT",
              "table": "user_unit_costs and units",
              "trigger": "Build the exported usage-detail rows for the invoice-backed tenant/billing-config set",
              "conditions": [
                "ListSentInvoicesByPaymentType(...) succeeded"
              ],
              "implementation": "costexplorer.CostExplorerModel.GetExportBillsDetailsByTenant(tenantIDs, billingConfigs, input.Year, input.Month, invoiceIDs)"
            },
            {
              "operation": "SELECT",
              "table": "payment_methods",
              "trigger": "Backfill missing billing-config payment codes while composing the CSV",
              "conditions": [
                "billingConfigPaymentCodeMap does not contain usageDetail.BillingConfigID"
              ],
              "implementation": "paymentModel.GetPaymentMethodWithPaymentType(usageDetail.TenantID, usageDetail.BillingConfigID, entity.PaymentType_AliCloud)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /inner/billing/sku_groups": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Always"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "sku_groups",
              "trigger": "List all sku group rows for inner callers",
              "conditions": [
                "Inner GetSKUGroupList handler invoked"
              ],
              "implementation": "entity.NewSKUGroupsQuerySet(db.GetDB()).All(&groupEntityList)"
            }
          ]
        }
      },
      "services": []
    },
    "HTTP GET /inner/billing/units": {
      "infrastructure": {
        "mysql": {
          "conditions": [
            "Only after optional group_id query parsing succeeds"
          ],
          "operations": [
            {
              "operation": "SELECT",
              "table": "units",
              "trigger": "List all units for inner callers when group_id is absent or zero",
              "conditions": [
                "uriForm.GroupID == 0"
              ],
              "implementation": "billing.UnitModel.GetAllUnits()"
            },
            {
              "operation": "SELECT",
              "table": "units",
              "trigger": "List units scoped to the requested sku group for inner callers",
              "conditions": [
                "uriForm.GroupID > 0"
              ],
              "implementation": "billing.UnitModel.ListUnitsByGroupID(uriForm.GroupID)"
            }
          ]
        }
      },
      "services": []
    }
  },
  "infrastructure_summary": {
    "mysql": {
      "client": "gorm.io/gorm",
      "operations": ["SELECT", "INSERT", "UPDATE", "DELETE"],
      "tables": [
        "billing_configs",
        "payment_methods",
        "invoices",
        "invoice_items",
        "credits_packages",
        "contracts",
        "measures",
        "user_unit_costs",
        "packages",
        "units",
        "billing_companies",
        "support_plans",
        "binded_support_plans",
        "spend_limits",
        "budgets",
        "notifications",
        "tenant_plans",
        "discounts",
        "commodities",
        "commodity_dimensions",
        "commodity_editions",
        "sku_templates",
        "sku_groups",
        "version_skus",
        "partner_configs",
        "unit_filters"
      ]
    },
    "redis": {
      "client": "github.com/go-redis/redis/v8",
      "operations": ["GET", "SET", "DEL"],
      "usage": "Query result caching"
    },
    "s3": {
      "client": "AWS SDK",
      "operations": ["GET", "PUT"],
      "buckets": [
        "tidbcloud-billing-ar-tables",
        "tidbcloud-marketplace-reconciliation"
      ]
    },
    "sqs": {
      "client": "AWS SDK",
      "operations": ["RECEIVE"],
      "usage": "Measure ingestion queue"
    }
  }
}
