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
|
import Foundation
// MARK: - Response types (file-private to avoid @MainActor Decodable issues)
private struct TrackerTicketsResponse: Decodable, Sendable {
let tracker: TrackerTicketsWrapper
}
private struct TrackerTicketsWrapper: Decodable, Sendable {
let tickets: TicketsPage
}
private struct TicketsPage: Decodable, Sendable {
let results: [TicketSummary]
let cursor: String?
}
private struct AssignmentMutationResponse: Decodable, Sendable {
struct EventRef: Decodable, Sendable {
let id: Int
}
let assignUser: EventRef?
let unassignUser: EventRef?
}
private struct LabelMutationResponse: Decodable, Sendable {
struct EventRef: Decodable, Sendable {
let id: Int
}
let labelTicket: EventRef?
let unlabelTicket: EventRef?
}
private struct TrackerLabelsResponse: Decodable, Sendable {
let tracker: TrackerLabelsWrapper
}
private struct TrackerLabelsWrapper: Decodable, Sendable {
let labels: LabelsPage
}
private struct LabelsPage: Decodable, Sendable {
let results: [TicketLabel]
}
private struct UpdateStatusResponse: Decodable, Sendable {
let updateTicketStatus: MutationEventRef
}
private struct MutationEventRef: Decodable, Sendable {
let eventType: String
}
// MARK: - Filter
enum TicketFilter: String, CaseIterable, Sendable {
case open = "Open"
case resolved = "Resolved"
case all = "All"
}
// MARK: - View Model
@Observable
@MainActor
final class TicketListViewModel {
let ownerUsername: String
let trackerName: String
let trackerId: Int
let trackerRid: String
private(set) var tickets: [TicketSummary] = []
private(set) var isLoading = false
private(set) var isLoadingMore = false
private(set) var isCreatingTicket = false
private(set) var isPerformingAction = false
private(set) var trackerLabels: [TicketLabel] = []
var error: String?
var filter: TicketFilter = .open {
didSet {
UserDefaults.standard.set(filter.rawValue, forKey: filterDefaultsKey)
}
}
var searchText = ""
private var cursor: String?
private var hasMore = true
private let client: SRHTClient
private var filterDefaultsKey: String {
"ticketFilter_\(trackerRid)"
}
init(ownerUsername: String, trackerName: String, trackerId: Int, trackerRid: String, client: SRHTClient) {
self.ownerUsername = ownerUsername
self.trackerName = trackerName
self.trackerId = trackerId
self.trackerRid = trackerRid
self.client = client
if let raw = UserDefaults.standard.string(forKey: filterDefaultsKey),
let restored = TicketFilter(rawValue: raw) {
self.filter = restored
}
}
// MARK: - Query
private static let query = """
query tickets($rid: ID!, $cursor: Cursor) {
tracker(rid: $rid) {
tickets(cursor: $cursor) {
results {
id
title: subject
status
resolution
created
submitter { canonicalName }
labels { id name backgroundColor foregroundColor }
assignees { canonicalName }
}
cursor
}
}
}
"""
private static let submitTicketMutation = """
mutation submitTicket($trackerId: Int!, $input: SubmitTicketInput!) {
submitTicket(trackerId: $trackerId, input: $input) {
id
title: subject
status
resolution
created
submitter { canonicalName }
labels { id name backgroundColor foregroundColor }
assignees { canonicalName }
}
}
"""
private static let updateStatusMutation = """
mutation updateTicketStatus($trackerId: Int!, $ticketId: Int!, $input: UpdateStatusInput!) {
updateTicketStatus(trackerId: $trackerId, ticketId: $ticketId, input: $input) {
eventType: __typename
}
}
"""
private static let assignUserMutation = """
mutation assignUser($trackerId: Int!, $ticketId: Int!, $userId: Int!) {
assignUser(trackerId: $trackerId, ticketId: $ticketId, userId: $userId) { id }
}
"""
private static let unassignUserMutation = """
mutation unassignUser($trackerId: Int!, $ticketId: Int!, $userId: Int!) {
unassignUser(trackerId: $trackerId, ticketId: $ticketId, userId: $userId) { id }
}
"""
private static let labelTicketMutation = """
mutation labelTicket($trackerId: Int!, $ticketId: Int!, $labelId: Int!) {
labelTicket(trackerId: $trackerId, ticketId: $ticketId, labelId: $labelId) { id }
}
"""
private static let unlabelTicketMutation = """
mutation unlabelTicket($trackerId: Int!, $ticketId: Int!, $labelId: Int!) {
unlabelTicket(trackerId: $trackerId, ticketId: $ticketId, labelId: $labelId) { id }
}
"""
private static let trackerLabelsQuery = """
query trackerLabels($rid: ID!) {
tracker(rid: $rid) {
labels {
results { id name backgroundColor foregroundColor }
}
}
}
"""
// MARK: - Computed
/// Tickets filtered by the selected status filter.
var filteredTickets: [TicketSummary] {
let statusFiltered: [TicketSummary]
switch filter {
case .open:
statusFiltered = tickets.filter { $0.status.isOpen }
case .resolved:
statusFiltered = tickets.filter { !$0.status.isOpen }
case .all:
statusFiltered = tickets
}
let q = searchText.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
guard !q.isEmpty else { return statusFiltered }
return statusFiltered.filter {
String($0.id).contains(q) ||
$0.title.lowercased().contains(q) ||
$0.submitter.canonicalName.lowercased().contains(q) ||
$0.labels.contains { $0.name.lowercased().contains(q) }
}
}
// MARK: - Public API
func loadTickets() async {
isLoading = true
error = nil
cursor = nil
hasMore = true
do {
let page = try await fetchPage(cursor: nil)
tickets = page.results
cursor = page.cursor
hasMore = page.cursor != nil
} catch {
self.error = error.userFacingMessage
}
isLoading = false
}
func loadMoreIfNeeded(currentItem: TicketSummary) async {
guard let last = tickets.last,
last.id == currentItem.id,
hasMore,
!isLoadingMore else {
return
}
isLoadingMore = true
do {
let page = try await fetchPage(cursor: cursor)
tickets.append(contentsOf: page.results)
cursor = page.cursor
hasMore = page.cursor != nil
} catch {
self.error = error.userFacingMessage
}
isLoadingMore = false
}
func createTicket(subject: String, body: String) async -> TicketSummary? {
guard !isCreatingTicket else { return nil }
let trimmedSubject = subject.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmedSubject.isEmpty else {
error = "Enter a ticket title."
return nil
}
isCreatingTicket = true
error = nil
defer { isCreatingTicket = false }
var input: [String: any Sendable] = [
"subject": trimmedSubject
]
let trimmedBody = body.trimmingCharacters(in: .whitespacesAndNewlines)
if !trimmedBody.isEmpty {
input["body"] = trimmedBody
}
let variables: [String: any Sendable] = [
"trackerId": trackerId,
"input": input
]
do {
let result = try await client.execute(
service: .todo,
query: Self.submitTicketMutation,
variables: variables,
responseType: SubmitTicketResponse.self
)
let ticket = result.submitTicket
tickets.insert(ticket, at: 0)
return ticket
} catch {
self.error = "Couldn’t create the ticket. \(error.userFacingMessage)"
return nil
}
}
func resolveTicket(_ ticket: TicketSummary) async {
let input: [String: any Sendable] = [
"status": TicketStatus.resolved.rawValue,
"resolution": TicketResolution.fixed.rawValue
]
await performStatusUpdate(ticket: ticket, input: input)
}
func reopenTicket(_ ticket: TicketSummary) async {
let input: [String: any Sendable] = [
"status": TicketStatus.reported.rawValue
]
await performStatusUpdate(ticket: ticket, input: input)
}
func assignToMe(ticket: TicketSummary, user: User) async {
guard !isPerformingAction else { return }
isPerformingAction = true
error = nil
let original = tickets
if let index = tickets.firstIndex(where: { $0.id == ticket.id }) {
let entity = Entity(canonicalName: user.canonicalName)
let updated = TicketSummary(
id: ticket.id,
title: ticket.title,
status: ticket.status,
resolution: ticket.resolution,
created: ticket.created,
submitter: ticket.submitter,
labels: ticket.labels,
assignees: ticket.assignees + [entity]
)
tickets[index] = updated
}
do {
_ = try await client.execute(
service: .todo,
query: Self.assignUserMutation,
variables: [
"trackerId": trackerId,
"ticketId": ticket.id,
"userId": user.id
],
responseType: AssignmentMutationResponse.self
)
} catch {
tickets = original
self.error = error.userFacingMessage
}
isPerformingAction = false
}
func unassignFromMe(ticket: TicketSummary, user: User) async {
guard !isPerformingAction else { return }
isPerformingAction = true
error = nil
let original = tickets
if let index = tickets.firstIndex(where: { $0.id == ticket.id }) {
let filtered = ticket.assignees.filter { assignee in
!Self.matchesAssignee(assignee, user: user)
}
let updated = TicketSummary(
id: ticket.id,
title: ticket.title,
status: ticket.status,
resolution: ticket.resolution,
created: ticket.created,
submitter: ticket.submitter,
labels: ticket.labels,
assignees: filtered
)
tickets[index] = updated
}
do {
_ = try await client.execute(
service: .todo,
query: Self.unassignUserMutation,
variables: [
"trackerId": trackerId,
"ticketId": ticket.id,
"userId": user.id
],
responseType: AssignmentMutationResponse.self
)
} catch {
tickets = original
self.error = error.userFacingMessage
}
isPerformingAction = false
}
func loadTrackerLabels() async {
do {
let result = try await client.execute(
service: .todo,
query: Self.trackerLabelsQuery,
variables: ["rid": trackerRid],
responseType: TrackerLabelsResponse.self
)
trackerLabels = result.tracker.labels.results
} catch {
self.error = error.userFacingMessage
}
}
func labelTicket(_ ticket: TicketSummary, label: TicketLabel) async {
guard !isPerformingAction else { return }
isPerformingAction = true
error = nil
let original = tickets
if let index = tickets.firstIndex(where: { $0.id == ticket.id }) {
let updated = TicketSummary(
id: ticket.id,
title: ticket.title,
status: ticket.status,
resolution: ticket.resolution,
created: ticket.created,
submitter: ticket.submitter,
labels: ticket.labels + [label],
assignees: ticket.assignees
)
tickets[index] = updated
}
do {
_ = try await client.execute(
service: .todo,
query: Self.labelTicketMutation,
variables: [
"trackerId": trackerId,
"ticketId": ticket.id,
"labelId": label.id
],
responseType: LabelMutationResponse.self
)
} catch {
tickets = original
self.error = error.userFacingMessage
}
isPerformingAction = false
}
func unlabelTicket(_ ticket: TicketSummary, label: TicketLabel) async {
guard !isPerformingAction else { return }
isPerformingAction = true
error = nil
let original = tickets
if let index = tickets.firstIndex(where: { $0.id == ticket.id }) {
let filtered = ticket.labels.filter { $0.id != label.id }
let updated = TicketSummary(
id: ticket.id,
title: ticket.title,
status: ticket.status,
resolution: ticket.resolution,
created: ticket.created,
submitter: ticket.submitter,
labels: filtered,
assignees: ticket.assignees
)
tickets[index] = updated
}
do {
_ = try await client.execute(
service: .todo,
query: Self.unlabelTicketMutation,
variables: [
"trackerId": trackerId,
"ticketId": ticket.id,
"labelId": label.id
],
responseType: LabelMutationResponse.self
)
} catch {
tickets = original
self.error = error.userFacingMessage
}
isPerformingAction = false
}
func ticket(withId ticketId: Int) -> TicketSummary? {
tickets.first(where: { $0.id == ticketId })
}
// MARK: - Private
private func performStatusUpdate(ticket: TicketSummary, input: [String: any Sendable]) async {
guard !isPerformingAction else { return }
isPerformingAction = true
error = nil
do {
let variables: [String: any Sendable] = [
"trackerId": trackerId,
"ticketId": ticket.id,
"input": input
]
let result = try await client.execute(
service: .todo,
query: Self.updateStatusMutation,
variables: variables,
responseType: UpdateStatusResponse.self
)
_ = result.updateTicketStatus
if let index = tickets.firstIndex(where: { $0.id == ticket.id }) {
tickets[index] = updatedTicket(from: ticket, input: input)
}
} catch {
self.error = error.userFacingMessage
}
isPerformingAction = false
}
private func fetchPage(cursor: String?) async throws -> TicketsPage {
var variables: [String: any Sendable] = ["rid": trackerRid]
if let cursor {
variables["cursor"] = cursor
}
let result = try await client.execute(
service: .todo,
query: Self.query,
variables: variables,
responseType: TrackerTicketsResponse.self
)
return result.tracker.tickets
}
private struct SubmitTicketResponse: Decodable, Sendable {
let submitTicket: TicketSummary
}
private static func matchesAssignee(_ entity: Entity, user: User) -> Bool {
let assigneeCanonical = normalizedCanonicalName(entity.canonicalName)
let userCanonical = normalizedCanonicalName(user.canonicalName)
if assigneeCanonical == userCanonical {
return true
}
return normalizedUsername(entity.canonicalName) == normalizedUsername(user.username)
}
private static func normalizedCanonicalName(_ value: String) -> String {
let trimmed = value.trimmingCharacters(in: .whitespacesAndNewlines)
if trimmed.hasPrefix("~") {
return trimmed
}
return "~\(trimmed)"
}
private static func normalizedUsername(_ value: String) -> String {
let trimmed = value.trimmingCharacters(in: .whitespacesAndNewlines)
return trimmed.hasPrefix("~") ? String(trimmed.dropFirst()) : trimmed
}
private func updatedTicket(from ticket: TicketSummary, input: [String: any Sendable]) -> TicketSummary {
let updatedStatus = (input["status"] as? String).flatMap(TicketStatus.init(rawValue:)) ?? ticket.status
let updatedResolution = (input["resolution"] as? String).flatMap(TicketResolution.init(rawValue:))
return TicketSummary(
id: ticket.id,
title: ticket.title,
status: updatedStatus,
resolution: updatedStatus == .resolved ? updatedResolution : nil,
created: ticket.created,
submitter: ticket.submitter,
labels: ticket.labels,
assignees: ticket.assignees
)
}
}
|