Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 39 additions & 11 deletions limacharlie/commands/api_cmd.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

import json
import os
import re
import sys
from typing import Any
from urllib.parse import quote
Expand All @@ -26,13 +27,34 @@

_TARGETS = {
"api": "https://api.limacharlie.io",
"billing": "https://billing.limacharlie.io",
"jwt": "https://jwt.limacharlie.io",
"stream": "https://stream-tmp.limacharlie.io",
"downloads": "https://downloads.limacharlie.io",
"cases": "https://cases.limacharlie.io",
}

# Compat shim: the legacy billing.limacharlie.io host is retired and its
# endpoints have been folded into lc_api under api.limacharlie.io/v1/.
# --target billing continues to accept the old relative paths and rewrites
# them to the new lc_api routes. Paths with no legacy counterpart (e.g.
# /v1/orgs/{oid}/billing/sku, which never existed on the old host) are
# passed through as-is.
_BILLING_PATH_REWRITES: list[tuple[re.Pattern[str], str]] = [
(re.compile(r"^orgs/([^/]+)/status$"), r"orgs/\1/billing/status"),
(re.compile(r"^orgs/([^/]+)/details$"), r"orgs/\1/billing/details"),
(re.compile(r"^orgs/([^/]+)/invoice_url/(\d{4})/(\d{1,2})$"), r"orgs/\1/billing/invoice/\2/\3"),
(re.compile(r"^user/self/plans$"), "plans"),
]


def _rewrite_billing_endpoint(endpoint: str) -> str:
"""Rewrite a legacy billing-service relative path to its lc_api equivalent."""
for pattern, replacement in _BILLING_PATH_REWRITES:
rewritten, n = pattern.subn(replacement, endpoint)
if n:
return rewritten
return endpoint


# ---------------------------------------------------------------------------
# Field parsing helpers
Expand Down Expand Up @@ -149,7 +171,10 @@ def _exit_code_for_status(status: int) -> int:
@file for reading values from files. Alternatively, use --input to send
a raw body from a file or stdin.

Target aliases: api (default), billing, jwt, stream, downloads, cases.
Target aliases: api (default), jwt, stream, downloads, cases.
The deprecated 'billing' alias is still accepted; legacy billing-service
paths (orgs/{oid}/status, user/self/plans, invoice_url/...) are rewritten
to their new /v1/ counterparts on api.limacharlie.io.
Any other value is treated as a raw https:// URL.

