Spaces:
Sleeping

File size: 11,195 Bytes
d091b2c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
"""Authenticated owner workspaces, stored in SQLite. Seed rows are fictional."""
import hashlib
import os
import re
import secrets
import sqlite3
import time
import uuid
from contextlib import closing
from datetime import datetime, timezone
from pathlib import Path

from fastapi import FastAPI, HTTPException, Request, Response
from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictInt

app = FastAPI(docs_url=None, redoc_url=None)
db_dir = Path(os.environ.get("KRIYA_DATA", "runtime"))
db_dir.mkdir(parents=True, exist_ok=True)
db_file = db_dir / "studio.sqlite3"
session_name = "kriya_session"
stages = ["DP", "Produksi", "Pelunasan", "Siap kirim"]

def connect():
    con = sqlite3.connect(db_file, timeout=15)
    con.row_factory = sqlite3.Row
    con.execute("PRAGMA foreign_keys=ON")
    return con

with closing(connect()) as db:
    db.executescript("""
    PRAGMA journal_mode=WAL;
    CREATE TABLE IF NOT EXISTS owners(id TEXT PRIMARY KEY, handle TEXT UNIQUE, salt TEXT, password BLOB, demo INTEGER NOT NULL);
    CREATE TABLE IF NOT EXISTS sessions(token TEXT PRIMARY KEY, owner TEXT REFERENCES owners(id), expires INTEGER);
    CREATE TABLE IF NOT EXISTS orders(owner TEXT REFERENCES owners(id), seq INTEGER, customer TEXT, phone TEXT, product TEXT, spec TEXT, address TEXT, quantity INTEGER, price INTEGER, deposit INTEGER, stage INTEGER, settled INTEGER, created TEXT, updated TEXT, PRIMARY KEY(owner,seq));
    CREATE TABLE IF NOT EXISTS history(id INTEGER PRIMARY KEY, owner TEXT, seq INTEGER, event TEXT, at TEXT, FOREIGN KEY(owner,seq) REFERENCES orders(owner,seq));
    CREATE INDEX IF NOT EXISTS history_order ON history(owner,seq,id);
    """)

def now():
    return datetime.now(timezone.utc).isoformat(timespec="microseconds")

def fail(status, message):
    raise HTTPException(status, message)

def digest(value):
    return hashlib.sha256(value.encode()).hexdigest()

def derive(password, salt):
    return hashlib.scrypt(password.encode("utf8"), salt=bytes.fromhex(salt), n=2**14, r=8, p=1, dklen=32)

def current(db, request, required=True):
    token = request.cookies.get(session_name, "")
    row = db.execute("SELECT owners.* FROM owners JOIN sessions ON sessions.owner=owners.id WHERE token=? AND expires>?", (digest(token), int(time.time()))).fetchone()
    if not row and required:
        fail(401, "Masuk untuk membuka pesanan studio.")
    return row

def public_owner(row):
    return {"handle": row["handle"] if not row["demo"] else "Studio contoh", "demo": bool(row["demo"])}

def cookie(response, token, request, age):
    secure = request.headers.get("x-kriya-https") == "1"
    flags = "; Secure; SameSite=None; Partitioned" if secure else "; SameSite=Lax"
    response.headers.append("Set-Cookie", f"{session_name}={token}; Max-Age={age}; Path=/; HttpOnly{flags}")

def issue(db, owner_id, response, request):
    token = secrets.token_urlsafe(36)
    db.execute("DELETE FROM sessions WHERE expires < ? OR token=?", (int(time.time()), digest(request.cookies.get(session_name, ""))))
    db.execute("INSERT INTO sessions VALUES(?,?,?)", (digest(token), owner_id, int(time.time()) + 86400))
    cookie(response,token,request,86400)
    return {"user": public_owner(db.execute("SELECT * FROM owners WHERE id=?",(owner_id,)).fetchone())}

class Form(BaseModel):
    model_config = ConfigDict(extra="forbid")

class Login(Form):
    handle: str = Field(min_length=3, max_length=48,pattern=r"^[a-zA-Z0-9_.-]+$")
    password: str = Field(min_length=8,max_length=128)

