You are not logged in. Log in. Or Sign up.

NOTE: Federation is disabled on this instance!

You can test federation between the following instances:
Vervis @ dev.angeley.es
HomeSharersfr33domloverReposvervisFilessrcVervisHandler Ticket.hs

Belongs to project Vervis

[[ 🧙 fr33domlover ]] :: [📥 Inbox] [📤 Outbox] [🐤 Followers] [🐔 Following] [🏗 Projects] [🗃 Repositories] [🔁 Workflows] [🐛 Tickets]
[[ 🏗 vervis ]] :: [📥 Inbox] [📤 Outbox] [🐤 Followers] [🤝 Collaborators] [🐛 Tickets] [✋ Ticket claim requests] [🔁 Ticket workflow: dummy ] [📖 Wiki] [✏ Edit]

Eventually-decentralized project hosting and management platform

[[ 🧙 fr33domlover ]] :: [📥 Inbox] [📤 Outbox] [🐤 Followers] [🐔 Following] [🏗 Projects] [🗃 Repositories] [🔁 Workflows] [🐛 Tickets]
[[ 🗃 vervis ]] :: [📥 Inbox] [📤 Outbox] [🐤 Followers] [🤝 Collaborators] [🛠 Changes]

Tags

TODO

src / Vervis / Handler /

Ticket.hs

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
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
{- This file is part of Vervis.
 -
 - Written in 2016, 2018, 2019, 2020 by fr33domlover <fr33domlover@riseup.net>.
 -
 - ♡ Copying is an act of love. Please copy, reuse and share.
 -
 - The author(s) have dedicated all copyright and related and neighboring
 - rights to this software to the public domain worldwide. This software is
 - distributed without any warranty.
 -
 - You should have received a copy of the CC0 Public Domain Dedication along
 - with this software. If not, see
 - <http://creativecommons.org/publicdomain/zero/1.0/>.
 -}

module Vervis.Handler.Ticket
    ( getProjectTicketsR
    , getProjectTicketTreeR
    , getProjectTicketNewR
    , getProjectTicketR
    , putProjectTicketR
    , deleteProjectTicketR
    , postProjectTicketR
    , getProjectTicketEditR
    , postProjectTicketAcceptR
    , postProjectTicketCloseR
    , postProjectTicketOpenR
    , postProjectTicketClaimR
    , postProjectTicketUnclaimR
    , getProjectTicketAssignR
    , postProjectTicketAssignR
    , postProjectTicketUnassignR
    , getClaimRequestsPersonR
    , getClaimRequestsProjectR
    , getClaimRequestsTicketR
    , postClaimRequestsTicketR
    , getClaimRequestNewR
    , getProjectTicketDiscussionR
    , postProjectTicketDiscussionR
    , getMessageR
    , postProjectTicketMessageR
    , getProjectTicketTopReplyR
    , getProjectTicketReplyR
    , getProjectTicketDepsR
    , postProjectTicketDepsR
    , getProjectTicketDepNewR
    , postTicketDepOldR
    , deleteTicketDepOldR
    , getProjectTicketReverseDepsR
    , getTicketDepR
    , getProjectTicketParticipantsR
    , getProjectTicketTeamR
    , getProjectTicketEventsR

    , getSharerTicketsR
    , getSharerTicketR
    , getSharerTicketDiscussionR
    , getSharerTicketDepsR
    , getSharerTicketReverseDepsR
    , getSharerTicketFollowersR
    , getSharerTicketTeamR
    , getSharerTicketEventsR
    )
where

import Control.Applicative (liftA2)
import Control.Monad
import Control.Monad.IO.Class (liftIO)
import Control.Monad.Logger.CallStack
import Control.Monad.Trans.Except
import Data.Aeson (encode)
import Data.Bifunctor
import Data.Bitraversable
import Data.Bool (bool)
import Data.Default.Class (def)
import Data.Foldable (traverse_)
import Data.Function
import Data.Maybe
import Data.Monoid ((<>))
import Data.Text (Text)
import Data.Time.Calendar (Day (..))
import Data.Time.Clock (UTCTime (..), getCurrentTime)
import Data.Time.Format (formatTime, defaultTimeLocale)
import Data.Traversable (for)
import Database.Persist
import Network.HTTP.Types (StdMethod (DELETE, POST))
import Text.Blaze.Html (Html, toHtml, preEscapedToHtml)
import Text.Blaze.Html.Renderer.Text
import Text.HTML.SanitizeXSS
import Yesod.Auth (requireAuthId, maybeAuthId)
import Yesod.Core hiding (logWarn)
import Yesod.Core.Handler
import Yesod.Form.Functions (runFormGet, runFormPost)
import Yesod.Form.Types (FormResult (..))
import Yesod.Persist.Core (runDB, get404, getBy404)

import qualified Data.ByteString.Lazy as BL
import qualified Data.List.Ordered as LO
import qualified Data.Text as T (filter, intercalate, pack)
import qualified Data.Text.Lazy as TL
import qualified Database.Esqueleto as E

import Database.Persist.Sql.Graph.TransitiveReduction (trrFix)

import Data.Aeson.Encode.Pretty.ToEncoding
import Data.MediaType
import Network.FedURI
import Web.ActivityPub hiding (Ticket (..), Project, TicketDependency)
import Yesod.ActivityPub
import Yesod.Auth.Unverified
import Yesod.FedURI
import Yesod.Hashids
import Yesod.MonadSite
import Yesod.RenderSource

import qualified Web.ActivityPub as AP

import Data.Either.Local
import Data.Maybe.Local (partitionMaybePairs)
import Data.Paginate.Local
import Database.Persist.Local
import Yesod.Persist.Local

import Vervis.ActivityPub
import Vervis.API
import Vervis.Discussion
import Vervis.Federation
import Vervis.FedURI
import Vervis.Form.Ticket
import Vervis.Foundation
import Vervis.Handler.Discussion
import Vervis.GraphProxy (ticketDepGraph)
import Vervis.Model
import Vervis.Model.Ident
import Vervis.Model.Ticket
import Vervis.Model.Workflow
import Vervis.Paginate
import Vervis.Settings
import Vervis.Style
import Vervis.Ticket
import Vervis.TicketFilter (filterTickets)
import Vervis.Time (showDate)
import Vervis.Widget (buttonW)
import Vervis.Widget.Discussion (discussionW)
import Vervis.Widget.Sharer
import Vervis.Widget.Ticket

