hgame 0.26.4

CG production management structs, e.g. of assets, personnels, progress, etc.
Documentation
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
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
use super::*;
use crate::{Locale, Staff};

#[cfg(feature = "gui")]
use mkutil::html_scraping::PlaceImageHint;

#[derive(Debug, Clone, Default)]
#[cfg_attr(feature = "mongo", derive(Serialize, Deserialize,))]
/// A batch that comprises of subtickets, i.e. feedback items.
/// LEGACY DESIGN: DO NOT change field names or `serde(rename)` values.
pub struct Ticket {
    #[cfg_attr(feature = "mongo", serde(skip))]
    pub ext: TicketExpand,

    #[cfg_attr(
        feature = "mongo",
        serde(rename = "_id", skip_serializing_if = "Option::is_none")
    )]
    pub id: Option<ObjectId>,

    #[cfg_attr(feature = "mongo", serde(default = "untitled", rename = "subject"))]
    pub(super) name: String,

    #[cfg_attr(feature = "mongo", serde(rename = "source_type"))]
    pub typ: TicketAuthorSource,

    /// The "subtickets". The `ObjectId`s refer to the [`SubTicket`]s.
    pub(super) content: Vec<ObjectId>,

    /// The `ObjectId`s refer to the [`ProductionAsset`]s.
    pub(super) topical_assets: Vec<ObjectId>,

    #[cfg_attr(feature = "mongo", serde(rename = "soup_format"))]
    /// This is to support running Python clients which uses a same data model for
    /// both `QueryMsg` and `FeedbackItem`, where `soup_format` is the primary value
    /// distinguishing between instances of the two groups.
    pub(super) topic: MsgTopic,

    pub(super) sender: String,

    #[cfg_attr(feature = "mongo", serde(rename = "orig_locale"))]
    pub composed_with_locale: Locale,

    #[cfg_attr(
        feature = "mongo",
        serde(
            rename = "datetime",
            with = "bson::serde_helpers::chrono_datetime_as_bson_datetime"
        )
    )]
    pub(super) created_at: DateTime<Utc>,

    pub(super) instantiated_for: Vec<String>,
}

fn untitled() -> String {
    String::from("Untitled")
}

impl BsonId for Ticket {
    fn bson_id_as_ref(&self) -> Option<&ObjectId> {
        self.id.as_ref()
    }

    fn bson_id(&self) -> AnyResult<&ObjectId> {
        self.id.as_ref().context("Ticket without BSON ObjectId")
    }
}

impl ReadWriteSuggest for Ticket {
    fn write_suggest() -> Self {
        Self::empty().with_mode(MediaMode::WriteSuggest)
    }

    fn with_mode(self, mode: MediaMode) -> Self {
        let mut ticket = Self::empty();
        ticket.mode_mut(mode);
        ticket
    }

    fn mode(&self) -> &MediaMode {
        &self.ext.mode
    }

    fn mode_mut(&mut self, mode: MediaMode) {
        self.ext.mode = mode;
    }

    #[cfg(feature = "gui")]
    /// Button to force reading images.
    fn read_mode_ui(&mut self, _ui: &mut egui::Ui) {
        #[cfg(feature = "image_processing")]
        if !self.ext.images_loaded {
            _ui.separator();
            if _ui
                .button(
                    RichText::new("🖳 Read Images")
                        .background_color(Color32::LIGHT_RED)
                        .color(Color32::BLACK),
                )
                .on_hover_text("Load all images for this ticket")
                .clicked()
            {
                self.texture_ids_mut();
            };
        };
    }

    #[cfg(feature = "gui")]
    fn write_suggest_ui(&mut self, ui: &mut egui::Ui) {
        if ui
            .button("➕ New Ticket")
            .on_hover_text("Add a new ticket for this asset")
            .clicked()
        {
            if self.ext.ticket_draft.is_none() {
                // init the `Composer`s once
                self.ext.start_new_composing();
            } else {
                // no need to init the `Composer`s again
                self.mode_mut(MediaMode::WriteCompose);
            };
        };
    }
}

