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
use super::*;

pub const NO_REVIEW_ITEM_TYPE_ERR: &str = "No Supervision (review item) type found";

#[derive(Debug, Clone, PartialEq, Eq)]
/// The possible reviewed state of a [`Notice`].
pub enum Reviewed {
    /// The item has been reviewed, -- by a given staff role --, in a given time period.
    Yes,

    /// The item has not been reviewed, -- by a given staff role --, in a given time period.
    No,

    /// The item is not submitted in a given time period.
    NoSubmission,

    /// The item's reviewed state is not tracked by the given staff role,
    /// or no data available to deduce from.
    Inapplicable,
}

impl Reviewed {
    /// Looks through an iterator of `Reviewed` and determines a conclusion about the sequence's review state.
    pub fn verdict<'a>(seq: impl Iterator<Item = &'a Self>) -> Self {
        let mut iter = seq.into_iter();
        match iter.next() {
            None => {
                // the iterator exhausts, this can't be considered `Reviewed::Yes`
                Self::Inapplicable
            }
            Some(reviewed) => match reviewed {
                Self::Inapplicable => {
                    // since `Self::Inapplicable` is not expected to change over time,
                    // we're just returning it right away
                    Self::Inapplicable
                }
                Self::Yes => {
                    // this is the closest known state of the review item
                    Self::Yes
                }
                Self::No => {
                    // this is the closest known state of the review item
                    Self::No
                }
                Self::NoSubmission => {
                    // `NoSubmission` means no data to decide, so we skips
                    // this position and performs recursively onwards
                    Self::verdict(iter)
                }
            },
        }
    }

    fn from_notice_option(notice: Option<&Notice>, reviewer_role: &ProductionRole) -> Self {
        match notice {
            Some(notice) => notice.is_reviewed_by(reviewer_role),
            None => Reviewed::NoSubmission,
        }
    }
}

// -------------------------------------------------------------------------------
#[derive(Debug, Clone, Serialize, Deserialize)]
/// Group of [`Notice`]s of different types, i.e. WIP, feedback, approval, client.
/// LEGACY DESIGN: DO NOT change field names or `serde(rename)` values.
pub struct DailyNotice {
    #[serde(rename = "wip_review", skip_serializing_if = "Option::is_none")]
    pub(crate) wip: Option<Notice>,

    #[serde(rename = "feedback_review", skip_serializing_if = "Option::is_none")]
    pub(crate) feedback: Option<Notice>,

    #[serde(rename = "approval_review", skip_serializing_if = "Option::is_none")]
    pub(crate) approval: Option<Notice>,

    #[serde(rename = "client_feedback", skip_serializing_if = "Option::is_none")]
    pub(crate) client: Option<Notice>,
}

impl DailyNotice {
    /// Gets specific review type, given the [`Supervision`] type.
    pub fn review_type(&self, typ: &Supervision) -> Option<&Notice> {
        match typ {
            Supervision::Wip => self.wip.as_ref(),
            Supervision::Feedback => self.feedback.as_ref(),
            Supervision::Approval => self.approval.as_ref(),
            Supervision::Client => self.client.as_ref(),
        }
    }

    pub fn is_empty(&self) -> bool {
        self.wip.is_none()
            && self.feedback.is_none()
            && self.approval.is_none()
            && self.client.is_none()
    }

    /// Applies trimming for all review type.
    pub fn trim(&mut self, evaluation_date: &NaiveDate, trim_options: &NaiveTrimOptions) {
        // Wip
        Notice::trim(&mut self.wip, evaluation_date, trim_options.wip.as_ref());
        // Feedback
        Notice::trim(
            &mut self.feedback,
            evaluation_date,
            trim_options.feedback.as_ref(),
        );
        // Approval
        Notice::trim(
            &mut self.approval,
            evaluation_date,
            trim_options.approval.as_ref(),
        );
        // Client
        Notice::trim(
            &mut self.client,
            evaluation_date,
            trim_options.client.as_ref(),
        );
    }

    /// For each field of `Option<Notice>`, sees if it's reviewed or not.
    /// This is receiving a [`ProductionRole`] as an argument since it might in the future
    /// expand to support for review by `ProductionRole::TeamLead` and probably others.
    /// If the field value -- for each review type -- is `Option::None` then it gets converted
    /// to `Reviewed::NoSubmission`.
    pub fn is_reviewed_by(&self, reviewer_role: &ProductionRole) -> DailyReview {
        DailyReview {
            wip: Reviewed::from_notice_option(self.wip.as_ref(), reviewer_role),
            feedback: Reviewed::from_notice_option(self.feedback.as_ref(), reviewer_role),
            approval: Reviewed::from_notice_option(self.approval.as_ref(), reviewer_role),
            client: Reviewed::from_notice_option(self.client.as_ref(), reviewer_role),
        }
    }