getProjectTicketsR :: ShrIdent -> PrjIdent -> Handler TypedContent
getProjectTicketsR shr prj = selectRep $ do
    provideRep $ do
        ((filtResult, filtWidget), filtEnctype) <- runFormGet ticketFilterForm
        let tf =
                case filtResult of
                    FormSuccess filt -> filt
                    FormMissing      -> def
                    FormFailure l    ->
                        error $ "Ticket filter form failed: " ++ show l
        (total, pages, mpage) <- runDB $ do
            Entity sid _ <- getBy404 $ UniqueSharer shr
            Entity jid _ <- getBy404 $ UniqueProject prj sid
            let countAllTickets = count [TicketProjectLocalProject ==. jid]
                selectTickets off lim =
                    getTicketSummaries
                        (filterTickets tf)
                        (Just $ \ t -> [E.asc $ t E.^. TicketId])
                        (Just (off, lim))
                        jid
            getPageAndNavCount countAllTickets selectTickets
        case mpage of
            Nothing -> redirectFirstPage here
            Just (rows, navModel) ->
                let pageNav = navWidget navModel
                in  defaultLayout $(widgetFile "ticket/list")
    provideAP' $ do
        (total, pages, mpage) <- runDB $ do
            Entity sid _ <- getBy404 $ UniqueSharer shr
            Entity jid _ <- getBy404 $ UniqueProject prj sid
            let countAllTickets = count [TicketProjectLocalProject ==. jid]
                selectTickets off lim = do
                    tids <- E.select $ E.from $ \ (tcl `E.InnerJoin` tpl) -> do
                        E.on $ tcl E.^. TicketContextLocalId E.==. tpl E.^. TicketProjectLocalContext
                        E.where_ $ tpl E.^. TicketProjectLocalProject E.==. E.val jid
                        E.orderBy [E.desc $ tcl E.^. TicketContextLocalTicket]
                        E.offset $ fromIntegral off
                        E.limit $ fromIntegral lim
                        return $ tcl E.^. TicketContextLocalTicket
                    let tids' = map E.unValue tids
                    locals <- E.select $ E.from $ \ (lt `E.LeftOuterJoin` (tal `E.InnerJoin` p `E.InnerJoin` s `E.LeftOuterJoin` tup)) -> do
                        E.on $ tal E.?. TicketAuthorLocalId E.==. tup E.?. TicketUnderProjectAuthor
                        E.on $ p E.?. PersonIdent E.==. s E.?. SharerId
                        E.on $ tal E.?. TicketAuthorLocalAuthor E.==. p E.?. PersonId
                        E.on $ E.just (lt E.^. LocalTicketId) E.==. tal E.?. TicketAuthorLocalTicket
                        E.where_ $ lt E.^. LocalTicketTicket `E.in_` E.valList tids'
                        E.orderBy [E.desc $ lt E.^. LocalTicketTicket]
                        return
                            ( lt E.^. LocalTicketTicket
                            , ( lt E.^. LocalTicketId
                              , tal E.?. TicketAuthorLocalId
                              , s E.?. SharerIdent
                              , tup E.?. TicketUnderProjectId
                              )
                            )
                    remotes <- E.select $ E.from $ \ (tcl `E.InnerJoin` tar `E.InnerJoin` rt `E.InnerJoin` ro `E.InnerJoin` i) -> do
                        E.on $ ro E.^. RemoteObjectInstance E.==. i E.^. InstanceId
                        E.on $ rt E.^. RemoteTicketIdent E.==. ro E.^. RemoteObjectId
                        E.on $ tar E.^. TicketAuthorRemoteId E.==. rt E.^. RemoteTicketTicket
                        E.on $ tcl E.^. TicketContextLocalId E.==. tar E.^. TicketAuthorRemoteTicket
                        E.where_ $ tcl E.^. TicketContextLocalTicket `E.in_` E.valList tids'
                        E.orderBy [E.desc $ tcl E.^. TicketContextLocalTicket]
                        return
                            ( tcl E.^. TicketContextLocalTicket
                            , ( i E.^. InstanceHost
                              , ro E.^. RemoteObjectIdent
                              )
                            )
                    return $
                        map snd $
                            LO.mergeBy
                                (flip compare `on` fst)
                                (map (second Left) locals)
                                (map (second Right) remotes)
            getPageAndNavCount countAllTickets selectTickets

        encodeRouteHome <- getEncodeRouteHome
        encodeRouteLocal <- getEncodeRouteLocal
        encodeRoutePageLocal <- getEncodeRoutePageLocal
        let pageUrl = encodeRoutePageLocal here
        host <- asksSite siteInstanceHost
        encodeLT <- getEncodeKeyHashid
        encodeTAL <- getEncodeKeyHashid

        return $
            case mpage of
                Nothing -> encodeStrict $ Doc host $ Collection
                    { collectionId         = encodeRouteLocal here
                    , collectionType       = CollectionTypeOrdered
                    , collectionTotalItems = Just total
                    , collectionCurrent    = Nothing
                    , collectionFirst      = Just $ pageUrl 1
                    , collectionLast       = Just $ pageUrl pages
                    , collectionItems      = [] :: [Text]
                    }
                Just (tickets, navModel) ->
                    let current = nmCurrent navModel
                    in  encodeStrict $ Doc host $ CollectionPage
                            { collectionPageId         = pageUrl current
                            , collectionPageType       = CollectionPageTypeOrdered
                            , collectionPageTotalItems = Nothing
                            , collectionPageCurrent    = Just $ pageUrl current
                            , collectionPageFirst      = Just $ pageUrl 1
                            , collectionPageLast       = Just $ pageUrl pages
                            , collectionPagePartOf     = encodeRouteLocal here
                            , collectionPagePrev       =
                                if current > 1
                                    then Just $ pageUrl $ current - 1
                                    else Nothing
                            , collectionPageNext       =
                                if current < pages
                                    then Just $ pageUrl $ current + 1
                                    else Nothing
                            , collectionPageStartIndex = Nothing
                            , collectionPageItems      =
                                map (ticketRoute encodeRouteHome encodeLT encodeTAL)
                                    tickets
                            }
    where
    here = ProjectTicketsR shr prj
    encodeStrict = BL.toStrict . encode
    ticketRoute encodeRoute encodeLT encodeTAL (Left (E.Value ltid, E.Value mtalid, E.Value mshr, E.Value mtupid)) =
        encodeRoute $
            case (mtalid, mshr, mtupid) of
                (Nothing, Nothing, Nothing) -> ProjectTicketR shr prj $ encodeLT ltid
                (Just talid, Just shrA, Nothing) -> SharerTicketR shrA $ encodeTAL talid
                (Just _, Just _, Just _) -> ProjectTicketR shr prj $ encodeLT ltid
                _ -> error "Impossible"
    ticketRoute _ _ _ (Right (E.Value h, E.Value lu)) = ObjURI h lu

getProjectTicketTreeR :: ShrIdent -> PrjIdent -> Handler Html
getProjectTicketTreeR shr prj = do
    (summaries, deps) <- runDB $ do
        Entity sid _ <- getBy404 $ UniqueSharer shr
        Entity jid _ <- getBy404 $ UniqueProject prj sid
        (,) <$> getTicketSummaries Nothing Nothing Nothing jid
            <*> getTicketDepEdges jid
    defaultLayout $ ticketTreeDW shr prj summaries deps

getProjectTicketNewR :: ShrIdent -> PrjIdent -> Handler Html
getProjectTicketNewR shr prj = do
    wid <- runDB $ do
        Entity sid _ <- getBy404 $ UniqueSharer shr
        Entity _   j <- getBy404 $ UniqueProject prj sid
        return $ projectWorkflow j
    ((_result, widget), enctype) <- runFormPost $ newTicketForm wid
    defaultLayout $(widgetFile "ticket/new")

