Spaces:
Sleeping

File size: 2,905 Bytes
3067a0c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90436a7
3067a0c
 
 
 
90436a7
 
 
 
 
 
 
3067a0c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a013512
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
"""Plans, credit costs and policy."""

from __future__ import annotations

import json
from dataclasses import dataclass
from pathlib import Path

from .errors import ApiError

GRACE_SECONDS = 3 * 86400  # a late renewal webhook must not lock a paying customer out


@dataclass(frozen=True)
class Plan:
    credits: int  # granted each period
    devices: int  # activations allowed at once
    days: int | None = None  # one-off plans (trial): length of the licence and of its credits


@dataclass(frozen=True)
class Config:
    costs: dict[str, int]
    plans: dict[str, Plan]
    packs: dict[str, int]
    topup_days: int | None = None  # purchased credits do not expire unless set
    refund_days: int = 30  # life of the credits returned for a lot that expired meanwhile
    hold_seconds: int = 600


DEFAULT = {
    "costs": {"produce.compose": 5, "produce.flp": 3, "mix.balance": 2},
    "plans": {
        "trial": {"credits": 15, "devices": 1, "days": 30},
        "pro": {"credits": 300, "devices": 2},
        "studio": {"credits": 1200, "devices": 5},
    },
    "packs": {"pack_100": 100, "pack100": 100, "pack_500": 500, "pack500": 500},
}


def load(path: str | Path | None = None) -> Config:
    extra: dict = {}
    if path and Path(path).is_file():
        try:
            extra = json.loads(Path(path).read_text("utf-8"))
        except Exception:
            extra = {}
    raw = {**DEFAULT, **extra}
    costs, packs = dict(raw["costs"]), dict(raw["packs"])
    plans = {name: Plan(**p) for name, p in raw["plans"].items()}
    if not costs or any(not isinstance(v, int) or v < 1 for v in costs.values()):
        raise ValueError("every cost must be a whole number of credits, at least 1")
    if any(not isinstance(v, int) or v < 1 for v in packs.values()):
        raise ValueError("every pack must be a whole number of credits, at least 1")
    if any(p.credits < 0 or p.devices < 1 for p in plans.values()):
        raise ValueError("plans need credits >= 0 and devices >= 1")
    return Config(
        costs,
        plans,
        packs,
        raw.get("topup_days"),
        int(raw.get("refund_days", 30)),
        int(raw.get("hold_seconds", 600)),
    )


def usable(status: str, period_end: int | None, now: int) -> bool:
    """active licences run a grace period past period_end; canceled ones stop at period_end."""
    if status not in ("active", "canceled"):
        return False
    if period_end is None:
        return True
    return now < period_end + (GRACE_SECONDS if status == "active" else 0)


def require_usable(status: str, period_end: int | None, now: int) -> None:
    if not usable(status, period_end, now):
        state = "expired" if status == "active" else status
        raise ApiError(
            403,
            "license_inactive",
            f"the subscription is {state}; renew it to continue",
            subscription=state,
        )