ContactManagementTasks.icl 30.3 KB
Newer Older
1
implementation module Incidone.OP.ContactManagementTasks
2
import iTasks, iTasks.Extensions.SQLDatabase, iTasks.Extensions.Web, iTasks.Extensions.Process
3 4 5 6 7 8 9
import Incidone.Configuration
import Incidone.OP.Concepts, Incidone.OP.SDSs, Incidone.OP.Conversions
import Incidone.OP.IncidentManagementTasks
import Incidone.Util.TaskPatterns
import Incidone.DeviceBased.VideoWall

import Incidone.Extensions.CrewLists //For demo
Bas Lijnse's avatar
Bas Lijnse committed
10

11
import qualified Data.Map as DM
Bas Lijnse's avatar
Bas Lijnse committed
12 13
import Text, Text.HTML, Data.Either, Data.Functor
import iTasks.UI.Editor.Controls
14 15 16 17 18 19 20 21 22 23 24 25 26

CONVERT_BIN :== "/opt/local/bin/convert"
//CONVERT_BIN :== "/usr/bin/convert"

openContactInWorkspace :: Workspace ContactNo -> Task ()
openContactInWorkspace ws contactNo = addOnceToWorkspace ("contact-"<+++contactNo) (doOrClose (manageContactInformation ws contactNo)) ws @! ()

selectContact :: Task (Either ContactNo MMSI)
selectContact = withShared Nothing
    \sel -> (
		(selectContactFromLists sel <<@ Title "Browse")
		 -||-
         (viewContactsOnMap mapContacts sel <<@ Title "Map")
Bas Lijnse's avatar
Bas Lijnse committed
27
		 <<@ ArrangeWithTabs True
28
        )
29
where
30 31 32 33
    mapContacts = mapRead (\(x,y) -> x++y) (contactsOfOpenIncidentsGeo |+| contactsProvidingHelpGeo)

	selectContactFromLists :: (Shared (Maybe (Either ContactNo MMSI))) -> Task (Either ContactNo MMSI)
	selectContactFromLists sel
Bas Lijnse's avatar
Bas Lijnse committed
34 35 36 37 38 39
		= anyTask [editSharedSelectionWithShared (Title "Involved in open incidents") False
						(SelectInTree groupByIncident select) contactsOfOpenIncidentsShort (selIds sel)
				  ,editSharedSelectionWithShared (Title "Available for help") False
						(SelectInTree groupByGroup select) contactsProvidingHelpShort (selIds sel)
                  ,editSharedSelectionWithShared (Title "All contacts") False
                        (SelectInTree groupByGroup select) allContactsShort (selIds sel)
40
/*
Bas Lijnse's avatar
Bas Lijnse committed
41 42
				  ,(editSharedSelectionWithShared (Title "AIS") False
						(SelectInTree ungrouped) (mapRead (sortBy (\x y -> contactTitle x < contactTitle y) o map aisToContact) allAISContacts) (Right o contactIdentity)) sel
43
*/				  ] <<@ (ArrangeSplit Horizontal True) @? tvHd
44

Bas Lijnse's avatar
Bas Lijnse committed
45 46 47 48 49 50 51 52 53 54
    fromOpenOption [{ContactShortWithIncidents|contactNo}] = contactNo

	selIds sel = mapReadWrite (toPrj,fromPrj) sel
	where
		toPrj Nothing = []
		toPrj (Just (Left contactNo)) = [contactNo]
		toPrj (Just (Right mmsi)) = [~ mmsi]

		fromPrj [s] _ = Just (Just (if (s > 0) (Left s) (Right (~s))))
		fromPrj _ _   = Just Nothing
55 56

	//Organize contacts into a tree
Bas Lijnse's avatar
Bas Lijnse committed
57 58 59 60
	groupByIncident contacts
        = [{ChoiceNode|id=c.ContactShortWithIncidents.contactNo, label=label c
					,icon=Just (contactIcon {Contact|defaultValue&type=c.ContactShortWithIncidents.type})
					,expanded=False,children=[]} \\ c <- contacts]
61 62 63 64
    where
        label {ContactShortWithIncidents|name,incidents}
            = fromMaybe "-" name +++ " (" +++ join "," [fromMaybe "-" title\\{IncidentShort|title}<-incidents] +++ ")"

Bas Lijnse's avatar
Bas Lijnse committed
65 66 67 68 69
    groupByGroup contacts
        = [{ChoiceNode|id=0,label=group,icon=Nothing,expanded=True,children=
			[{ChoiceNode|id=c.ContactShort.contactNo, label=fromMaybe "-" c.ContactShort.name
					,icon=Just (contactIcon c)
					,expanded=False,children=[]} \\ c <- items]} \\ (group,items) <- 'DM'.toList (foldl group 'DM'.newMap contacts)]
70
    where
