@zauru-sdk/services 1.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +32 -0
- package/LICENCE.md +11 -0
- package/dist/common.server.d.ts +55 -0
- package/dist/common.server.js +179 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.js +8 -0
- package/dist/sessions/sessions.server.d.ts +2 -0
- package/dist/sessions/sessions.server.js +13 -0
- package/dist/sessions/upstash.server.d.ts +1 -0
- package/dist/sessions/upstash.server.js +52 -0
- package/dist/zauru/httpGraphQL.server.d.ts +2 -0
- package/dist/zauru/httpGraphQL.server.js +37 -0
- package/dist/zauru/httpOauth.server.d.ts +2 -0
- package/dist/zauru/httpOauth.server.js +37 -0
- package/dist/zauru/httpZauru.server.d.ts +14 -0
- package/dist/zauru/httpZauru.server.js +51 -0
- package/dist/zauru/zauru-agencies.server.d.ts +9 -0
- package/dist/zauru/zauru-agencies.server.js +21 -0
- package/dist/zauru/zauru-profiles.server.d.ts +167 -0
- package/dist/zauru/zauru-profiles.server.js +68 -0
- package/package.json +31 -0
- package/src/common.server.ts +293 -0
- package/src/index.ts +11 -0
- package/src/sessions/sessions.server.ts +17 -0
- package/src/sessions/upstash.server.ts +55 -0
- package/src/zauru/httpGraphQL.server.ts +55 -0
- package/src/zauru/httpOauth.server.ts +55 -0
- package/src/zauru/httpZauru.server.ts +78 -0
- package/src/zauru/zauru-agencies.server.ts +35 -0
- package/src/zauru/zauru-profiles.server.ts +243 -0
- package/tsconfig.json +24 -0
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
import type { Session } from "@remix-run/node";
|
|
2
|
+
import type { AxiosUtilsResponse } from "./httpZauru.server.js";
|
|
3
|
+
import { EmployeeGraphQL } from "@zauru-sdk/graphql";
|
|
4
|
+
interface Logo {
|
|
5
|
+
url: null | string;
|
|
6
|
+
thumb: {
|
|
7
|
+
url: null | string;
|
|
8
|
+
};
|
|
9
|
+
standard: {
|
|
10
|
+
url: null | string;
|
|
11
|
+
};
|
|
12
|
+
header: {
|
|
13
|
+
url: null | string;
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
export type OauthProfile = {
|
|
17
|
+
id: number;
|
|
18
|
+
uid: number;
|
|
19
|
+
username: string;
|
|
20
|
+
name: string;
|
|
21
|
+
time_zone: string;
|
|
22
|
+
mobile_phone: string;
|
|
23
|
+
admin: boolean;
|
|
24
|
+
selected_entity: number;
|
|
25
|
+
selected_entity_name: string;
|
|
26
|
+
selected_entity_logo: string;
|
|
27
|
+
selected_entity_role: number;
|
|
28
|
+
employee_id: number;
|
|
29
|
+
crm_admin: boolean;
|
|
30
|
+
crm_supervisor: boolean;
|
|
31
|
+
crm_user: boolean;
|
|
32
|
+
currency_id: number;
|
|
33
|
+
currency_name: string;
|
|
34
|
+
currency_prefix: string;
|
|
35
|
+
api_key: string;
|
|
36
|
+
scope: string;
|
|
37
|
+
email: string;
|
|
38
|
+
};
|
|
39
|
+
interface Entity {
|
|
40
|
+
id: number;
|
|
41
|
+
name: string;
|
|
42
|
+
tin: string;
|
|
43
|
+
country: string;
|
|
44
|
+
currency_id: number;
|
|
45
|
+
entity_type_id: number;
|
|
46
|
+
industry: string;
|
|
47
|
+
web: string;
|
|
48
|
+
notes: string;
|
|
49
|
+
vat: number;
|
|
50
|
+
vat_included: boolean;
|
|
51
|
+
logo: Logo;
|
|
52
|
+
logo_2: Logo;
|
|
53
|
+
created_at: string;
|
|
54
|
+
updated_at: string;
|
|
55
|
+
distributor: number;
|
|
56
|
+
costing_method: string;
|
|
57
|
+
address: string;
|
|
58
|
+
state: string;
|
|
59
|
+
city: string;
|
|
60
|
+
income_tax: number;
|
|
61
|
+
report_logo: Logo;
|
|
62
|
+
distributor_contract_id: number | null;
|
|
63
|
+
producer_contract_id: number | null;
|
|
64
|
+
legal_representative_name: string | null;
|
|
65
|
+
legal_representative_identification: string | null;
|
|
66
|
+
legal_representative_birthday: string | null;
|
|
67
|
+
legal_representative_gender: boolean;
|
|
68
|
+
legal_representative_marital_status: string | null;
|
|
69
|
+
legal_representative_occupation: string | null;
|
|
70
|
+
legal_representative_nationality: string | null;
|
|
71
|
+
exporter_code: string | null;
|
|
72
|
+
}
|
|
73
|
+
export type Agency = {
|
|
74
|
+
id: number;
|
|
75
|
+
zid: number;
|
|
76
|
+
active: boolean;
|
|
77
|
+
ean13: string;
|
|
78
|
+
name: string;
|
|
79
|
+
employee_id: number | null;
|
|
80
|
+
updater_id: number;
|
|
81
|
+
entity_id: number;
|
|
82
|
+
virtual: boolean;
|
|
83
|
+
virtual_type: string | null;
|
|
84
|
+
warehouse: boolean;
|
|
85
|
+
point_of_sale: boolean;
|
|
86
|
+
workshop: boolean;
|
|
87
|
+
factory: boolean;
|
|
88
|
+
contact: string;
|
|
89
|
+
city: string;
|
|
90
|
+
address_line_1: string;
|
|
91
|
+
address_line_2: string;
|
|
92
|
+
phone: string;
|
|
93
|
+
notes: string;
|
|
94
|
+
created_at: string;
|
|
95
|
+
updated_at: string;
|
|
96
|
+
price_list_id: number | null;
|
|
97
|
+
quote: boolean;
|
|
98
|
+
ecommerce: boolean;
|
|
99
|
+
external_storage_service_name: string;
|
|
100
|
+
agency_category_id: number | null;
|
|
101
|
+
};
|
|
102
|
+
export type Membership = {
|
|
103
|
+
id: number;
|
|
104
|
+
active: boolean;
|
|
105
|
+
current: boolean;
|
|
106
|
+
reference: string;
|
|
107
|
+
starts: string;
|
|
108
|
+
expires: string;
|
|
109
|
+
eternal: boolean;
|
|
110
|
+
entity_id: number;
|
|
111
|
+
notes: string;
|
|
112
|
+
created_at: string;
|
|
113
|
+
updated_at: string;
|
|
114
|
+
licenses_count: number;
|
|
115
|
+
entity: Entity;
|
|
116
|
+
};
|
|
117
|
+
type Profile = {
|
|
118
|
+
id: number;
|
|
119
|
+
email: string;
|
|
120
|
+
active: boolean;
|
|
121
|
+
admin: boolean;
|
|
122
|
+
name: string;
|
|
123
|
+
address: null | string;
|
|
124
|
+
mobile_phone: string;
|
|
125
|
+
birthday: null | string;
|
|
126
|
+
gender: boolean;
|
|
127
|
+
notes: null | string;
|
|
128
|
+
time_zone: string;
|
|
129
|
+
language: string;
|
|
130
|
+
selected_entity_id: number;
|
|
131
|
+
created_at: string;
|
|
132
|
+
updated_at: string;
|
|
133
|
+
authentication_token: string;
|
|
134
|
+
provider: string;
|
|
135
|
+
provider_token: string;
|
|
136
|
+
};
|
|
137
|
+
export type ProfileResponse = {
|
|
138
|
+
profile: Profile;
|
|
139
|
+
memberships: Membership[];
|
|
140
|
+
};
|
|
141
|
+
/**
|
|
142
|
+
* getOauthUserInfo
|
|
143
|
+
* @param codeValue
|
|
144
|
+
* @returns
|
|
145
|
+
*/
|
|
146
|
+
export declare const getOauthUserInfo: (codeValue: string) => Promise<AxiosUtilsResponse<OauthProfile>>;
|
|
147
|
+
/**
|
|
148
|
+
*
|
|
149
|
+
* @param employeeId
|
|
150
|
+
* @param headers
|
|
151
|
+
* @returns
|
|
152
|
+
*/
|
|
153
|
+
export declare const getEmployeeInfo: (id: number, headers: any) => Promise<AxiosUtilsResponse<EmployeeGraphQL>>;
|
|
154
|
+
/**
|
|
155
|
+
* getProfileInformation
|
|
156
|
+
* @param headers
|
|
157
|
+
* @returns
|
|
158
|
+
*/
|
|
159
|
+
export declare const getProfileInformation: (headers: any) => Promise<AxiosUtilsResponse<ProfileResponse>>;
|
|
160
|
+
export declare const changeEntity: (headers: any, entityId: string) => Promise<any>;
|
|
161
|
+
/**
|
|
162
|
+
*
|
|
163
|
+
* @param headers
|
|
164
|
+
* @returns
|
|
165
|
+
*/
|
|
166
|
+
export declare const getAgencyInfo: (headers: any, session: Session) => Promise<AxiosUtilsResponse<Agency>>;
|
|
167
|
+
export {};
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import httpZauru, { handlePossibleAxiosErrors } from "./httpZauru.server.js";
|
|
2
|
+
import httpOauth from "./httpOauth.server.js";
|
|
3
|
+
import { config } from "@zauru-sdk/config";
|
|
4
|
+
/**
|
|
5
|
+
* getOauthUserInfo
|
|
6
|
+
* @param codeValue
|
|
7
|
+
* @returns
|
|
8
|
+
*/
|
|
9
|
+
export const getOauthUserInfo = async (codeValue) => {
|
|
10
|
+
return handlePossibleAxiosErrors(async () => {
|
|
11
|
+
const response = await httpOauth.get(`/api/userinfo`, {
|
|
12
|
+
headers: {
|
|
13
|
+
Authorization: `Bearer ${codeValue}`,
|
|
14
|
+
},
|
|
15
|
+
});
|
|
16
|
+
return response.data;
|
|
17
|
+
});
|
|
18
|
+
};
|
|
19
|
+
/**
|
|
20
|
+
*
|
|
21
|
+
* @param employeeId
|
|
22
|
+
* @param headers
|
|
23
|
+
* @returns
|
|
24
|
+
*/
|
|
25
|
+
export const getEmployeeInfo = async (id, headers) => {
|
|
26
|
+
return handlePossibleAxiosErrors(async () => {
|
|
27
|
+
const employeeInfo = await httpZauru.get(`/settings/employees/${id}.json`, { headers });
|
|
28
|
+
return employeeInfo.data;
|
|
29
|
+
});
|
|
30
|
+
};
|
|
31
|
+
/**
|
|
32
|
+
* getProfileInformation
|
|
33
|
+
* @param headers
|
|
34
|
+
* @returns
|
|
35
|
+
*/
|
|
36
|
+
export const getProfileInformation = async (headers) => {
|
|
37
|
+
return handlePossibleAxiosErrors(async () => {
|
|
38
|
+
const response = await httpZauru.get(`/profile.json`, {
|
|
39
|
+
headers,
|
|
40
|
+
});
|
|
41
|
+
return response.data;
|
|
42
|
+
});
|
|
43
|
+
};
|
|
44
|
+
export const changeEntity = async (headers, entityId) => {
|
|
45
|
+
const changeEntityFetch = await httpZauru.patch(`${config.zauruBaseURL}/company.json`, JSON.stringify({
|
|
46
|
+
selected_entity_id: entityId,
|
|
47
|
+
}), {
|
|
48
|
+
headers,
|
|
49
|
+
});
|
|
50
|
+
return changeEntityFetch.data;
|
|
51
|
+
};
|
|
52
|
+
/**
|
|
53
|
+
*
|
|
54
|
+
* @param headers
|
|
55
|
+
* @returns
|
|
56
|
+
*/
|
|
57
|
+
export const getAgencyInfo = async (headers, session) => {
|
|
58
|
+
return handlePossibleAxiosErrors(async () => {
|
|
59
|
+
const agency_id = session.get("agency_id");
|
|
60
|
+
if (!agency_id) {
|
|
61
|
+
throw new Error("No hay una agencia asignada para este usuario... Contacte con su administrador.");
|
|
62
|
+
}
|
|
63
|
+
const response = await httpZauru.get(`/settings/agencies/${agency_id}.json`, {
|
|
64
|
+
headers,
|
|
65
|
+
});
|
|
66
|
+
return response?.data;
|
|
67
|
+
});
|
|
68
|
+
};
|
package/package.json
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@zauru-sdk/services",
|
|
3
|
+
"version": "1.0.4",
|
|
4
|
+
"description": "Configuración centralizada para aplicaciones Zauru SDK",
|
|
5
|
+
"main": "dist/index.js",
|
|
6
|
+
"types": "dist/index.d.ts",
|
|
7
|
+
"type": "module",
|
|
8
|
+
"publishConfig": {
|
|
9
|
+
"access": "public"
|
|
10
|
+
},
|
|
11
|
+
"scripts": {
|
|
12
|
+
"build": "tsc",
|
|
13
|
+
"test": "echo \"Error: no test specified\" && exit 1"
|
|
14
|
+
},
|
|
15
|
+
"author": "Oscar Cuéllar",
|
|
16
|
+
"license": "MIT",
|
|
17
|
+
"devDependencies": {
|
|
18
|
+
"typescript": "^5.1.6"
|
|
19
|
+
},
|
|
20
|
+
"dependencies": {
|
|
21
|
+
"@remix-run/node": "^2.8.1",
|
|
22
|
+
"@zauru-sdk/config": "^1.0.4",
|
|
23
|
+
"@zauru-sdk/graphql": "^1.0.4",
|
|
24
|
+
"axios": "^1.6.7",
|
|
25
|
+
"chalk": "5.3.0"
|
|
26
|
+
},
|
|
27
|
+
"engines": {
|
|
28
|
+
"node": ">=18.0.0"
|
|
29
|
+
},
|
|
30
|
+
"gitHead": "75cef0c437edf8240adc811bc7b395e1030adf90"
|
|
31
|
+
}
|
|
@@ -0,0 +1,293 @@
|
|
|
1
|
+
import { Session, redirect } from "@remix-run/node";
|
|
2
|
+
import { commitSession, getSession } from "./sessions/sessions.server.js";
|
|
3
|
+
import { AxiosRequestHeaders } from "axios";
|
|
4
|
+
import chalk from "chalk";
|
|
5
|
+
import httpZauru, {
|
|
6
|
+
AxiosUtilsResponse,
|
|
7
|
+
handlePossibleAxiosErrors,
|
|
8
|
+
} from "./zauru/httpZauru.server.js";
|
|
9
|
+
import {
|
|
10
|
+
Agency,
|
|
11
|
+
OauthProfile,
|
|
12
|
+
ProfileResponse,
|
|
13
|
+
getAgencyInfo,
|
|
14
|
+
getEmployeeInfo,
|
|
15
|
+
getOauthUserInfo,
|
|
16
|
+
getProfileInformation,
|
|
17
|
+
} from "./zauru/zauru-profiles.server.js";
|
|
18
|
+
import { EmployeeGraphQL } from "@zauru-sdk/graphql";
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* loginWebApp
|
|
22
|
+
* @param session
|
|
23
|
+
* @param codeValue
|
|
24
|
+
* @param cookie
|
|
25
|
+
* @returns
|
|
26
|
+
*/
|
|
27
|
+
export const loginWebApp = async (
|
|
28
|
+
session: Session,
|
|
29
|
+
codeValue: string,
|
|
30
|
+
cookie: string
|
|
31
|
+
): Promise<
|
|
32
|
+
AxiosUtilsResponse<{
|
|
33
|
+
headers: any;
|
|
34
|
+
oauthProfile: OauthProfile;
|
|
35
|
+
employeeProfile: EmployeeGraphQL;
|
|
36
|
+
userProfile: ProfileResponse;
|
|
37
|
+
agencyProfile: Agency;
|
|
38
|
+
}>
|
|
39
|
+
> => {
|
|
40
|
+
return handlePossibleAxiosErrors(async () => {
|
|
41
|
+
const userInfoResponse = await getOauthUserInfo(codeValue ?? "");
|
|
42
|
+
if (userInfoResponse.error) {
|
|
43
|
+
throw new Error(userInfoResponse.userMsg);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const userInfo = userInfoResponse.data;
|
|
47
|
+
session.set("username", userInfo?.username);
|
|
48
|
+
session.set("token", userInfo?.api_key);
|
|
49
|
+
session.set("code", codeValue);
|
|
50
|
+
session.set("name", userInfo?.name);
|
|
51
|
+
session.set("email", userInfo?.email);
|
|
52
|
+
session.set("employee_id", userInfo?.employee_id);
|
|
53
|
+
|
|
54
|
+
const headers = await getHeaders(cookie, session, {
|
|
55
|
+
token: userInfo?.api_key ?? "",
|
|
56
|
+
username: userInfo?.username ?? "",
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
const res_emp = await getEmployeeInfo(userInfo?.employee_id ?? 0, headers);
|
|
60
|
+
if (res_emp.error) {
|
|
61
|
+
throw new Error(res_emp.userMsg);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const empInfo = res_emp.data;
|
|
65
|
+
session.set("agency_id", empInfo?.agency_id);
|
|
66
|
+
session.set("email", empInfo?.email);
|
|
67
|
+
session.set("selectedEntity", empInfo?.entity_id);
|
|
68
|
+
|
|
69
|
+
const profileInfoResponse = await getProfileInformation(headers);
|
|
70
|
+
if (profileInfoResponse.error) {
|
|
71
|
+
throw new Error(profileInfoResponse.userMsg);
|
|
72
|
+
}
|
|
73
|
+
const profileInfo = profileInfoResponse.data;
|
|
74
|
+
|
|
75
|
+
if (!profileInfo?.memberships?.length) {
|
|
76
|
+
throw new Error("El usuario no tiene suscripciones...");
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const membership = profileInfo?.memberships?.filter(
|
|
80
|
+
(member: any) => member?.entity?.id === empInfo?.entity_id
|
|
81
|
+
);
|
|
82
|
+
|
|
83
|
+
if (!membership) {
|
|
84
|
+
throw new Error(
|
|
85
|
+
"No se encontró una suscripción para este usuario en la entidad asignada."
|
|
86
|
+
);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
if (membership?.length)
|
|
90
|
+
session.set("entityName", membership[0]?.entity?.name);
|
|
91
|
+
|
|
92
|
+
const agencyInfoResponse = await getAgencyInfo(headers, session);
|
|
93
|
+
if (agencyInfoResponse.error) {
|
|
94
|
+
throw new Error(agencyInfoResponse.userMsg);
|
|
95
|
+
}
|
|
96
|
+
session.set("agency_name", agencyInfoResponse.data?.name);
|
|
97
|
+
|
|
98
|
+
return {
|
|
99
|
+
headers,
|
|
100
|
+
oauthProfile: userInfo as OauthProfile,
|
|
101
|
+
employeeProfile: empInfo as EmployeeGraphQL,
|
|
102
|
+
userProfile: profileInfo as ProfileResponse,
|
|
103
|
+
agencyProfile: agencyInfoResponse.data as Agency,
|
|
104
|
+
};
|
|
105
|
+
});
|
|
106
|
+
};
|
|
107
|
+
|
|
108
|
+
export type GraphQLToken = {
|
|
109
|
+
status: number;
|
|
110
|
+
message: string;
|
|
111
|
+
token: string;
|
|
112
|
+
expires: string;
|
|
113
|
+
expiresMsg: string;
|
|
114
|
+
graphqlUrl: string;
|
|
115
|
+
};
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Obtiene los headers que se usan en todos los endpoints de zauru
|
|
119
|
+
* @param cookie
|
|
120
|
+
* @param _session La session es opcional, se envía sólo si ya se tiene a la mano, para ya no volverla a consultar.
|
|
121
|
+
* @returns
|
|
122
|
+
*/
|
|
123
|
+
export const getHeaders = async (
|
|
124
|
+
cookie: string | null,
|
|
125
|
+
_session?: Session | null,
|
|
126
|
+
config?: { token: string; username: string } | null,
|
|
127
|
+
extraConfig?: { withOutContentType: string }
|
|
128
|
+
) => {
|
|
129
|
+
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>Session and Header Info<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
|
|
130
|
+
const session = _session ?? (await getSession(cookie));
|
|
131
|
+
|
|
132
|
+
if (!session.has("username") && !config) {
|
|
133
|
+
redirect("/");
|
|
134
|
+
return {};
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
const headers = {
|
|
138
|
+
"X-User-Email": config?.username ?? session.get("username"),
|
|
139
|
+
"X-User-Token": config?.token ?? session.get("token"),
|
|
140
|
+
"Content-type": "application/json",
|
|
141
|
+
Accept: "application/json",
|
|
142
|
+
} as { [key: string]: string };
|
|
143
|
+
|
|
144
|
+
if (extraConfig?.withOutContentType) {
|
|
145
|
+
delete headers["Content-type"];
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
return headers;
|
|
149
|
+
};
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* getGraphQLToken
|
|
153
|
+
* @param session
|
|
154
|
+
* @returns
|
|
155
|
+
*/
|
|
156
|
+
async function getGraphQLToken(
|
|
157
|
+
session: Session
|
|
158
|
+
): Promise<AxiosUtilsResponse<GraphQLToken>> {
|
|
159
|
+
return handlePossibleAxiosErrors(async () => {
|
|
160
|
+
const token = (await session.get("graphqlToken")) as GraphQLToken;
|
|
161
|
+
const headers = (await getHeaders(null, session)) as any;
|
|
162
|
+
|
|
163
|
+
const tokenHasExpired =
|
|
164
|
+
token &&
|
|
165
|
+
token.expires &&
|
|
166
|
+
new Date(new Date().getTime() - 3 * 60 * 60 * 1000) >=
|
|
167
|
+
new Date(token.expires);
|
|
168
|
+
|
|
169
|
+
//Si no hay token, es la primera vez que se recibe, lo voy a traer de zauru
|
|
170
|
+
if (!token || tokenHasExpired) {
|
|
171
|
+
tokenHasExpired
|
|
172
|
+
? console.log(
|
|
173
|
+
chalk.yellow(
|
|
174
|
+
`=============== ⚠️ EL TOKEN GRAPHQL ESTÁ EXPIRADO ⚠️ ====================`
|
|
175
|
+
)
|
|
176
|
+
)
|
|
177
|
+
: console.log(
|
|
178
|
+
chalk.yellow(
|
|
179
|
+
`=============== ⚠️ NO HAY UN TOKEN GRAPHQL GUARDADO ⚠️ ====================`
|
|
180
|
+
)
|
|
181
|
+
);
|
|
182
|
+
|
|
183
|
+
const responseToken = await httpZauru.get<GraphQLToken>(
|
|
184
|
+
"/apps/graphql.json",
|
|
185
|
+
{
|
|
186
|
+
headers,
|
|
187
|
+
}
|
|
188
|
+
);
|
|
189
|
+
|
|
190
|
+
if (responseToken.data) {
|
|
191
|
+
session.set("graphqlToken", responseToken.data);
|
|
192
|
+
await commitSession(session);
|
|
193
|
+
console.log(
|
|
194
|
+
chalk.green(
|
|
195
|
+
`=============== ✅ TOKEN GRAPHQL GUARDADO EN SESION Y DEVUELTO ✅ ====================`
|
|
196
|
+
)
|
|
197
|
+
);
|
|
198
|
+
return responseToken.data;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
console.log(
|
|
202
|
+
chalk.red(
|
|
203
|
+
`=============== ❗ NO HAY INFORMACIÓN OBTENIDA DEL REQUEST A ZAURU - GET_TOKEN ❗ ====================`
|
|
204
|
+
)
|
|
205
|
+
);
|
|
206
|
+
throw new Error(
|
|
207
|
+
"No viene información en la solicitud de getGraphQLToken a Zauru"
|
|
208
|
+
);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
//Si ya está guardado un token en la sesión y aún no a expirado.
|
|
212
|
+
return token;
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* getGraphQLAPIHeaders
|
|
218
|
+
* @param session
|
|
219
|
+
* @returns
|
|
220
|
+
*/
|
|
221
|
+
export const getGraphQLAPIHeaders = async (session: Session) => {
|
|
222
|
+
const { data: token, error, userMsg } = await getGraphQLToken(session);
|
|
223
|
+
|
|
224
|
+
if (error) {
|
|
225
|
+
console.log(
|
|
226
|
+
chalk.red(
|
|
227
|
+
`=============== ❗ OCURRIÓ UN ERROR DEL REQUEST A ZAURU - GET_TOKEN ❗ ==================== ${userMsg}`
|
|
228
|
+
)
|
|
229
|
+
);
|
|
230
|
+
return {
|
|
231
|
+
Authorization: `Bearer token_no_existe`,
|
|
232
|
+
"Content-Type": "application/json",
|
|
233
|
+
} as AxiosRequestHeaders;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
return {
|
|
237
|
+
Authorization: `Bearer ${token?.token}`,
|
|
238
|
+
"Content-Type": "application/json",
|
|
239
|
+
} as AxiosRequestHeaders;
|
|
240
|
+
};
|
|
241
|
+
|
|
242
|
+
export type SessionMessage = { id: string; title: string; message: string };
|
|
243
|
+
export const saveSessionMessage = async (
|
|
244
|
+
session: Session,
|
|
245
|
+
info: SessionMessage
|
|
246
|
+
): Promise<void> => {
|
|
247
|
+
const updateTasks = (session.get("sessionMessages") ??
|
|
248
|
+
[]) as SessionMessage[];
|
|
249
|
+
session.set("updateTasks", [...updateTasks, info]);
|
|
250
|
+
await commitSession(session);
|
|
251
|
+
};
|
|
252
|
+
|
|
253
|
+
export const deleteSessionMessage = async (
|
|
254
|
+
session: Session,
|
|
255
|
+
id: string
|
|
256
|
+
): Promise<boolean> => {
|
|
257
|
+
let updateTasks = session.get("sessionMessages") as Array<SessionMessage>;
|
|
258
|
+
if (
|
|
259
|
+
Array.isArray(updateTasks) &&
|
|
260
|
+
updateTasks.some((task: SessionMessage) => task.id === id)
|
|
261
|
+
) {
|
|
262
|
+
//La elimino de la lista
|
|
263
|
+
updateTasks = updateTasks.filter((task) => task.id !== id);
|
|
264
|
+
session.set("sessionMessages", updateTasks);
|
|
265
|
+
await commitSession(session);
|
|
266
|
+
return true;
|
|
267
|
+
}
|
|
268
|
+
return false;
|
|
269
|
+
};
|
|
270
|
+
|
|
271
|
+
function generarUUID() {
|
|
272
|
+
// Retorna un arreglo de 9 bytes con valores aleatorios
|
|
273
|
+
const array = new Uint8Array(9);
|
|
274
|
+
crypto.getRandomValues(array);
|
|
275
|
+
|
|
276
|
+
// Convertir Uint8Array a array normal
|
|
277
|
+
const normalArray = Array.from(array);
|
|
278
|
+
|
|
279
|
+
// Codificación en base 64
|
|
280
|
+
const base64 = btoa(String.fromCharCode.apply(null, normalArray))
|
|
281
|
+
.replace("+", "0") // Reemplaza caracteres no alfanuméricos
|
|
282
|
+
.replace("/", "1")
|
|
283
|
+
.substring(0, 11); // Acorta a 11 caracteres
|
|
284
|
+
|
|
285
|
+
return base64;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
// Función para generar un código de producto a partir de un UUID
|
|
289
|
+
export function generateDistinctCode(prefix: string) {
|
|
290
|
+
const uuid = generarUUID();
|
|
291
|
+
const codigoProducto = `${prefix}-${uuid}`;
|
|
292
|
+
return codigoProducto;
|
|
293
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export * from "./common.server.js";
|
|
2
|
+
|
|
3
|
+
export * from "./sessions/sessions.server.js";
|
|
4
|
+
export * from "./sessions/upstash.server.js";
|
|
5
|
+
|
|
6
|
+
export * from "./zauru/httpGraphQL.server.js";
|
|
7
|
+
export * from "./zauru/httpOauth.server.js";
|
|
8
|
+
export * from "./zauru/httpZauru.server.js";
|
|
9
|
+
|
|
10
|
+
export * from "./zauru/zauru-agencies.server.js";
|
|
11
|
+
export * from "./zauru/zauru-profiles.server.js";
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { createCookie } from "@remix-run/node";
|
|
2
|
+
import { createUpstashSessionStorage } from "./upstash.server.js";
|
|
3
|
+
|
|
4
|
+
const sessionCookie = createCookie("_rj_session", {
|
|
5
|
+
secrets: ["r3m1xr0ck1"],
|
|
6
|
+
path: "/",
|
|
7
|
+
sameSite: process.env.NODE_ENV === "production" ? "none" : "lax",
|
|
8
|
+
httpOnly: true,
|
|
9
|
+
maxAge: 60 * 60 * 24,
|
|
10
|
+
//expires,
|
|
11
|
+
secure: process.env.NODE_ENV === "production",
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
const { getSession, commitSession, destroySession } =
|
|
15
|
+
createUpstashSessionStorage({ cookie: sessionCookie });
|
|
16
|
+
|
|
17
|
+
export { getSession, commitSession, destroySession };
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { createSessionStorage } from "@remix-run/node";
|
|
2
|
+
import crypto from "crypto";
|
|
3
|
+
import { config } from "@zauru-sdk/config";
|
|
4
|
+
|
|
5
|
+
const redisBaseURL = config.redisBaseURL;
|
|
6
|
+
|
|
7
|
+
const headers = {
|
|
8
|
+
Authorization: `Bearer ${config.redisToken}`,
|
|
9
|
+
Accept: "application/json",
|
|
10
|
+
"Content-Type": "application/json",
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
const expiresToSeconds = (expires: Date | undefined) => {
|
|
14
|
+
return 3600 * 8;
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
// For more info check https://remix.run/docs/en/v1/api/remix#createsessionstorage
|
|
18
|
+
export function createUpstashSessionStorage({ cookie }: any) {
|
|
19
|
+
return createSessionStorage({
|
|
20
|
+
cookie,
|
|
21
|
+
async createData(data, expires) {
|
|
22
|
+
const id: string = crypto.randomUUID();
|
|
23
|
+
await fetch(`${redisBaseURL}/set/${id}?EX=${expiresToSeconds(expires)}`, {
|
|
24
|
+
method: "post",
|
|
25
|
+
body: JSON.stringify({ data }),
|
|
26
|
+
headers,
|
|
27
|
+
});
|
|
28
|
+
return id;
|
|
29
|
+
},
|
|
30
|
+
async readData(id) {
|
|
31
|
+
const response = await fetch(`${redisBaseURL}/get/${id}`, {
|
|
32
|
+
headers,
|
|
33
|
+
});
|
|
34
|
+
try {
|
|
35
|
+
const { result } = (await response.json()) as any;
|
|
36
|
+
return JSON.parse(result).data;
|
|
37
|
+
} catch (error) {
|
|
38
|
+
return null;
|
|
39
|
+
}
|
|
40
|
+
},
|
|
41
|
+
async updateData(id, data, expires) {
|
|
42
|
+
await fetch(`${redisBaseURL}/set/${id}?EX=${expiresToSeconds(expires)}`, {
|
|
43
|
+
method: "post",
|
|
44
|
+
body: JSON.stringify({ data }),
|
|
45
|
+
headers,
|
|
46
|
+
});
|
|
47
|
+
},
|
|
48
|
+
async deleteData(id) {
|
|
49
|
+
await fetch(`${redisBaseURL}/del/${id}`, {
|
|
50
|
+
method: "post",
|
|
51
|
+
headers,
|
|
52
|
+
});
|
|
53
|
+
},
|
|
54
|
+
});
|
|
55
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import axios from "axios";
|
|
2
|
+
import chalk from "chalk";
|
|
3
|
+
import { config } from "@zauru-sdk/config";
|
|
4
|
+
|
|
5
|
+
const axiosInstance = axios.create({
|
|
6
|
+
baseURL: `${config.graphqlAPIBaseURL}`,
|
|
7
|
+
});
|
|
8
|
+
|
|
9
|
+
axiosInstance.interceptors.request.use(
|
|
10
|
+
function (request) {
|
|
11
|
+
// Do something before request is sent
|
|
12
|
+
console.log("---------------- EJECUTANDO REQUEST GRAPHQL ----------------");
|
|
13
|
+
//console.time(`${request.baseURL}${request.url}`);
|
|
14
|
+
console.log(chalk.green(`${request.baseURL}${request.url}`));
|
|
15
|
+
request.timeout = 120000;
|
|
16
|
+
|
|
17
|
+
return request;
|
|
18
|
+
},
|
|
19
|
+
function (error) {
|
|
20
|
+
console.log(
|
|
21
|
+
chalk.red("---------------- ERROR CON REQUEST GRAPHQL ----------------")
|
|
22
|
+
);
|
|
23
|
+
console.log(`${error}`);
|
|
24
|
+
// Do something with request error
|
|
25
|
+
return Promise.reject(error);
|
|
26
|
+
}
|
|
27
|
+
);
|
|
28
|
+
|
|
29
|
+
// Add a response interceptor
|
|
30
|
+
axiosInstance.interceptors.response.use(
|
|
31
|
+
function (response) {
|
|
32
|
+
// Do something with response data
|
|
33
|
+
//console.timeEnd(`${response.config.baseURL}${response.config.url}`);
|
|
34
|
+
return response;
|
|
35
|
+
},
|
|
36
|
+
function (error) {
|
|
37
|
+
console.log(
|
|
38
|
+
chalk.red("---------------- ERROR CON REQUEST GRAPHQL ----------------")
|
|
39
|
+
);
|
|
40
|
+
console.log(`${error}`);
|
|
41
|
+
// Do something with response error
|
|
42
|
+
const { response } = error;
|
|
43
|
+
const msgError = response
|
|
44
|
+
? `HTTP ${response.status} ${response.statusText} - URL: ${
|
|
45
|
+
response?.config?.baseURL
|
|
46
|
+
}${response?.config?.url} - ${JSON.stringify(response?.data)}`
|
|
47
|
+
: error;
|
|
48
|
+
console.log(chalk.red(`${msgError}`));
|
|
49
|
+
throw new Error(msgError);
|
|
50
|
+
}
|
|
51
|
+
);
|
|
52
|
+
|
|
53
|
+
const httpGraphQLAPI = axiosInstance;
|
|
54
|
+
|
|
55
|
+
export default httpGraphQLAPI;
|