    /// Converts `submit_time` from `String` to `NaiveTime`.
    pub fn parse_submit_time(&mut self, fmt: &str) {
        if let Some(n) = self.wip.as_mut() {
            n.parse_submit_time(fmt);
        };
        if let Some(n) = self.feedback.as_mut() {
            n.parse_submit_time(fmt);
        };
        if let Some(n) = self.approval.as_mut() {
            n.parse_submit_time(fmt);
        };
        if let Some(n) = self.client.as_mut() {
            n.parse_submit_time(fmt);
        };
    }
}

// -------------------------------------------------------------------------------
#[derive(Debug, Clone)]
/// A grouped "review verdicts" of an asset, which is the record of the review state
/// of each review type within a [`DailyNotice`].
pub struct DailyReview {
    pub wip: Reviewed,
    pub feedback: Reviewed,
    pub approval: Reviewed,
    pub client: Reviewed,
}

impl DailyReview {
    /// Gets the inner depending on the [`Supervision`] type.
    pub fn review_item(&self, typ: &Supervision) -> &Reviewed {
        match typ {
            Supervision::Wip => &self.wip,
            Supervision::Feedback => &self.feedback,
            Supervision::Approval => &self.approval,
            Supervision::Client => &self.client,
        }
    }
}

// -------------------------------------------------------------------------------
/// NOTE: one should take care of the `Notice::enabled` to hold a boolean value instead
/// of `None`.
pub struct NoticeWriteBuilder(Notice);

impl NoticeWriteBuilder {
    pub fn new(notice: Notice) -> Self {
        Self(notice)
    }

    fn created_at(mut self, submit_time: &DateTime<Local>) -> AnyResult<Self> {
        self.0.created_at_str = Some(submit_time_str(submit_time)?);
        Ok(self)
    }

    pub fn finish(self, submit_time: &DateTime<Local>) -> AnyResult<Notice> {
        Ok(self.created_at(submit_time)?.0)
    }
}

// -------------------------------------------------------------------------------
#[derive(Debug, Clone, Serialize, Deserialize)]
/// An simple communication to signal the supervisors about things which
/// need their attention.
/// LEGACY DESIGN: DO NOT change field names or `serde(rename)` values.
pub struct Notice {
    #[serde(skip)]
    /// Used chiefly for displaying as "drafts" in UI for the artists to use, so that they'll
    /// toggle/enable the submit status, thus contributing to the stats table.
    pub typ: Option<Supervision>,
    #[serde(rename = "submit_enabled")]
    /// The original `submit_enabled` field. Put behind an [`Option`] to support legacy documents.
    enabled: Option<bool>,
    #[serde(rename = "submit_time")]
    /// The original `submit_time` field. Put behind an [`Option`] to support legacy documents.
    created_at_str: Option<String>,
    #[serde(skip)]
    created_at: Option<NaiveTime>,
    #[serde(rename = "viewed_by_AD")]
    /// The original `viewed_by_AD` field. Put behind an [`Option`] to support legacy documents.
    ad_viewed: Option<bool>,
}

impl Notice {
    /// Constructor with `Self::enabled` set to `false` and with `Self::typ` we
    /// know for sure `is_some`. All "viewed_by" state(s), e.g. `Self::ad_viewed`
    /// are set to `false`.
    pub fn draft(typ: Supervision) -> Self {
        Self {
            typ: Some(typ),
            enabled: Some(false),
            created_at_str: None,
            created_at: None,
            ad_viewed: Some(false),
        }
    }

    #[cfg(feature = "gui")]
    /// SAFETY: caller is responsible to make sure both `notice::typ` and `notice::enabled` `is_some`.
    pub fn draft_unwrap_ui(&mut self, ui: &mut egui::Ui) -> egui::Response {
        let typ = self.typ.as_ref().unwrap();
        let enabled = self.enabled.as_mut().unwrap();
        ui.toggle_value(enabled, typ.signaling_label())
            .on_hover_text(typ.draft_tooltip())
    }

    /// Constructor with `Self::enabled` set to `target`.
    pub fn enabled(typ: Supervision, target: bool) -> Self {
        Self {
            typ: Some(typ),
            enabled: Some(target),
            created_at_str: None,
            created_at: None,
            ad_viewed: Some(false),
        }
    }

    /// Constructor with `viewed by` state set to `target`. Not all [`ProductionRole`]s as reviewers are supported.
    pub fn reviewed(
        typ: Supervision,
        reviewer_role: &ProductionRole,
        target: bool,
    ) -> Option<Self> {
        match reviewer_role {
            ProductionRole::ArtDirector | ProductionRole::TechSupport => Some(Self {
                typ: Some(typ),
                enabled: Some(true),
                created_at_str: None,
                created_at: None,
                ad_viewed: Some(target),
            }),
            _ => {
                // unsupported
                None
            }
        }
    }