Bas Lijnse's avatar
Bas Lijnse committed
71 72
        label {ContactShort|name} = fromMaybe "-" name
        group groups c=:{ContactShort|group}
73
            # g = fromMaybe "Uncategorized" group
Bas Lijnse's avatar
Bas Lijnse committed
74 75 76 77 78 79 80 81 82
            = 'DM'.put g (fromMaybe [] ('DM'.get g groups) ++ [c]) groups

	ungrouped contacts =
		[{ChoiceNode|id=c.ContactShort.contactNo, label=fromMaybe "-" c.ContactShort.name, icon=Just (contactIcon c),expanded=False,children=[]} \\ c <- contacts]

	select _ [0] = []
	select _ [s] = [if (s > 0) (Left s) (Right (~s))]
	select _ _   = []

83 84 85 86 87 88 89 90 91 92 93 94

manageContactInformation :: Workspace ContactNo -> Task ()
manageContactInformation ws contactNo
	= 	withHeader (viewTitle contactNo)
		(allTasks
			[manageContactBasics contactNo
			,manageContactDetails contactNo
			,manageContactPhotos contactNo
			,viewAISInfo contactNo
			,manageContactCommunication contactNo
			,manageContactIncidents ws contactNo
            ,manageContactActions False contactNo
95
            ,manageContactCrew` contactNo <<@ Title "Crew"
Bas Lijnse's avatar
Bas Lijnse committed
96
            ] <<@ ArrangeWithTabs True) @! ()
97 98 99 100 101 102 103 104 105 106 107 108 109 110
where
    viewTitle contactNo	= viewSharedTitle (mapRead contactTitle (sdsFocus contactNo contactByNo))

    manageContactCrew` contactNo = whileUnchanged (mapRead (\{Contact|type,providesHelp}->(type,providesHelp)) (sdsFocus contactNo contactByNo))
        \(type,providesHelp) -> if (type === Just Vessel && providesHelp)
            (manageContactCrew contactNo)
            (viewInformation () [] () <<@ NoUserInterface)

manageContactBasics :: ContactNo -> Task ()
manageContactBasics contactNo = (
    allTasks
        [viewAndEdit (viewContactBasics contactNo) (editContactBasics contactNo)
        ,manageContactAccess contactNo
        ]
Bas Lijnse's avatar
Bas Lijnse committed
111
    >^*[OnAction (Action "/Share to wall") (\_ -> Just (shareContact contactNo))
112
       ] @! ()) <<@ Title "General" <<@ (ApplyAttribute "icon" "basic-information")
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
where

    contactBasics contactNo = mapReadWrite (toPrj,fromPrj) (sdsFocus contactNo contactByNo)
    where
        toPrj {Contact|type,name,group,position,heading,needsHelp,providesHelp,status,notes}
            = {ContactBasic|type=type,name=name,group=group,position=position,heading=heading,needsHelp=needsHelp,providesHelp=providesHelp,status=status,notes=notes}
        fromPrj {ContactBasic|type,name,group,position,heading,needsHelp,providesHelp,status,notes} c
            = Just {Contact|c & type=type,name=name,group=group,position=position,heading=heading,needsHelp=needsHelp,providesHelp=providesHelp,status=status,notes=notes}

    viewContactBasics contactNo
        = viewSharedInformation () [] (contactBasics contactNo)

    editContactBasics contactNo
        =   (get (contactBasics contactNo)
        >>= \old ->
            updateInformation () [] old
        >>? \new -> set new (contactBasics contactNo)
        >>| logContactBasicsUpdated contactNo old new
        ) @! ()

    shareContact contactNo
        = set (WallContactSummary (Just contactNo)) wallContent @! ()

manageContactDetails :: ContactNo -> Task ()
manageContactDetails contactNo
    = whileUnchanged (mapRead (\{Contact|type} -> type) (sdsFocus contactNo contactByNo))
        \mbType -> case mbType of
            Just Person = manageDetails (sdsFocus contactNo personDetailsByNo) (logPersonDetailsUpdated contactNo)  @! ()
            Just Vessel = manageDetails (sdsFocus contactNo vesselDetailsByNo) (logVesselDetailsUpdated contactNo) @! ()
            Just Surfer = manageDetails (sdsFocus contactNo surferDetailsByNo) (logSurferDetailsUpdated contactNo) @! ()
            Just Diver  = manageDetails (sdsFocus contactNo diverDetailsByNo) (logDiverDetailsUpdated contactNo) @! ()
            Just Airplane = manageDetails (sdsFocus contactNo airplaneDetailsByNo) (logAirplaneDetailsUpdated contactNo) @! ()
            Just Helicopter = manageDetails (sdsFocus contactNo helicopterDetailsByNo) (logHelicopterDetailsUpdated contactNo) @! ()
            _               = viewInformation ("Details","No details can be entered if the contact type is unknown.") [] ()
where
    manageDetails share log = forever (
            viewSharedInformation [Att (Title "Details"),Att (Icon "details")] [] share
Bas Lijnse's avatar
Bas Lijnse committed
150
        >>* [OnAction (Action "/Edit") (always (editDetails share log))]
151 152 153 154 155 156 157 158 159 160
        )

    editDetails share log
        =   get share
        >>- \old -> updateInformation [Att (Title "Details (editing)"),Att (Icon "details")] [] old
        >>? \new -> set new share
        >>| log old new

manageContactPhotos :: ContactNo -> Task ()
manageContactPhotos contactNo
161
    =   (enterChoiceWithShared () [ChooseFromList toPrj] (sdsFocus contactNo contactPhotos)
Bas Lijnse's avatar
Bas Lijnse committed
162 163
    >^* [OnAction (Action "/Add photo") (always (addPhoto <<@ InWindow))
        ,OnAction (Action "/Delete photo") (hasValue (\p -> delPhoto p <<@ InWindow))
164 165 166 167 168 169 170 171 172 173 174 175
        ])
        <<@ Title "Photos"
        <<@ Icon "photos"
    @!  ()
where
    toPrj {original,thumb} = ATag [StyleAttr "margin: 5px; float:left",HrefAttr original.Document.contentUrl] [ImgTag [WidthAttr "200",HeightAttr "200",SrcAttr thumb.Document.contentUrl]]

    addPhoto
        =   enterInformation ("Add photo","Please select a photo to upload") []
        >>? addContactPhoto contactNo

    delPhoto photo
176
        =   viewInformation ("Delete photo","Do you want to delete this photo?") [ViewAs (\{original} ->original.Document.name)] photo
177 178 179 180
        >>? removeContactPhoto contactNo

manageContactCommunication :: ContactNo -> Task ()
manageContactCommunication contactNo
181
    = ((manageContactCommunicationMeans True contactNo) // <<@ AfterLayout (tweakUI fill)) //FIXME
182
       -&&-
183
       (viewContactCommunications contactNo) //<<@ AfterLayout (tweakUI fill)) //FIXME
184 185 186 187 188 189 190 191
      ) <<@ ArrangeWithSideBar 0 LeftSide 200 True <<@ Title "Communication" <<@ Icon "communication"
    @! ()
where
    viewContactCommunications contactNo
        = enterChoiceWithShared (Title "Communication history") [] (sdsFocus contactNo contactCommunications)

manageContactCommunicationMeans :: Bool ContactNo -> Task CommunicationMean
manageContactCommunicationMeans compact contactNo = forever (
192 193 194
		enterInformation "FIXME" []

//        editSelectionWithShared (Title "Communication means") [SelectInTree group] (sdsFocus contactNo contactCommunicationMeans) @? tvHd
195 196 197
    >^* [OnAction ActionAdd  (always (addMean contactNo <<@ InWindow @! ()))
        ,OnAction ActionEdit (hasValue (\{CommunicationMean|id} -> editMean id <<@ InWindow @! ()))
        ,OnAction ActionRemove (hasValue (\{CommunicationMean|id} -> removeMean id))
198
        ]
199 200
    )
where
Bas Lijnse's avatar
Bas Lijnse committed
201 202 203
    ActionAdd = Action (if compact "Add" "/Add")
    ActionEdit = Action (if compact "Edit" "/Edit")
    ActionRemove = Action (if compact "Remove" "/Remove")
204

205
    group means expanded = [] /*[{ChoiceTree|label=label m,icon=Just (icon m.CommunicationMean.type),value=ChoiceNode i,type=LeafNode} \\ (i,m) <- means]
206 207 208 209 210 211 212 213 214 215
    where
        label {CommunicationMean|type=CMPhone,phoneNo} = fromMaybe "-" phoneNo
        label {CommunicationMean|type=CMVHF,callSign,mmsi} = fromMaybe "-" callSign +++ " / " +++ maybe "-" toString mmsi
        label {CommunicationMean|type=CMEmail,emailAddress} = maybe "-" toSingleLineText emailAddress
        label {CommunicationMean|type=CMP2000,capCode} = fromMaybe "-" capCode

        icon CMPhone = "phone-call"
        icon CMVHF = "vhf-call"
        icon CMEmail = "e-mail-message"
        icon CMP2000 = "p2000-message"
216
*/
217 218

    addMean contactNo
219
        =   enterInformation (Title "Add communication mean") [EnterAs toNewCommunicationMean]
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
        >>? createCommunicationMean contactNo

    editMean id
        = get (sdsFocus id communicationMeanById)
        >>- \c=:{CommunicationMean|type,phoneNo,callSign,mmsi,emailAddress,capCode} -> case type of
            CMPhone -> updateInformation (Title "Edit telephone details") [] {TelephoneDetails|phoneNo=phoneNo}
                       @ \{TelephoneDetails|phoneNo} -> {CommunicationMean|c & phoneNo = phoneNo}
            CMVHF   -> updateInformation (Title "Edit VHF details") [] {VHFRadioDetails|callSign=callSign,mmsi=mmsi}
                       @ \{VHFRadioDetails|callSign,mmsi} -> {CommunicationMean|c & callSign=callSign, mmsi=mmsi}
            CMEmail -> updateInformation (Title "Edit e-mail details") [] {EmailAccountDetails|emailAddress=emailAddress}
                       @ \{EmailAccountDetails|emailAddress} -> {CommunicationMean|c & emailAddress = emailAddress}
            CMP2000 -> updateInformation (Title "Edit P2000 details") [] {P2000ReceiverDetails|capCode = capCode}
                       @ \{P2000ReceiverDetails|capCode} -> {CommunicationMean|c & capCode = capCode}
        >>? \new ->
            set new (sdsFocus id communicationMeanById)

    removeMean id = deleteCommunicationMean id

manageContactActions :: Bool ContactNo -> Task ()
manageContactActions compact contactNo
	=	if compact selectActions selectAndWorkOnActions
    >^* [OnAction ActionAdd (always (addTopActionItem [contactNo] [] @! ()))
        ,OnAction ActionEdit (hasValue (\a -> editActionItem a @! ()))
        ]
	@!  ()
where
Bas Lijnse's avatar
Bas Lijnse committed
246 247
    ActionAdd = Action (if compact "Add" "/Add action")
    ActionEdit = Action (if compact "Edit" "/Edit action")
248 249 250

    title = (Title (if compact "Actions" "Overview"))
    selectActions
251
        = chooseActionItem title False False (sdsFocus contactNo actionStatusesByContact) // <<@ AfterLayout (tweakUI fill) //FIXME
252 253

    selectAndWorkOnActions
254
        = ( chooseActionItem title False True (sdsFocus contactNo actionStatusesByContact) // <<@ AfterLayout (tweakUI fill)) //FIXME
255 256 257 258 259 260 261 262 263 264 265
            >&> \s -> whileUnchanged s
                (\t -> case t of
                Just taskId    = workOnActionItem taskId @! taskId
                Nothing        = viewInformation () [] () @? const NoValue
                )
          ) <<@ (ArrangeWithSideBar 0 LeftSide 250 True) <<@ (Icon "actions") <<@ (Title "Actions")

manageContactIncidents :: Workspace ContactNo -> Task ()
manageContactIncidents ws contactNo
    =	feedForward choose
    (	\sel ->
266
        withSelection viewNoSelection viewIncidentDetails sel
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
        -&&-
        doAddRemoveOpen (add <<@ InWindow) (\c -> (remove c) <<@ InWindow) (\c -> doOrClose (open c)) ws sel
    )	<<@ (ArrangeWithSideBar 1 RightSide 300 True) <<@ (Icon "incidents") <<@ (Title "Incidents")
    @! ()
where
    incidents   =   sdsFocus contactNo incidentsByContactDetails
    choose		=	enterChoiceWithSharedAs () [] incidents incidentDetailsIdentity
    open sel	=	manageIncidentInformation ws sel
    add			=	enterChoiceWithSharedAs ("Add contact to incident","Select an incident to add this contact to") [] allIncidentsShort incidentShortIdentity
                >>? \i ->
                    upd (\is -> [incidentNo \\{IncidentDetails|incidentNo} <-is] ++ [i]) incidents
                >>| logContactAdded i contactNo
    remove sel	=	viewSharedInformation ("Remove contact from incident","Are your sure you want this contact to be removed from this incident?") [] (sdsFocus sel incidentTitleByNo)
                >>* [OnAction ActionNo (always (return ()))
                    ,OnAction ActionYes (always (upd (\is -> [ incidentNo \\ {IncidentDetails|incidentNo} <- is | incidentNo <> sel]) incidents >>| logContactRemoved sel contactNo))
                    ]

284
	viewNoSelection = return () //FIXME
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
    incidentShortIdentity {IncidentShort|incidentNo} = incidentNo
    incidentDetailsIdentity {IncidentDetails|incidentNo} = incidentNo


viewAISInfo :: ContactNo -> Task ()
viewAISInfo contactNo = whileUnchanged (sdsFocus contactNo contactMMSI)
    \mbMMSI -> case mbMMSI of
        Nothing = viewInformation () [] () <<@ NoUserInterface
        Just mmsi = viewSharedInformation (Icon "ais","AIS","Latest AIS data") [] (sdsFocus mmsi AISContactByMMSI) @! ()

manageContactAccess :: ContactNo -> Task ()
manageContactAccess contactNo = (
        viewAndEdit (viewContactAccess contactNo) (editContactAccess contactNo)
    @!  ()
    ) <<@ Title "Partner access" <<@ Icon "access"
where
    access = sdsFocus contactNo contactAccess

    viewContactAccess contactNo
304
        = viewSharedInformation () [ViewAs view] access
305 306 307 308 309 310 311 312 313 314
    where
        view {ContactAccess|account=Nothing} = "This contact can not log in to Incidone"
        view {ContactAccess|account=Just {Credentials|username=Username uname}}
            = "This contact can log in to Incidone as user '"+++uname+++"'"

    editContactAccess contactNo
        =   get access
        >>- \original ->
            ( (Label "Account" @>> updateInformation () [] original.ContactAccess.account)
              -&&-
315
              (Label "Access level" @>> updateChoice () [ChooseFromCheckGroup viewLevel] [PartnerAccess,WOAccess] (fromMaybe PartnerAccess original.ContactAccess.access))
316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331
            )
        >>? \(updatedAccount,updatedAccess) ->
            set {ContactAccess|account=updatedAccount,access=Just updatedAccess} access

    viewLevel WOAccess = "Watch Officer access"
    viewLevel PartnerAccess = "Partner access"

viewContactDetails :: ContactNo -> Task ()
viewContactDetails contactNo
	= withHeader (viewSharedTitle (mapRead contactTitle contact))
	( viewPhoto contact
	  -&&-
	  viewSharedInformation () [] (mapRead contactDetails contact)
      -&&-
      viewContactCommunicationMeans contactNo
      -&&-
332
      viewSharedInformation "Actions:" [ViewAs viewActions] (sdsFocus contactNo actionStatusesByContact)
333 334 335 336 337
	) @! ()
where
	contact = sdsFocus contactNo contactByNo

	viewPhoto contact
338
		= viewSharedInformation () [ViewAs contactThumbHtml] contact
339 340 341 342 343 344 345

    viewActions items = case [title \\ (_,_,{ActionStatus|title}) <- items] of
        []      = ["There are no actions for this contact"]
        titles  = titles

viewContactCommunicationMeans :: ContactNo -> Task [CommunicationMean]
viewContactCommunicationMeans contactNo
346
    = viewSharedInformation "Communication means:" [ViewAs viewComms] (sdsFocus contactNo contactCommunicationMeans)
347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
where
    viewComms items = TableTag [] (map viewComm items)
    where
        viewComm {CommunicationMean|type=CMPhone,phoneNo} = commRow "phone-call" ("Telephone :" +++ fromMaybe "-" phoneNo)
        viewComm {CommunicationMean|type=CMVHF,callSign,mmsi} = commRow "vhf-call" ("Callsign: " +++ fromMaybe "-" callSign +++ " / MMSI: " +++ maybe "-" toString mmsi)
        viewComm {CommunicationMean|type=CMEmail,emailAddress} = commRow "e-mail-message" ("E-mail: " +++ maybe "-" toSingleLineText emailAddress)
        viewComm {CommunicationMean|type=CMP2000,capCode} = commRow "p2000-message" ("P2000: " +++ fromMaybe "-" capCode)

        commRow icon label
            = TrTag [] [TdTag [] [DivTag [StyleAttr "width:16px;height:16px;",ClassAttr ("icon-"+++icon)] []],TdTag [] [Text label]]


viewAISContactDetails :: MMSI -> Task ()
viewAISContactDetails mmsi
    = withHeader (viewTitle (toString mmsi))
362
        (viewSharedInformation () [ViewAs (fmap aisToDetails)] (sdsFocus mmsi AISContactByMMSI)
363 364 365 366 367 368
         -&&-
         viewVesselWebLinks mmsi
        ) @! ()

viewContactHeader :: ContactNo -> Task ()
viewContactHeader contactNo
369
    = viewSharedInformation () [ViewAs toView] (sdsFocus contactNo contactByNo) @! ()
370 371 372 373 374 375 376 377 378 379 380 381 382
where
    toView c=:{Contact|photos,name}
        = DivTag [] [ImgTag [StyleAttr "float: left; margin-right: 5px":attributes]
                    ,H1Tag [StyleAttr "font-size: 30px; font-weight: normal"] [Text (contactTitle c)]
                    ]
    where
        (ImgTag attributes) = contactAvatarHtml c

viewVesselWebLinks :: MMSI -> Task ()
viewVesselWebLinks mmsi
    =   get webLinksConfig
    >>- \webLinks -> if (isEmpty webLinks.vesselLinks)
        (return ())
383
        (viewInformation "Find on the web" [ViewAs toLinks] webLinks.vesselLinks @! ())
384 385 386 387 388 389 390 391 392 393
where
    toLinks links
        = UlTag [] [LiTag [] [ATag [TargetAttr "_blank", HrefAttr (replaceSubString "{mmsi}" (toString mmsi) url)] [Text title]]\\{WebLink|title,url=URL url} <- links]

updateContactPosition :: ContactNo -> Task (Maybe (Maybe ContactPosition))
updateContactPosition contactNo
    =   get (sdsFocus contactNo contactByNo |+| standardMapLayers)
    >>- \({Contact|name,type,position},baseLayers) ->
        withShared (position,initPerspective position)
        \tmpInfo ->
394
        (updateSharedInformation ("Position update","Update position of contact "<+++ name) [UpdateAs fst (\(_,y) x -> (x,y))] tmpInfo
395
         -||-
396
         updateSharedInformation () [UpdateAs (toMap baseLayers) (fromMap baseLayers)] tmpInfo
397
         -||-
398
         viewSharedInformation "Search the web" [ViewAs (toSearchURLs o fst)] tmpInfo
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
        ) @ fst
    >>? \newPosition ->
        upd (\c -> {Contact|c&position=newPosition}) (sdsFocus contactNo contactByNo)
    >>| logContactPositionUpdated contactNo position newPosition
    @!  newPosition
where
	initPerspective position = {ContactMapPerspective|defaultValue & center = fromMaybe defaultValue.ContactMapPerspective.center contactPos, zoom = 7, cursor = contactPos}
    where
        contactPos = maybe Nothing latLng position

    toMap baseLayers (pos,perspective)
        = toLeafletMap (contactMap baseLayers (pos,perspective))
    fromMap baseLayers (pos,perspective) leafletMap
        # {ContactMap|perspective} = fromLeafletMap (contactMap baseLayers (pos,perspective)) leafletMap
        = case perspective.ContactMapPerspective.cursor of
            (Just cursor)   = (Just (PositionLatLng cursor),perspective)
            _               = (pos, perspective)

    fromMap _ info _ = info

    contactMap baseLayers (pos,perspective)
        = {ContactMap|defaultValue & perspective = {ContactMapPerspective|perspective & cursor = maybe Nothing latLng pos},layers = baseLayers}

    toSearchURLs Nothing    = UlTag [] []
    toSearchURLs (Just pos) = UlTag [] [LiTag [] [ATag [TargetAttr "_blank", HrefAttr ("http://maps.google.com/?q="+++toSingleLineText pos)] [Text "Search with Google Maps"]]
                                       ,LiTag [] [ATag [TargetAttr "_blank", HrefAttr ("http://www.bing.com/maps/?q="+++toSingleLineText pos)] [Text "Search with Bing Maps"]]
                                       ]

updateContactStatus :: ContactNo -> Task (Maybe (Maybe ContactStatus))
updateContactStatus contactNo
    =   get (sdsFocus contactNo contactByNo)
    >>- \{Contact|status} ->
        updateInformation (Title "Status") [] status
    >>? \newStatus ->
        upd (\c -> {Contact|c&status = newStatus}) (sdsFocus contactNo contactByNo)
    >>| logContactStatusUpdated contactNo status newStatus
    @!  newStatus

437
updateSharedContactRefList :: d (RWShared () [ContactNo] [ContactNo]) -> Task [ContactNo] | toPrompt d
438 439
updateSharedContactRefList d refs
    =   manageCurrentItems
Bas Lijnse's avatar
Bas Lijnse committed
440
    >^* [OnAction (Action "Add") (always (addItem <<@ InWindow))]
441 442
where
    manageCurrentItems
443
        = updateSharedInformation d [UpdateAs toPrj fromPrj] items @ map contactIdentity
444 445
    where
        items = sdsDeref refs id contactsByNosShort (\_ cs -> cs)
Bas Lijnse's avatar
Bas Lijnse committed
446 447
        toPrj l = [(contactIdentity c,contactTitle c) \\ c <-l]
        fromPrj _ items = map fst items
448 449 450 451 452 453 454 455 456 457 458 459

    addItem
        =   selectKnownOrDefineNewContact
        >>? (\def -> createContactIfNew def >>- \contactNo -> upd (\r -> r ++ [contactNo]) refs)

selectKnownOrDefineNewContact :: Task (Either ContactNo NewContact)
selectKnownOrDefineNewContact
    = oneOrAnother ("Add contact...","You can either select a know contact, or define a new one.")
        ("Known contact", chooseKnownContact)
        ("Add new contact",enterNewContact)
where
    chooseKnownContact
460
        = enterChoiceWithSharedAs () [ChooseFromDropdown id] allContactsShort contactIdentity
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
    enterNewContact
        = enterInformation () []

createContactIfNew :: (Either ContactNo NewContact) -> Task ContactNo
createContactIfNew (Left no) = return no
createContactIfNew (Right contact) = createContact contact

createContact :: NewContact -> Task ContactNo
createContact {NewContact|type,name,position,needsHelp}
	=   get databaseDef
	>>- \db -> sqlExecute db ["allContacts"] (
		execInsert "INSERT INTO Contact (`type`,`name`,`position_lat`,`position_lon`,`position_desc`,`needsHelp`) VALUES (?,?,?,?,?,?)"
			(flatten
            [mbToSQL type
			,mbToSQL name
			,mbToSQL position
			,toSQL   needsHelp
			]))

deleteContact :: ContactNo -> Task ()
deleteContact contactNo
	=		delete contactNo
	-&&-	upd (\m -> 'DM'.put contactNo [] m) (sdsFocus (Just [contactNo]) incidentNosByContactNosIndexed)
	-&&-	upd (\m -> 'DM'.put contactNo [] m) (sdsFocus (Just [contactNo]) communicationNosByContactNosIndexed)
	@!  ()
where
	delete :: ContactNo -> Task ()
	delete contactNo
		=	get databaseDef
		>>= \db -> sqlExecute db ["allContacts"] (execDelete "DELETE FROM Contact WHERE contactNo = ?" (toSQL contactNo)) @! ()

addContactPhoto :: ContactNo Document -> Task ContactPhoto
addContactPhoto contactNo original
    =   withTemporaryDirectory
        \tmp ->
        exportDocument (tmp</>"orig.jpg") original
    >>- \_ ->
        callProcess "Creating thumbnail..." [] CONVERT_BIN
Steffen Michels's avatar
Steffen Michels committed
499
            ["-define","jpeg:size=400x400",(tmp</>"orig.jpg"),"-thumbnail","200x200^","-gravity","center","-extent","200x200",(tmp</>"thumb.png")] Nothing Nothing
500 501 502 503
    >>- \_ ->
        importDocument (tmp</>"thumb.png")
    >>- \thumb ->
        callProcess "Creating avatar..." [] CONVERT_BIN
Steffen Michels's avatar
Steffen Michels committed
504
            ["-define","jpeg:size=100x100",(tmp</>"orig.jpg"),"-thumbnail","50x50^","-gravity","center","-extent","50x50",(tmp</>"avatar.png")] Nothing Nothing
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
    >>- \_ ->
        importDocument (tmp</>"avatar.png")
    >>- \avatar -> let photo = {ContactPhoto|original = original, thumb = thumb, avatar = avatar} in
        upd (\photos -> 'DM'.put contactNo [photo:fromMaybe [] ('DM'.get contactNo photos)] photos) allContactPhotos
    >>- \_ ->
        logContactPhotoAdded contactNo photo
    @!  photo

removeContactPhoto :: ContactNo ContactPhoto -> Task ContactPhoto
removeContactPhoto contactNo photo
    =  upd (\photos -> 'DM'.put contactNo (removePhoto photo (fromMaybe [] ('DM'.get contactNo photos))) photos) allContactPhotos
    @! photo
where
    removePhoto photo photos = [p \\ p <- photos | p =!= photo]

createCommunicationMean :: ContactNo NewCommunicationMean -> Task CommunicationMeanId
createCommunicationMean contactNo mean=:{NewCommunicationMean|type,phoneNo,callSign,mmsi,emailAddress,capCode}
    =   get databaseDef
    >>- \db ->
        sqlExecute db ["allCommunicationMeans"] (execInsert "INSERT INTO CommunicationMean (type) VALUES (?)" (toSQL type))
    >>- \id ->
        sqlExecute db [] (execInsert "INSERT INTO communicationMeans1_communicationMeans2 (communicationMeans1,communicationMeans2) VALUES (?,?)" (toSQL id ++ toSQL contactNo))
    >>- \_ -> case type of
        CMPhone = sqlExecute db [] (execInsert "INSERT INTO Telephone (id,phoneNo) VALUES (?,?)" (toSQL id ++ mbToSQL phoneNo))
        CMVHF   = sqlExecute db [] (execInsert "INSERT INTO VHFRadio (id,callSign,mmsi) VALUES (?,?,?)" (toSQL id ++ mbToSQL callSign ++ mbToSQL mmsi))
        CMEmail = sqlExecute db [] (execInsert "INSERT INTO EmailAccount (id,emailAddress) VALUES (?,?)" (toSQL id ++ mbToSQL emailAddress))
        CMP2000 = sqlExecute db [] (execInsert "INSERT INTO P2000Receiver (id,capCode) VALUES (?,?)" (toSQL id ++ mbToSQL capCode))

deleteCommunicationMean :: CommunicationMeanId -> Task ()
deleteCommunicationMean id
    =   get databaseDef
    >>- \db ->
        sqlExecute db ["allCommunicationMeans"] (execDelete "DELETE FROM communicationMeans1_communicationMeans2 WHERE communicationMeans1 = ? " (toSQL id))
    >>- \_ ->
        allTasks [sqlExecute db [] (execDelete ("DELETE FROM " +++ table +++" WHERE id = ? ") (toSQL id)) \\ table <-
                    ["CommunicationMean","Telephone","VHFRadio","EmailAccount","P2000Receiver"]]
    @!  ()

updatePosition :: ContactPosition String (Shared Contact) -> Task Contact
updatePosition newposition src contact
	= upd (update newposition src) contact
where
	update newposition src contact=:{Contact|position}
		= {Contact|contact & position = Just newposition}

verifyContactCredentials :: Credentials -> Task (Maybe User)
verifyContactCredentials credentials
    = get (sdsFocus credentials contactByCredentials)
    @ fmap contactUser

Bas Lijnse's avatar
Bas Lijnse committed
555
viewContactsOnMap :: (ReadWriteShared [ContactGeo] w) (Shared (Maybe (Either ContactNo MMSI))) -> Task (Either ContactNo MMSI) | iTask w
556 557 558 559 560
viewContactsOnMap sharedContacts sel
   =   get (standardMapLayers |+| standardPerspective)
   >>- \(baseLayers,perspective) ->
       withShared (False,perspective)
       \localState ->
561
            updateSharedInformation "Show AIS contacts:" [UpdateAs fst (\(_,y) x -> (x,y))] localState
562
            ||-
563
            (updateSharedInformation () [UpdateAs (toPrj baseLayers) fromPrj] (mapState localState sharedContacts sel)) @ (\(a,b,c) -> (b,c))
Bas Lijnse's avatar
Bas Lijnse committed
564
            >^* [OnAction (Action "/Share map to wall") (hasValue sharePerspective)
565 566 567 568 569 570
                ]
        @? selection
where
    mapState :: (Shared (Bool,ContactMapPerspective))
                (ReadWriteShared [ContactGeo] w)
                (Shared (Maybe (Either ContactNo MMSI))) ->
Bas Lijnse's avatar
Bas Lijnse committed
571 572
                ReadWriteShared ([(Bool,ContactGeo)], Maybe (Either ContactNo MMSI), ContactMapPerspective) (Maybe (Either ContactNo MMSI), ContactMapPerspective) | iTask w
    mapState local contacts sel = sdsSequence "mapState" id (\_ r -> r) (\_ _ -> Right read) writel writer (local >+< sel) mapContacts
573
    where
574
        mapContacts = sdsSelect "mapContacts" choose (SDSNotifyConst (\_ _ _ _-> False)) (SDSNotifyConst (\_ _ _ _-> False)) withoutAISContacts withAISContacts
575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598
        where
            choose ((withAIS,{ContactMapPerspective|bounds=Just bounds}),_) = (if withAIS (Right bounds) (Left bounds))
            choose _                                                        = (Left defaultValue)

            baseContacts = mapRead (\cs -> [(False,c) \\ c<-cs]) (toReadOnly contacts)
            aisContacts = mapRead (\cs -> [(True,c)\\c=:{ContactGeo|position=Just position}<-map aisToContactGeo cs]) (toReadOnly boundedAISContacts)

            withoutAISContacts = sdsFocus () baseContacts
            withAISContacts = mapRead (\(a,b) -> a++b) (aisContacts |+| sdsFocus () baseContacts)

        read (((showAis,perspective),mbSel),contacts) = (contacts,mbSel,perspective)
        writel = SDSWrite (\_ ((showAis,_),_) (mbSel,perspective) -> Ok (Just ((showAis,perspective),mbSel)))
        writer = SDSWriteConst (\_ _ -> Ok Nothing)

    toPrj baseLayers (contacts,sel,perspective)
        = toLeafletMap {ContactMap|perspective=perspective,layers=[{title="Contacts",def=CMMarkersLayer (toMarkers sel contacts)}:baseLayers]}

    fromPrj (contacts,sel,_) map=:{LeafletMap|perspective}
        = (maybe sel Just (updateSelection (selectionFromLeafletMap map)),fromLeafletPerspective perspective)

	selection (Value (Just no,_) stable)	= Value no stable
	selection _								= NoValue

    sharePerspective (_,perspective) = set (WallOverview perspective) wallContent @! ()
599

600 601 602 603 604 605 606 607 608 609 610 611
    toMarkers sel contacts
        = [contactGeoToMapMarker ais (isSelected contactNo sel) c \\ (ais,c=:{ContactGeo|contactNo,name=Just _,position=Just _}) <- contacts]

    isSelected contactNo (Just (Left no)) = no == contactNo
    isSelected contactNo (Just (Right no)) = no == contactNo
    isSelected _ _ = False

    updateSelection [] = Nothing
	updateSelection [markerId:ms]
        | startsWith "c" markerId   = Just (Left (toInt (subString 1 (textSize markerId) markerId)))
        | startsWith "a" markerId   = Just (Right (toInt (subString 1 (textSize markerId) markerId)))
                                    = updateSelection ms
612

613 614 615 616 617
	findContactNo title contacts = case [(isAis,contactNo) \\ (isAis,{ContactGeo|contactNo,name}) <- contacts | name == title] of
		[(False,contactNo)] = Just (Left contactNo)
		[(True,mmsi)]   = Just (Right mmsi)
		_			    = Nothing