getProjectTicketR :: ShrIdent -> PrjIdent -> KeyHashid LocalTicket -> Handler TypedContent
getProjectTicketR shar proj ltkhid = do
    mpid <- maybeAuthId
    ( wshr, wfl,
      author, massignee, mcloser, ticket, lticket, tparams, eparams, cparams,
      deps, rdeps) <-
        runDB $ do
            (Entity sid sharer, Entity jid project, Entity tid ticket, Entity _ lticket, _etcl, _etpl, author) <- getProjectTicket404 shar proj ltkhid
            (wshr, wid, wfl) <- do
                w <- get404 $ projectWorkflow project
                wsharer <-
                    if workflowSharer w == sid
                        then return sharer
                        else get404 $ workflowSharer w
                return
                    ( sharerIdent wsharer
                    , projectWorkflow project
                    , workflowIdent w
                    )
            author' <-
                case author of
                    Left (Entity _ tal, _) -> Left <$> do
                        p <- getJust $ ticketAuthorLocalAuthor tal
                        getJust $ personIdent p
                    Right (Entity _ tar) -> Right <$> do
                        ra <- getJust $ ticketAuthorRemoteAuthor tar
                        ro <- getJust $ remoteActorIdent ra
                        i <- getJust $ remoteObjectInstance ro
                        return (i, ro, ra)
            massignee <- for (ticketAssignee ticket) $ \ apid -> do
                person <- get404 apid
                sharer <- get404 $ personIdent person
                return (sharer, fromMaybe False $ (== apid) <$> mpid)
            mcloser <-
                case ticketStatus ticket of
                    TSClosed ->
                        case ticketCloser ticket of
                            Just pidCloser -> Just <$> do
                                person <- getJust pidCloser
                                getJust $ personIdent person
                            Nothing -> error "Closer not set for closed ticket"
                    _ ->
                        case ticketCloser ticket of
                            Just _ -> error "Closer set for open ticket"
                            Nothing -> return Nothing
            tparams <- getTicketTextParams tid wid
            eparams <- getTicketEnumParams tid wid
            cparams <- getTicketClasses tid wid
            deps <- E.select $ E.from $ \ (dep `E.InnerJoin` t `E.InnerJoin` lt) -> do
                E.on $ t E.^. TicketId E.==. lt E.^. LocalTicketTicket
                E.on $ dep E.^. TicketDependencyChild E.==. t E.^. TicketId
                E.where_ $ dep E.^. TicketDependencyParent E.==. E.val tid
                return (lt E.^. LocalTicketId, t)
            rdeps <- E.select $ E.from $ \ (dep `E.InnerJoin` t `E.InnerJoin` lt) -> do
                E.on $ t E.^. TicketId E.==. lt E.^. LocalTicketTicket
                E.on $ dep E.^. TicketDependencyParent E.==. t E.^. TicketId
                E.where_ $ dep E.^. TicketDependencyChild E.==. E.val tid
                return (lt E.^. LocalTicketId, t)
            return
                ( wshr, wfl
                , author', massignee, mcloser, ticket, lticket
                , tparams, eparams, cparams
                , deps, rdeps
                )
    encodeHid <- getEncodeKeyHashid
    let desc :: Widget
        desc = toWidget $ preEscapedToMarkup $ ticketDescription ticket
        discuss =
            discussionW
                (return $ localTicketDiscuss lticket)
                (ProjectTicketTopReplyR shar proj ltkhid)
                (ProjectTicketReplyR shar proj ltkhid . encodeHid)
    cRelevant <- newIdent
    cIrrelevant <- newIdent
    let relevant filt =
            bool cIrrelevant cRelevant $
            case ticketStatus ticket of
                TSNew    -> wffNew filt
                TSTodo   -> wffTodo filt
                TSClosed -> wffClosed filt
    hLocal <- getsYesod siteInstanceHost
    encodeRouteLocal <- getEncodeRouteLocal
    encodeRouteHome <- getEncodeRouteHome
    let host =
            case author of
                Left _          -> hLocal
                Right (i, _, _) -> instanceHost i
        ticketAP = AP.Ticket
            { AP.ticketLocal        = Just
                ( hLocal
                , AP.TicketLocal
                    { AP.ticketId =
                        encodeRouteLocal $ ProjectTicketR shar proj ltkhid
                    , AP.ticketReplies =
                        encodeRouteLocal $ ProjectTicketDiscussionR shar proj ltkhid
                    , AP.ticketParticipants =
                        encodeRouteLocal $ ProjectTicketParticipantsR shar proj ltkhid
                    , AP.ticketTeam =
                        Just $ encodeRouteLocal $ ProjectTicketTeamR shar proj ltkhid
                    , AP.ticketEvents =
                        encodeRouteLocal $ ProjectTicketEventsR shar proj ltkhid
                    , AP.ticketDeps =
                        encodeRouteLocal $ ProjectTicketDepsR shar proj ltkhid
                    , AP.ticketReverseDeps =
                        encodeRouteLocal $ ProjectTicketReverseDepsR shar proj ltkhid
                    }
                )

            , AP.ticketAttributedTo =
                case author of
                    Left sharer ->
                        encodeRouteLocal $ SharerR $ sharerIdent sharer
                    Right (_inztance, object, _actor) ->
                        remoteObjectIdent object
            , AP.ticketPublished    = Just $ ticketCreated ticket
            , AP.ticketUpdated      = Nothing
            , AP.ticketContext      =
                Just $ encodeRouteHome $ ProjectR shar proj
            -- , AP.ticketName         = Just $ "#" <> T.pack (show num)
            , AP.ticketSummary      = TextHtml $ ticketTitle ticket
            , AP.ticketContent      = TextHtml $ ticketDescription ticket
            , AP.ticketSource       = TextPandocMarkdown $ ticketSource ticket
            , AP.ticketAssignedTo   =
                encodeRouteHome . SharerR . sharerIdent . fst <$> massignee
            , AP.ticketIsResolved   = ticketStatus ticket == TSClosed
            , AP.ticketAttachment   = Nothing
            }
    provideHtmlAndAP' host ticketAP $
        let followButton =
                followW
                    (ProjectTicketFollowR shar proj ltkhid)
                    (ProjectTicketUnfollowR shar proj ltkhid)
                    (return $ localTicketFollowers lticket)
        in  $(widgetFile "ticket/one")