Non-200 responses are NOT errors: the raw response body is printed and the
Expand All @@ -166,7 +191,7 @@ def _exit_code_for_status(status: int) -> int:
@click.option("--json", "use_json", is_flag=True, help="Send fields as JSON body instead of form-encoded.")
@click.option("--input", "input_file", default=None, help="Request body from file (use '-' for stdin).")
@click.option("--content-type", "content_type_override", default=None, help="Content-Type for --input body (default: auto-detect).")
@click.option("--target", default="api", help="API host alias or URL (aliases: api, billing, jwt, stream, downloads, cases).")
@click.option("--target", default="api", help="API host alias or URL (aliases: api, jwt, stream, downloads, cases; billing is a deprecated alias that rewrites legacy paths to api).")
@click.option("-i", "--include", "include_status", is_flag=True, help="Show HTTP status code in output.")
@click.option("--silent", is_flag=True, help="Suppress response body.")
@click.option("--no-auth", is_flag=True, help="Skip authentication.")
Expand Down Expand Up @@ -200,16 +225,19 @@ def cmd(ctx: click.Context, endpoint: str, method: str | None, raw_field: tuple[
effective_method = method.upper()

# --- Resolve target ---
if target in _TARGETS:
target_url = _TARGETS[target]
# The legacy "billing" alias is a compat shim: rewrite the endpoint and
# route through api.limacharlie.io/v1/ like the default "api" target.
if target == "billing":
endpoint = _rewrite_billing_endpoint(endpoint)
alt_root = None
elif target == "api":
alt_root = None
elif target in _TARGETS:
alt_root = _TARGETS[target]
elif target.startswith("https://") or target.startswith("http://"):
target_url = target
alt_root = target
else:
target_url = f"https://{target}"

# For the default "api" target, use alt_root=None so _rest_call
# builds ROOT_URL/v1/<endpoint>. For everything else, use alt_root.
alt_root = None if target == "api" else target_url
alt_root = f"https://{target}"

# --- Create client ---
client = Client(oid=ctx.obj.oid, environment=ctx.obj.environment, print_debug_fn=ctx.obj.debug_fn, debug_full_response=ctx.obj.debug_full, debug_curl=ctx.obj.debug_curl, debug_verbose=ctx.obj.debug_verbose)
Expand Down
2 changes: 1 addition & 1 deletion limacharlie/help_topics.py
Original file line number Diff line number Diff line change
Expand Up @@ -601,7 +601,7 @@
limacharlie billing plans - Available plan options
limacharlie billing invoice - Invoice history

Billing API uses a separate endpoint (billing.limacharlie.io).
Billing endpoints are served under api.limacharlie.io at /v1/orgs/{oid}/billing/ and /v1/plans.

Related commands: billing, org
"""
Expand Down
13 changes: 5 additions & 8 deletions limacharlie/sdk/billing.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,6 @@
if TYPE_CHECKING:
from .organization import Organization

BILLING_URL = "https://billing.limacharlie.io/"


class Billing:
"""Billing and subscription management for a LimaCharlie organization."""
Expand All @@ -23,11 +21,11 @@ def client(self) -> Any:

def get_status(self) -> dict[str, Any]:
"""Get the current billing status for the organization."""
return self.client.request("GET", f"orgs/{self._org.oid}/status", alt_root=BILLING_URL)
return self.client.request("GET", f"orgs/{self._org.oid}/billing/status")

def get_details(self) -> dict[str, Any]:
"""Get detailed billing information for the organization."""
return self.client.request("GET", f"orgs/{self._org.oid}/details", alt_root=BILLING_URL)
return self.client.request("GET", f"orgs/{self._org.oid}/billing/details")

def get_invoice_url(self, year: int | str, month: int | str, fmt: str | None = None) -> dict[str, Any]:
"""Get the invoice URL for a specific month.
Expand All @@ -45,10 +43,9 @@ def get_invoice_url(self, year: int | str, month: int | str, fmt: str | None = N
qp: dict[str, str] = {}
if fmt:
qp["format"] = fmt
return self.client.request("GET", f"orgs/{self._org.oid}/invoice_url/{year}/{month}",
alt_root=BILLING_URL, query_params=qp or None)
return self.client.request("GET", f"orgs/{self._org.oid}/billing/invoice/{year}/{month}",
query_params=qp or None)

def get_plans(self) -> dict[str, Any]:
"""Get available billing plans."""
return self.client.request("GET", "user/self/plans", alt_root=BILLING_URL)

return self.client.request("GET", "plans")
47 changes: 44 additions & 3 deletions tests/unit/test_api_cmd.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,13 +98,54 @@ def test_default_target_uses_no_alt_root(self):
_, kwargs = mock_cls.return_value.raw_request.call_args
assert kwargs.get("alt_root") is None

def test_billing_target(self):
def test_billing_target_is_rewritten_to_api(self):
# --target billing is a deprecated shim: it routes through api.limacharlie.io
# (alt_root=None) and rewrites legacy billing-service paths to /v1/ paths.
with _patch_client() as mock_cls:
runner = CliRunner()
result = runner.invoke(cli, ["api", "--target", "billing", "orgs/{oid}/status"])
assert result.exit_code == 0
_, kwargs = mock_cls.return_value.raw_request.call_args
assert kwargs["alt_root"] == "https://billing.limacharlie.io"
args, kwargs = mock_cls.return_value.raw_request.call_args
assert kwargs["alt_root"] is None
assert args[1] == f"orgs/{_MOCK_OID}/billing/status"

def test_billing_target_rewrites_details(self):
with _patch_client() as mock_cls:
runner = CliRunner()
result = runner.invoke(cli, ["api", "--target", "billing", "orgs/{oid}/details"])
assert result.exit_code == 0
args, kwargs = mock_cls.return_value.raw_request.call_args
assert kwargs["alt_root"] is None
assert args[1] == f"orgs/{_MOCK_OID}/billing/details"

def test_billing_target_rewrites_invoice_url(self):
with _patch_client() as mock_cls:
runner = CliRunner()
result = runner.invoke(cli, ["api", "--target", "billing", "orgs/{oid}/invoice_url/2024/03"])
assert result.exit_code == 0
args, kwargs = mock_cls.return_value.raw_request.call_args
assert kwargs["alt_root"] is None
assert args[1] == f"orgs/{_MOCK_OID}/billing/invoice/2024/03"

def test_billing_target_rewrites_plans(self):
with _patch_client() as mock_cls:
runner = CliRunner()
result = runner.invoke(cli, ["api", "--target", "billing", "user/self/plans"])
assert result.exit_code == 0
args, kwargs = mock_cls.return_value.raw_request.call_args
assert kwargs["alt_root"] is None
assert args[1] == "plans"

def test_billing_target_passes_through_unmapped_paths(self):
# Paths whose path didn't change (user/self/auth, orgs/{oid}/quota,
# domain/{d}/auth) still route through api — endpoint unchanged.
with _patch_client() as mock_cls:
runner = CliRunner()
result = runner.invoke(cli, ["api", "--target", "billing", "user/self/auth"])
assert result.exit_code == 0
args, kwargs = mock_cls.return_value.raw_request.call_args
assert kwargs["alt_root"] is None
assert args[1] == "user/self/auth"

def test_cases_target(self):
with _patch_client() as mock_cls:
Expand Down
18 changes: 7 additions & 11 deletions tests/unit/test_sdk_billing.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from unittest.mock import MagicMock
import pytest

from limacharlie.sdk.billing import Billing, BILLING_URL
from limacharlie.sdk.billing import Billing


@pytest.fixture
Expand All @@ -24,7 +24,7 @@ def test_get_status(self, billing, mock_org):
mock_org.client.request.return_value = {"status": "active"}
result = billing.get_status()
mock_org.client.request.assert_called_once_with(
"GET", "orgs/test-oid/status", alt_root=BILLING_URL,
"GET", "orgs/test-oid/billing/status",
)
assert result["status"] == "active"

Expand All @@ -34,7 +34,7 @@ def test_get_details(self, billing, mock_org):
mock_org.client.request.return_value = {"plan": "enterprise"}
result = billing.get_details()
mock_org.client.request.assert_called_once_with(
"GET", "orgs/test-oid/details", alt_root=BILLING_URL,
"GET", "orgs/test-oid/billing/details",
)
assert result["plan"] == "enterprise"

Expand All @@ -44,8 +44,8 @@ def test_get_invoice_url(self, billing, mock_org):
mock_org.client.request.return_value = {"url": "https://invoice.example.com"}
billing.get_invoice_url(2024, 1)
mock_org.client.request.assert_called_once_with(
"GET", "orgs/test-oid/invoice_url/2024/01",
alt_root=BILLING_URL, query_params=None,
"GET", "orgs/test-oid/billing/invoice/2024/01",
query_params=None,
)

def test_month_zero_padded(self, billing, mock_org):
Expand All @@ -65,23 +65,19 @@ def test_with_format_param(self, billing, mock_org):
billing.get_invoice_url(2024, 6, fmt="pdf")
call_args = mock_org.client.request.call_args
assert call_args[1]["query_params"] == {"format": "pdf"}
assert call_args[1]["alt_root"] == BILLING_URL

def test_string_year_month(self, billing, mock_org):
mock_org.client.request.return_value = {}
billing.get_invoice_url("2024", "7")
path = mock_org.client.request.call_args[0][1]
assert path == "orgs/test-oid/invoice_url/2024/07"
assert path == "orgs/test-oid/billing/invoice/2024/07"


class TestBillingGetPlans:
def test_get_plans(self, billing, mock_org):
mock_org.client.request.return_value = {"plans": []}
result = billing.get_plans()
mock_org.client.request.assert_called_once_with(
"GET", "user/self/plans", alt_root=BILLING_URL,
"GET", "plans",
)
assert result == {"plans": []}

def test_billing_url_constant(self):
assert BILLING_URL == "https://billing.limacharlie.io/"