Compare commits

...
4 Commits
7 changed files with 114 additions and 18 deletions
+3
View File
@@ -13,6 +13,9 @@ CLAIM_V2_TOTAL_PAYMENT_CAP_TOMAN=53000000
# 🌐 Application URLs
# ---------------------------------------------
URL =
# Optional path where the user panel is mounted behind the public URL.
# Example: URL=https://chatr.parsianinsurance.com/car-damage and USER_BASE_PATH=user
# produces SMS links under https://chatr.parsianinsurance.com/car-damage/user/v1/...
USER_BASE_PATH =
BASE_URL_DEV =
+5
View File
@@ -30,6 +30,11 @@ FANAVARAN_CLIENT=moallem
# CONTRACT_ID=
# LOCATION=
# Moallem is always authenticated against api.inssw.ir. The flow script enforces
# this endpoint even if an inherited API .env contains another Fanavaran host.
# FANAVARAN_BASE_URL=https://api.inssw.ir/BimeApiManager/api
# FANAVARAN_BIME_URL=https://api.inssw.ir/BimeApiManager/api/BimeApi/v2.0
# --- tenant lookup ids (from this insurer's Fanavaran lookups) ---
CLAIM_EXPERT_ID=
EXPERTISE_CLAIM_EXPERT_ID=
+23
View File
@@ -295,6 +295,28 @@ apply_client_auth_defaults() {
esac
}
# Each tenant's authentication token is only valid on the API host that issued
# it. In particular, Moallem uses api.inssw.ir while the other seeded tenants
# use apimanager.iraneit.com. Do not let an inherited API .env or a stale flow
# env file silently send Moallem credentials to the shared host.
apply_client_endpoint_defaults() {
if [[ "$FANAVARAN_CLIENT" != "moallem" ]]; then
return 0
fi
local moallem_api_base="https://api.inssw.ir/BimeApiManager/api"
local moallem_bime_base="$moallem_api_base/BimeApi/v2.0"
if [[ -n "${FANAVARAN_BASE_URL:-}" && "$FANAVARAN_BASE_URL" != "$moallem_api_base" ]]; then
warn "Ignoring FANAVARAN_BASE_URL for moallem; Moallem tokens must use api.inssw.ir"
fi
if [[ -n "${FANAVARAN_BIME_URL:-}" && "$FANAVARAN_BIME_URL" != "$moallem_bime_base" ]]; then
warn "Ignoring FANAVARAN_BIME_URL for moallem; Moallem tokens must use api.inssw.ir"
fi
FANAVARAN_BASE_URL="$moallem_api_base"
FANAVARAN_BIME_URL="$moallem_bime_base"
export FANAVARAN_BASE_URL FANAVARAN_BIME_URL
}
apply_shared_defaults() {
ACCIDENT_CITY_ID="${ACCIDENT_CITY_ID:-701}"
ACCIDENT_REPORT_TYPE_ID="${ACCIDENT_REPORT_TYPE_ID:-155}"
@@ -1042,6 +1064,7 @@ ask_var FANAVARAN_CLIENT "Fanavaran client (parsian|tejaratno|moallem)"
FANAVARAN_CLIENT="${FANAVARAN_CLIENT,,}"
apply_client_auth_defaults
apply_client_endpoint_defaults
apply_shared_defaults
STAGES="$(echo "$STAGES" | tr '[:upper:]' '[:lower:]' | tr -d ' ')"
+46 -11
View File
@@ -29,6 +29,7 @@ loadRootDotEnv();
let running = false;
let sandhubToken = null;
let sandhubTokenAt = 0;
let incompatibleTokenRefresh = null;
function loadRootDotEnv() {
const file = path.join(ROOT, ".env");
@@ -394,13 +395,7 @@ async function fetchRemoteLookup(client, name) {
const rel = LOOKUP_PATHS[name];
if (!rel) throw new Error("Unknown lookup " + name);
const env = loadEnv();
const tokens = loadAuthTokens(client);
if (!tokens || !tokens.AUTHENTICATION_TOKEN) {
throw new Error(
"توکن " + client + " نیست. یک بار Submit بزنید تا لاگین انجام شود، یا scripts/fanavaran-auth.sh " + client,
);
}
const base = fanavaranBimeBaseForToken(client, tokens);
const { tokens, base } = await getCompatibleAuthContext(client);
const result = await curlJson(
"GET",
`${base}/${rel}`,
@@ -464,6 +459,44 @@ function loadAuthTokens(client) {
return parseEnvText(fs.readFileSync(file, "utf8"));
}
/**
* A token cannot be transferred between Fanavaran API hosts. Older Moallem
* flow envs could create a cache on apimanager.iraneit.com; heal that cache on
* first use instead of making the operator discover and delete it manually.
*/
async function getCompatibleAuthContext(client) {
const normalizedClient = String(client || "tejaratno").toLowerCase();
let tokens = loadAuthTokens(normalizedClient);
if (!tokens || !tokens.AUTHENTICATION_TOKEN) {
throw new Error(
"توکن " + normalizedClient + " نیست. ابتدا از بخش Auth وارد شوید.",
);
}
try {
return { tokens, base: fanavaranBimeBaseForToken(normalizedClient, tokens) };
} catch (error) {
const message = String(error?.message || error);
if (!message.startsWith("Cached ") || normalizedClient !== "moallem") throw error;
if (!incompatibleTokenRefresh) {
incompatibleTokenRefresh = runStage("auth", { forceLogin: true }).finally(() => {
incompatibleTokenRefresh = null;
});
}
const refreshed = await incompatibleTokenRefresh;
if (!refreshed.ok) {
throw new Error(
"توکن ناسازگار Moallem به صورت خودکار نوسازی نشد. جزئیات را در خروجی سرور بررسی کنید.",
);
}
tokens = loadAuthTokens(normalizedClient);
if (!tokens || !tokens.AUTHENTICATION_TOKEN) {
throw new Error("نوسازی توکن Moallem انجام شد، اما توکن جدید ذخیره نشد.");
}
return { tokens, base: fanavaranBimeBaseForToken(normalizedClient, tokens) };
}
}
function curlJson(method, url, headers, proxy) {
return new Promise((resolve) => {
const args = ["-sS", "--max-time", "40", "-X", method, url];
@@ -493,11 +526,13 @@ function curlJson(method, url, headers, proxy) {
}
async function inquireParties({ nationalCode, birthYear, birthMonth, birthDay, client, location, proxy }) {
const tokens = loadAuthTokens(client || "tejaratno");
if (!tokens || !tokens.AUTHENTICATION_TOKEN) {
return { ok: false, error: "No cached Fanavaran token. Submit a stage once or run scripts/fanavaran-auth.sh " + (client || "tejaratno") };
let auth;
try {
auth = await getCompatibleAuthContext(client || "tejaratno");
} catch (error) {
return { ok: false, error: String(error?.message || error) };
}
const base = fanavaranBimeBaseForToken(client, tokens);
const { tokens, base } = auth;
const qs = new URLSearchParams({
NationalCode: String(nationalCode || ""),
BirthYear: String(birthYear || ""),
@@ -3820,7 +3820,7 @@ export class ClaimRequestManagementService {
return null;
}
const url = `${getFanavaranLookupBaseUrl(clientKey)}/common/other-people`;
const url = `${getFanavaranLookupBaseUrl(input.clientKey)}/common/other-people`;
const startedAt = Date.now();
const auditSession: FanavaranAuditSession = {
trackingCode: this.fanavaranAuditService.generateTrackingCode(),
@@ -2885,19 +2885,26 @@ export class RequestManagementService {
?.phoneNumber;
const secondPhone = (req.parties?.[secondIdx]?.person as any)
?.phoneNumber;
const baseUrl = process.env.URL;
const token = String(req._id);
const targets = [
firstPhone
? {
receptor: firstPhone,
link: `${baseUrl}/user?token=${token}`,
link: this.smsOrchestrationService.buildBlamePartyLink(
token,
"FIRST",
"v1",
),
}
: null,
secondPhone
? {
receptor: secondPhone,
link: `${baseUrl}/user2?token=${token}`,
link: this.smsOrchestrationService.buildBlamePartyLink(
token,
"SECOND",
"v1",
),
}
: null,
].filter(
@@ -38,12 +38,35 @@ export class SmsOrchestrationService implements OnModuleInit {
);
}
/**
* `URL` is the public application/API base (and is also used for file URLs).
* Some deployments mount the user panel below a separate reverse-proxy path,
* e.g. `/car-damage/user`; keep that panel-only segment out of `URL`.
*/
private userPanelBaseUrl(): string {
const applicationUrl = String(process.env.URL ?? "")
.trim()
.replace(/\/+$/, "");
const userBasePath = String(process.env.USER_BASE_PATH ?? "")
.trim()
.replace(/^\/+|\/+$/g, "");
return userBasePath ? `${applicationUrl}/${userBasePath}` : applicationUrl;
}
private buildUserPanelLink(...segments: string[]): string {
const path = segments
.map((segment) => String(segment).replace(/^\/+|\/+$/g, ""))
.filter(Boolean)
.join("/");
return `${this.userPanelBaseUrl()}/${path}`;
}
buildInviteLink(
frontendRoute: string,
requestId: string,
versionPrefix: string,
): string {
return `${process.env.URL}/${versionPrefix}/${frontendRoute}?token=${requestId}`;
return `${this.buildUserPanelLink(versionPrefix, frontendRoute)}?token=${requestId}`;
}
buildBlamePartyLink(
@@ -52,11 +75,11 @@ export class SmsOrchestrationService implements OnModuleInit {
versionPrefix: string,
): string {
const route = partyRole === "SECOND" ? "user2" : "user";
return `${process.env.URL}/${versionPrefix}/${route}?token=${requestId}`;
return `${this.buildUserPanelLink(versionPrefix, route)}?token=${requestId}`;
}
buildClaimLink(claimRequestId: string, versionPrefix: string): string {
return `${process.env.URL}/${versionPrefix}/caseClaim?token=${claimRequestId}`;
return `${this.buildUserPanelLink(versionPrefix, "caseClaim")}?token=${claimRequestId}`;
}
async sendInviteLink(