impl Ticket {
    pub fn empty() -> Self {
        Self {
            topic: MsgTopic::Defect,
            created_at: Utc::now(),
            ..Default::default()
        }
    }

    fn sent_by(mut self, user: Staff) -> Self {
        self.sender = user.name_owned();
        self
    }

    fn topical_asset(mut self, topical: &ProductionAsset) -> AnyResult<Self> {
        self.topical_assets.push(topical.bson_id()?.clone());
        Ok(self)
    }

    fn created_now(mut self) -> Self {
        self.created_at = Utc::now();
        self
    }

    #[cfg(feature = "gui")]
    pub fn subtickets_result(
        mut self,
        subtickets: Result<Vec<SubTicket>, DatabaseError>,
        current_username: &str,
        chrono_fmt: &str,
        layout: &EmbedLayoutPref,
        img_hint: &PlaceImageHint,
    ) -> Self {
        self.ext.subtickets = subtickets.map(|subtickets| {
            subtickets
                .into_iter()
                .map(|s| {
                    SubTicketReadBuilder::new(s).finish(
                        current_username,
                        chrono_fmt,
                        layout,
                        img_hint,
                    )
                })
                .collect()
        });
        self
    }

    fn selected_if_any_unclosed_subticket(mut self) -> Self {
        self.ext = self.ext.selected_if_any_unclosed_subticket();
        self
    }

    /// Makes `TextureId`s for all images in the selected `Ticket`s.
    fn preload_tex_ids_if_selected(mut self) -> Self {
        if self.ext.selected {
            self.texture_ids_mut();
        };
        self
    }

    fn convert_local_time(mut self, chrono_fmt: &str) -> Self {
        self.ext.created_at_local = local_time(self.created_at, chrono_fmt);
        self
    }

    /// Finds the index for the "next" -- if being added -- `SubTicket` of this `Ticket`,
    /// in order to display to user the number of subticket they're writing.
    fn subticket_draft_number(mut self) -> Self {
        let next_number = match &self.ext.subtickets {
            Ok(subtickets) => subtickets
                .iter()
                .map(|s| s.number)
                .max()
                .map(|i| i + 1)
                .unwrap_or(1),
            Err(_) => 1,
        };

        self.ext.subticket_draft = self.ext.subticket_draft.number(next_number);
        self
    }

    /// Replaces default, empty, `TicketTally` with processed one.
    fn tally(mut self) -> Self {
        self.ext = self.ext.tally();
        self
    }

    fn untitled_if_empty(mut self) -> Self {
        if self.name.is_empty() {
            self.name = untitled();
        };
        self
    }

    fn expand(mut self, ext: TicketExpand) -> Self {
        self.ext = ext;
        self
    }
}

impl Ticket {
    /// This resets the `Self::ext` to default.
    fn clone_with_composer(&mut self) -> Self {
        let ext = std::mem::take(&mut self.ext);
        self.clone().expand(ext)
    }

    /// If any `DiscardableComposer` has some content input.
    pub(super) fn is_draft_unwrap_not_empty(&self) -> bool {
        self.ext
            .ticket_draft
            .as_ref()
            .unwrap()
            .iter()
            .filter(|draft| draft.composer.is_some())
            .any(|draft| !draft.composer.inner_as_ref_unwrap().is_empty())
    }

    /// Gets all pairs of subject and `Composer` where the `Composer` has some content.
    pub fn take_draft_unwrap(&mut self) -> Vec<SubTicketCompose> {
        self.ext
            .ticket_draft
            .take()
            .unwrap()
            .into_iter()
            // removes all `None` variant of `DiscardableComposer::0`s
            .filter_map(|draft| draft.try_into().ok())
            // and then all empty `Composer`s
            .filter(|draft: &SubTicketCompose| !draft.composer.is_empty())
            .collect()
    }

    pub fn subtickets_ids(&self) -> &Vec<ObjectId> {
        &self.content
    }

    pub fn selected(&self) -> bool {
        self.ext.selected
    }

