didi-website-erp-crm/erp_crm/test-scenarii-integrare.sh

109 lines
8.1 KiB
Bash

#!/usr/bin/env bash
# ============================================================================
# Scenarii de testare integrare Website/ERP-CRM <-> backend DiDi
# Contra contractelor din pachetul de integrare (SSO, credite, one-time buy,
# alocare M2M).
#
# IMPLICIT ruleaza pe MOCK-ul din pachetul de integrare (mock-server.js pe :4000)
# — porneste-l intai: node mock-server.js
#
# Pentru platforma reala, exporta variabilele inainte de rulare (valorile le
# livreaza operatorul platformei; NU se comit in git):
# export KC_URL=https://<KEYCLOAK_HOST>/auth
# export DIDI_FRAMEWORK_URL=http://<HOST>:<PORT_FRAMEWORK>
# export DIDI_API_URL=http://<HOST>:<PORT_AGENT>/api
# export DIDI_ADMIN_CLIENT_SECRET=<secret M2M>
# export TEST_USER=<email user test> TEST_PASS=<parola>
#
# Rulare: bash test-scenarii-integrare.sh
# ============================================================================
set -uo pipefail
# ── Config (din env, cu default-uri pe mock) ────────────────────────────────
KC="${KC_URL:-http://localhost:4000}"
FRAMEWORK="${DIDI_FRAMEWORK_URL:-http://localhost:4000}"
AGENT="${DIDI_API_URL:-http://localhost:4000/api}"
REALM_USERS="${REALM_USERS:-didi-clients}" # realm-ul real e didi-clients (NU didi-website)
REALM_ADMIN="${REALM_ADMIN:-didi-admins}"
WEB_CLIENT="${WEB_CLIENT_ID:-didi-web-app}" # client SSO user (public)
M2M_CLIENT="${DIDI_ADMIN_CLIENT_ID:-didi-website-m2m}" # client M2M (client_credentials)
M2M_SECRET="${DIDI_ADMIN_CLIENT_SECRET:-mock-secret}"
TEST_USER="${TEST_USER:-demo@clossers.com}"
TEST_PASS="${TEST_PASS:-demo}"
pass=0; fail=0
ok() { echo " ✅ PASS — $1"; pass=$((pass+1)); }
ko() { echo " ❌ FAIL — $1"; fail=$((fail+1)); }
hdr() { echo; echo "════ $1"; }
jq_get() { python3 -c "import sys,json;d=json.load(sys.stdin);print(eval('d'+sys.argv[1]))" "$1" 2>/dev/null; }
# ── Token utilizator (simuleaza login SSO) ──────────────────────────────────
USER_TOKEN=$(curl -sk -X POST "$KC/realms/$REALM_USERS/protocol/openid-connect/token" \
-d grant_type=password -d client_id=$WEB_CLIENT -d username="$TEST_USER" -d password="$TEST_PASS" \
| jq_get "['access_token']")
SUB=$(echo "$USER_TOKEN" | cut -d. -f2 | base64 -d 2>/dev/null | jq_get "['sub']")
# ── Token M2M (client_credentials, realm admin) ─────────────────────────────
M2M_TOKEN=$(curl -sk -X POST "$KC/realms/$REALM_ADMIN/protocol/openid-connect/token" \
-d grant_type=client_credentials -d client_id=$M2M_CLIENT -d client_secret="$M2M_SECRET" \
| jq_get "['access_token']")
# ════════════════════════════════════════════════════════════════════════════
hdr "S1 · SSO / IAM — autentificare utilizator (OIDC)"
[ -n "$USER_TOKEN" ] && [ "$USER_TOKEN" != "None" ] && ok "token JWT obtinut pt $TEST_USER (sub=$SUB)" || ko "nu s-a obtinut token user"
hdr "S2 · Provisioning la primul login (register idempotent + me)"
REG=$(curl -s -o /dev/null -w "%{http_code}" -X POST -H "Authorization: Bearer $USER_TOKEN" -H "Content-Type: application/json" "$FRAMEWORK/api/auth/register" -d '{}')
{ [ "$REG" = "409" ] || [ "$REG" = "200" ] || [ "$REG" = "201" ]; } && ok "register -> HTTP $REG (409=deja existent, idempotent)" || ko "register -> HTTP $REG neasteptat"
ME=$(curl -s -H "Authorization: Bearer $USER_TOKEN" "$FRAMEWORK/api/auth/me")
echo "$ME" | grep -q '"email"' && ok "GET /api/auth/me returneaza profilul" || ko "me nu returneaza profil: ${ME:0:120}"
hdr "S3 · Credite — backend = sursa unica de adevar"
CRED=$(curl -s -H "Authorization: Bearer $USER_TOKEN" "$FRAMEWORK/api/auth/credits")
C_REMAIN=$(echo "$CRED" | jq_get "['data']['creditsRemained']")
echo "$CRED" | grep -q creditsRemained && ok "credits: remained=$C_REMAIN plan=$(echo "$CRED" | jq_get "['data']['planName']")" || ko "credits endpoint invalid"
hdr "S4 · Cataloage (planuri abonament + produse one-time)"
count() { python3 -c "import sys,json;d=json.load(sys.stdin);print(len(d.get('data',d)) if isinstance(d.get('data',d),list) else 0)" 2>/dev/null; }
NPLANS=$(curl -s -H "Authorization: Bearer $USER_TOKEN" "$FRAMEWORK/api/subscriptions/plans" | count)
NPROD=$(curl -s -H "Authorization: Bearer $USER_TOKEN" "$FRAMEWORK/api/subscriptions/one-time-products" | count)
[ "$NPLANS" -ge 1 ] 2>/dev/null && ok "$NPLANS planuri de abonament" || ko "catalog planuri gol"
[ "$NPROD" -ge 1 ] 2>/dev/null && ok "$NPROD produse one-time" || ko "catalog produse gol"
hdr "S5 · ONE-TIME BUY — alocare pachet dupa plata (flux M2M, punctul 4)"
[ -n "$M2M_TOKEN" ] && [ "$M2M_TOKEN" != "None" ] && ok "token M2M obtinut (client_credentials, realm $REALM_ADMIN)" || ko "M2M token esuat"
# pasul 2: rezolvare user
USR=$(curl -s -H "Authorization: Bearer $M2M_TOKEN" "$FRAMEWORK/api/admin/users?search=$TEST_USER")
IUID=$(echo "$USR" | python3 -c "import sys,json;d=json.load(sys.stdin);data=d.get('data',d);u=data[0] if isinstance(data,list) else data;print(u['internetUserId'] if 'internetUserId' in u else u['id'])" 2>/dev/null)
BEFORE=$(echo "$USR" | python3 -c "import sys,json;d=json.load(sys.stdin);data=d.get('data',d);u=data[0] if isinstance(data,list) else data;print(u['creditsRemained'])" 2>/dev/null)
[ -n "$IUID" ] && ok "user rezolvat: internetUserId=$IUID, sold curent=$BEFORE" || ko "nu s-a rezolvat userul via M2M"
# pasul 3: alocare (simulam cumparare produs 104 Techniques-Video = 5 credite)
PKG=5
NEWBAL=$((BEFORE + PKG))
ALLOC=$(curl -s -X PUT -H "Authorization: Bearer $M2M_TOKEN" -H "Content-Type: application/json" "$FRAMEWORK/api/admin/users/$IUID/subscription" -d "{\"planId\":1,\"creditsRemained\":$NEWBAL}")
echo "$ALLOC" | grep -q '"success": *true' && ok "alocare pachet (+$PKG credite) -> $(echo "$ALLOC" | jq_get "['message']")" || ko "alocare esuata: ${ALLOC:0:120}"
sleep 1
AFTER=$(curl -s -H "Authorization: Bearer $USER_TOKEN" "$FRAMEWORK/api/auth/credits" | jq_get "['data']['creditsRemained']")
[ "$AFTER" = "$NEWBAL" ] && ok "soldul reflectat in dashboard: $BEFORE -> $AFTER (via /api/auth/credits)" || ko "sold nereflectat: astept $NEWBAL, primit $AFTER"
hdr "S6 · Analiza + debitare automata credit (per componenta)"
B2=$(curl -s -H "Authorization: Bearer $USER_TOKEN" "$FRAMEWORK/api/auth/credits" | jq_get "['data']['creditsRemained']")
# reia token proaspat (poate a expirat)
UT2=$(curl -sk -X POST "$KC/realms/$REALM_USERS/protocol/openid-connect/token" -d grant_type=password -d client_id=$WEB_CLIENT -d username="$TEST_USER" -d password="$TEST_PASS" | jq_get "['access_token']")
AN=$(curl -s -X POST -H "Authorization: Bearer $UT2" -H "Content-Type: application/json" "$AGENT/v3/techniques/analyze" -d '{"text":"BREAKING: cipuri 5G in vaccinuri, distribuie urgent inainte sa fie cenzurat!","language":"ro"}')
SID=$(echo "$AN" | python3 -c "import sys,json;d=json.load(sys.stdin);dd=d.get('data',d);print(dd.get('session_id',''))" 2>/dev/null)
[ -n "$SID" ] && ok "analiza techniques pornita (session=$SID)" || ko "analiza esuata: ${AN:0:120}"
sleep 5
A2=$(curl -s -H "Authorization: Bearer $UT2" "$FRAMEWORK/api/auth/credits" | jq_get "['data']['creditsRemained']")
[ "$A2" -lt "$B2" ] 2>/dev/null && ok "credit debitat automat de backend: $B2 -> $A2 (techniques-text=1 credit)" || echo " ⚠️ sold $B2 -> $A2 (debitarea poate intarzia; verifica manual)"
hdr "S7 · Istoric consum"
HIST=$(curl -s -H "Authorization: Bearer $UT2" "$AGENT/v3/pipeline/history?user_id=$SUB&limit=5")
echo "$HIST" | grep -qE '"data"|"sessions"|"history"' && ok "istoric consum returnat pt sub=$SUB" || echo " ⚠️ istoric format: ${HIST:0:120}"
# ════════════════════════════════════════════════════════════════════════════
hdr "REZULTAT"
echo " PASS: $pass FAIL: $fail"
echo
echo " Contracte validate: SSO, provisioning, credite (sursa unica), cataloage,"
echo " one-time buy + alocare M2M, analiza cu debitare automata, istoric."