@itutoring/itutoring_application_js_api 1.0.0

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.
@@ -0,0 +1,34 @@
1
+ class CookiesManager
2
+ {
3
+ static SetCookie(name, value, expiracy)
4
+ {
5
+ if (this.GetCookie(name) != null)
6
+ return;
7
+
8
+ document.cookie = name + "=" + value + "; expires=" + expiracy + ";path=/";
9
+ }
10
+
11
+ static GetCookie(name)
12
+ {
13
+ var cookie = decodeURIComponent(document.cookie);
14
+ var values = cookie.split(';');
15
+
16
+ for (var i = 0; i < values.length; i++)
17
+ {
18
+ var c = values[i];
19
+
20
+ while (c.charAt(0) == ' ')
21
+ {
22
+ c = c.substring(1);
23
+ }
24
+ if (c.indexOf(name) == 0)
25
+ {
26
+ return c.substring(name.length + 1, c.length);
27
+ }
28
+ }
29
+
30
+ return null;
31
+ }
32
+ }
33
+
34
+ export default CookiesManager;
package/README.md ADDED
@@ -0,0 +1 @@
1
+ # iTutoring_Application_API-js
@@ -0,0 +1,227 @@
1
+ import CookiesManager from "./CookiesManager";
2
+ import R_KEYs from "./objects/Enums";
3
+
4
+ /**
5
+ * Main class for comunicating with our backend REST api.
6
+ */
7
+ class APIController
8
+ {
9
+ static #R_KEY = "-1";
10
+ static #CLIENT_KEY = "-1";
11
+
12
+ /**
13
+ *
14
+ * @returns Returns apropriate rest url based on current server.
15
+ */
16
+ static REST_URL()
17
+ {
18
+ if (location.hostname == 'localhost')
19
+ {
20
+ return "https://itutoring.9e.cz/server/php/API/";
21
+
22
+ }
23
+ else
24
+ {
25
+ return "server/php/API/";
26
+ }
27
+ }
28
+
29
+ static CreateVisitorSession()
30
+ {
31
+ var id = Date.now();
32
+ var date = new Date();
33
+ date.setTime(date.getTime() + (7 * 24 * 60 * 60 * 1000));
34
+
35
+ CookiesManager.SetCookie("session", id, date.toUTCString());
36
+ }
37
+
38
+ static GetVisitorSessionID()
39
+ {
40
+ console.log(CookiesManager.GetCookie("session"));
41
+ return CookiesManager.GetCookie("session");
42
+ }
43
+
44
+ /**
45
+ *
46
+ * @param module "Name of API module"
47
+ * @param method "Name of API method "
48
+ * @param data "data must be as array - key, value pair. They'll be passed into the request"
49
+ * @returns "Response from server"
50
+ */
51
+ static async Get(module, method, data)
52
+ {
53
+ await APIController.GetLocalRKey();
54
+ await APIController.GetClientKey();
55
+
56
+ return new Promise(resolve =>
57
+ {
58
+ var args = APIController.GetArgsFromArray(data);
59
+
60
+ var request = new XMLHttpRequest();
61
+ request.withCredentials = true;
62
+ request.open("GET", APIController.REST_URL() + module + "/" + method + "?" + args, true);
63
+ request.onreadystatechange = function ()
64
+ {
65
+ if (request.readyState == 4)
66
+ {
67
+ resolve(request.responseText);
68
+ }
69
+ }
70
+
71
+ request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
72
+ request.setRequestHeader("r-key", APIController.#R_KEY);
73
+ request.setRequestHeader("sites", location.hostname);
74
+ request.setRequestHeader("key", APIController.#CLIENT_KEY);
75
+ request.setRequestHeader("visitor-session", this.GetVisitorSessionID());
76
+ request.send();
77
+ });
78
+ }
79
+
80
+ /**
81
+ *
82
+ * @param module "Name of API module"
83
+ * @param method "Name of API method "
84
+ * @param data "data must be as array - key, value pair. They'll be passed into the request"
85
+ * @returns "Response from server"
86
+ */
87
+ static async Post(module, method, data)
88
+ {
89
+ await APIController.GetLocalRKey();
90
+ await APIController.GetClientKey();
91
+
92
+ return new Promise(resolve =>
93
+ {
94
+ var args = APIController.GetArgsFromArray(data);
95
+
96
+ var request = new XMLHttpRequest();
97
+ request.open("POST", APIController.REST_URL() + module + "/" + method, true);
98
+
99
+ request.onreadystatechange = function ()
100
+ {
101
+ if (request.readyState == 4)
102
+ {
103
+ resolve(request.responseText);
104
+ }
105
+ }
106
+
107
+ request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
108
+ request.setRequestHeader("r-key", APIController.#R_KEY);
109
+ request.setRequestHeader("sites", location.hostname);
110
+ request.setRequestHeader("key", APIController.#CLIENT_KEY);
111
+ request.setRequestHeader("visitor-session", this.GetVisitorSessionID());
112
+ request.send(args);
113
+ });
114
+ }
115
+
116
+ static GetArgsFromArray(args)
117
+ {
118
+ var argsString = "";
119
+
120
+ if (args != null)
121
+ {
122
+ for (const [key, value] of Object.entries(args))
123
+ {
124
+ argsString += key + "=" + value + "&";
125
+ }
126
+ }
127
+ return argsString;
128
+ }
129
+
130
+ /**
131
+ *
132
+ * @returns r_key for this server
133
+ */
134
+ static GetLocalRKey()
135
+ {
136
+ return new Promise(resolve =>
137
+ {
138
+ if (APIController.#R_KEY != "-1")
139
+ {
140
+ resolve(APIController.#R_KEY);
141
+ }
142
+
143
+ // For localhost don't use xml config, but automaticly
144
+ // return test key.
145
+ if (location.hostname === "localhost")
146
+ {
147
+ APIController.#R_KEY = R_KEYs.r_key_test;
148
+ resolve(APIController.#R_KEY);
149
+ }
150
+ else
151
+ {
152
+ fetch('/key_config.xml').then(response => response.text()).then((data) =>
153
+ {
154
+ var parser = new DOMParser();
155
+ var rKeyXML = parser.parseFromString(data, "text/xml");
156
+ var rKey = rKeyXML.getElementsByTagName("key")[0].childNodes[0].nodeValue;
157
+
158
+ APIController.#R_KEY = rKey;
159
+ resolve(APIController.#R_KEY);
160
+ });
161
+ }
162
+ });
163
+ }
164
+
165
+ static GetClientKey()
166
+ {
167
+ return new Promise(resolve =>
168
+ {
169
+ if (APIController.#CLIENT_KEY != "-1")
170
+ {
171
+ resolve(APIController.#CLIENT_KEY);
172
+ }
173
+
174
+ // For localhost don't use xml config, but automaticly
175
+ // return test key.
176
+ if (location.hostname === "localhost")
177
+ {
178
+ APIController.#CLIENT_KEY = "r5u8x/A?D(G+KbPeShVmYp3s6v9y$B&E";
179
+ resolve(APIController.#R_KEY);
180
+ }
181
+ else
182
+ {
183
+ fetch('/client_key.xml').then(response => response.text()).then((data) =>
184
+ {
185
+ var parser = new DOMParser();
186
+ var keyXML = parser.parseFromString(data, "text/xml");
187
+ var key = keyXML.getElementsByTagName("key")[0].childNodes[0].nodeValue;
188
+
189
+ APIController.#CLIENT_KEY = key;
190
+ resolve(APIController.#CLIENT_KEY);
191
+ });
192
+ }
193
+ });
194
+ }
195
+
196
+ static async GetCurrentHostURl()
197
+ {
198
+ if (location.hostname == 'localhost')
199
+ {
200
+ return "http://localhost:3000";
201
+ }
202
+ else
203
+ {
204
+ var r_key = await this.GetLocalRKey();
205
+ if (r_key == R_KEYs.r_key_test)
206
+ {
207
+ return "https://itutoring.9e.cz";
208
+ }
209
+ else
210
+ {
211
+ return "https://itutoring.cz";
212
+ }
213
+ }
214
+ }
215
+
216
+ static IntToBool(value)
217
+ {
218
+ return value == 1 ? true : false;
219
+ }
220
+
221
+ static BoolToInt(value)
222
+ {
223
+ return value ? 1 : 0;
224
+ }
225
+ }
226
+
227
+ export default APIController;
package/cache.js ADDED
@@ -0,0 +1,19 @@
1
+ class APICache
2
+ {
3
+ static Cache(key, data)
4
+ {
5
+ localStorage.setItem(key, data);
6
+ }
7
+
8
+ static Retrive(key)
9
+ {
10
+ return localStorage.getItem(key);
11
+ }
12
+
13
+ static IsCached(key)
14
+ {
15
+ return !(localStorage.getItem(key) === null);
16
+ }
17
+ }
18
+
19
+ export default APICache;
package/index.js ADDED
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+
@@ -0,0 +1,209 @@
1
+ import APIController from "./../apiController";
2
+ import Course from "./../objects/Course";
3
+ import CourseReservation from "../objects/CourseReservation";
4
+
5
+ class CoursesSystem
6
+ {
7
+ /**
8
+ * Respective module name for this class
9
+ */
10
+ static #MODULE = "CourseSystem";
11
+
12
+ // All method names
13
+ static #GET_ALL_AVAILABLE_COURSES = "GetAvailableCourses";
14
+ static #GET_PRICE = "GetPrice";
15
+ static #BOOK = "Book";
16
+ static #RESERVE_PLACE = "ReservePlace";
17
+ static #CONFIRM_COURSE = "ConfirmCourse";
18
+ static #ORDER_TIMEOUT = "OrderTimeout";
19
+ static #GET_RESERVATION = "GetReservation";
20
+ static #IS_RESERVATION_PAID = "IsReservationPaid";
21
+ static #MARK_RESERVATION_PAID = "MarkReservationPaid";
22
+
23
+ static async MarkReservationPaid(reservationId, transactionId)
24
+ {
25
+ var res = await APIController.Get(this.#MODULE, this.#MARK_RESERVATION_PAID, {
26
+ 'reservationId': reservationId,
27
+ 'transactionId': transactionId,
28
+ });
29
+
30
+ return APIController.IntToBool(res);
31
+ }
32
+
33
+ /**
34
+ * Get if reservation is paid or not
35
+ * @param {*} id reservation order ID
36
+ * @returns bool
37
+ */
38
+ static async IsReservationPaid(id)
39
+ {
40
+ var res = await APIController.Get(this.#MODULE, this.#IS_RESERVATION_PAID, {
41
+ 'order': id,
42
+ });
43
+
44
+ return APIController.IntToBool(res);
45
+ }
46
+
47
+ /**
48
+ * Get reservation by its ID.
49
+ * @param {*} id reservation order ID
50
+ * @returns CourseReservation object
51
+ */
52
+ static async GetReservation(id)
53
+ {
54
+ var reservationJSON = await APIController.Get(this.#MODULE, this.#GET_RESERVATION, {
55
+ 'order': id,
56
+ });
57
+
58
+ var reservationArray = JSON.parse(reservationJSON);
59
+
60
+ var reservation = new CourseReservation();
61
+ reservation.CourseId = reservationArray['CourseId'];
62
+ reservation.Email = reservationArray['Email'];
63
+ reservation.FirstName = reservationArray['FirstName'];
64
+ reservation.LastName = reservationArray['LastName'];
65
+ reservation.TeacherId = reservationArray['TeacherId'];
66
+
67
+ return reservation;
68
+ }
69
+
70
+ /**
71
+ * Checks if your reserved place is still in DB, if not returns true.
72
+ *
73
+ * This method uses token stored in session, so you have to run ReservePlace
74
+ * before to be able to run this method.
75
+ *
76
+ * Represents creating order timeout.
77
+ * @returns bool
78
+ */
79
+ static async OrderTimeout()
80
+ {
81
+ var res = await APIController.Get(this.#MODULE, this.#ORDER_TIMEOUT);
82
+
83
+ return APIController.IntToBool(res);
84
+ }
85
+
86
+ /**
87
+ * Send notification email about reserving course. Reservation is taken from book,
88
+ * which means this method will work only after book.
89
+ * @param {*} resend
90
+ * @returns Returns true if succeded.
91
+ */
92
+ static async ConfirmCourse(resend)
93
+ {
94
+ var res = await APIController.Get(this.#MODULE, this.#CONFIRM_COURSE, {
95
+ 'resend': APIController.BoolToInt(resend),
96
+ });
97
+
98
+ return APIController.IntToBool(res);
99
+ }
100
+
101
+ /**
102
+ * This method is used to reserve place in course without creating reservation.
103
+ * Is used to hold course during creating order. Will create unique token which
104
+ * is used to identify your reserved place. This token is not returned and is kept
105
+ * on backend side.
106
+ * @param {*} courseId
107
+ * @returns int (BookReturn enum)
108
+ */
109
+ static async ReservePlace(courseId)
110
+ {
111
+ var res = await APIController.Post(this.#MODULE, this.#RESERVE_PLACE, {
112
+ 'courseId': courseId,
113
+ });
114
+
115
+ return res;
116
+ }
117
+
118
+ /**
119
+ * Book specific course.
120
+ *
121
+ * Teacher id is not needed to be specified as will be fetched by course id.
122
+ * @param {*} courseReservation CourseReservation object
123
+ * @returns int (BookReturn enum)
124
+ */
125
+ static async Book(courseReservation)
126
+ {
127
+ var res = await APIController.Post(this.#MODULE, this.#BOOK, {
128
+ 'reservation': encodeURIComponent(JSON.stringify(courseReservation)),
129
+ });
130
+
131
+ return res;
132
+ }
133
+
134
+ /**
135
+ * Get all available courses by specific parameters
136
+ * @param {*} school type of scool for the course
137
+ * @param {*} subject subject id (0 - math 1 - czech)
138
+ * @param {*} length course length (lessons)
139
+ * @param {*} capacity course capacity
140
+ * @returns Course[]
141
+ */
142
+ static async GetAvailableCourses(school, subject, length, capacity)
143
+ {
144
+ var data = await APIController.Get(this.#MODULE, this.#GET_ALL_AVAILABLE_COURSES, {
145
+ 'school': school,
146
+ 'subject': subject,
147
+ 'length': length,
148
+ 'capacity': capacity,
149
+ });
150
+
151
+ // Check if returned data are valid JSON object.
152
+ try
153
+ {
154
+ JSON.parse(data);
155
+ }
156
+ catch
157
+ {
158
+ return [];
159
+ }
160
+
161
+ var dataArray = JSON.parse(data);
162
+
163
+ var availableCourses = [];
164
+
165
+ for (const [key, value] of Object.entries(dataArray))
166
+ {
167
+ var course = new Course();
168
+
169
+ course.Name = value['Name'];
170
+ course.NameRaw = value['NameRaw'];
171
+ course.School = value['School'];
172
+ course.Price = value['Price'];
173
+ course.CreditPrice = value['CreditPrice'];
174
+ course.ID = value['ID'];
175
+ course.Day = value['Day'];
176
+ course.Time = value['Time'];
177
+ course.Length = value['Length'];
178
+ course.Lessons = value['Lessons'];
179
+ course.Capacity = value['Capacity'];
180
+ course.Item = value['Item'];
181
+ course.Subject = value['Subject'];
182
+ course.PriceBeforeSale = value['PriceBeforeSale'];
183
+ course.IsSaled = value['IsSaled'];
184
+
185
+ availableCourses[course.ID] = course;
186
+ }
187
+
188
+ return availableCourses;
189
+ }
190
+
191
+ /**
192
+ * Get price of courses
193
+ * @param {*} cheap if you want to get the cheapest or the most expensive price tag - bool
194
+ * @param {*} paramas - optional - JSON url encoded - additional params to filter the courses - key must be variable name of Course object
195
+ * @returns int
196
+ */
197
+ static async GetPrice(cheap, paramas = [])
198
+ {
199
+ var price = await APIController.Get(this.#MODULE, this.#GET_PRICE, {
200
+ 'cheap': APIController.BoolToInt(cheap),
201
+ 'params': encodeURIComponent(JSON.stringify(paramas)),
202
+ });
203
+
204
+ console.log(price);
205
+ return parseInt(price);
206
+ }
207
+ }
208
+
209
+ export default CoursesSystem;
@@ -0,0 +1,76 @@
1
+ import APIController from "./../apiController";
2
+ //import EventHandling from "./EventHandling";
3
+
4
+ class CustomerAuth
5
+ {
6
+ /**
7
+ * Respective module name for this class
8
+ */
9
+ static #MODULE = "CustomerAuth";
10
+
11
+ // All method names
12
+ static #IS_AUTHENTICATED = "IsAuthenticated";
13
+ static #LOG_IN = "Login";
14
+ static #SIGN_ING = "SignIn";
15
+
16
+ /**
17
+ * Checks if currunet user(customer) is authenticated or not.
18
+ * @returns bool
19
+ */
20
+ static async IsAuthenticated()
21
+ {
22
+ var result = await APIController.Get(this.#MODULE, this.#IS_AUTHENTICATED);
23
+
24
+ return APIController.IntToBool(result);
25
+ }
26
+
27
+ /**
28
+ *
29
+ * @param {*} email
30
+ * @param {*} pass
31
+ * @param {*} fname
32
+ * @param {*} lname
33
+ * @returns Int (AuthResult)
34
+ */
35
+ static async SignIn(email, pass, fname, lname)
36
+ {
37
+ var result = await APIController.Post(this.#MODULE, this.#SIGN_ING, {
38
+ 'email': email,
39
+ 'pass': pass,
40
+ 'fname': fname,
41
+ 'lname': lname,
42
+ });
43
+
44
+ /*EventHandling.OnUserSignIn.publish(
45
+ {
46
+ result: result
47
+ }
48
+ );*/
49
+
50
+ return result;
51
+ }
52
+
53
+ /**
54
+ *
55
+ * @param {*} email
56
+ * @param {*} password
57
+ * @returns Int (AuthResult)
58
+ */
59
+ static async LogIn(email, password)
60
+ {
61
+ var result = await APIController.Post(this.#MODULE, this.#LOG_IN, {
62
+ 'email': email,
63
+ 'pass': password,
64
+ });
65
+
66
+ /*EventHandling.OnUserLogIn.publish(
67
+ {
68
+ result: result,
69
+ }
70
+ );
71
+ */
72
+ return result;
73
+ }
74
+ }
75
+
76
+ export default CustomerAuth;
@@ -0,0 +1,38 @@
1
+ import APIController from "./../apiController";
2
+ import Customer from "./../objects/Customer";
3
+
4
+ class CustomerPortal
5
+ {
6
+ /**
7
+ * Respective module name for this class
8
+ */
9
+ static #MODULE = "CustomerPortal";
10
+
11
+ // All method names
12
+ static #GET_CUSTOMER_INFO = "GetCustomerInfo";
13
+
14
+ /**
15
+ * Customer must be logged in otherwise this method will return null object.
16
+ * @returns Customer object
17
+ */
18
+ static async GetCustomerInfo()
19
+ {
20
+ var customerString = await APIController.Get(this.#MODULE, this.#GET_CUSTOMER_INFO);
21
+ if (customerString == "null")
22
+ {
23
+ return null;
24
+
25
+ }
26
+ var customerArray = JSON.parse(customerString);
27
+
28
+ var customer = new Customer();
29
+ customer.Email = customerArray['Email'];
30
+ customer.FirstName = customerArray['FirstName'];
31
+ customer.LastName = customerArray['LastName'];
32
+ customer.ID = customerArray['ID'];
33
+
34
+ return customer;
35
+ }
36
+ }
37
+
38
+ export default CustomerPortal;
@@ -0,0 +1,63 @@
1
+ import APIController from "./../apiController";
2
+
3
+ class Email
4
+ {
5
+ /**
6
+ * Respective module name for this class
7
+ */
8
+ static #MODULE = "Email";
9
+
10
+ static #SEND = "Send";
11
+
12
+ /**
13
+ * Send email
14
+ *
15
+ * @param {*} header email header
16
+ * @param {*} message email main text (p)
17
+ * @param {*} params email parameters as key: value \n (as array)
18
+ * @param {*} fHeader heading in footer
19
+ * @param {*} fMessage main text in footer
20
+ * @param {*} fReason text below footer, saying like: You receiving this email because...
21
+ * @param {*} buttonText button text in email
22
+ * @param {*} buttonLink button url link in email
23
+ * @param {*} title 'optional' int 0/1 to hide the buttons
24
+ * @param {*} toEmail Email title
25
+ * @param {*} toName Receipent name
26
+ * @param {*} buttonHide bool to hide button (false is default)
27
+ * @param {*} fromEmail 'optional' - sender email (itutoring is default)
28
+ * @param {*} fromName 'optional' - sender name {itutoring is default)
29
+ * @returns bool
30
+ */
31
+ static async Send(header, message, params, fHeader, fMessage, fReason, buttonText, buttonLink, title, toEmail, toName, buttonHide = false, fromEmail = 'default', fromName = 'default')
32
+ {
33
+ var postQuery = {
34
+ 'header': header,
35
+ 'message': message,
36
+ 'params': JSON.stringify(params),
37
+ 'fHeader': fHeader,
38
+ 'fMessage': fMessage,
39
+ 'fReason': fReason,
40
+ 'buttonText': buttonText,
41
+ 'buttonLink': buttonLink,
42
+ 'buttonHide': APIController.BoolToInt(buttonHide),
43
+ 'title': title,
44
+ 'toEmail': toEmail,
45
+ 'toName': toName,
46
+ }
47
+ if (fromEmail != 'default')
48
+ {
49
+ postQuery.fromEmail = fromEmail;
50
+ }
51
+
52
+ if (fromName != 'default')
53
+ {
54
+ postQuery.fromName = fromName;
55
+ }
56
+
57
+ await APIController.Post(this.#MODULE, this.#SEND, postQuery);
58
+
59
+ return true;
60
+ }
61
+ }
62
+
63
+ export default Email;
@@ -0,0 +1,22 @@
1
+ import APIController from "./../apiController";
2
+
3
+ class Newsletters
4
+ {
5
+ /**
6
+ * Respective module name for this class
7
+ */
8
+ static #MODULE = "Newsletters";
9
+
10
+ static #ADD_CUSTOMER = "AddCustomer";
11
+
12
+ static async AddCustomer(email)
13
+ {
14
+ await APIController.Get(this.#MODULE, this.#ADD_CUSTOMER, {
15
+ 'email': email
16
+ });
17
+
18
+ return true;
19
+ }
20
+ }
21
+
22
+ export default Newsletters;