    pub fn selected_mut(&mut self, selected: bool) {
        self.ext.selected = selected;
    }

    /// Loads `TextureId` for all children `SubTicket`s' content and discussion thread.
    pub fn texture_ids_mut(&mut self) {
        if let Ok(subtickets) = self.ext.subtickets.as_mut() {
            subtickets.iter_mut().for_each(|s| {
                s.texture_ids_mut();
            });
            #[cfg(feature = "image_processing")]
            {
                self.ext.images_loaded = true;
            }
        };
    }

    fn viewing_locale_mut(&mut self, locale: &Locale) {
        if let Ok(subtickets) = self.ext.subtickets.as_mut() {
            subtickets.iter_mut().for_each(|s| {
                s.viewing_locale_mut(locale);
            });
        };
        self.ext.viewing_locale = locale.clone();
    }

    fn type_as_str(&self) -> &str {
        self.typ.as_ref()
    }

    pub fn reply_box_width_mut(&mut self, width: f32) {
        if let Ok(subtickets) = self.ext.subtickets.as_mut() {
            subtickets.iter_mut().for_each(|s| {
                s.reply_box_width_mut(width);
            });
        };
    }
}

#[cfg(feature = "gui")]
/// All UI-related methods.
impl Ticket {
    /// A `toggle_value` for `Self::ext::metadata::selected`.
    pub fn show_toggle_vis_button(&mut self, ui: &mut egui::Ui) {
        if ui
            .toggle_value(&mut self.ext.selected, &self.name)
            .clicked()
        {
            #[cfg(feature = "image_processing")]
            if !self.ext.images_loaded {
                self.texture_ids_mut();
            };
        };
    }

    pub fn show_ticket_details(&self, ui: &mut egui::Ui) {
        ui.label(format!(
            "{} {} Feedback",
            self.ext.created_at_local,
            self.type_as_str()
        ));
        ui.heading(&self.name);
    }

    pub fn show_tally(&self, ui: &mut egui::Ui) {
        self.ext.tally.ui(ui);
    }

    /// Locale option radio buttons.
    pub fn show_viewing_locale_options(&mut self, ui: &mut egui::Ui) {
        if let Ok(settings) = ClientCfgCel::settings() {
            ui.horizontal(|ui| {
                for locale in Locale::iter() {
                    if settings.locales().contains(&locale.as_ref().to_owned()) {
                        if ui
                            .add(egui::RadioButton::new(
                                self.ext.viewing_locale == locale,
                                locale.as_ref(),
                            ))
                            .clicked()
                        {
                            self.viewing_locale_mut(&locale)
                        };
                    };
                }
            });
        };
    }

    pub fn edit_metadata_ui(&mut self, ui: &mut egui::Ui) {
        // Ticket agent
        ticket_author_source_options_ui(ui, &mut self.typ);

        // Ticket name
        ui.horizontal(|ui| {
            ui.label(RichText::new("Ticket Name:").heading().strong());
            ui.add(egui::TextEdit::singleline(&mut self.name).desired_width(f32::INFINITY));
        });
        // Ticket locale
        locale::locale_options_ui(ui, &mut self.composed_with_locale);
    }

    pub fn discardable_composers_unwrap_ui(&mut self, ui: &mut egui::Ui, palette: &Palette) {
        // subticket drafts
        self.ext.discardable_composers_unwrap_ui(ui, palette);

        // "Add Subticket" button
        ui.with_layout(Layout::right_to_left(Align::Min), |ui| {
            self.ext.show_add_subticket_draft_unwrap_button(ui);
        });
    }

    pub fn show_delete_button(&self, ui: &mut egui::Ui, tx: &Sender<TicketAction>) {
        if ui
            .button("🗑")
            .on_hover_text(
                RichText::new(format!(
                    "Delete this whole {} Feedback Ticket",
                    self.type_as_str()
                ))
                .color(Color32::RED),
            )
            .clicked()
        {
            if dialog::confirm_dialog(
                &format!("Delete this {} Feedback Ticket?", self.type_as_str()),
                "Deleting ticket cannot be undone",
            ) {
                tx.send(TicketAction::DeleteTicket {
                    ticket: self.bson_id_as_ref().cloned(),
                })
                .ok();
            };
        };
    }

