Endpoints.swift
20.8 KB
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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
//
// Endpoints.swift
// SwiftWarplyFramework
//
// Created by Warply on 06/06/2025.
// Copyright © 2025 Warply. All rights reserved.
//
import Foundation
// MARK: - HTTP Method
public enum HTTPMethod: String {
case GET = "GET"
case POST = "POST"
case PUT = "PUT"
case DELETE = "DELETE"
case PATCH = "PATCH"
}
// MARK: - Endpoint Categories
public enum EndpointCategory {
case standardContext // /api/mobile/v2/{appUUID}/context/
case authenticatedContext // /oauth/{appUUID}/context
case authentication // /oauth/{appUUID}/login, /oauth/{appUUID}/token
case userManagement // /user/{appUUID}/register, /user/v5/{appUUID}/logout
case partnerCosmote // /partners/cosmote/verify, /partners/oauth/{appUUID}/token
case session // /api/session/{sessionUuid}
case analytics // /api/async/analytics/{appUUID}/
case deviceInfo // /api/async/info/{appUUID}/
case mapData // /partners/cosmote/{environment}/map_data
case profileImage // /api/{appUUID}/handle_image
}
// MARK: - Authentication Types
public enum AuthenticationType {
case standard // loyalty headers only
case bearerToken // loyalty headers + Authorization: Bearer {access_token}
case basicAuth // loyalty headers + Authorization: Basic {encoded_credentials}
}
// MARK: - API Endpoints
public enum Endpoint {
// Registration
case register(parameters: [String: Any])
// User Management
case changePassword(oldPassword: String, newPassword: String)
case resetPassword(email: String)
case requestOtp(phoneNumber: String)
// Authentication
case verifyTicket(guid: String, ticket: String)
case refreshToken(clientId: String, clientSecret: String, refreshToken: String)
case logout
case getCosmoteUser(guid: String)
case deiLogin(email: String)
// Campaigns
case getCampaigns(language: String, filters: [String: Any])
case getCampaignsPersonalized(language: String, filters: [String: Any])
case getSingleCampaign(sessionUuid: String)
// Coupons
case getCoupons(language: String, couponsetType: String)
case getCouponSets(language: String, active: Bool, visible: Bool, uuids: [String]?)
case getAvailableCoupons
// Market & Merchants
case getMarketPassDetails
case getMerchants(language: String, categories: [String], defaultShown: Bool, center: Double, tags: [String], uuid: String, distance: Int, parentUuids: [String])
case getMerchantCategories(language: String)
// Articles
case getArticles(language: String, categories: [String]?)
// Card Management
case addCard(cardNumber: String, cardIssuer: String, cardHolder: String, expirationMonth: String, expirationYear: String)
case getCards
case deleteCard(token: String)
// Transaction History
case getTransactionHistory(productDetail: String = "minimal")
case getPointsHistory
// Coupon Operations
case validateCoupon(coupon: [String: Any])
case redeemCoupon(productId: String, productUuid: String, merchantId: String)
// Profile
case getProfile
// Events
case sendEvent(eventName: String, priority: Bool)
// Device
case sendDeviceInfo(deviceToken: String)
// Network status
case getNetworkStatus
// MARK: - Endpoint Properties
public var path: String {
switch self {
// Registration endpoint
case .register:
return "/api/mobile/v2/{appUUID}/register/"
// User Management endpoints
case .changePassword:
return "/user/{appUUID}/change_password"
case .resetPassword:
return "/user/{appUUID}/password_reset"
case .requestOtp:
return "/user/{appUUID}/otp/generate"
// Partner Cosmote endpoints
case .verifyTicket:
return "/partners/cosmote/verify"
case .getCosmoteUser:
return "/partners/oauth/{appUUID}/token"
case .deiLogin:
return "/partners/dei/app_login"
// Authentication endpoints
case .refreshToken:
return "/oauth/{appUUID}/token"
case .logout:
return "/user/v5/{appUUID}/logout"
// Standard Context endpoints - /api/mobile/v2/{appUUID}/context/
case .getCampaigns, .getAvailableCoupons, .getCouponSets, .getMerchantCategories, .getArticles:
return "/api/mobile/v2/{appUUID}/context/"
// Authenticated Context endpoints - /oauth/{appUUID}/context
case .getCampaignsPersonalized, .getCoupons, .getMarketPassDetails, .getProfile, .addCard, .getCards, .deleteCard, .getTransactionHistory, .getPointsHistory, .validateCoupon, .redeemCoupon:
return "/oauth/{appUUID}/context"
// Session endpoints - /api/session/{sessionUuid}
case .getSingleCampaign(let sessionUuid):
return "/api/session/\(sessionUuid)"
// Analytics endpoints - /api/async/analytics/{appUUID}/
case .sendEvent:
return "/api/async/analytics/{appUUID}/"
// Device Info endpoints - /api/async/info/{appUUID}/
case .sendDeviceInfo:
return "/api/async/info/{appUUID}/"
// Merchants (using merchants-specific endpoint)
case .getMerchants:
return "/api/mobile/v2/{appUUID}/merchants/"
// Network status (special case - keeping original for now)
case .getNetworkStatus:
return "/network_status"
}
}
public var method: HTTPMethod {
switch self {
case .register, .changePassword, .resetPassword, .requestOtp, .verifyTicket, .refreshToken, .logout, .getCampaigns, .getCampaignsPersonalized,
.getCoupons, .getCouponSets, .getAvailableCoupons,
.getMarketPassDetails, .getProfile, .addCard, .getCards, .deleteCard, .getTransactionHistory, .getPointsHistory, .validateCoupon, .redeemCoupon, .getMerchants, .getMerchantCategories, .getArticles, .sendEvent, .sendDeviceInfo, .getCosmoteUser, .deiLogin:
return .POST
case .getSingleCampaign, .getNetworkStatus:
return .GET
}
}
public var parameters: [String: Any]? {
switch self {
// Registration endpoint - device registration parameters
case .register(let parameters):
return parameters
// User Management endpoints - direct parameter structure
case .changePassword(let oldPassword, let newPassword):
return [
"old_password": oldPassword,
"new_password": newPassword,
"channel": "mobile"
]
case .resetPassword(let email):
return [
"email": email,
"channel": "mobile"
]
case .requestOtp(let phoneNumber):
return [
"phone": phoneNumber,
"channel": "mobile"
]
// Partner Cosmote endpoints - verifyTicket needs app_uuid
case .verifyTicket(let guid, let ticket):
return [
"guid": guid,
"app_uuid": "{appUUID}", // Will be replaced by NetworkService
"ticket": ticket
]
// Authentication endpoints - refresh token with OAuth2 grant_type
case .refreshToken(let clientId, let clientSecret, let refreshToken):
return [
"client_id": clientId,
"client_secret": clientSecret,
"refresh_token": refreshToken,
"grant_type": "refresh_token"
]
// Authentication endpoints - logout needs tokens
case .logout:
return [
"access_token": "{access_token}", // Will be replaced by NetworkService
"refresh_token": "{refresh_token}" // Will be replaced by NetworkService
]
// Partner Cosmote - getCosmoteUser uses different structure
case .getCosmoteUser(let guid):
return [
"user_identifier": guid
]
// DEI Login - simple email parameter structure
case .deiLogin(let email):
return [
"email": email
]
// Campaign endpoints - nested structure with campaigns wrapper
case .getCampaigns(let language, let filters):
return [
"campaigns": [
"action": "retrieve",
"language": language,
"filters": filters
]
]
case .getCampaignsPersonalized(let language, let filters):
return [
"campaigns": [
"action": "retrieve",
"language": language,
"filters": filters
]
]
// Session endpoints - getSingleCampaign is GET request, no body
case .getSingleCampaign:
return nil
// Coupon endpoints - nested structure with coupon wrapper
case .getCoupons(let language, let couponsetType):
var couponsetTypes: [String] = []
if !couponsetType.isEmpty {
couponsetTypes = [couponsetType]
}
return [
"coupon": [
"action": "user_coupons",
"details": ["merchant", "redemption"],
"language": language,
"couponset_types": couponsetTypes
]
]
case .getCouponSets(let language, let active, let visible, let uuids):
var couponParams: [String: Any] = [
"action": "retrieve_multilingual",
"active": active,
"visible": visible,
"language": language
// "exclude": [
// [
// "field": "couponset_type",
// "value": ["supermarket"]
// ]
// ]
]
if let uuids = uuids {
couponParams["uuids"] = uuids
}
return [
"coupon": couponParams
]
case .getAvailableCoupons:
return [
"coupon": [
"action": "availability",
"filters": [
"uuids": NSNull(),
"availability_enabled": true
]
]
]
// Market & Profile endpoints - consumer_data wrapper
case .getMarketPassDetails:
return [
"consumer_data": [
"method": "supermarket_profile",
"action": "integration"
]
]
case .getProfile:
return [
"consumer_data": [
"action": "handle_user_details",
"process": "get"
]
]
// Card Management endpoints - nested structure with cards wrapper
case .addCard(let cardNumber, let cardIssuer, let cardHolder, let expirationMonth, let expirationYear):
return [
"cards": [
"action": "add_card",
"card_number": cardNumber,
"card_issuer": cardIssuer,
"cardholder": cardHolder,
"expiration_month": expirationMonth,
"expiration_year": expirationYear
]
]
case .getCards:
return [
"cards": [
"action": "get_cards"
]
]
case .deleteCard(let token):
return [
"cards": [
"action": "delete_card",
"token": token
]
]
// Transaction History endpoints - nested structure with consumer_data wrapper
case .getTransactionHistory(let productDetail):
return [
"consumer_data": [
"action": "get_transaction_history",
"product_detail": productDetail
]
]
case .getPointsHistory:
return [
"consumer_data": [
"action": "get_points_history"
]
]
// Coupon Operations endpoints - different wrapper types
case .validateCoupon(let coupon):
return [
"coupon": [
"action": "validate",
"coupon": coupon
]
]
case .redeemCoupon(let productId, let productUuid, let merchantId):
return [
"transactions": [
"action": "vcurrency_purchase",
"cause": "coupon",
"merchant_id": merchantId,
"product_id": productId,
"product_uuid": productUuid
]
]
// Merchants - using correct shops structure for DEI API
case .getMerchants(let language, let categories, let defaultShown, let center, let tags, let uuid, let distance, let parentUuids):
return [
"shops": [
"language": language,
"action": "retrieve_multilingual"
]
]
// Merchant Categories - using shops structure for DEI API
case .getMerchantCategories(let language):
return [
"shops": [
"language": language,
"action": "retrieve_categories"
]
]
// Articles - using content structure for DEI API
case .getArticles(let language, let categories):
var contentParams: [String: Any] = [
"language": language,
"action": "retrieve_multilingual"
]
// Only add category field if categories are provided
if let categories = categories, !categories.isEmpty {
contentParams["category"] = categories
}
return [
"content": contentParams
]
// Analytics endpoints - events structure
case .sendEvent(let eventName, let priority):
return [
"events": [
[
"event_name": eventName,
"priority": priority
]
]
]
// Device Info endpoints - device structure
case .sendDeviceInfo(let deviceToken):
return [
"device": [
"device_token": deviceToken
]
]
// Network status - no body needed
case .getNetworkStatus:
return nil
}
}
public var headers: [String: String] {
var defaultHeaders = [
"Content-Type": "application/json",
"Accept": "application/json"
]
// Add authentication headers if needed
// This will be handled by the NetworkService
return defaultHeaders
}
public var requiresAuthentication: Bool {
switch self {
case .register, .verifyTicket, .getCosmoteUser, .deiLogin, .getNetworkStatus:
return false
default:
return true
}
}
// MARK: - Endpoint Categorization
public var category: EndpointCategory {
switch self {
// User Management - /user/{appUUID}/* and /api/mobile/v2/{appUUID}/register/
case .register, .changePassword, .resetPassword, .requestOtp:
return .userManagement
// Standard Context - /api/mobile/v2/{appUUID}/context/
case .getCampaigns, .getAvailableCoupons, .getCouponSets, .getMerchantCategories, .getArticles:
return .standardContext
// Authenticated Context - /oauth/{appUUID}/context
case .getCampaignsPersonalized, .getCoupons, .getMarketPassDetails, .getProfile, .addCard, .getCards, .deleteCard, .getTransactionHistory, .getPointsHistory, .validateCoupon, .redeemCoupon:
return .authenticatedContext
// Authentication - /oauth/{appUUID}/login, /oauth/{appUUID}/token
case .refreshToken, .logout:
return .authentication
// Partner Cosmote - /partners/cosmote/verify, /partners/oauth/{appUUID}/token, /partners/dei/app_login
case .verifyTicket, .getCosmoteUser, .deiLogin:
return .partnerCosmote
// Session - /api/session/{sessionUuid}
case .getSingleCampaign:
return .session
// Analytics - /api/async/analytics/{appUUID}/
case .sendEvent:
return .analytics
// Device Info - /api/async/info/{appUUID}/
case .sendDeviceInfo:
return .deviceInfo
// Merchants (using standard context for now)
case .getMerchants:
return .standardContext
// Network status (special case)
case .getNetworkStatus:
return .standardContext
}
}
public var authType: AuthenticationType {
switch self {
// Standard Authentication (loyalty headers only)
case .register, .resetPassword, .requestOtp, .getCampaigns, .getAvailableCoupons, .getCouponSets, .refreshToken, .logout,
.verifyTicket, .getSingleCampaign, .sendEvent, .sendDeviceInfo,
.getMerchants, .getMerchantCategories, .getArticles, .getNetworkStatus, .deiLogin:
return .standard
// Bearer Token Authentication (loyalty headers + Authorization: Bearer)
case .changePassword, .getCampaignsPersonalized, .getCoupons, .getMarketPassDetails, .getProfile, .addCard, .getCards, .deleteCard, .getTransactionHistory, .getPointsHistory, .validateCoupon, .redeemCoupon:
return .bearerToken
// Basic Authentication (loyalty headers + Authorization: Basic)
case .getCosmoteUser:
return .basicAuth
}
}
// MARK: - URL Construction
/// Builds the complete URL by replacing placeholders with actual values
/// - Parameters:
/// - baseURL: The base URL of the API server
/// - appUUID: The application UUID to substitute in the path
/// - Returns: Complete URL string ready for network requests
public func buildURL(baseURL: String, appUUID: String) -> String {
let pathWithUUID = path.replacingOccurrences(of: "{appUUID}", with: appUUID)
return baseURL.trimmingCharacters(in: CharacterSet(charactersIn: "/")) + pathWithUUID
}
/// Returns the path with appUUID placeholder replaced
/// - Parameter appUUID: The application UUID to substitute
/// - Returns: Path string with appUUID substituted
public func pathWithAppUUID(_ appUUID: String) -> String {
return path.replacingOccurrences(of: "{appUUID}", with: appUUID)
}
}
// MARK: - Network Error
public enum NetworkError: Error, LocalizedError {
case invalidURL
case noData
case decodingError(Error)
case serverError(Int)
case networkError(Error)
case authenticationRequired
case invalidResponse
public var errorDescription: String? {
switch self {
case .invalidURL:
return "Invalid URL"
case .noData:
return "No data received"
case .decodingError(let error):
return "Decoding error: \(error.localizedDescription)"
case .serverError(let code):
return "Server error with code: \(code)"
case .networkError(let error):
return "Network error: \(error.localizedDescription)"
case .authenticationRequired:
return "Authentication required"
case .invalidResponse:
return "Invalid response"
}
}
public var code: Int {
switch self {
case .invalidURL:
return -1001
case .noData:
return -1002
case .decodingError:
return -1003
case .serverError(let code):
return code
case .networkError(let error):
return (error as NSError).code
case .authenticationRequired:
return 401
case .invalidResponse:
return -1004
}
}
}