    /// Same as `Self::reviewed` but inherits the submit time.
    pub fn reviewed_enabled(
        mut self,
        reviewer_role: &ProductionRole,
        target: bool,
    ) -> Option<Self> {
        match reviewer_role {
            ProductionRole::ArtDirector | ProductionRole::TechSupport => {
                self.enabled = Some(true);
                self.ad_viewed = Some(target);
                Some(self)
            }
            _ => {
                // unsupported
                None
            }
        }
    }

    pub fn is_enabled_or_false(&self) -> bool {
        match &self.enabled {
            Some(enabled) => *enabled,
            None => false,
        }
    }

    /// The `notice` is normally the result received from fetching the DB, and through which
    /// we're mutating `Self::enabled` state.
    pub fn enabled_mut(&mut self, notice: Result<Self, DatabaseError>) {
        match notice {
            Err(_) => {
                // default it to `false`
                self.enabled = Some(false);
            }
            Ok(notice) => {
                self.enabled = Some(notice.enabled.unwrap_or(false));
            }
        }
    }

    /// This relies on `Supervision::AsRefStr` values to produce correct key literals.
    fn review_type_as_str(&self) -> AnyResult<&str> {
        Ok(self.typ.as_ref().context(NO_REVIEW_ITEM_TYPE_ERR)?.as_ref())
    }

    pub fn submit_target_desc(&self) -> AnyResult<String> {
        let desc = match self
            .enabled
            .as_ref()
            .context("No \"submit_enabled\" target found")?
        {
            true => "Enabled Successfully",
            false => "Disabled Successfully",
        };
        Ok(desc.to_string())
    }

    pub fn submit_type_desc(&self) -> AnyResult<String> {
        Ok(format!("Review item type: {}", self.review_type_as_str()?,))
    }

    fn trim(
        notice: &mut Option<Self>,
        evaluation_date: &NaiveDate,
        range: Option<&AnyResult<Vec<NaiveDate>>>,
    ) {
        if let Some(_) = notice {
            match range {
                Some(Ok(range)) => {
                    if !range.contains(evaluation_date) {
                        // not within interest
                        notice.take();
                    };
                }
                Some(Err(_)) => {
                    // range is invalid, let's take the `notice`
                    notice.take();
                }
                None => {} // doing nothing
            };
        };
    }

    /// Converts `submit_time` from `String` to `NaiveTime`.
    fn parse_submit_time(&mut self, fmt: &str) {
        if let Some(created_at) = &self.created_at_str {
            self.created_at = NaiveTime::parse_from_str(&created_at, fmt).ok();
        }
    }

    pub fn is_reviewed_by(&self, reviewer_role: &ProductionRole) -> Reviewed {
        match self.enabled {
            Some(enabled) => {
                if !enabled {
                    // the item is no longer enabled
                    return Reviewed::NoSubmission;
                };
                match reviewer_role {
                    ProductionRole::ArtDirector => {
                        // converts from `Self::ad_viewed` value
                        match self.ad_viewed {
                            Some(ad_viewed) => match ad_viewed {
                                true => Reviewed::Yes,
                                false => Reviewed::No,
                            },
                            None => {
                                // probably missing field from legacy docs, if a review item
                                // does not have `viewed_by_AD` field then we regard it as NOT reviewed
                                Reviewed::No
                            }
                        }
                    }
                    // roles for which reviewed state is untracked
                    _ => Reviewed::Inapplicable,
                }
            }
            None => {
                // probably missing field from legacy docs, if a review item
                // does not have `submit_enabled` field then we regard it as reviewed
                Reviewed::Yes
            }
        }
    }
}

// -------------------------------------------------------------------------------
#[derive(Debug)]
/// Populates necessary fields for UI, namely `Notice:typ` and `Notice::enabled`.
pub struct NoticeReadBuilder(Notice);

impl NoticeReadBuilder {
    pub fn new(notice: Notice) -> Self {
        Self(notice)
    }

    pub fn finish(mut self, _typ: &Supervision) -> AnyResult<Notice> {
        // prepares `NaiveTime`
        self.0.parse_submit_time(time_fmt_cfg()?);

        // since we're all using `Notice::draft` for constructing UI checkboxes, for now
        // we can skip the modifications of `Notice::typ` and `Notice::enabled` as commented below

        // // sets `Notice::typ`
        // self.0.typ = Some(typ);
        // // must also ensure the `Notice::enabled` `is_some`
        // if self.0.enabled.is_none() {
        //     self.0.enabled = Some(false);
        // };

        Ok(self.0)
    }
}