class Draft(Form):
    customer: str = Field(max_length=70)
    phone: str = Field(max_length=28)
    product: str = Field(max_length=85)
    spec: str = Field(max_length=350)
    address: str = Field(max_length=350)
    quantity: StrictInt = Field(ge=1,le=1000)
    price: StrictInt = Field(ge=1,le=100000000)
    deposit: StrictInt = Field(ge=0)

class Edit(Form):
    expectedStage: StrictInt = Field(ge=0,le=3)
    updatedAt: str = Field(min_length=8,max_length=48)
    confirmed: StrictBool = False
    deposit: StrictInt | None = Field(default=None,ge=0)

def add_order(db, owner_id, seq, form, stage=0, settled=False, stamp=None):
    attrs = [getattr(form,k).strip() for k in ["customer","phone","product","spec","address"]]
    if not all(attrs):
        fail(422, "Lengkapi nama, kontak, produk, spesifikasi, dan alamat.")
    if not re.fullmatch(r"[+0-9 ()\-.]+",attrs[1]) or not 8 <= len(re.sub(r"\D","",attrs[1])) <=16:
        fail(422, "Periksa nomor kontak pelanggan.")
    if form.deposit > form.quantity * form.price:
        fail(422, "DP melebihi nilai pesanan.")
    stamp = stamp or now()
    paid = settled or form.deposit == form.quantity * form.price
    db.execute("INSERT INTO orders VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)", (owner_id,seq,*attrs,form.quantity,form.price,form.deposit,stage,int(paid),stamp,stamp))
    event(db,owner_id,seq,"Pesanan dicatat",stamp)

def event(db,owner,seq,label,stamp):
    db.execute("INSERT INTO history(owner,seq,event,at) VALUES(?,?,?,?)",(owner,seq,label,stamp))

def as_order(row, events):
    return {**{k: row[k] for k in ("customer","phone","product","spec","address","quantity","price","deposit","stage")},
            "id":f"KT-{row['seq']:03}", "settled":bool(row["settled"]), "createdAt":row["created"], "updatedAt":row["updated"], "history":events}

def get_one(db,owner,seq):
    rec=db.execute("SELECT * FROM orders WHERE owner=? AND seq=?",(owner,seq)).fetchone()
    if not rec: fail(404,"Pesanan tidak ditemukan.")
    ev=db.execute("SELECT event,at FROM history WHERE owner=? AND seq=? ORDER BY id",(owner,seq))
    return as_order(rec,[dict(e) for e in ev])

def seed(db,owner):
    rows=[
        (28,"Nara","Pouch bordir inisial",2,85000,80000,2,"Kanvas nila, inisial NP, resleting kuningan."),
        (27,"Laras","Totebag sulam daun",1,160000,60000,1,"Sulam daun krem, tali panjang."),
        (26,"Sinta","Gantungan rajut",3,35000,40000,0,"Tiga warna benang berbeda."),
        (25,"Mira","Dompet kain motif",1,95000,35000,3,"Kancing magnet dan lapisan katun."),
        (24,"Tari","Pouch serut linen",2,70000,50000,1,"Linen putih dengan tali zaitun."),
        (23,"Rani","Sampul jurnal bordir",1,120000,60000,0,"Ukuran A5, sulam bunga kecil."),
    ]
    for seq,name,product,qty,price,dp,stage,spec in rows:
        stamp=f"2026-11-{seq-12:02}T03:00:00+00:00"
        draft=Draft(customer=name+" (contoh)",phone=f"08000000{seq:04}",product=product,quantity=qty,price=price,deposit=dp,spec=spec,address="Alamat contoh, Bandung")
        add_order(db,owner,seq,draft,stage,stage==3,stamp)
        for i in range(1,stage+1):
            when=stamp.replace("03:",f"{3+i:02}:")
            if i==3: event(db,owner,seq,"Pelunasan diterima",when)
            event(db,owner,seq,stages[i],when)
            db.execute("UPDATE orders SET updated=? WHERE owner=? AND seq=?",(when,owner,seq))

@app.get("/api/session")
def session(request:Request):
    with closing(connect()) as db:
        rec=current(db,request,False)
        return {"user":public_owner(rec) if rec else None}

@app.post("/api/auth/demo")
def demo(request:Request,response:Response):
    with closing(connect()) as db, db:
        owner=uuid.uuid4().hex
        db.execute("INSERT INTO owners VALUES(?,?,?,?,1)",(owner,"demo-"+owner,None,None))
        seed(db,owner)
        return issue(db,owner,response,request)