    fn collapse_subtickets(&mut self, open: bool) {
        if let Ok(subtickets) = self.ext.subtickets.as_mut() {
            subtickets.iter_mut().for_each(|s| s.ext.open = open);
        };
    }

    fn expand_unclosed_subtickets(&mut self) {
        if let Ok(subtickets) = self.ext.subtickets.as_mut() {
            subtickets.iter_mut().for_each(|s| s.open_mut_if_unclosed());
        };
    }

    fn show_toggle_all_collapse_states_button(&mut self, ui: &mut egui::Ui) {
        let text = RichText::new(if self.ext.batch_collapse {
            "⏷ Expand All"
        } else {
            "➖ Collapse All"
        });
        if ui
            .button(text)
            .on_hover_text("Toggle all Subtickets' collapse states")
            .clicked()
        {
            self.collapse_subtickets(self.ext.batch_collapse);
            self.ext.batch_collapse = !self.ext.batch_collapse;
        };
    }

    /// Collapses/expands all `CollapsingHeader`s of the `SubTicket`s.
    pub fn show_batch_action_buttons(&mut self, ui: &mut egui::Ui) {
        // ui.menu_button("☰", |ui| {
        //     ui.close_menu();
        // });

        if ui
            .button("👁 All Unclosed")
            .on_hover_text("Expand all unclosed Subtickets")
            .clicked()
        {
            self.expand_unclosed_subtickets();
        };

        self.show_toggle_all_collapse_states_button(ui);
    }

    pub fn show_create_ticket_buttons(&mut self, ui: &mut egui::Ui, tx: &Sender<TicketAction>) {
        ui.horizontal(|ui| {
            ui.with_layout(Layout::right_to_left(Align::Max), |ui| {
                // reset all drafts
                if ui
                    .button("🕱 Reset Drafts")
                    .on_hover_text(
                        RichText::new(
                            "Start over by removing all what are being written, including chosen images",
                        )
                        .color(Color32::RED),
                    )
                    .clicked()
                {
                    self.ext.start_new_composing()
                };

                // cancel compose mode
                if ui.button("❌ Cancel").clicked() {
                    self.mode_mut(MediaMode::WriteSuggest);
                };

                // submit `Ticket` draft
                if ui
                    .add_enabled(
                        self.is_draft_unwrap_not_empty(),
                        egui::Button::new(format!("✔ Create {} Feedback Ticket", self.type_as_str())),
                    )
                    .clicked()
                {
                    tx.send(TicketAction::CreateTicket {
                        // must move `Composer` from `Self::ext` to the cloned `Ticket`
                        ticket: self.clone_with_composer(),
                        typ: self.typ.clone(),
                    }).ok();
                };
            });
        });
    }
}

// ----------------------------------------------------------------------------
#[derive(Debug, Clone)]
pub struct TicketExpand {
    mode: MediaMode,

    pub created_at_local: String,

    pub tally: TicketTally,

    viewing_locale: Locale,

    // #[serde(default = "default_uninitialized")]
    /// Deserialized `SubTicket`s for viewing.
    pub subtickets: Result<Vec<SubTicket>, DatabaseError>,

    /// For adding a `SubTicket` to this `Ticket`.
    pub subticket_draft: SubTicket,

    /// For creating a brand-new `Ticket` container which hosts many
    /// [`SubTicket`] children. The `String` is for `SubTicket::subject`.
    ticket_draft: Option<Vec<SubTicketDiscardableCompose>>,

    /// Whether its corresponding checkbox should be checked.
    selected: bool,

    /// State to perform next batch collapse action on all `SubTicket`s' `CollapsingHeader`s.
    batch_collapse: bool,

    #[cfg(feature = "image_processing")]
    images_loaded: bool,
}