putProjectTicketR :: ShrIdent -> PrjIdent -> KeyHashid LocalTicket -> Handler Html
putProjectTicketR shr prj ltkhid = do
    (tid, ticket, wid) <- runDB $ do
        (_es, Entity _ project, Entity tid ticket, _elt, _etcl, _etpl, _author) <- getProjectTicket404 shr prj ltkhid
        return (tid, ticket, projectWorkflow project)
    ((result, widget), enctype) <-
        runFormPost $ editTicketContentForm tid ticket wid
    case result of
        FormSuccess (ticket', tparams, eparams, cparams) -> do
            newDescHtml <-
                case renderPandocMarkdown $ ticketSource ticket' of
                    Left err -> do
                        setMessage $ toHtml err
                        redirect $ ProjectTicketEditR shr prj ltkhid
                    Right t -> return t
            let ticket'' = ticket' { ticketDescription = newDescHtml }
            runDB $ do
                replace tid ticket''
                let (tdel, tins, tupd) = partitionMaybePairs tparams
                deleteWhere [TicketParamTextId <-. tdel]
                let mktparam (fid, v) = TicketParamText
                        { ticketParamTextTicket = tid
                        , ticketParamTextField  = fid
                        , ticketParamTextValue  = v
                        }
                insertMany_ $ map mktparam tins
                traverse_
                    (\ (aid, (_fid, v)) ->
                        update aid [TicketParamTextValue =. v]
                    )
                    tupd
                let (edel, eins, eupd) = partitionMaybePairs eparams
                deleteWhere [TicketParamEnumId <-. edel]
                let mkeparam (fid, v) = TicketParamEnum
                        { ticketParamEnumTicket = tid
                        , ticketParamEnumField  = fid
                        , ticketParamEnumValue  = v
                        }
                insertMany_ $ map mkeparam eins
                traverse_
                    (\ (aid, (_fid, v)) ->
                        update aid [TicketParamEnumValue =. v]
                    )
                    eupd
                let (cdel, cins, _ckeep) = partitionMaybePairs cparams
                deleteWhere [TicketParamClassId <-. cdel]
                let mkcparam fid = TicketParamClass
                        { ticketParamClassTicket = tid
                        , ticketParamClassField  = fid
                        }
                insertMany_ $ map mkcparam cins
            setMessage "Ticket updated."
            redirect $ ProjectTicketR shr prj ltkhid
        FormMissing -> do
            setMessage "Field(s) missing."
            defaultLayout $(widgetFile "ticket/edit")
        FormFailure _l -> do
            setMessage "Ticket update failed, see errors below."
            defaultLayout $(widgetFile "ticket/edit")

deleteProjectTicketR :: ShrIdent -> PrjIdent -> KeyHashid LocalTicket -> Handler Html
deleteProjectTicketR _shr _prj _ltkhid =
    --TODO: I can easily implement this, but should it even be possible to
    --delete tickets?
    error "Not implemented"

postProjectTicketR :: ShrIdent -> PrjIdent -> KeyHashid LocalTicket -> Handler Html
postProjectTicketR shr prj ltkhid = do
    mmethod <- lookupPostParam "_method"
    case mmethod of
        Just "PUT"    -> putProjectTicketR shr prj ltkhid
        Just "DELETE" -> deleteProjectTicketR shr prj ltkhid
        _             -> notFound

getProjectTicketEditR :: ShrIdent -> PrjIdent -> KeyHashid LocalTicket -> Handler Html
getProjectTicketEditR shr prj ltkhid = do
    (tid, ticket, wid) <- runDB $ do
        (_es, Entity _ project, Entity tid ticket, _elt, _etcl, _etpl, _author) <- getProjectTicket404 shr prj ltkhid
        return (tid, ticket, projectWorkflow project)
    ((_result, widget), enctype) <-
        runFormPost $ editTicketContentForm tid ticket wid
    defaultLayout $(widgetFile "ticket/edit")

postProjectTicketAcceptR
    :: ShrIdent -> PrjIdent -> KeyHashid LocalTicket -> Handler Html
postProjectTicketAcceptR shr prj ltkhid = do
    succ <- runDB $ do
        (_es, _ej, Entity tid ticket, _elt, _etcl, _etpl, _author) <- getProjectTicket404 shr prj ltkhid
        case ticketStatus ticket of
            TSNew -> do
                update tid [TicketStatus =. TSTodo]
                return True
            _ -> return False
    setMessage $
        if succ
            then "Ticket accepted."
            else "Ticket is already accepted."
    redirect $ ProjectTicketR shr prj ltkhid

postProjectTicketCloseR
    :: ShrIdent -> PrjIdent -> KeyHashid LocalTicket -> Handler Html
postProjectTicketCloseR shr prj ltkhid = do
    pid <- requireAuthId
    now <- liftIO getCurrentTime
    succ <- runDB $ do
        (_es, _ej, Entity tid ticket, _elt, _etcl, _etpl, _author) <- getProjectTicket404 shr prj ltkhid
        case ticketStatus ticket of
            TSClosed -> return False
            _        -> do
                update tid
                    [ TicketAssignee =. Nothing
                    , TicketStatus   =. TSClosed
                    , TicketClosed   =. now
                    , TicketCloser   =. Just pid
                    ]
                return True
    setMessage $
        if succ
            then "Ticket closed."
            else "Ticket is already closed."
    redirect $ ProjectTicketR shr prj ltkhid

postProjectTicketOpenR
    :: ShrIdent -> PrjIdent -> KeyHashid LocalTicket -> Handler Html
postProjectTicketOpenR shr prj ltkhid = do
    pid <- requireAuthId
    now <- liftIO getCurrentTime
    succ <- runDB $ do
        (_es, _ej, Entity tid ticket, _elt, _etcl, _etpl, _author) <- getProjectTicket404 shr prj ltkhid
        case ticketStatus ticket of
            TSClosed -> do
                update tid
                    [ TicketStatus =. TSTodo
                    , TicketCloser =. Nothing
                    ]
                return True
            _        -> return False
    setMessage $
        if succ
            then "Ticket reopened"
            else "Ticket is already open."
    redirect $ ProjectTicketR shr prj ltkhid

postProjectTicketClaimR
    :: ShrIdent -> PrjIdent -> KeyHashid LocalTicket -> Handler Html
postProjectTicketClaimR shr prj ltkhid = do
    pid <- requireAuthId
    mmsg <- runDB $ do
        (_es, _ej, Entity tid ticket, _elt, _etcl, _etpl, _author) <- getProjectTicket404 shr prj ltkhid
        case (ticketStatus ticket, ticketAssignee ticket) of
            (TSNew, _) ->
                return $
                Just "The ticket isn’t accepted yet. Can’t claim it."
            (TSClosed, _) ->
                return $
                Just "The ticket is closed. Can’t claim closed tickets."
            (TSTodo, Just _) ->
                return $
                Just "The ticket is already assigned to someone."
            (TSTodo, Nothing) -> do
                update tid [TicketAssignee =. Just pid]
                return Nothing
    setMessage $ fromMaybe "The ticket is now assigned to you." mmsg
    redirect $ ProjectTicketR shr prj ltkhid

postProjectTicketUnclaimR
    :: ShrIdent -> PrjIdent -> KeyHashid LocalTicket -> Handler Html
postProjectTicketUnclaimR shr prj ltkhid = do
    pid <- requireAuthId
    mmsg <- runDB $ do
        (_es, _ej, Entity tid ticket, _elt, _etcl, _etpl, _author) <- getProjectTicket404 shr prj ltkhid
        case ((== pid) <$> ticketAssignee ticket, ticketStatus ticket) of
            (Nothing, _) ->
                return $ Just "The ticket is already unassigned."
            (Just False, _) ->
                return $ Just "The ticket is assigned to someone else."
            (Just True, TSNew) -> do
                logWarn "Found a new claimed ticket, this is invalid"
                return $
                    Just "The ticket isn’t accepted yet. Can’t unclaim it."
            (Just True, TSClosed) -> do
                logWarn "Found a closed claimed ticket, this is invalid"
                return $
                    Just "The ticket is closed. Can’t unclaim closed tickets."
            (Just True, TSTodo) -> do
                update tid [TicketAssignee =. Nothing]
                return Nothing
    setMessage $ fromMaybe "The ticket is now unassigned." mmsg
    redirect $ ProjectTicketR shr prj ltkhid

getProjectTicketAssignR
    :: ShrIdent -> PrjIdent -> KeyHashid LocalTicket -> Handler Html
getProjectTicketAssignR shr prj ltkhid = do
    vpid <- requireAuthId
    (_es, Entity jid _, Entity tid ticket, _elt, _etcl, _etpl, _author) <- runDB $ getProjectTicket404 shr prj ltkhid
    let msg t = do
            setMessage t
            redirect $ ProjectTicketR shr prj ltkhid
    case (ticketStatus ticket, ticketAssignee ticket) of
        (TSNew, _) -> msg "The ticket isn’t accepted yet. Can’t assign it."
        (TSClosed, _) -> msg "The ticket is closed. Can’t assign it."
        (TSTodo, Just _) -> msg "The ticket is already assigned to someone."
        (TSTodo, Nothing) -> do
            ((_result, widget), enctype) <-
                runFormPost $ assignTicketForm vpid jid
            defaultLayout $(widgetFile "ticket/assign")

postProjectTicketAssignR
    :: ShrIdent -> PrjIdent -> KeyHashid LocalTicket -> Handler Html
postProjectTicketAssignR shr prj ltkhid = do
    vpid <- requireAuthId
    (_es, Entity jid _, Entity tid ticket, _elt, _etcl, _etpl, _author) <- runDB $ getProjectTicket404 shr prj ltkhid
    let msg t = do
            setMessage t
            redirect $ ProjectTicketR shr prj ltkhid
    case (ticketStatus ticket, ticketAssignee ticket) of
        (TSNew, _) -> msg "The ticket isn’t accepted yet. Can’t assign it."
        (TSClosed, _) -> msg "The ticket is closed. Can’t assign it."
        (TSTodo, Just _) -> msg "The ticket is already assigned to someone."
        (TSTodo, Nothing) -> do
            ((result, widget), enctype) <-
                runFormPost $ assignTicketForm vpid jid
            case result of
                FormSuccess pid -> do
                    sharer <- runDB $ do
                        update tid [TicketAssignee =. Just pid]
                        person <- getJust pid
                        getJust $ personIdent person
                    let si = sharerIdent sharer
                    msg $ toHtml $
                        "The ticket is now assigned to " <> shr2text si <> "."
                FormMissing -> do
                    setMessage "Field(s) missing."
                    defaultLayout $(widgetFile "ticket/assign")
                FormFailure _l -> do
                    setMessage "Ticket assignment failed, see errors below."
                    defaultLayout $(widgetFile "ticket/assign")

postProjectTicketUnassignR
    :: ShrIdent -> PrjIdent -> KeyHashid LocalTicket -> Handler Html
postProjectTicketUnassignR shr prj ltkhid = do
    pid <- requireAuthId
    mmsg <- runDB $ do
        (_es, _ej, Entity tid ticket, _elt, _etcl, _etpl, _author) <- getProjectTicket404 shr prj ltkhid
        case ((== pid) <$> ticketAssignee ticket, ticketStatus ticket) of
            (Nothing, _) ->
                return $ Just "The ticket is already unassigned."
            (Just True, _) ->
                return $ Just "The ticket is assigned to you, unclaim instead."
            (Just False, TSNew) -> do
                logWarn "Found a new claimed ticket, this is invalid"
                return $
                    Just "The ticket isn’t accepted yet. Can’t unclaim it."
            (Just False, TSClosed) -> do
                logWarn "Found a closed claimed ticket, this is invalid"
                return $
                    Just "The ticket is closed. Can’t unclaim closed tickets."
            (Just False, TSTodo) -> do
                update tid [TicketAssignee =. Nothing]
                return Nothing
    setMessage $ fromMaybe "The ticket is now unassigned." mmsg
    redirect $ ProjectTicketR shr prj ltkhid

-- | The logged-in user gets a list of the ticket claim requests they have
-- opened, in any project.
getClaimRequestsPersonR :: Handler Html
getClaimRequestsPersonR = do
    pid <- requireAuthId
    rqs <- runDB $ E.select $ E.from $
        \ (tcr `E.InnerJoin` ticket `E.InnerJoin` lticket `E.InnerJoin` tcl `E.InnerJoin` tpl `E.InnerJoin` project `E.InnerJoin` sharer) -> do
            E.on $ project E.^. ProjectSharer E.==. sharer E.^. SharerId
            E.on $ tpl E.^. TicketProjectLocalProject E.==. project E.^. ProjectId
            E.on $ tcl E.^. TicketContextLocalId E.==. tpl E.^. TicketProjectLocalContext
            E.on $ ticket E.^. TicketId E.==. tcl E.^. TicketContextLocalTicket
            E.on $ ticket E.^. TicketId E.==. lticket E.^. LocalTicketTicket
            E.on $ tcr E.^. TicketClaimRequestTicket E.==. ticket E.^. TicketId
            E.where_ $ tcr E.^. TicketClaimRequestPerson E.==. E.val pid
            E.orderBy [E.desc $ tcr E.^. TicketClaimRequestCreated]
            return
                ( sharer E.^. SharerIdent
                , project E.^. ProjectIdent
                , lticket E.^. LocalTicketId
                , ticket E.^. TicketTitle
                , tcr E.^. TicketClaimRequestCreated
                )
    encodeHid <- getEncodeKeyHashid
    defaultLayout $(widgetFile "person/claim-requests")

-- | Get a list of ticket claim requests for a given project.
getClaimRequestsProjectR :: ShrIdent -> PrjIdent -> Handler Html
getClaimRequestsProjectR shr prj = do
    rqs <- runDB $ do
        Entity sid _ <- getBy404 $ UniqueSharer shr
        Entity jid _ <- getBy404 $ UniqueProject prj sid
        E.select $ E.from $
            \ ( tcr     `E.InnerJoin`
                ticket  `E.InnerJoin`
                lticket `E.InnerJoin`
                tcl     `E.InnerJoin`
                tpl     `E.InnerJoin`
                person  `E.InnerJoin`
                sharer
              ) -> do
                E.on $ person E.^. PersonIdent E.==. sharer E.^. SharerId
                E.on $ tcr E.^. TicketClaimRequestPerson E.==. person E.^. PersonId
                E.on $ tcl E.^. TicketContextLocalId E.==. tpl E.^. TicketProjectLocalContext
                E.on $ ticket E.^. TicketId E.==. tcl E.^. TicketContextLocalTicket
                E.on $ ticket E.^. TicketId E.==. lticket E.^. LocalTicketTicket
                E.on $ tcr E.^. TicketClaimRequestTicket E.==. ticket E.^. TicketId
                E.where_ $ tpl E.^. TicketProjectLocalProject E.==. E.val jid
                E.orderBy [E.desc $ tcr E.^. TicketClaimRequestCreated]
                return
                    ( sharer
                    , lticket E.^. LocalTicketId
                    , ticket E.^. TicketTitle
                    , tcr E.^. TicketClaimRequestCreated
                    )
    encodeHid <- getEncodeKeyHashid
    defaultLayout $(widgetFile "project/claim-request/list")

-- | Get a list of ticket claim requests for a given ticket.
getClaimRequestsTicketR
    :: ShrIdent -> PrjIdent -> KeyHashid LocalTicket -> Handler Html
getClaimRequestsTicketR shr prj ltkhid = do
    rqs <- runDB $ do
        (_es, _ej, Entity tid _, _elt, _etcl, _etpl, _author) <- getProjectTicket404 shr prj ltkhid
        E.select $ E.from $ \ (tcr `E.InnerJoin` person `E.InnerJoin` sharer) -> do
                E.on $ person E.^. PersonIdent E.==. sharer E.^. SharerId
                E.on $ tcr E.^. TicketClaimRequestPerson E.==. person E.^. PersonId
                E.where_ $ tcr E.^. TicketClaimRequestTicket E.==. E.val tid
                E.orderBy [E.desc $ tcr E.^. TicketClaimRequestCreated]
                return (sharer, tcr)
    defaultLayout $(widgetFile "ticket/claim-request/list")

getClaimRequestNewR
    :: ShrIdent -> PrjIdent -> KeyHashid LocalTicket -> Handler Html
getClaimRequestNewR shr prj ltkhid = do
    ((_result, widget), etype) <- runFormPost claimRequestForm
    defaultLayout $(widgetFile "ticket/claim-request/new")

postClaimRequestsTicketR
    :: ShrIdent -> PrjIdent -> KeyHashid LocalTicket -> Handler Html
postClaimRequestsTicketR shr prj ltkhid = do
    ((result, widget), etype) <- runFormPost claimRequestForm
    case result of
        FormSuccess msg -> do
            now <- liftIO getCurrentTime
            pid <- requireAuthId
            runDB $ do
                (_es, _ej, Entity tid _, _elt, _etcl, _etpl, _author) <- getProjectTicket404 shr prj ltkhid
                let cr = TicketClaimRequest
                        { ticketClaimRequestPerson  = pid
                        , ticketClaimRequestTicket  = tid
                        , ticketClaimRequestMessage = msg
                        , ticketClaimRequestCreated = now
                        }
                insert_ cr
            setMessage "Ticket claim request opened."
            redirect $ ProjectTicketR shr prj ltkhid
        FormMissing -> do
            setMessage "Field(s) missing."
            defaultLayout $(widgetFile "ticket/claim-request/new")
        FormFailure _l -> do
            setMessage "Submission failed, see errors below."
            defaultLayout $(widgetFile "ticket/claim-request/new")

selectDiscussionId
    :: ShrIdent -> PrjIdent -> KeyHashid LocalTicket -> AppDB DiscussionId
selectDiscussionId shr prj ltkhid = do
    (_es, _ej, _et, Entity _ lticket, _etcl, _etpl, _author) <- getProjectTicket404 shr prj ltkhid
    return $ localTicketDiscuss lticket

getProjectTicketDiscussionR
    :: ShrIdent -> PrjIdent -> KeyHashid LocalTicket -> Handler Html
getProjectTicketDiscussionR shar proj ltkhid = do
    encodeHid <- getEncodeKeyHashid
    getDiscussion
        (ProjectTicketReplyR shar proj ltkhid . encodeHid)
        (ProjectTicketTopReplyR shar proj ltkhid)
        (selectDiscussionId shar proj ltkhid)

postProjectTicketDiscussionR
    :: ShrIdent -> PrjIdent -> KeyHashid LocalTicket -> Handler Html
postProjectTicketDiscussionR shr prj ltkhid = do
    hLocal <- getsYesod $ appInstanceHost . appSettings
    postTopReply
        hLocal
        [ProjectR shr prj]
        [ ProjectFollowersR shr prj
        , ProjectTicketParticipantsR shr prj ltkhid
        , ProjectTicketTeamR shr prj ltkhid
        ]
        (ProjectTicketR shr prj ltkhid)
        (ProjectR shr prj)
        (ProjectTicketDiscussionR shr prj ltkhid)
        (const $ ProjectTicketR shr prj ltkhid)

getMessageR :: ShrIdent -> KeyHashid LocalMessage -> Handler TypedContent
getMessageR shr hid = do
    lmid <- decodeKeyHashid404 hid
    getDiscussionMessage shr lmid

postProjectTicketMessageR
    :: ShrIdent
    -> PrjIdent
    -> KeyHashid LocalTicket
    -> KeyHashid Message
    -> Handler Html
postProjectTicketMessageR shr prj ltkhid mkhid = do
    encodeHid <- getEncodeKeyHashid
    mid <- decodeKeyHashid404 mkhid
    hLocal <- getsYesod $ appInstanceHost . appSettings
    postReply
        hLocal
        [ProjectR shr prj]
        [ ProjectFollowersR shr prj
        , ProjectTicketParticipantsR shr prj ltkhid
        , ProjectTicketTeamR shr prj ltkhid
        ]
        (ProjectTicketR shr prj ltkhid)
        (ProjectR shr prj)
        (ProjectTicketReplyR shr prj ltkhid . encodeHid)
        (ProjectTicketMessageR shr prj ltkhid . encodeHid)
        (const $ ProjectTicketR shr prj ltkhid)
        (selectDiscussionId shr prj ltkhid)
        mid

getProjectTicketTopReplyR
    :: ShrIdent -> PrjIdent -> KeyHashid LocalTicket -> Handler Html
getProjectTicketTopReplyR shr prj ltkhid =
    getTopReply $ ProjectTicketDiscussionR shr prj ltkhid

getProjectTicketReplyR
    :: ShrIdent -> PrjIdent -> KeyHashid LocalTicket -> KeyHashid Message -> Handler Html
getProjectTicketReplyR shr prj ltkhid mkhid = do
    encodeHid <- getEncodeKeyHashid
    mid <- decodeKeyHashid404 mkhid
    getReply
        (ProjectTicketReplyR shr prj ltkhid . encodeHid)
        (ProjectTicketMessageR shr prj ltkhid . encodeHid)
        (selectDiscussionId shr prj ltkhid)
        mid

getTicketDeps
    :: Bool -> ShrIdent -> PrjIdent -> KeyHashid LocalTicket -> Handler TypedContent
getTicketDeps forward shr prj ltkhid = do
    (deps, rows) <- unzip <$> runDB getDepsFromDB
    depsAP <- makeDepsCollection deps
    encodeHid <- getEncodeKeyHashid
    provideHtmlAndAP depsAP $(widgetFile "ticket/dep/list")
    where
    getDepsFromDB = do
        let from' =
                if forward then TicketDependencyParent else TicketDependencyChild
            to' =
                if forward then TicketDependencyChild else TicketDependencyParent
        (_es, _ej, Entity tid _, _elt, _etcl, _etpl, _author) <- getProjectTicket404 shr prj ltkhid
        fmap (map toRow) $ E.select $ E.from $
            \ ( td
              `E.InnerJoin` t
              `E.InnerJoin` lt
              `E.InnerJoin` tcl
              `E.InnerJoin` tpl
              `E.LeftOuterJoin` (tal `E.InnerJoin` p `E.InnerJoin` s)
              `E.LeftOuterJoin` (tar `E.InnerJoin` ra `E.InnerJoin` ro `E.InnerJoin` i)
              ) -> do
                E.on $ ro E.?. RemoteObjectInstance E.==. i E.?. InstanceId
                E.on $ ra E.?. RemoteActorIdent E.==. ro E.?. RemoteObjectId
                E.on $ tar E.?. TicketAuthorRemoteAuthor E.==. ra E.?. RemoteActorId
                E.on $ E.just (tcl E.^. TicketContextLocalId) E.==. tar E.?. TicketAuthorRemoteTicket
                E.on $ p E.?. PersonIdent E.==. s E.?. SharerId
                E.on $ tal E.?. TicketAuthorLocalAuthor E.==. p E.?. PersonId
                E.on $ E.just (lt E.^. LocalTicketId) E.==. tal E.?. TicketAuthorLocalTicket
                E.on $ tcl E.^. TicketContextLocalId E.==. tpl E.^. TicketProjectLocalContext
                E.on $ t E.^. TicketId E.==. tcl E.^. TicketContextLocalTicket
                E.on $ t E.^. TicketId E.==. lt E.^. LocalTicketTicket
                E.on $ td E.^. to' E.==. t E.^. TicketId
                E.where_ $ td E.^. from' E.==. E.val tid
                E.orderBy [E.asc $ t E.^. TicketId]
                return
                    ( td E.^. TicketDependencyId
                    , lt E.^. LocalTicketId
                    , s
                    , i
                    , ro
                    , ra
                    , t E.^. TicketTitle
                    , t E.^. TicketStatus
                    )
        where
        toRow (E.Value dep, E.Value ltid, ms, mi, mro, mra, E.Value title, E.Value status) =
            ( dep
            , ( ltid
              , case (ms, mi, mro, mra) of
                  (Just s, Nothing, Nothing, Nothing) ->
                      Left $ entityVal s
                  (Nothing, Just i, Just ro, Just ra) ->
                      Right (entityVal i, entityVal ro, entityVal ra)
                  _ -> error "Ticket author DB invalid state"
              , title
              , status
              )
            )
    makeDepsCollection tdids = do
        encodeRouteLocal <- getEncodeRouteLocal
        encodeRouteHome <- getEncodeRouteHome
        encodeKeyHashid <- getEncodeKeyHashid
        let here =
                let route =
                        if forward
                            then ProjectTicketDepsR
                            else ProjectTicketReverseDepsR
                in  route shr prj ltkhid
        return Collection
            { collectionId         = encodeRouteLocal here
            , collectionType       = CollectionTypeUnordered
            , collectionTotalItems = Just $ length tdids
            , collectionCurrent    = Nothing
            , collectionFirst      = Nothing
            , collectionLast       = Nothing
            , collectionItems      =
                map (encodeRouteHome . TicketDepR . encodeKeyHashid) tdids
            }

getProjectTicketDepsR
    :: ShrIdent -> PrjIdent -> KeyHashid LocalTicket -> Handler TypedContent
getProjectTicketDepsR = getTicketDeps True

postProjectTicketDepsR
    :: ShrIdent -> PrjIdent -> KeyHashid LocalTicket -> Handler Html
postProjectTicketDepsR shr prj ltkhid = do
    (_es, Entity jid _, Entity tid _, _elt, _etcl, _etpl, _author) <- runDB $ getProjectTicket404 shr prj ltkhid
    ((result, widget), enctype) <- runFormPost $ ticketDepForm jid tid
    case result of
        FormSuccess ctid -> do
            pidAuthor <- requireVerifiedAuthId
            now <- liftIO getCurrentTime
            runDB $ do
                let td = TicketDependency
                        { ticketDependencyParent  = tid
                        , ticketDependencyChild   = ctid
                        , ticketDependencyAuthor  = pidAuthor
                        , ticketDependencySummary = "(A ticket dependency)"
                        , ticketDependencyCreated = now
                        }
                insert_ td
                trrFix td ticketDepGraph
            setMessage "Ticket dependency added."
            redirect $ ProjectTicketR shr prj ltkhid
        FormMissing -> do
            setMessage "Field(s) missing."
            defaultLayout $(widgetFile "ticket/dep/new")
        FormFailure _l -> do
            setMessage "Submission failed, see errors below."
            defaultLayout $(widgetFile "ticket/dep/new")

getProjectTicketDepNewR
    :: ShrIdent -> PrjIdent -> KeyHashid LocalTicket -> Handler Html
getProjectTicketDepNewR shr prj ltkhid = do
    (_es, Entity jid _, Entity tid _, _elt, _etcl, _etpl, _author) <- runDB $ getProjectTicket404 shr prj ltkhid
    ((_result, widget), enctype) <- runFormPost $ ticketDepForm jid tid
    defaultLayout $(widgetFile "ticket/dep/new")

postTicketDepOldR
    :: ShrIdent -> PrjIdent -> KeyHashid LocalTicket -> KeyHashid LocalTicket -> Handler Html
postTicketDepOldR shr prj pnum cnum = do
    mmethod <- lookupPostParam "_method"
    case mmethod of
        Just "DELETE" -> deleteTicketDepOldR shr prj pnum cnum
        _             -> notFound

deleteTicketDepOldR
    :: ShrIdent -> PrjIdent -> KeyHashid LocalTicket -> KeyHashid LocalTicket -> Handler Html
deleteTicketDepOldR shr prj pnum cnum = do
    runDB $ do
        (_es, Entity jid _, Entity ptid _, _elt, _etcl, _etpl, _author) <- getProjectTicket404 shr prj pnum

        cltid <- decodeKeyHashid404 cnum
        clt <- get404 cltid
        let ctid = localTicketTicket clt
        ctclid <- getKeyBy404 $ UniqueTicketContextLocal ctid
        ctpl <- getValBy404 $ UniqueTicketProjectLocal ctclid
        unless (ticketProjectLocalProject ctpl == jid) notFound

        Entity tdid _ <- getBy404 $ UniqueTicketDependency ptid ctid
        delete tdid
    setMessage "Ticket dependency removed."
    redirect $ ProjectTicketDepsR shr prj pnum

getProjectTicketReverseDepsR
    :: ShrIdent -> PrjIdent -> KeyHashid LocalTicket -> Handler TypedContent
getProjectTicketReverseDepsR = getTicketDeps False

getTicketDepR :: KeyHashid TicketDependency -> Handler TypedContent
getTicketDepR tdkhid = do
    tdid <- decodeKeyHashid404 tdkhid
    ( td,
      (sParent, jParent, ltParent),
      (sChild, jChild, ltChild),
      (sAuthor, pAuthor)
      ) <- runDB $ do
        tdep <- get404 tdid
        (,,,) tdep
            <$> getTicket (ticketDependencyParent tdep)
            <*> getTicket (ticketDependencyChild tdep)
            <*> getAuthor (ticketDependencyAuthor tdep)

    encodeRouteLocal <- getEncodeRouteLocal
    encodeRouteHome <- getEncodeRouteHome
    encodeHid <- getEncodeKeyHashid
    let ticketRoute s j lt =
            ProjectTicketR (sharerIdent s) (projectIdent j) (encodeHid lt)
        here = TicketDepR tdkhid
        tdepAP = AP.TicketDependency
            { ticketDepId           = Just $ encodeRouteHome here
            , ticketDepParent       =
                encodeRouteHome $ ticketRoute sParent jParent ltParent
            , ticketDepChild        =
                encodeRouteHome $ ticketRoute sChild jChild ltChild
            , ticketDepAttributedTo =
                encodeRouteLocal $ SharerR $ sharerIdent sAuthor
            , ticketDepPublished    = Just $ ticketDependencyCreated td
            , ticketDepUpdated      = Just $ ticketDependencyCreated td
            , ticketDepSummary      = TextHtml $ ticketDependencySummary td
            }

    provideHtmlAndAP tdepAP $ redirectToPrettyJSON here
    where
    getTicket tid = do
        ltid <- do
            mltid <- getKeyBy $ UniqueLocalTicket tid
            case mltid of
                Nothing -> error "No LocalTicket"
                Just v -> return v
        tclid <- do
            mtclid <- getKeyBy $ UniqueTicketContextLocal tid
            case mtclid of
                Nothing -> error "No TicketContextLocal"
                Just v -> return v
        tpl <- do
            mtpl <- getValBy $ UniqueTicketProjectLocal tclid
            case mtpl of
                Nothing -> error "No TicketProjectLocal"
                Just v -> return v
        j <- getJust $ ticketProjectLocalProject tpl
        s <- getJust $ projectSharer j
        return (s, j, ltid)
    getAuthor pid = do
        p <- getJust pid
        s <- getJust $ personIdent p
        return (s, p)

getProjectTicketParticipantsR
    :: ShrIdent -> PrjIdent -> KeyHashid LocalTicket -> Handler TypedContent
getProjectTicketParticipantsR shr prj ltkhid = getFollowersCollection here getFsid
    where
    here = ProjectTicketParticipantsR shr prj ltkhid
    getFsid = do
        (_es, _ej, _et, Entity _ lt, _etcl, _etpl, _author) <- getProjectTicket404 shr prj ltkhid
        return $ localTicketFollowers lt

getProjectTicketTeamR
    :: ShrIdent -> PrjIdent -> KeyHashid LocalTicket -> Handler TypedContent
getProjectTicketTeamR shr prj ltkhid = do
    memberShrs <- runDB $ do
        (Entity sid _, _ej, _et, _elt, _etcl, _etpl, _author) <- getProjectTicket404 shr prj ltkhid
        id_ <-
            requireEitherAlt
                (getKeyBy $ UniquePersonIdent sid)
                (getKeyBy $ UniqueGroup sid)
                "Found sharer that is neither person nor group"
                "Found sharer that is both person and group"
        case id_ of
            Left pid -> return [shr]
            Right gid -> do
                pids <-
                    map (groupMemberPerson . entityVal) <$>
                        selectList [GroupMemberGroup ==. gid] []
                sids <-
                    map (personIdent . entityVal) <$>
                        selectList [PersonId <-. pids] []
                map (sharerIdent . entityVal) <$>
                    selectList [SharerId <-. sids] []

    let here = ProjectTicketTeamR shr prj ltkhid

    encodeRouteLocal <- getEncodeRouteLocal
    encodeRouteHome <- getEncodeRouteHome
    let team = Collection
            { collectionId         = encodeRouteLocal here
            , collectionType       = CollectionTypeUnordered
            , collectionTotalItems = Just $ length memberShrs
            , collectionCurrent    = Nothing
            , collectionFirst      = Nothing
            , collectionLast       = Nothing
            , collectionItems      = map (encodeRouteHome . SharerR) memberShrs
            }
    provideHtmlAndAP team $ redirectToPrettyJSON here

getProjectTicketEventsR
    :: ShrIdent -> PrjIdent -> KeyHashid LocalTicket -> Handler TypedContent
getProjectTicketEventsR _shr _prj _ltkhid = error "TODO not implemented"

getSharerTicketsR :: ShrIdent -> Handler TypedContent
getSharerTicketsR =
    getSharerWorkItems SharerTicketsR SharerTicketR countTickets selectTickets
    where
    countTickets pid = fmap toOne $
        E.select $ E.from $ \ (tal `E.InnerJoin` lt `E.LeftOuterJoin` tup `E.LeftOuterJoin` pt) -> do
            E.on $ E.just (lt E.^. LocalTicketTicket) E.==. pt E.?. PatchTicket
            E.on $ E.just (tal E.^. TicketAuthorLocalId) E.==. tup E.?. TicketUnderProjectAuthor
            E.on $ tal E.^. TicketAuthorLocalTicket E.==. lt E.^. LocalTicketId
            E.where_ $
                tal E.^. TicketAuthorLocalAuthor E.==. E.val pid E.&&.
                E.isNothing (tup E.?. TicketUnderProjectId) E.&&.
                E.isNothing (pt E.?. PatchId)
            return $ E.count $ tal E.^. TicketAuthorLocalId
        where
        toOne [x] = E.unValue x
        toOne []  = error "toOne = 0"
        toOne _   = error "toOne > 1"
    selectTickets pid off lim =
        E.select $ E.from $ \ (tal `E.InnerJoin` lt `E.LeftOuterJoin` tup `E.LeftOuterJoin` pt) -> do
            E.on $ E.just (lt E.^. LocalTicketTicket) E.==. pt E.?. PatchTicket
            E.on $ E.just (tal E.^. TicketAuthorLocalId) E.==. tup E.?. TicketUnderProjectAuthor
            E.on $ tal E.^. TicketAuthorLocalTicket E.==. lt E.^. LocalTicketId
            E.where_ $
                tal E.^. TicketAuthorLocalAuthor E.==. E.val pid E.&&.
                E.isNothing (tup E.?. TicketUnderProjectId) E.&&.
                E.isNothing (pt E.?. PatchId)
            E.orderBy [E.desc $ tal E.^. TicketAuthorLocalId]
            E.offset $ fromIntegral off
            E.limit $ fromIntegral lim
            return $ tal E.^. TicketAuthorLocalId

getSharerTicketR
    :: ShrIdent -> KeyHashid TicketAuthorLocal -> Handler TypedContent
getSharerTicketR shr talkhid = do
    (ticket, project, massignee) <- runDB $ do
        (_, _, Entity _ t, tp) <- getSharerTicket404 shr talkhid
        (,,) t
            <$> bitraverse
                    (\ (_, Entity _ tpl) -> do
                        j <- getJust $ ticketProjectLocalProject tpl
                        s <- getJust $ projectSharer j
                        return (s, j)
                    )
                    (\ (Entity _ tpr, _) -> do
                        roid <-
                            case ticketProjectRemoteProject tpr of
                                Nothing ->
                                    remoteActorIdent <$>
                                        getJust (ticketProjectRemoteTracker tpr)
                                Just roid -> return roid
                        ro <- getJust roid
                        i <- getJust $ remoteObjectInstance ro
                        return (i, ro)
                    )
                    tp
            <*> (for (ticketAssignee t) $ \ pidAssignee -> do
                    p <- getJust pidAssignee
                    getJust $ personIdent p
                )
    hLocal <- getsYesod siteInstanceHost
    encodeRouteLocal <- getEncodeRouteLocal
    encodeRouteHome <- getEncodeRouteHome
    let ticketAP = AP.Ticket
            { AP.ticketLocal        = Just
                ( hLocal
                , AP.TicketLocal
                    { AP.ticketId =
                        encodeRouteLocal $ SharerTicketR shr talkhid
                    , AP.ticketReplies =
                        encodeRouteLocal $ SharerTicketDiscussionR shr talkhid
                    , AP.ticketParticipants =
                        encodeRouteLocal $ SharerTicketFollowersR shr talkhid
                    , AP.ticketTeam =
                        Just $ encodeRouteLocal $ SharerTicketTeamR shr talkhid
                    , AP.ticketEvents =
                        encodeRouteLocal $ SharerTicketEventsR shr talkhid
                    , AP.ticketDeps =
                        encodeRouteLocal $ SharerTicketDepsR shr talkhid
                    , AP.ticketReverseDeps =
                        encodeRouteLocal $ SharerTicketReverseDepsR shr talkhid
                    }
                )
            , AP.ticketAttributedTo = encodeRouteLocal $ SharerR shr
            , AP.ticketPublished    = Just $ ticketCreated ticket
            , AP.ticketUpdated      = Nothing
            , AP.ticketContext      =
                Just $
                    case project of
                        Left (s, j) ->
                            encodeRouteHome $
                                ProjectR (sharerIdent s) (projectIdent j)
                        Right (i, ro) ->
                            ObjURI (instanceHost i) (remoteObjectIdent ro)
            , AP.ticketSummary      = TextHtml $ ticketTitle ticket
            , AP.ticketContent      = TextHtml $ ticketDescription ticket
            , AP.ticketSource       = TextPandocMarkdown $ ticketSource ticket
            , AP.ticketAssignedTo   =
                encodeRouteHome . SharerR . sharerIdent <$> massignee
            , AP.ticketIsResolved   = ticketStatus ticket == TSClosed
            , AP.ticketAttachment   = Nothing
            }
    provideHtmlAndAP ticketAP $ redirectToPrettyJSON here
    where
    here = SharerTicketR shr talkhid

getSharerTicketDiscussionR
    :: ShrIdent -> KeyHashid TicketAuthorLocal -> Handler TypedContent
getSharerTicketDiscussionR shr talkhid =
    getRepliesCollection (SharerTicketDiscussionR shr talkhid) $ do
        (_, Entity _ lt, _, _) <- getSharerTicket404 shr talkhid
        return $ localTicketDiscuss lt

getSharerTicketDeps
    :: Bool -> ShrIdent -> KeyHashid TicketAuthorLocal -> Handler TypedContent
getSharerTicketDeps forward shr talkhid =
    getDependencyCollection here getTicketId404 forward
    where
    here =
        let route =
                if forward then SharerTicketDepsR else SharerTicketReverseDepsR
        in  route shr talkhid
    getTicketId404 = do
        (_, _, Entity tid _, _) <- getSharerTicket404 shr talkhid
        return tid

getSharerTicketDepsR
    :: ShrIdent -> KeyHashid TicketAuthorLocal -> Handler TypedContent
getSharerTicketDepsR = getSharerTicketDeps True

getSharerTicketReverseDepsR
    :: ShrIdent -> KeyHashid TicketAuthorLocal -> Handler TypedContent
getSharerTicketReverseDepsR = getSharerTicketDeps False

getSharerTicketFollowersR
    :: ShrIdent -> KeyHashid TicketAuthorLocal -> Handler TypedContent
getSharerTicketFollowersR shr talkhid = getFollowersCollection here getFsid
    where
    here = SharerTicketFollowersR shr talkhid
    getFsid = do
        (_, Entity _ lt, _, _) <- getSharerTicket404 shr talkhid
        return $ localTicketFollowers lt

getSharerTicketTeamR
    :: ShrIdent -> KeyHashid TicketAuthorLocal -> Handler TypedContent
getSharerTicketTeamR shr talkhid = do
    _ <- runDB $ getSharerTicket404 shr talkhid
    provideEmptyCollection
        CollectionTypeUnordered
        (SharerTicketTeamR shr talkhid)

getSharerTicketEventsR
    :: ShrIdent -> KeyHashid TicketAuthorLocal -> Handler TypedContent
getSharerTicketEventsR shr talkhid = do
    _ <- runDB $ getSharerTicket404 shr talkhid
    provideEmptyCollection
        CollectionTypeOrdered
        (SharerTicketEventsR shr talkhid)
[See repo JSON]