-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmedical.script
179 lines (148 loc) · 5.7 KB
/
medical.script
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
// Добавляем меню:
function onOpen() {
SpreadsheetApp.getUi().createMenu("Меню").addItem("Получить данные", "updateOperationJournal").addToUi();
}
// получает данные по api из БД клиники, собирает их в массив и вставляет их во вкладку "Журнал операций" шаблона для фин. аналитики:
let lnkpart = "kt-domodedovo";
function updateOperationJournal() {
let ui = SpreadsheetApp.getUi();
let responseBegin = ui.prompt("Введите дату начала загрузки в формате", "dd.mm.yyyy", ui.ButtonSet.OK_CANCEL);
let startDate = responseBegin.getResponseText().split(".").reverse().join("-"); // дату начала загрузки
let responseEnd = ui.prompt("Введите дату окончания загрузки в формате", "dd.mm.yyyy", ui.ButtonSet.OK_CANCEL);
let endDate = responseEnd.getResponseText().split(".").reverse().join("-"); // дату окончания загрузки
let defParams = {
headers: {
Accept: "application/json",
Authorization: GetToken(),
},
}
// Получаем список счетов через API:
let resultArray = [];
getAppointments().map((item) => {
Utilities.sleep(500);
const client = getClientById(item.clientId);
const user = getUserById(item.userId);
const entries = item.orderId && getEntriesByOrderId(item.orderId);
resultArray.push([
item.date,
`${item.time} ${item.duration} мин`,
getStatus(item.status),
[client.surname, client.name, client.secondName].join(" "),
client.birthdate,
item.orderId && entries.map(item => item.title).join("\n"),
item.orderId && entries.length,
item.orderId && parseFloat(entries.length > 1 ? entries.reduce((prev, curr) => prev.finalsum + curr.finalsum) : entries[0].finalsum),
"", // диск
"", // врач
"", // реферал
"", // company ? company.title : "", // партнеры
`${user.surname} ${user.name.charAt(0)}. ${user.secondName.charAt(0)}.`,
item.note,
getClinicById(item.clinicId).title
]);
});
// Вспомогательные функции:
function getStatus (status) {
switch (status) {
case "need_approval" : return "Не подтвержден";
case "confirmed_by_administrator": return "Подтвержден";
case "approved": return "Подвержден";
case "arrived": return "Клиент пришел";
case "serviced": return "Прием завершен";
case "billed": return "Счет выставлен";
case "paid": return "Счет оплачен";
case "canceled": return "Отменен";
case "failed": return "Неявка";
}
};
function getClientById(id) {
return JSON.parse(UrlFetchApp.fetch(`https://${lnkpart}.medods.ru/api/v2/clients/${id}`, defParams));
}
function getEntriesByOrderId(id) {
return JSON.parse(UrlFetchApp.fetch(`https://${lnkpart}.medods.ru/api/v2/entries?orderId=${id}&limit=100&offset=0`, defParams)).data;
}
function getClinicById(id) {
Utilities.sleep(200);
return JSON.parse(UrlFetchApp.fetch(`https://${lnkpart}.medods.ru/api/v2/clinics/${id}`, defParams))
}
function getUserById(id) {
return JSON.parse(UrlFetchApp.fetch(`https://${lnkpart}.medods.ru/api/v2/users/${id}`, defParams))
}
// Получаем токен для авторизации
function GetToken() {
let createJwt = ({ privateKey, expiresInSeconds, data = {} }) => {
// Sign token using HMAC with SHA-256 algorithm
let header = {
alg: "HS512",
typ: "JWT",
};
let now = Date.now();
let expires = new Date(now);
expires.setSeconds(expires.getSeconds() + expiresInSeconds);
// iat = issued time, exp = expiration time
let payload = {
exp: Math.round(expires.getTime() / 1000) - 1,
iat: Math.round(now / 1000) - 1,
iss: "...",
};
// add user payload
Object.keys(data).forEach(function (key) {
payload[key] = data[key];
});
let base64Encode = (text, json = true) => {
let data = json ? JSON.stringify(text) : text;
return Utilities.base64EncodeWebSafe(data).replace(/=+$/, "");
};
let toSign = `${base64Encode(header)}.${base64Encode(payload)}`;
let signatureBytes = Utilities.computeHmacSignature(
Utilities.MacAlgorithm.HMAC_SHA_512,
toSign,
privateKey
);
let signature = base64Encode(signatureBytes, false);
return `${toSign}.${signature}`;
};
return createJwt({
privateKey: "...",
expiresInSeconds: 64, // expires in 64 seconds
data: {},
});
}
function getAppointments() {
let resultArray = [];
let pageNumberNext = 0;
let resultFetch = [];
let token = GetToken();
do {
resultFetch = JSON.parse(
UrlFetchApp.fetch(
`https://${lnkpart}.medods.ru/api/v2/appointments?dateStart=${startDate}&dateEnd=${endDate}&limit=100&offset=${pageNumberNext}`,
{
headers: {
accept: "application/json",
Authorization: token,
},
}
)
);
if (pageNumberNext === 1900) token = GetToken();
resultArray.push(...resultFetch.data);
pageNumberNext = resultArray.length;
Utilities.sleep(1000);
} while (pageNumberNext !== resultFetch.totalItems);
return resultArray;
}
// Вставляем :
let spreadSheet = SpreadsheetApp.getActiveSpreadsheet();
let operationJournalSheet = spreadSheet.getSheetByName("Лист1");
let kont = operationJournalSheet.getRange("A2:A").getValues();
let lr = 0;
for (let i = 0; i < kont.length; i++) {
if (kont[i] != "") {
lr++;
}
}
if (resultArray.length > 0) {
operationJournalSheet.getRange(lr + 2, 1, resultArray.length, resultArray[0].length).setValues(resultArray);
}
}