Hướng dẫn

Nối dữ liệu với Stata

Tải dữ liệu ra CSV bằng script Python rồi nhập vào Stata để làm sạch và phân tích. Cần Stata 17 trở lên.

  1. 1Cất API key

    Tạo API key chỉ đọc ở Cài đặt → Ứng dụng & API → Khóa API, rồi đặt vào environment variable. Thử ở sandbox trước.

    Terminal
    # Windows PowerShell
    $env:NEXTX_API_KEY = "<your API key>"
    
    # macOS or Linux
    export NEXTX_API_KEY="<your API key>"

    API key →Sandbox →

  2. 2Lưu script

    Lưu đoạn mã dưới đây thành nextx_extract.py. Script chỉ cần Python 3.8 trở lên và không ghi số điện thoại, email, địa chỉ.

    nextx_extract.py
    #!/usr/bin/env python3
    """Export API data to UTF-8 CSV. Standard library only, Python 3.8+.
    
    The API key comes from the NEXTX_API_KEY environment variable.
    Example:
      python nextx_extract.py orders --env sandbox --from 2026-10-01 --to 2026-10-31 --out data/raw/orders.csv
    """
    import argparse, csv, datetime, json, os, sys, time
    import urllib.error, urllib.parse, urllib.request
    
    BASE = {"sandbox": "https://api-dev.nextx.vn", "prod": "https://api.nextx.vn"}
    
    # fields is an allow-list: phone, email, address and notes are never written.
    DATASETS = {
        "orders": {
            "path": "/api/v1/sales/orders", "date": ("dateFrom", "dateTo"),
            "fields": ["id", "code", "orderType", "status", "salesCustomerId", "branchId", "branchName",
                       "subtotal", "discountAmount", "taxAmount", "shippingFee", "total", "paidAmount",
                       "debtAmount", "paymentMethod", "channelCode", "orderDate", "createdAt",
                       "confirmedAt", "cancelledAt", "itemCount"]},
        "contacts": {
            "path": "/api/v1/crm/contacts", "date": ("fromDate", "toDate"),
            "fields": ["id", "code", "contactType", "tier", "lifecycleStage", "city", "provinceCode",
                       "assigneeId", "assigneeName", "branchName", "sourceName", "orderCount", "dealCount",
                       "leadScore", "leadTier", "createdAt", "lastActivityAt"]},
        "opportunities": {
            "path": "/api/v1/crm/opportunities", "date": ("fromDate", "toDate"),
            "fields": ["id", "code", "contactId", "pipelineStageName", "estimatedValue", "probability",
                       "expectedCloseDate", "assigneeId", "assigneeName", "status", "wonAt", "createdAt",
                       "isOverdue", "daysOverdue", "callCount"]},
        "calls": {
            "path": "/api/v1/call/calls", "date": ("dateFrom", "dateTo"),
            "fields": ["id", "direction", "agentId", "agentName", "queueId", "queueName", "status",
                       "startedAt", "answeredAt", "endedAt", "waitDurationSec", "talkDurationSec",
                       "hasRecording", "csatScore", "crmContactId", "disposition", "createdAt"]},
        "transactions": {
            "path": "/api/v1/payment/transactions", "date": ("fromDate", "toDate"), "date_only": True,
            "fields": ["id", "providerCode", "referenceType", "referenceId", "amount", "netAmount",
                       "currency", "paidAt", "createdAt", "refundedAmount", "refundCount",
                       "latestRefundStatus"]},
    }
    
    PAGE_SIZE = 100       # opportunities, calls and transactions cap at 100
    PAUSE = 0.25          # about 240 requests per minute
    MAX_TRIES = 6
    
    
    def get_json(url, key):
        for attempt in range(1, MAX_TRIES + 1):
            req = urllib.request.Request(url, headers={"X-Api-Key": key, "Accept": "application/json"})
            try:
                with urllib.request.urlopen(req, timeout=60) as r:
                    return json.load(r)
            except urllib.error.HTTPError as e:
                if e.code in (401, 403):
                    sys.exit(f"HTTP {e.code}: invalid key, expired key or missing scope.")
                if e.code == 429 or e.code >= 500:
                    wait = int(e.headers.get("Retry-After") or 2 ** attempt)
                    print(f"  HTTP {e.code}, waiting {wait}s ({attempt}/{MAX_TRIES})", file=sys.stderr)
                    time.sleep(wait)
                    continue
                sys.exit(f"HTTP {e.code}: {e.read()[:300].decode('utf8', 'replace')}")
            except (urllib.error.URLError, TimeoutError) as e:
                print(f"  Network error: {e} ({attempt}/{MAX_TRIES})", file=sys.stderr)
                time.sleep(2 ** attempt)
        sys.exit("Too many failures. No file was written.")
    
    
    def vn_day_utc(day, clock):
        local = datetime.datetime.fromisoformat(f"{day}T{clock}+07:00")
        return local.astimezone(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
    
    
    def pull(ds, base, key, date_from, date_to):
        params = {"pageSize": PAGE_SIZE}
        # Date-time filters are inclusive instants. transactions takes plain dates.
        if date_from:
            params[ds["date"][0]] = date_from if ds.get("date_only") else vn_day_utc(date_from, "00:00:00")
        if date_to:
            params[ds["date"][1]] = date_to if ds.get("date_only") else vn_day_utc(date_to, "23:59:59")
        rows, seen, n, total = [], set(), 1, None
        while True:
            params["pageNumber"] = n
            body = get_json(f"{base}{ds['path']}?{urllib.parse.urlencode(params)}", key)
            items = body.get("items") or []
            total = body.get("totalCount", body.get("totalRecords", total))
            if not items:
                break
            for it in items:
                if it.get("id") not in seen:   # new rows can push a row onto the next page
                    seen.add(it.get("id"))
                    rows.append({f: it.get(f) for f in ds["fields"]})
            print(f"  page {n}: {len(rows)}/{total if total is not None else '?'}", file=sys.stderr)
            n += 1
            time.sleep(PAUSE)
        if total is not None and len(rows) < total:
            sys.exit(f"Missing rows: got {len(rows)}, API reported {total}. Run again.")
        return rows
    
    
    def write_csv(path, fields, rows):
        os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
        tmp = path + ".tmp"
        with open(tmp, "w", newline="", encoding="utf-8") as f:
            w = csv.DictWriter(f, fieldnames=fields)
            w.writeheader()
            w.writerows(rows)
        os.replace(tmp, path)     # only replace the old file on success
    
    
    def main():
        ap = argparse.ArgumentParser()
        ap.add_argument("dataset", choices=DATASETS)
        ap.add_argument("--env", choices=BASE, default="sandbox")
        ap.add_argument("--base-url", help="For testing only")
        ap.add_argument("--from", dest="date_from", help="YYYY-MM-DD")
        ap.add_argument("--to", dest="date_to", help="YYYY-MM-DD")
        ap.add_argument("--out", required=True)
        a = ap.parse_args()
        key = os.environ.get("NEXTX_API_KEY")
        if not key:
            sys.exit("Set the NEXTX_API_KEY environment variable.")
        ds = DATASETS[a.dataset]
        rows = pull(ds, a.base_url or BASE[a.env], key, a.date_from, a.date_to)
        write_csv(a.out, ds["fields"], rows)
        print(f"Wrote {len(rows)} rows to {a.out}")
    
    
    if __name__ == "__main__":
        main()
  3. 3Tải dữ liệu

    Chọn bảng và khoảng ngày. Các bảng có sẵn: orders, contacts, opportunities, calls, transactions.

    Terminal
    python nextx_extract.py orders --env sandbox --from 2026-10-01 --to 2026-10-31 --out data/raw/orders.csv
  4. 4Phân tích trong Stata

    Mở Stata tại thư mục dự án và chạy do-file. Mẫu kiểm tra id không trùng, đổi về giờ Việt Nam và tổng hợp doanh thu theo tuần.

    01_orders.do
    * 01_orders.do
    * Run nextx_extract.py first, then open Stata in the project folder.
    version 17
    clear all
    set more off
    capture mkdir "logs"
    capture mkdir "data/clean"
    capture log close
    log using "logs/01_orders.log", replace text
    
    import delimited using "data/raw/orders.csv", ///
        clear varnames(1) case(lower) encoding("utf-8") bindquotes(strict)
    
    * Stop here if id is not unique.
    isid id
    
    * Timestamps are converted from UTC to Vietnam time.
    * orderDate is empty on regular orders. The API filter uses the same rule.
    generate str32 effective_date = orderdate
    replace effective_date = createdat if missing(effective_date)
    generate double order_tc = clock(substr(effective_date, 1, 19), "YMD#hms") + 7 * 60 * 60 * 1000
    format order_tc %tc
    generate order_d = dofc(order_tc)
    format order_d %td
    assert !missing(order_d)
    
    * Net revenue: excludes VAT and shipping.
    generate byte is_revenue = inlist(status, "COMPLETED", "CLOSED")
    label variable is_revenue "Counts as revenue"
    generate double net_revenue = total - cond(missing(taxamount), 0, taxamount) ///
        - cond(missing(shippingfee), 0, shippingfee)
    label variable net_revenue "Revenue before VAT and shipping"
    
    save "data/clean/orders.dta", replace
    
    * Weekly revenue by branch
    keep if is_revenue
    generate week_d = wofd(order_d)
    format week_d %tw
    collapse (sum) revenue = net_revenue (count) orders = net_revenue, by(branchname week_d)
    list in 1/10, abbreviate(16)
    
    log close

    Rate limit →Data model →