// -------------------------------------------------------------------------------
// daily_review: {
//     '2020-11-30': {
//         feedback_review: {
//             submit_enabled: true,
//             submit_time: '15:41:44.334996',
//             viewed_by_AD: true
//         },
//         approval_review: {
//             submit_enabled: true,
//             submit_time: '15:22:51.533574',
//             viewed_by_AD: true
//         }
//     },
//     '2020-12-01': {
//         wip_review: {
//             submit_enabled: true,
//             submit_time: '18:58:02.885608',
//             viewed_by_AD: false
//         }
//     },
//     '2020-12-17': {
//         feedback_review: {
//             submit_enabled: true,
//             submit_time: '15:58:12.704727',
//             viewed_by_AD: true
//         },
//         unite_tt_review: {
//             submit_enabled: true,
//             submit_time: '19:13:07.629434',
//             viewed_by_AD: false
//         },
//         approval_review: {
//             submit_enabled: true,
//             submit_time: '19:20:05.878520',
//             viewed_by_AD: false
//         }
//     },
//     '2021-03-04': {
//         client_feedback: {
//             submit_enabled: true,
//             submit_time: '17:33:14.803184',
//             viewed_by_AD: false
//         }
//     },
//     '2021-03-08': {
//         client_feedback: {
//             submit_enabled: true,
//             submit_time: '10:53:55.753272',
//             viewed_by_AD: false
//         }
//     }
// }

// -------------------------------------------------------------------------------
/// Each original [`DateRange`] can be unvalid when converted to the dates between, therefore
/// we're retaining the `Result`s.
pub struct NaiveTrimOptions {
    wip: Option<AnyResult<Vec<NaiveDate>>>,
    feedback: Option<AnyResult<Vec<NaiveDate>>>,
    approval: Option<AnyResult<Vec<NaiveDate>>>,
    client: Option<AnyResult<Vec<NaiveDate>>>,
}

impl From<&TrimOptions> for NaiveTrimOptions {
    fn from(trim: &TrimOptions) -> Self {
        Self {
            wip: trim.wip.as_ref().map(|r| r.dates_between()),
            feedback: trim.feedback.as_ref().map(|r| r.dates_between()),
            approval: trim.approval.as_ref().map(|r| r.dates_between()),
            client: trim.client.as_ref().map(|r| r.dates_between()),
        }
    }
}

// -------------------------------------------------------------------------------
#[derive(Debug, Clone, Default)]
pub struct TrimOptions {
    pub wip: Option<DateRange>,
    pub feedback: Option<DateRange>,
    pub approval: Option<DateRange>,
    pub client: Option<DateRange>,
}

impl TrimOptions {
    /// Does not trim any review type.
    pub fn none() -> Self {
        Self::default()
    }

    /// Trims the `client_feedback` with its own date range, and the rest with the same date range.
    pub fn client_special(client: DateRange, others: Option<DateRange>) -> Self {
        Self {
            wip: others.clone(),
            feedback: others.clone(),
            approval: others,
            client: Some(client),
        }
    }

    /// All review types with the same date range for trimming.
    pub fn homogeneous(range: Option<DateRange>) -> Self {
        Self {
            wip: range.clone(),
            feedback: range.clone(),
            approval: range.clone(),
            client: range,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn reviewed_verdicts() {
        // Sequence 1: with `No` after a series of `NoSubmission`s
        let seq = [Reviewed::NoSubmission, Reviewed::NoSubmission, Reviewed::No];
        let reviewed = Reviewed::verdict(seq.iter());
        assert_eq!(reviewed, Reviewed::No);

        // Sequence 2: with `Yes` after a series of `NoSubmission`s and a trailing `Inapplicable`
        let seq = [
            Reviewed::NoSubmission,
            Reviewed::NoSubmission,
            Reviewed::Yes,
            Reviewed::Inapplicable,
        ];
        let reviewed = Reviewed::verdict(seq.iter());
        assert_eq!(reviewed, Reviewed::Yes);

        // Sequence 3: with `No` at the start
        let seq = [
            Reviewed::No,
            Reviewed::NoSubmission,
            Reviewed::NoSubmission,
            Reviewed::Yes,
        ];
        let reviewed = Reviewed::verdict(seq.iter());
        assert_eq!(reviewed, Reviewed::No);

        // Sequence 4: empty sequence
        let seq = [];
        let reviewed = Reviewed::verdict(seq.iter());
        assert_eq!(reviewed, Reviewed::Yes);

        // Sequence 5: array of only `NoSubmission`s
        let seq = [
            Reviewed::NoSubmission,
            Reviewed::NoSubmission,
            Reviewed::NoSubmission,
            Reviewed::NoSubmission,
            Reviewed::NoSubmission,
        ];
        let reviewed = Reviewed::verdict(seq.iter());
        assert_eq!(reviewed, Reviewed::Yes);
    }
}