@app.post("/api/auth/register")
def register(data:Login,request:Request,response:Response):
    with closing(connect()) as db, db:
        owner=uuid.uuid4().hex; salt=secrets.token_hex(16)
        try:
            db.execute("INSERT INTO owners VALUES(?,?,?,?,0)",(owner,data.handle.lower(),salt,derive(data.password,salt)))
        except sqlite3.IntegrityError:
            fail(409,"Nama akun sudah digunakan.")
        return issue(db,owner,response,request)

@app.post("/api/auth/login")
def login(data:Login,request:Request,response:Response):
    with closing(connect()) as db, db:
        row=db.execute("SELECT * FROM owners WHERE handle=? AND demo=0",(data.handle.lower(),)).fetchone()
        signature=derive(data.password,row["salt"] if row else "0"*32)
        if not row or not secrets.compare_digest(signature,row["password"]):
            fail(401,"Nama akun atau kata sandi keliru.")
        return issue(db,row["id"],response,request)

@app.post("/api/auth/logout")
def logout(request:Request,response:Response):
    with closing(connect()) as db, db:
        db.execute("DELETE FROM sessions WHERE token=?",(digest(request.cookies.get(session_name,"")),))
        cookie(response,"",request,0)
        return {"ok":True}

@app.get("/api/orders")
def orders(request:Request):
    with closing(connect()) as db, db:
        owner=current(db,request)["id"]
        db.execute("BEGIN")
        groups={}
        for e in db.execute("SELECT seq,event,at FROM history WHERE owner=? ORDER BY id",(owner,)):
            groups.setdefault(e["seq"],[]).append({"event":e["event"],"at":e["at"]})
        return {"orders":[as_order(row,groups.get(row["seq"],[])) for row in db.execute("SELECT * FROM orders WHERE owner=? ORDER BY seq DESC",(owner,))]}

@app.post("/api/orders",status_code=201)
def create(data:Draft, request:Request):
    with closing(connect()) as db, db:
        owner=current(db,request)["id"]; db.execute("BEGIN IMMEDIATE")
        seq=db.execute("SELECT COALESCE(MAX(seq),0)+1 FROM orders WHERE owner=?",(owner,)).fetchone()[0]
        add_order(db,owner,seq,data)
        return {"ok":True,"order":get_one(db,owner,seq)}

@app.post("/api/orders/{code}/{action}")
def edit(code:str,action:str,data:Edit,request:Request):
    if not re.fullmatch(r"KT-[0-9]{1,10}",code) or action not in ("advance","deposit"):
        fail(404,"Perubahan pesanan tidak dikenal.")
    seq=int(code[3:])
    with closing(connect()) as db, db:
        owner=current(db,request)["id"]; db.execute("BEGIN IMMEDIATE")
        order=get_one(db,owner,seq)
        stage=order["stage"]; dp=order["deposit"]; paid=order["settled"]; total=order["price"]*order["quantity"]
        if stage!=data.expectedStage or order["updatedAt"]!=data.updatedAt: fail(409,"Pesanan sudah berubah. Periksa data terbaru.")
        if action=="advance":
            if stage==3: fail(422,"Pesanan sudah siap kirim.")
            if stage==0 and dp<=0: fail(422,"Catat DP sebelum mulai produksi.")
            if stage==2 and not paid: fail(422,"Catat pelunasan sebelum menandai siap kirim.")
            stage+=1; label=stages[stage]
        elif stage==0 and data.deposit is not None:
            if data.deposit>total: fail(422,"DP melebihi nilai pesanan.")
            dp=data.deposit; paid=dp==total; label=f"DP diperbarui menjadi Rp{dp:,}".replace(",",".")
        elif stage==2 and data.confirmed and not paid and data.deposit is None:
            paid=True; label="Pelunasan diterima"
        else: fail(422,"Periksa tahap dan konfirmasi penerimaan pembayaran.")
        stamp=now()
        db.execute("UPDATE orders SET stage=?,deposit=?,settled=?,updated=? WHERE owner=? AND seq=?",(stage,dp,int(paid),stamp,owner,seq))
        event(db,owner,seq,label,stamp)
        return {"ok":True,"order":get_one(db,owner,seq)}