@vulog/aima-booking 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.
package/.eslintrc.js ADDED
@@ -0,0 +1,112 @@
1
+ module.exports = {
2
+ parser: '@typescript-eslint/parser',
3
+ parserOptions: {
4
+ // Indicates the location of the TypeScript configuration file
5
+ project: 'tsconfig.json',
6
+ // Sets the root directory for the TypeScript configuration
7
+ tsconfigRootDir: __dirname,
8
+ // Specifies the version of ECMAScript syntax to be used
9
+ ecmaVersion: 'latest',
10
+ // Indicates the type of source code (script or module)
11
+ sourceType: 'module',
12
+ },
13
+ plugins: ['@typescript-eslint', 'prettier', 'import'],
14
+ extends: [
15
+ 'airbnb-base',
16
+ 'airbnb-typescript/base',
17
+ 'plugin:@typescript-eslint/recommended',
18
+ 'prettier',
19
+ 'plugin:prettier/recommended',
20
+ ],
21
+ root: true,
22
+ env: {
23
+ es6: true,
24
+ node: true,
25
+ },
26
+ ignorePatterns: [
27
+ '/dist/**/*', // Ignore built files.
28
+ '.eslintrc.js',
29
+ '**/*.test.ts',
30
+ ],
31
+ rules: {
32
+ // Configures the Prettier integration with ESLint
33
+ 'prettier/prettier': ['error', { endOfLine: 'auto' }],
34
+ // Disables the rule requiring an 'I' prefix for interfaces
35
+ '@typescript-eslint/interface-name-prefix': 'off',
36
+ // Configures the naming conventions for various code constructs
37
+ '@typescript-eslint/naming-convention': [
38
+ // ... various naming convention configurations ...
39
+ 'error',
40
+ // Allows any naming format for destructured variables
41
+ {
42
+ selector: 'variable',
43
+ modifiers: ['destructured'],
44
+ format: null,
45
+ },
46
+ // Requires strict camelCase for function names
47
+ {
48
+ selector: 'function',
49
+ format: ['strictCamelCase'],
50
+ },
51
+ // Requires boolean variables to have one of the specified prefixes
52
+ {
53
+ selector: 'variable',
54
+ format: null,
55
+ types: ['boolean'],
56
+ prefix: ['is', 'should', 'has', 'can', 'did', 'will'],
57
+ },
58
+ // Requires enum names to have a strict PascalCase format
59
+ {
60
+ selector: 'enum',
61
+ format: ['StrictPascalCase'],
62
+ },
63
+ ],
64
+ 'import/extensions': 'off',
65
+ // Disables the rule requiring explicit return types for functions
66
+ '@typescript-eslint/explicit-function-return-type': 'off',
67
+ // Disables the rule requiring explicit boundary types for modules
68
+ '@typescript-eslint/explicit-module-boundary-types': 'off',
69
+ // Disables the rule prohibiting the use of 'any' type
70
+ '@typescript-eslint/no-explicit-any': 'off',
71
+ // Disables the rule detecting unused variables
72
+ 'no-unused-vars': 0,
73
+ // Disables the rule disallowing named exports used as a default export
74
+ 'import/no-named-as-default': 0,
75
+ // Configures the order and formatting of import statements
76
+ 'import/order': [
77
+ // ... import order configuration ...
78
+ 'error',
79
+ {
80
+ // Configure the alphabetization settings
81
+ alphabetize: {
82
+ // Enforce ascending alphabetical order
83
+ order: 'asc',
84
+ // Do not ignore the case while sorting
85
+ caseInsensitive: false,
86
+ },
87
+ // Enforce newlines between different groups and inside groups of imports
88
+ 'newlines-between': 'always-and-inside-groups',
89
+ // Warn when there is an import statement that is not part of any group
90
+ warnOnUnassignedImports: true,
91
+ },
92
+ ],
93
+ // Configures the rule detecting extraneous dependencies
94
+ 'import/no-extraneous-dependencies': [
95
+ // ... extraneous dependencies configuration ...
96
+ 'error',
97
+ {
98
+ // Specify the file patterns where devDependencies imports are allowed
99
+ devDependencies: [
100
+ // Allow devDependencies imports in test and spec files
101
+ '**/*.test.{ts,js}',
102
+ '**/*.spec.{ts,js}',
103
+ // Allow devDependencies imports in the 'test' folder
104
+ './test/**.{ts,js}',
105
+ // Allow devDependencies imports in the 'scripts' folder
106
+ './scripts/**/*.{ts,js}',
107
+ ],
108
+ },
109
+ ],
110
+ 'import/prefer-default-export': 'off',
111
+ },
112
+ };
@@ -0,0 +1,2 @@
1
+
2
+ export { }
@@ -0,0 +1,2 @@
1
+
2
+ export { }
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ "use strict";
package/dist/index.mjs ADDED
File without changes
package/package.json ADDED
@@ -0,0 +1,41 @@
1
+ {
2
+ "name": "@vulog/aima-booking",
3
+ "version": "1.0.0",
4
+ "main": "dist/index.js",
5
+ "module": "dist/index.mjs",
6
+ "types": "dist/index.d.ts",
7
+ "scripts": {
8
+ "build": "tsup",
9
+ "dev": "tsup --watch",
10
+ "test": "vitest run",
11
+ "test:watch": "vitest"
12
+ },
13
+ "keywords": [
14
+ "AIMA",
15
+ "VULOG",
16
+ "BOOKING"
17
+ ],
18
+ "author": "Vulog",
19
+ "license": "ISC",
20
+ "devDependencies": {
21
+ "@types/lodash": "^4.17.12",
22
+ "@types/node": "^22.7.9",
23
+ "eslint-config-airbnb-base": "^15.0.0",
24
+ "eslint-config-airbnb-typescript": "^18.0.0",
25
+ "eslint-config-prettier": "^9.1.0",
26
+ "eslint-plugin-import": "^2.31.0",
27
+ "eslint-plugin-prettier": "^5.2.1",
28
+ "eslint-plugin-unused-imports": "^4.1.4",
29
+ "prettier": "^3.3.3",
30
+ "tsup": "^8.3.0",
31
+ "typescript": "^5.6.3",
32
+ "vitest": "^2.1.3"
33
+ },
34
+ "peerDependencies": {
35
+ "@vulog/aima-client": "^1.0.0",
36
+ "@vulog/aima-core": "^1.0.0",
37
+ "lodash": "^4.17.21",
38
+ "zod": "^3.23.8"
39
+ },
40
+ "description": ""
41
+ }
@@ -0,0 +1,146 @@
1
+ import { describe, test, expect, vi, beforeEach, afterEach } from 'vitest';
2
+ import { getBookingRequests } from './getBookingRequests';
3
+ import { Client } from '@vulog/aima-client';
4
+
5
+ describe('getBookingRequests', () => {
6
+ const getMock = vi.fn();
7
+ const client = {
8
+ get: getMock,
9
+ clientOptions: {
10
+ fleetId: 'FLEET_ID',
11
+ },
12
+ } as unknown as Client;
13
+
14
+ beforeEach(() => {
15
+ getMock.mockReset();
16
+ vi.useFakeTimers({ now: new Date('2025-01-12T13:35:50.123Z') });
17
+ });
18
+
19
+ afterEach(() => {
20
+ // restoring date after each test run
21
+ vi.useRealTimers();
22
+ });
23
+
24
+ test('Fake status', async () => {
25
+ const rejects = await expect(() => getBookingRequests({} as Client, 'FAKE' as any)).rejects;
26
+ rejects.toThrowError('Invalid status');
27
+ rejects.toSatisfy((error: any) => {
28
+ expect(error).toHaveProperty('cause');
29
+ expect(error.cause).toHaveLength(1);
30
+ expect(error.cause[0]).toHaveProperty('received');
31
+ expect(error.cause[0]).toHaveProperty('code');
32
+ expect(error.cause[0].received).toBe('FAKE');
33
+ expect(error.cause[0].code).toBe('invalid_enum_value');
34
+ return true;
35
+ });
36
+ });
37
+
38
+ test('negative page', async () => {
39
+ const rejects = await expect(() =>
40
+ getBookingRequests({} as Client, 'UPCOMING', {
41
+ page: -1,
42
+ })
43
+ ).rejects;
44
+ rejects.toThrowError('Invalid options');
45
+ rejects.toSatisfy((error: any) => {
46
+ expect(error).toHaveProperty('cause');
47
+ expect(error.cause).toHaveLength(1);
48
+ expect(error.cause[0]).toHaveProperty('path');
49
+ expect(error.cause[0]).toHaveProperty('code');
50
+ expect(error.cause[0].path[0]).toBe('page');
51
+ expect(error.cause[0].code).toBe('too_small');
52
+ return true;
53
+ });
54
+ });
55
+
56
+ test('negative pageSize', async () => {
57
+ const rejects = await expect(() =>
58
+ getBookingRequests({} as Client, 'UPCOMING', {
59
+ page: 0,
60
+ pageSize: -1,
61
+ })
62
+ ).rejects;
63
+ rejects.toThrowError('Invalid options');
64
+ rejects.toSatisfy((error: any) => {
65
+ expect(error).toHaveProperty('cause');
66
+ expect(error.cause).toHaveLength(1);
67
+ expect(error.cause[0]).toHaveProperty('path');
68
+ expect(error.cause[0]).toHaveProperty('code');
69
+ expect(error.cause[0].path[0]).toBe('pageSize');
70
+ expect(error.cause[0].code).toBe('too_small');
71
+ return true;
72
+ });
73
+ });
74
+
75
+ test('too big pageSize', async () => {
76
+ const rejects = await expect(() =>
77
+ getBookingRequests({} as Client, 'UPCOMING', {
78
+ pageSize: 1001,
79
+ })
80
+ ).rejects;
81
+ rejects.toThrowError('Invalid options');
82
+ rejects.toSatisfy((error: any) => {
83
+ expect(error).toHaveProperty('cause');
84
+ expect(error.cause).toHaveLength(1);
85
+ expect(error.cause[0]).toHaveProperty('path');
86
+ expect(error.cause[0]).toHaveProperty('code');
87
+ expect(error.cause[0].path[0]).toBe('pageSize');
88
+ expect(error.cause[0].code).toBe('too_big');
89
+ return true;
90
+ });
91
+ });
92
+
93
+ test('call Base', async () => {
94
+ getMock.mockResolvedValueOnce({
95
+ data: [],
96
+ headers: {
97
+ number: 0,
98
+ size: 100,
99
+ totalelements: 0,
100
+ totalpages: 0,
101
+ },
102
+ });
103
+
104
+ const result = await getBookingRequests(client, 'UPCOMING');
105
+ expect(getMock).toBeCalled();
106
+ expect(getMock).toBeCalledWith(
107
+ '/boapi/proxy/user/scheduledBooking/fleets/FLEET_ID/bookingrequests/status/UPCOMING/filters?page=0&pageSize=100&startDate=2025-01-12T13%3A35%3A50Z&endDate=2025-03-12T13%3A35%3A50Z'
108
+ );
109
+ expect(result).toEqual({
110
+ data: [],
111
+ page: 0,
112
+ pageSize: 100,
113
+ total: 0,
114
+ totalPages: 0,
115
+ });
116
+ });
117
+
118
+ test('call serviceTypes', async () => {
119
+ getMock.mockResolvedValueOnce({
120
+ data: [],
121
+ headers: {
122
+ number: 0,
123
+ size: 100,
124
+ totalelements: 0,
125
+ totalpages: 0,
126
+ },
127
+ });
128
+
129
+ const result = await getBookingRequests(client, 'UPCOMING', {
130
+ filters: {
131
+ serviceTypes: ['ROUND_TRIP_BOOKING', 'SCHEDULED_BOOKING_STATION'],
132
+ },
133
+ });
134
+ expect(getMock).toBeCalled();
135
+ expect(getMock).toBeCalledWith(
136
+ '/boapi/proxy/user/scheduledBooking/fleets/FLEET_ID/bookingrequests/status/UPCOMING/filters?page=0&pageSize=100&serviceTypes=ROUND_TRIP_BOOKING%2CSCHEDULED_BOOKING_STATION&startDate=2025-01-12T13%3A35%3A50Z&endDate=2025-03-12T13%3A35%3A50Z'
137
+ );
138
+ expect(result).toEqual({
139
+ data: [],
140
+ page: 0,
141
+ pageSize: 100,
142
+ total: 0,
143
+ totalPages: 0,
144
+ });
145
+ });
146
+ });
@@ -0,0 +1,148 @@
1
+ import { Client } from '@vulog/aima-client';
2
+ import { createPaginableOptionsSchema, PaginableOptions, PaginableResponse } from '@vulog/aima-core';
3
+ import { isNumber } from 'lodash';
4
+ import { z } from 'zod';
5
+
6
+ const BookingRequestStatusSchema = z.enum([
7
+ 'ALERT',
8
+ 'UPCOMING',
9
+ 'ONGOING',
10
+ 'COMPLETED',
11
+ 'CANCELLED',
12
+ 'PENDING_APPROVAL',
13
+ ]);
14
+ export type BookingRequestStatus = z.infer<typeof BookingRequestStatusSchema>;
15
+
16
+ const ServiceTypeSchema = z.enum(['SUBSCRIPTION', 'ROUND_TRIP_BOOKING', 'SCHEDULED_BOOKING_STATION']);
17
+ export type ServiceType = z.infer<typeof ServiceTypeSchema>;
18
+
19
+ export type SpecificBookingRequestFilters = {
20
+ serviceIds?: string[];
21
+ userId?: string;
22
+ modelId?: number;
23
+ vehicleId?: string;
24
+ stationId?: string;
25
+ /**
26
+ * Format: yyyy-MM-dd
27
+ */
28
+ creationDate?: string;
29
+ /**
30
+ * Format: yyyy-MM-dd'T'HH:mm:ssZ
31
+ * default now plus 2 months
32
+ */
33
+ startDate?: string;
34
+ /**
35
+ * Format: yyyy-MM-dd'T'HH:mm:ssZ
36
+ * default now plus 2 months
37
+ */
38
+ endDate?: string;
39
+ };
40
+ export type BookingRequestFilters = SpecificBookingRequestFilters & {
41
+ serviceTypes?: ServiceType[];
42
+ };
43
+
44
+ export type BookingRequest = {
45
+ [key: string]: any;
46
+ };
47
+
48
+ export const getBookingRequests = async (
49
+ client: Client,
50
+ status: BookingRequestStatus,
51
+ options?: PaginableOptions<BookingRequestFilters>
52
+ ): Promise<PaginableResponse<BookingRequest>> => {
53
+ const resultStatus = BookingRequestStatusSchema.safeParse(status);
54
+ if (!resultStatus.success) {
55
+ throw new TypeError('Invalid status', {
56
+ cause: resultStatus.error.issues,
57
+ });
58
+ }
59
+
60
+ const date = new Date();
61
+ date.setMilliseconds(0);
62
+ const startDate = date.toISOString().replace('.000Z', 'Z');
63
+ date.setMonth(date.getMonth() + 2);
64
+ const endDate = date.toISOString().replace('.000Z', 'Z');
65
+ const BookingRequestFiltersSchema = z.object({
66
+ serviceTypes: z.array(ServiceTypeSchema).optional(),
67
+ serviceIds: z.array(z.string().uuid()).optional(),
68
+ userId: z.string().uuid().optional(),
69
+ modelId: z.number().positive().optional(),
70
+ vehicleId: z.string().uuid().optional(),
71
+ stationId: z.string().uuid().optional(),
72
+ creationDate: z.string().date().optional(),
73
+ startDate: z.string().datetime({ offset: false, precision: 0 }).default(startDate),
74
+ endDate: z.string().datetime({ offset: false, precision: 0 }).default(endDate),
75
+ });
76
+
77
+ const PaginableOptionsSchema = createPaginableOptionsSchema(BookingRequestFiltersSchema).default({});
78
+
79
+ const resultOptions = PaginableOptionsSchema.safeParse(options);
80
+ if (!resultOptions.success) {
81
+ throw new TypeError('Invalid options', {
82
+ cause: resultOptions.error.issues,
83
+ });
84
+ }
85
+
86
+ const finalOptions = resultOptions.data;
87
+
88
+ const searchParams = new URLSearchParams();
89
+ searchParams.append('page', finalOptions.page!.toString());
90
+ searchParams.append('pageSize', finalOptions.pageSize!.toString());
91
+
92
+ Object.entries(finalOptions.filters!).forEach(([key, value]) => {
93
+ if (value === undefined) {
94
+ return;
95
+ }
96
+ if (Array.isArray(value) && value.length > 0) {
97
+ searchParams.append(key, value.join(','));
98
+ return;
99
+ }
100
+ if (isNumber(value)) {
101
+ searchParams.append(key, value.toString());
102
+ return;
103
+ }
104
+ searchParams.append(key, value as string);
105
+ });
106
+
107
+ return client
108
+ .get<
109
+ BookingRequest[]
110
+ >(`/boapi/proxy/user/scheduledBooking/fleets/${client.clientOptions.fleetId}/bookingrequests/status/${status}/filters?${searchParams.toString()}`)
111
+ .then(({ data, headers }) => {
112
+ return {
113
+ data,
114
+ page: headers.number,
115
+ pageSize: headers.size,
116
+ total: headers.totalelements,
117
+ totalPages: headers.totalpages,
118
+ };
119
+ });
120
+ };
121
+
122
+ export const getScheduleBookingRequests = async (
123
+ client: Client,
124
+ status: BookingRequestStatus,
125
+ options?: PaginableOptions<SpecificBookingRequestFilters>
126
+ ): Promise<PaginableResponse<BookingRequest>> => {
127
+ return getBookingRequests(client, status, {
128
+ ...options,
129
+ filters: {
130
+ ...options?.filters,
131
+ serviceTypes: ['ROUND_TRIP_BOOKING', 'SCHEDULED_BOOKING_STATION'],
132
+ },
133
+ });
134
+ };
135
+
136
+ export const getSubscriptionBookingRequests = async (
137
+ client: Client,
138
+ status: BookingRequestStatus,
139
+ options?: PaginableOptions<SpecificBookingRequestFilters>
140
+ ): Promise<PaginableResponse<BookingRequest>> => {
141
+ return getBookingRequests(client, status, {
142
+ ...options,
143
+ filters: {
144
+ ...options?.filters,
145
+ serviceTypes: ['SUBSCRIPTION'],
146
+ },
147
+ });
148
+ };
package/src/index.ts ADDED
File without changes
package/tsconfig.json ADDED
@@ -0,0 +1,16 @@
1
+ {
2
+ "include": ["src"],
3
+ "exclude": ["**/*.test.ts"],
4
+ "compilerOptions": {
5
+ "module": "esnext",
6
+ "target": "esnext",
7
+ "lib": ["esnext"],
8
+ "declaration": true,
9
+ "strict": true,
10
+ "moduleResolution": "node",
11
+ "skipLibCheck": true,
12
+ "esModuleInterop": true,
13
+ "outDir": "dist",
14
+ "rootDir": "src"
15
+ }
16
+ }
package/tsup.config.ts ADDED
@@ -0,0 +1,8 @@
1
+ import { defineConfig } from 'tsup';
2
+
3
+ export default defineConfig({
4
+ entry: ['src/index.ts'],
5
+ clean: true,
6
+ format: ['cjs', 'esm'],
7
+ dts: true,
8
+ });
@@ -0,0 +1,8 @@
1
+ import { defineConfig } from 'vitest/config';
2
+
3
+ export default defineConfig({
4
+ test: {
5
+ globals: true,
6
+ environment: 'node',
7
+ },
8
+ });