impl Default for TicketExpand {
    fn default() -> Self {
        Self {
            mode: Default::default(),
            created_at_local: String::new(),
            tally: Default::default(),
            viewing_locale: Default::default(),
            subtickets: Err(DatabaseError::Uninitialized),
            subticket_draft: SubTicket::write_suggest(),
            ticket_draft: None,
            selected: false,
            batch_collapse: false,
            #[cfg(feature = "image_processing")]
            images_loaded: false,
        }
    }
}

impl TicketExpand {
    fn start_new_composing(&mut self) {
        self.ticket_draft = Some(vec![SubTicketDiscardableCompose::first()]);
        self.mode = MediaMode::WriteCompose;
    }

    /// NOTE: `SubTicket::ext` must be processed prior to this.
    fn selected_if_any_unclosed_subticket(mut self) -> Self {
        if let Ok(subtickets) = self.subtickets.as_ref() {
            if subtickets.iter().any(|subticket| !subticket.is_closed()) {
                self.selected = true;
            };
        };

        self
    }

    fn tally(mut self) -> Self {
        self.tally =
            TicketTally::from_subtickets(self.subtickets.as_ref().ok().map(|s| s.as_slice()));
        self
    }
}

#[cfg(feature = "gui")]
impl TicketExpand {
    fn show_add_subticket_draft_unwrap_button(&mut self, ui: &mut egui::Ui) {
        if ui
            .button(RichText::new("➕ Add Subticket").strong())
            .on_hover_text("Insert next subticket draft")
            .clicked()
        {
            let len = self.ticket_draft.as_ref().unwrap().len();
            self.ticket_draft
                .as_mut()
                .unwrap()
                .push(SubTicketDiscardableCompose::next(len + 1));
        }
    }

    fn discardable_composers_unwrap_ui(&mut self, ui: &mut egui::Ui, palette: &Palette) {
        egui::ScrollArea::vertical()
            // sometimes a ticket has a lot of subtickets
            .max_height(700.)
            .show(ui, |ui| {
                self.ticket_draft
                    .as_mut()
                    .unwrap()
                    .iter_mut()
                    .enumerate()
                    // stops showing what has been previously discarded by user
                    .filter(|(_, s)| !s.composer.is_none())
                    .for_each(|(i, s)| {
                        ui.allocate_space(egui::vec2(0., 10.));
                        s.unwrap_ui(ui, i, palette);
                        ui.separator();
                    });
            });
    }
}

/// Converts the `Ticket::created_at` value from UTC to local time.
fn local_time(utc: DateTime<Utc>, chrono_fmt: &str) -> String {
    let local_time: DateTime<Local> = DateTime::from(utc);
    format!("{}", local_time.format(chrono_fmt))
}

// ----------------------------------------------------------------------------
#[derive(Debug)]
pub struct TicketReadBuilder(Ticket);

impl TicketReadBuilder {
    pub fn new(ticket: Ticket) -> Self {
        Self(ticket)
    }

    /// NOTE: The `Ticket::ext` should already be fully expanded, e.g., its [`SubTicket`] childrens have been deserialized,
    /// prior to this being used.
    pub fn finish(self, chrono_fmt: &str, preload_images: bool) -> Ticket {
        let ticket = self
            .0
            .untitled_if_empty()
            // makes the `Ticket` selected if it contains any unclosed `SubTicket`
            .selected_if_any_unclosed_subticket()
            .subticket_draft_number()
            .tally()
            .convert_local_time(chrono_fmt);

        if preload_images {
            // NOTE: this might be slow
            ticket.preload_tex_ids_if_selected()
        } else {
            ticket
        }
    }
}

// ----------------------------------------------------------------------------
#[derive(Debug)]
pub struct TicketWriteBuilder(Ticket);

impl TicketWriteBuilder {
    pub fn new(ticket: Ticket) -> Self {
        Self(ticket)
    }

    pub fn finish(self, sent_by: Staff, topical: &ProductionAsset) -> AnyResult<Ticket> {
        Ok(self
            .0
            .topical_asset(topical)?
            .sent_by(sent_by)
            .created_now())
    }
}