Compare commits
74 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 1e6d984d95 | |||
| 9af41447b7 | |||
| f8b5902aa1 | |||
| 5f425adc1d | |||
| b0bf2cb083 | |||
| a5727a84fc | |||
| 817d7876db | |||
| 00034c0a26 | |||
| 907d759a23 | |||
| 7421f9c788 | |||
| dc31b65be8 | |||
| fa281124bb | |||
| 9491359b52 | |||
| 0ec4fd017f | |||
| 3df5c71d81 | |||
| c697001736 | |||
|
|
6c28cfc1ec | ||
| 8702723e01 | |||
| d621ede7bb | |||
| a826275510 | |||
| 2a86e41fe3 | |||
| babc77bbd0 | |||
| 997279783f | |||
| 77c85f516c | |||
| ca622aa4b7 | |||
| cce4f17cd8 | |||
| 0bf73e49c9 | |||
| a84d54c095 | |||
|
|
68f4a1b9b2 | ||
| 23ccd3ac67 | |||
| d4823c15f7 | |||
| fc01e79337 | |||
| fa9c902af7 | |||
|
|
ed762ea03e | ||
| 3675af3dca | |||
|
|
1830e01ad6 | ||
|
|
ffe057d7ee | ||
|
|
bafdfb1af5 | ||
|
|
3d907e9569 | ||
|
|
c8ef6e8714 | ||
| 266243423c | |||
| 92a493251a | |||
| c7c63d01f8 | |||
|
|
62a18a8b09 | ||
| d1a9eb62c3 | |||
| 407222d06a | |||
| 044283709c | |||
|
|
be86fbfcba | ||
|
|
63b3037ede | ||
| d239b16d33 | |||
| a9ab0446c4 | |||
| 366ed2ed2f | |||
|
|
fb304c26b6 | ||
|
|
7b11e70e76 | ||
|
|
f50a8ae83e | ||
|
|
aa0864416f | ||
|
|
05a1b7adda | ||
|
|
f833598cdd | ||
|
|
dfd1c59554 | ||
|
|
83b70073e9 | ||
|
|
11025cc39a | ||
|
|
fb908a1cef | ||
|
|
6a6f7b35c7 | ||
| 715df08cbe | |||
|
|
ac8b39fff9 | ||
|
|
2bf54136ca | ||
|
|
0709cabea1 | ||
|
|
cbd9114599 | ||
|
|
097ee2deb4 | ||
| fa78e86de6 | |||
|
|
ce588b6a43 | ||
|
|
57cd17c734 | ||
|
|
42615dae82 | ||
|
|
68b650e31d |
15
.gitignore
vendored
15
.gitignore
vendored
@@ -252,12 +252,9 @@ paket-files/
|
|||||||
.idea/
|
.idea/
|
||||||
*.sln.iml
|
*.sln.iml
|
||||||
|
|
||||||
# Compiled files / application
|
# Ionide VSCode extension
|
||||||
src/api/build
|
.ionide
|
||||||
src/api/MyPrayerJournal.Api/wwwroot/favicon.ico
|
|
||||||
src/api/MyPrayerJournal.Api/wwwroot/index.html
|
# in-progress: PHP version
|
||||||
src/api/MyPrayerJournal.Api/wwwroot/css
|
src/app/vendor
|
||||||
src/api/MyPrayerJournal.Api/wwwroot/js
|
**/.env
|
||||||
src/api/MyPrayerJournal.Api/appsettings.development.json
|
|
||||||
/build
|
|
||||||
src/*.exe
|
|
||||||
|
|||||||
@@ -6,6 +6,11 @@ Journaling has a long history; it helps people remember what happened, and the a
|
|||||||
|
|
||||||
myPrayerJournal was borne of out of a personal desire [Daniel](https://github.com/danieljsummers) had to have something that would help him with his prayer life. When it's time to pray, it's not really time to use an app, so the design goal here is to keep it simple and unobtrusive. It will also help eliminate some of the downsides to a paper prayer journal, like not remembering whether you've prayed for a request, or running out of room to write another update on one.
|
myPrayerJournal was borne of out of a personal desire [Daniel](https://github.com/danieljsummers) had to have something that would help him with his prayer life. When it's time to pray, it's not really time to use an app, so the design goal here is to keep it simple and unobtrusive. It will also help eliminate some of the downsides to a paper prayer journal, like not remembering whether you've prayed for a request, or running out of room to write another update on one.
|
||||||
|
|
||||||
## Futher Reading
|
## Further Reading
|
||||||
|
|
||||||
The documentation for the site is at <https://bit-badger.github.io/myPrayerJournal/>.
|
The documentation for the site is at <https://bit-badger.github.io/myPrayerJournal/>.
|
||||||
|
|
||||||
|
---
|
||||||
|
_Thanks to [JetBrains](https://jb.gg/OpenSource) for licensing their awesome toolset to this project._
|
||||||
|
|
||||||
|
[<img src="https://resources.jetbrains.com/storage/products/company/brand/logos/jb_beam.png" alt="JetBrains Logo (Main) logo" width="100" height="100">](https://jb.gg/OpenSource)
|
||||||
|
|||||||
3
publish.ps1
Executable file
3
publish.ps1
Executable file
@@ -0,0 +1,3 @@
|
|||||||
|
#!/snap/bin/pwsh
|
||||||
|
Set-Location src/MyPrayerJournal
|
||||||
|
dotnet publish -c Release -r linux-x64 -p:PublishSingleFile=true --self-contained false --nologo
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<OutputType>Exe</OutputType>
|
||||||
|
<TargetFramework>net6.0</TargetFramework>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<Compile Include="Program.fs" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\MyPrayerJournal\MyPrayerJournal.fsproj" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
114
src/MyPrayerJournal.ConvertRecurrence/Program.fs
Normal file
114
src/MyPrayerJournal.ConvertRecurrence/Program.fs
Normal file
@@ -0,0 +1,114 @@
|
|||||||
|
open MyPrayerJournal.Domain
|
||||||
|
open NodaTime
|
||||||
|
|
||||||
|
/// The old definition of the history entry
|
||||||
|
[<CLIMutable; NoComparison; NoEquality>]
|
||||||
|
type OldHistory =
|
||||||
|
{ /// The time when this history entry was made
|
||||||
|
asOf : int64
|
||||||
|
/// The status for this history entry
|
||||||
|
status : RequestAction
|
||||||
|
/// The text of the update, if applicable
|
||||||
|
text : string option
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The old definition of of the note entry
|
||||||
|
[<CLIMutable; NoComparison; NoEquality>]
|
||||||
|
type OldNote =
|
||||||
|
{ /// The time when this note was made
|
||||||
|
asOf : int64
|
||||||
|
|
||||||
|
/// The text of the notes
|
||||||
|
notes : string
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Request is the identifying record for a prayer request
|
||||||
|
[<CLIMutable; NoComparison; NoEquality>]
|
||||||
|
type OldRequest =
|
||||||
|
{ /// The ID of the request
|
||||||
|
id : RequestId
|
||||||
|
|
||||||
|
/// The time this request was initially entered
|
||||||
|
enteredOn : int64
|
||||||
|
|
||||||
|
/// The ID of the user to whom this request belongs ("sub" from the JWT)
|
||||||
|
userId : UserId
|
||||||
|
|
||||||
|
/// The time at which this request should reappear in the user's journal by manual user choice
|
||||||
|
snoozedUntil : int64
|
||||||
|
|
||||||
|
/// The time at which this request should reappear in the user's journal by recurrence
|
||||||
|
showAfter : int64
|
||||||
|
|
||||||
|
/// The type of recurrence for this request
|
||||||
|
recurType : string
|
||||||
|
|
||||||
|
/// How many of the recurrence intervals should occur between appearances in the journal
|
||||||
|
recurCount : int16
|
||||||
|
|
||||||
|
/// The history entries for this request
|
||||||
|
history : OldHistory[]
|
||||||
|
|
||||||
|
/// The notes for this request
|
||||||
|
notes : OldNote[]
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
open LiteDB
|
||||||
|
open MyPrayerJournal.Data
|
||||||
|
|
||||||
|
let db = new LiteDatabase ("Filename=./mpj.db")
|
||||||
|
Startup.ensureDb db
|
||||||
|
|
||||||
|
/// Map the old recurrence to the new style
|
||||||
|
let mapRecurrence old =
|
||||||
|
match old.recurType with
|
||||||
|
| "Days" -> Days old.recurCount
|
||||||
|
| "Hours" -> Hours old.recurCount
|
||||||
|
| "Weeks" -> Weeks old.recurCount
|
||||||
|
| _ -> Immediate
|
||||||
|
|
||||||
|
/// Convert an old history entry to the new form
|
||||||
|
let convertHistory (old : OldHistory) =
|
||||||
|
{ AsOf = Instant.FromUnixTimeMilliseconds old.asOf
|
||||||
|
Status = old.status
|
||||||
|
Text = old.text
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Convert an old note to the new form
|
||||||
|
let convertNote (old : OldNote) =
|
||||||
|
{ AsOf = Instant.FromUnixTimeMilliseconds old.asOf
|
||||||
|
Notes = old.notes
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Convert items that may be Instant.MinValue or Instant(0) to None
|
||||||
|
let noneIfOld ms =
|
||||||
|
match Instant.FromUnixTimeMilliseconds ms with
|
||||||
|
| instant when instant > Instant.FromUnixTimeMilliseconds 0 -> Some instant
|
||||||
|
| _ -> None
|
||||||
|
|
||||||
|
/// Map the old request to the new request
|
||||||
|
let convert old =
|
||||||
|
{ Id = old.id
|
||||||
|
EnteredOn = Instant.FromUnixTimeMilliseconds old.enteredOn
|
||||||
|
UserId = old.userId
|
||||||
|
SnoozedUntil = noneIfOld old.snoozedUntil
|
||||||
|
ShowAfter = noneIfOld old.showAfter
|
||||||
|
Recurrence = mapRecurrence old
|
||||||
|
History = old.history |> Array.map convertHistory |> List.ofArray
|
||||||
|
Notes = old.notes |> Array.map convertNote |> List.ofArray
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Remove the old request, add the converted one (removes recurType / recurCount fields)
|
||||||
|
let replace (req : Request) =
|
||||||
|
db.Requests.Delete (Mapping.RequestId.toBson req.Id) |> ignore
|
||||||
|
db.Requests.Insert req |> ignore
|
||||||
|
db.Checkpoint ()
|
||||||
|
|
||||||
|
db.GetCollection<OldRequest>("request").FindAll ()
|
||||||
|
|> Seq.map convert
|
||||||
|
|> List.ofSeq
|
||||||
|
|> List.iter replace
|
||||||
|
|
||||||
|
// For more information see https://aka.ms/fsharp-console-apps
|
||||||
|
printfn "Done"
|
||||||
28
src/MyPrayerJournal.sln
Normal file
28
src/MyPrayerJournal.sln
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
|
||||||
|
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||||
|
# Visual Studio Version 16
|
||||||
|
VisualStudioVersion = 16.0.30114.105
|
||||||
|
MinimumVisualStudioVersion = 10.0.40219.1
|
||||||
|
Project("{F2A71F9B-5D33-465A-A702-920D77279786}") = "MyPrayerJournal", "MyPrayerJournal\MyPrayerJournal.fsproj", "{6BD5A3C8-F859-42A0-ACD7-A5819385E828}"
|
||||||
|
EndProject
|
||||||
|
Project("{F2A71F9B-5D33-465A-A702-920D77279786}") = "MyPrayerJournal.ConvertRecurrence", "MyPrayerJournal.ConvertRecurrence\MyPrayerJournal.ConvertRecurrence.fsproj", "{72B57736-8721-4636-A309-49FA4222416E}"
|
||||||
|
EndProject
|
||||||
|
Global
|
||||||
|
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||||
|
Debug|Any CPU = Debug|Any CPU
|
||||||
|
Release|Any CPU = Release|Any CPU
|
||||||
|
EndGlobalSection
|
||||||
|
GlobalSection(SolutionProperties) = preSolution
|
||||||
|
HideSolutionNode = FALSE
|
||||||
|
EndGlobalSection
|
||||||
|
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||||
|
{6BD5A3C8-F859-42A0-ACD7-A5819385E828}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||||
|
{6BD5A3C8-F859-42A0-ACD7-A5819385E828}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
|
{6BD5A3C8-F859-42A0-ACD7-A5819385E828}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
|
{6BD5A3C8-F859-42A0-ACD7-A5819385E828}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
|
{72B57736-8721-4636-A309-49FA4222416E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||||
|
{72B57736-8721-4636-A309-49FA4222416E}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
|
{72B57736-8721-4636-A309-49FA4222416E}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
|
{72B57736-8721-4636-A309-49FA4222416E}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
|
EndGlobalSection
|
||||||
|
EndGlobal
|
||||||
5
src/MyPrayerJournal/.gitignore
vendored
Normal file
5
src/MyPrayerJournal/.gitignore
vendored
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
## LiteDB database file
|
||||||
|
*.db
|
||||||
|
|
||||||
|
## Development settings
|
||||||
|
appsettings.Development.json
|
||||||
199
src/MyPrayerJournal/Data.fs
Normal file
199
src/MyPrayerJournal/Data.fs
Normal file
@@ -0,0 +1,199 @@
|
|||||||
|
module MyPrayerJournal.Data
|
||||||
|
|
||||||
|
open LiteDB
|
||||||
|
open MyPrayerJournal
|
||||||
|
open System.Threading.Tasks
|
||||||
|
|
||||||
|
/// LiteDB extensions
|
||||||
|
[<AutoOpen>]
|
||||||
|
module Extensions =
|
||||||
|
|
||||||
|
/// Extensions on the LiteDatabase class
|
||||||
|
type LiteDatabase with
|
||||||
|
|
||||||
|
/// The Request collection
|
||||||
|
member this.Requests = this.GetCollection<Request> "request"
|
||||||
|
|
||||||
|
/// Async version of the checkpoint command (flushes log)
|
||||||
|
member this.SaveChanges () =
|
||||||
|
this.Checkpoint ()
|
||||||
|
Task.CompletedTask
|
||||||
|
|
||||||
|
|
||||||
|
/// Map domain to LiteDB
|
||||||
|
// It does mapping, but since we're so DU-heavy, this gives us control over the JSON representation
|
||||||
|
[<RequireQualifiedAccess>]
|
||||||
|
module Mapping =
|
||||||
|
|
||||||
|
open NodaTime
|
||||||
|
open NodaTime.Text
|
||||||
|
|
||||||
|
/// A NodaTime instant pattern to use for parsing instants from the database
|
||||||
|
let instantPattern = InstantPattern.CreateWithInvariantCulture "g"
|
||||||
|
|
||||||
|
/// Mapping for NodaTime's Instant type
|
||||||
|
module Instant =
|
||||||
|
let fromBson (value : BsonValue) = (instantPattern.Parse value.AsString).Value
|
||||||
|
let toBson (value : Instant) : BsonValue = value.ToString ("g", null)
|
||||||
|
|
||||||
|
/// Mapping for option types
|
||||||
|
module Option =
|
||||||
|
let instantFromBson (value : BsonValue) = if value.IsNull then None else Some (Instant.fromBson value)
|
||||||
|
let instantToBson (value : Instant option) = match value with Some it -> Instant.toBson it | None -> null
|
||||||
|
|
||||||
|
let stringFromBson (value : BsonValue) = match value.AsString with "" -> None | x -> Some x
|
||||||
|
let stringToBson (value : string option) : BsonValue = match value with Some txt -> txt | None -> ""
|
||||||
|
|
||||||
|
/// Mapping for Recurrence
|
||||||
|
module Recurrence =
|
||||||
|
let fromBson (value : BsonValue) = Recurrence.ofString value
|
||||||
|
let toBson (value : Recurrence) : BsonValue = Recurrence.toString value
|
||||||
|
|
||||||
|
/// Mapping for RequestAction
|
||||||
|
module RequestAction =
|
||||||
|
let fromBson (value : BsonValue) = RequestAction.ofString value.AsString
|
||||||
|
let toBson (value : RequestAction) : BsonValue = RequestAction.toString value
|
||||||
|
|
||||||
|
/// Mapping for RequestId
|
||||||
|
module RequestId =
|
||||||
|
let fromBson (value : BsonValue) = RequestId.ofString value.AsString
|
||||||
|
let toBson (value : RequestId) : BsonValue = RequestId.toString value
|
||||||
|
|
||||||
|
/// Mapping for UserId
|
||||||
|
module UserId =
|
||||||
|
let fromBson (value : BsonValue) = UserId value.AsString
|
||||||
|
let toBson (value : UserId) : BsonValue = UserId.toString value
|
||||||
|
|
||||||
|
/// Set up the mapping
|
||||||
|
let register () =
|
||||||
|
BsonMapper.Global.RegisterType<Instant>(Instant.toBson, Instant.fromBson)
|
||||||
|
BsonMapper.Global.RegisterType<Instant option>(Option.instantToBson, Option.instantFromBson)
|
||||||
|
BsonMapper.Global.RegisterType<Recurrence>(Recurrence.toBson, Recurrence.fromBson)
|
||||||
|
BsonMapper.Global.RegisterType<RequestAction>(RequestAction.toBson, RequestAction.fromBson)
|
||||||
|
BsonMapper.Global.RegisterType<RequestId>(RequestId.toBson, RequestId.fromBson)
|
||||||
|
BsonMapper.Global.RegisterType<string option>(Option.stringToBson, Option.stringFromBson)
|
||||||
|
BsonMapper.Global.RegisterType<UserId>(UserId.toBson, UserId.fromBson)
|
||||||
|
|
||||||
|
/// Code to be run at startup
|
||||||
|
module Startup =
|
||||||
|
|
||||||
|
/// Ensure the database is set up
|
||||||
|
let ensureDb (db : LiteDatabase) =
|
||||||
|
db.Requests.EnsureIndex (fun it -> it.UserId) |> ignore
|
||||||
|
Mapping.register ()
|
||||||
|
|
||||||
|
|
||||||
|
/// Async wrappers for LiteDB, and request -> journal mappings
|
||||||
|
[<AutoOpen>]
|
||||||
|
module private Helpers =
|
||||||
|
|
||||||
|
open System.Linq
|
||||||
|
|
||||||
|
/// Convert a sequence to a list asynchronously (used for LiteDB IO)
|
||||||
|
let toListAsync<'T> (q : 'T seq) =
|
||||||
|
(q.ToList >> Task.FromResult) ()
|
||||||
|
|
||||||
|
/// Convert a sequence to a list asynchronously (used for LiteDB IO)
|
||||||
|
let firstAsync<'T> (q : 'T seq) =
|
||||||
|
q.FirstOrDefault () |> Task.FromResult
|
||||||
|
|
||||||
|
/// Async wrapper around a request update
|
||||||
|
let doUpdate (db : LiteDatabase) (req : Request) =
|
||||||
|
db.Requests.Update req |> ignore
|
||||||
|
Task.CompletedTask
|
||||||
|
|
||||||
|
|
||||||
|
/// Retrieve a request, including its history and notes, by its ID and user ID
|
||||||
|
let tryFullRequestById reqId userId (db : LiteDatabase) = backgroundTask {
|
||||||
|
let! req = db.Requests.Find (Query.EQ ("_id", RequestId.toString reqId)) |> firstAsync
|
||||||
|
return match box req with null -> None | _ when req.UserId = userId -> Some req | _ -> None
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Add a history entry
|
||||||
|
let addHistory reqId userId hist db = backgroundTask {
|
||||||
|
match! tryFullRequestById reqId userId db with
|
||||||
|
| Some req -> do! doUpdate db { req with History = Array.append [| hist |] req.History }
|
||||||
|
| None -> invalidOp $"{RequestId.toString reqId} not found"
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Add a note
|
||||||
|
let addNote reqId userId note db = backgroundTask {
|
||||||
|
match! tryFullRequestById reqId userId db with
|
||||||
|
| Some req -> do! doUpdate db { req with Notes = Array.append [| note |] req.Notes }
|
||||||
|
| None -> invalidOp $"{RequestId.toString reqId} not found"
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Add a request
|
||||||
|
let addRequest (req : Request) (db : LiteDatabase) =
|
||||||
|
db.Requests.Insert req |> ignore
|
||||||
|
|
||||||
|
/// Find all requests for the given user
|
||||||
|
let private getRequestsForUser (userId : UserId) (db : LiteDatabase) = backgroundTask {
|
||||||
|
return! db.Requests.Find (Query.EQ (nameof Request.empty.UserId, Mapping.UserId.toBson userId)) |> toListAsync
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Retrieve all answered requests for the given user
|
||||||
|
let answeredRequests userId db = backgroundTask {
|
||||||
|
let! reqs = getRequestsForUser userId db
|
||||||
|
return
|
||||||
|
reqs
|
||||||
|
|> Seq.map JournalRequest.ofRequestFull
|
||||||
|
|> Seq.filter (fun it -> it.LastStatus = Answered)
|
||||||
|
|> Seq.sortByDescending (fun it -> it.AsOf)
|
||||||
|
|> List.ofSeq
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Retrieve the user's current journal
|
||||||
|
let journalByUserId userId db = backgroundTask {
|
||||||
|
let! reqs = getRequestsForUser userId db
|
||||||
|
return
|
||||||
|
reqs
|
||||||
|
|> Seq.map JournalRequest.ofRequestLite
|
||||||
|
|> Seq.filter (fun it -> it.LastStatus <> Answered)
|
||||||
|
|> Seq.sortBy (fun it -> it.AsOf)
|
||||||
|
|> List.ofSeq
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Does the user have any snoozed requests?
|
||||||
|
let hasSnoozed userId now (db : LiteDatabase) = backgroundTask {
|
||||||
|
let! jrnl = journalByUserId userId db
|
||||||
|
return jrnl |> List.exists (fun r -> defaultArg (r.SnoozedUntil |> Option.map (fun it -> it > now)) false)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Retrieve a request by its ID and user ID (without notes and history)
|
||||||
|
let tryRequestById reqId userId db = backgroundTask {
|
||||||
|
let! req = tryFullRequestById reqId userId db
|
||||||
|
return req |> Option.map (fun r -> { r with History = [||]; Notes = [||] })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Retrieve notes for a request by its ID and user ID
|
||||||
|
let notesById reqId userId (db : LiteDatabase) = backgroundTask {
|
||||||
|
match! tryFullRequestById reqId userId db with | Some req -> return req.Notes | None -> return [||]
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Retrieve a journal request by its ID and user ID
|
||||||
|
let tryJournalById reqId userId (db : LiteDatabase) = backgroundTask {
|
||||||
|
let! req = tryFullRequestById reqId userId db
|
||||||
|
return req |> Option.map JournalRequest.ofRequestLite
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Update the recurrence for a request
|
||||||
|
let updateRecurrence reqId userId recurType db = backgroundTask {
|
||||||
|
match! tryFullRequestById reqId userId db with
|
||||||
|
| Some req -> do! doUpdate db { req with Recurrence = recurType }
|
||||||
|
| None -> invalidOp $"{RequestId.toString reqId} not found"
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Update a snoozed request
|
||||||
|
let updateSnoozed reqId userId until db = backgroundTask {
|
||||||
|
match! tryFullRequestById reqId userId db with
|
||||||
|
| Some req -> do! doUpdate db { req with SnoozedUntil = until; ShowAfter = until }
|
||||||
|
| None -> invalidOp $"{RequestId.toString reqId} not found"
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Update the "show after" timestamp for a request
|
||||||
|
let updateShowAfter reqId userId showAfter db = backgroundTask {
|
||||||
|
match! tryFullRequestById reqId userId db with
|
||||||
|
| Some req -> do! doUpdate db { req with ShowAfter = showAfter }
|
||||||
|
| None -> invalidOp $"{RequestId.toString reqId} not found"
|
||||||
|
}
|
||||||
76
src/MyPrayerJournal/Dates.fs
Normal file
76
src/MyPrayerJournal/Dates.fs
Normal file
@@ -0,0 +1,76 @@
|
|||||||
|
/// Date formatting helpers
|
||||||
|
// Many thanks to date-fns (https://date-fns.org) for this logic
|
||||||
|
module MyPrayerJournal.Dates
|
||||||
|
|
||||||
|
open NodaTime
|
||||||
|
|
||||||
|
type internal FormatDistanceToken =
|
||||||
|
| LessThanXMinutes
|
||||||
|
| XMinutes
|
||||||
|
| AboutXHours
|
||||||
|
| XHours
|
||||||
|
| XDays
|
||||||
|
| AboutXWeeks
|
||||||
|
| XWeeks
|
||||||
|
| AboutXMonths
|
||||||
|
| XMonths
|
||||||
|
| AboutXYears
|
||||||
|
| XYears
|
||||||
|
| OverXYears
|
||||||
|
| AlmostXYears
|
||||||
|
|
||||||
|
let internal locales =
|
||||||
|
let format = PrintfFormat<int -> string, unit, string, string>
|
||||||
|
Map.ofList [
|
||||||
|
"en-US", Map.ofList [
|
||||||
|
LessThanXMinutes, ("less than a minute", format "less than %i minutes")
|
||||||
|
XMinutes, ("a minute", format "%i minutes")
|
||||||
|
AboutXHours, ("about an hour", format "about %i hours")
|
||||||
|
XHours, ("an hour", format "%i hours")
|
||||||
|
XDays, ("a day", format "%i days")
|
||||||
|
AboutXWeeks, ("about a week", format "about %i weeks")
|
||||||
|
XWeeks, ("a week", format "%i weeks")
|
||||||
|
AboutXMonths, ("about a month", format "about %i months")
|
||||||
|
XMonths, ("a month", format "%i months")
|
||||||
|
AboutXYears, ("about a year", format "about %i years")
|
||||||
|
XYears, ("a year", format "%i years")
|
||||||
|
OverXYears, ("over a year", format "over %i years")
|
||||||
|
AlmostXYears, ("almost a year", format "almost %i years")
|
||||||
|
]
|
||||||
|
]
|
||||||
|
|
||||||
|
let aDay = 1_440.
|
||||||
|
let almost2Days = 2_520.
|
||||||
|
let aMonth = 43_200.
|
||||||
|
let twoMonths = 86_400.
|
||||||
|
|
||||||
|
open System
|
||||||
|
|
||||||
|
/// Format the distance between two instants in approximate English terms
|
||||||
|
let formatDistance (startOn : Instant) (endOn : Instant) =
|
||||||
|
let format (token, number) locale =
|
||||||
|
let labels = locales |> Map.find locale
|
||||||
|
match number with 1 -> fst labels[token] | _ -> sprintf (snd labels[token]) number
|
||||||
|
let round (it : float) = Math.Round it |> int
|
||||||
|
|
||||||
|
let diff = startOn - endOn
|
||||||
|
let minutes = Math.Abs diff.TotalMinutes
|
||||||
|
let formatToken =
|
||||||
|
let months = minutes / aMonth |> round
|
||||||
|
let years = months / 12
|
||||||
|
match true with
|
||||||
|
| _ when minutes < 1. -> LessThanXMinutes, 1
|
||||||
|
| _ when minutes < 45. -> XMinutes, round minutes
|
||||||
|
| _ when minutes < 90. -> AboutXHours, 1
|
||||||
|
| _ when minutes < aDay -> AboutXHours, round (minutes / 60.)
|
||||||
|
| _ when minutes < almost2Days -> XDays, 1
|
||||||
|
| _ when minutes < aMonth -> XDays, round (minutes / aDay)
|
||||||
|
| _ when minutes < twoMonths -> AboutXMonths, round (minutes / aMonth)
|
||||||
|
| _ when months < 12 -> XMonths, round (minutes / aMonth)
|
||||||
|
| _ when months % 12 < 3 -> AboutXYears, years
|
||||||
|
| _ when months % 12 < 9 -> OverXYears, years
|
||||||
|
| _ -> AlmostXYears, years + 1
|
||||||
|
|
||||||
|
format formatToken "en-US"
|
||||||
|
|> match startOn > endOn with true -> sprintf "%s ago" | false -> sprintf "in %s"
|
||||||
|
|
||||||
280
src/MyPrayerJournal/Domain.fs
Normal file
280
src/MyPrayerJournal/Domain.fs
Normal file
@@ -0,0 +1,280 @@
|
|||||||
|
/// The data model for myPrayerJournal
|
||||||
|
[<AutoOpen>]
|
||||||
|
module MyPrayerJournal.Domain
|
||||||
|
|
||||||
|
open System
|
||||||
|
open Cuid
|
||||||
|
open NodaTime
|
||||||
|
|
||||||
|
/// An identifier for a request
|
||||||
|
type RequestId = RequestId of Cuid
|
||||||
|
|
||||||
|
/// Functions to manipulate request IDs
|
||||||
|
module RequestId =
|
||||||
|
|
||||||
|
/// The string representation of the request ID
|
||||||
|
let toString = function RequestId x -> Cuid.toString x
|
||||||
|
|
||||||
|
/// Create a request ID from a string representation
|
||||||
|
let ofString = Cuid >> RequestId
|
||||||
|
|
||||||
|
|
||||||
|
/// The identifier of a user (the "sub" part of the JWT)
|
||||||
|
type UserId = UserId of string
|
||||||
|
|
||||||
|
/// Functions to manipulate user IDs
|
||||||
|
module UserId =
|
||||||
|
|
||||||
|
/// The string representation of the user ID
|
||||||
|
let toString = function UserId x -> x
|
||||||
|
|
||||||
|
|
||||||
|
/// How frequently a request should reappear after it is marked "Prayed"
|
||||||
|
type Recurrence =
|
||||||
|
|
||||||
|
/// A request should reappear immediately at the bottom of the list
|
||||||
|
| Immediate
|
||||||
|
|
||||||
|
/// A request should reappear in the given number of hours
|
||||||
|
| Hours of int16
|
||||||
|
|
||||||
|
/// A request should reappear in the given number of days
|
||||||
|
| Days of int16
|
||||||
|
|
||||||
|
/// A request should reappear in the given number of weeks (7-day increments)
|
||||||
|
| Weeks of int16
|
||||||
|
|
||||||
|
/// Functions to manipulate recurrences
|
||||||
|
module Recurrence =
|
||||||
|
|
||||||
|
/// Create a string representation of a recurrence
|
||||||
|
let toString =
|
||||||
|
function
|
||||||
|
| Immediate -> "Immediate"
|
||||||
|
| Hours h -> $"{h} Hours"
|
||||||
|
| Days d -> $"{d} Days"
|
||||||
|
| Weeks w -> $"{w} Weeks"
|
||||||
|
|
||||||
|
/// Create a recurrence value from a string
|
||||||
|
let ofString =
|
||||||
|
function
|
||||||
|
| "Immediate" -> Immediate
|
||||||
|
| it when it.Contains " " ->
|
||||||
|
let parts = it.Split " "
|
||||||
|
let length = Convert.ToInt16 parts[0]
|
||||||
|
match parts[1] with
|
||||||
|
| "Hours" -> Hours length
|
||||||
|
| "Days" -> Days length
|
||||||
|
| "Weeks" -> Weeks length
|
||||||
|
| _ -> invalidOp $"{parts[1]} is not a valid recurrence"
|
||||||
|
| it -> invalidOp $"{it} is not a valid recurrence"
|
||||||
|
|
||||||
|
/// An hour's worth of seconds
|
||||||
|
let private oneHour = 3_600L
|
||||||
|
|
||||||
|
/// The duration of the recurrence (in milliseconds)
|
||||||
|
let duration =
|
||||||
|
function
|
||||||
|
| Immediate -> 0L
|
||||||
|
| Hours h -> int64 h * oneHour
|
||||||
|
| Days d -> int64 d * oneHour * 24L
|
||||||
|
| Weeks w -> int64 w * oneHour * 24L * 7L
|
||||||
|
|
||||||
|
|
||||||
|
/// The action taken on a request as part of a history entry
|
||||||
|
type RequestAction =
|
||||||
|
| Created
|
||||||
|
| Prayed
|
||||||
|
| Updated
|
||||||
|
| Answered
|
||||||
|
|
||||||
|
/// Functions to manipulate request actions
|
||||||
|
module RequestAction =
|
||||||
|
|
||||||
|
/// Create a string representation of an action
|
||||||
|
let toString =
|
||||||
|
function
|
||||||
|
| Created -> "Created"
|
||||||
|
| Prayed -> "Prayed"
|
||||||
|
| Updated -> "Updated"
|
||||||
|
| Answered -> "Answered"
|
||||||
|
|
||||||
|
/// Create a RequestAction from a string
|
||||||
|
let ofString =
|
||||||
|
function
|
||||||
|
| "Created" -> Created
|
||||||
|
| "Prayed" -> Prayed
|
||||||
|
| "Updated" -> Updated
|
||||||
|
| "Answered" -> Answered
|
||||||
|
| it -> invalidOp $"Bad request action {it}"
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/// History is a record of action taken on a prayer request, including updates to its text
|
||||||
|
[<CLIMutable; NoComparison; NoEquality>]
|
||||||
|
type History =
|
||||||
|
{ /// The time when this history entry was made
|
||||||
|
AsOf : Instant
|
||||||
|
|
||||||
|
/// The status for this history entry
|
||||||
|
Status : RequestAction
|
||||||
|
|
||||||
|
/// The text of the update, if applicable
|
||||||
|
Text : string option
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Functions to manipulate history entries
|
||||||
|
module History =
|
||||||
|
|
||||||
|
/// Determine if a history's status is `Created`
|
||||||
|
let isCreated hist = hist.Status = Created
|
||||||
|
|
||||||
|
/// Determine if a history's status is `Prayed`
|
||||||
|
let isPrayed hist = hist.Status = Prayed
|
||||||
|
|
||||||
|
/// Determine if a history's status is `Answered`
|
||||||
|
let isAnswered hist = hist.Status = Answered
|
||||||
|
|
||||||
|
|
||||||
|
/// Note is a note regarding a prayer request that does not result in an update to its text
|
||||||
|
[<CLIMutable; NoComparison; NoEquality>]
|
||||||
|
type Note =
|
||||||
|
{ /// The time when this note was made
|
||||||
|
AsOf : Instant
|
||||||
|
|
||||||
|
/// The text of the notes
|
||||||
|
Notes : string
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// Request is the identifying record for a prayer request
|
||||||
|
[<CLIMutable; NoComparison; NoEquality>]
|
||||||
|
type Request =
|
||||||
|
{ /// The ID of the request
|
||||||
|
Id : RequestId
|
||||||
|
|
||||||
|
/// The time this request was initially entered
|
||||||
|
EnteredOn : Instant
|
||||||
|
|
||||||
|
/// The ID of the user to whom this request belongs ("sub" from the JWT)
|
||||||
|
UserId : UserId
|
||||||
|
|
||||||
|
/// The time at which this request should reappear in the user's journal by manual user choice
|
||||||
|
SnoozedUntil : Instant option
|
||||||
|
|
||||||
|
/// The time at which this request should reappear in the user's journal by recurrence
|
||||||
|
ShowAfter : Instant option
|
||||||
|
|
||||||
|
/// The recurrence for this request
|
||||||
|
Recurrence : Recurrence
|
||||||
|
|
||||||
|
/// The history entries for this request
|
||||||
|
History : History[]
|
||||||
|
|
||||||
|
/// The notes for this request
|
||||||
|
Notes : Note[]
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Functions to support requests
|
||||||
|
module Request =
|
||||||
|
|
||||||
|
/// An empty request
|
||||||
|
let empty =
|
||||||
|
{ Id = Cuid.generate () |> RequestId
|
||||||
|
EnteredOn = Instant.MinValue
|
||||||
|
UserId = UserId ""
|
||||||
|
SnoozedUntil = None
|
||||||
|
ShowAfter = None
|
||||||
|
Recurrence = Immediate
|
||||||
|
History = [||]
|
||||||
|
Notes = [||]
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// JournalRequest is the form of a prayer request returned for the request journal display. It also contains
|
||||||
|
/// properties that may be filled for history and notes.
|
||||||
|
[<NoComparison; NoEquality>]
|
||||||
|
type JournalRequest =
|
||||||
|
{ /// The ID of the request (just the CUID part)
|
||||||
|
RequestId : RequestId
|
||||||
|
|
||||||
|
/// The ID of the user to whom the request belongs
|
||||||
|
UserId : UserId
|
||||||
|
|
||||||
|
/// The current text of the request
|
||||||
|
Text : string
|
||||||
|
|
||||||
|
/// The last time action was taken on the request
|
||||||
|
AsOf : Instant
|
||||||
|
|
||||||
|
/// The last time a request was marked as prayed
|
||||||
|
LastPrayed : Instant option
|
||||||
|
|
||||||
|
/// The last status for the request
|
||||||
|
LastStatus : RequestAction
|
||||||
|
|
||||||
|
/// The time that this request should reappear in the user's journal
|
||||||
|
SnoozedUntil : Instant option
|
||||||
|
|
||||||
|
/// The time after which this request should reappear in the user's journal by configured recurrence
|
||||||
|
ShowAfter : Instant option
|
||||||
|
|
||||||
|
/// The recurrence for this request
|
||||||
|
Recurrence : Recurrence
|
||||||
|
|
||||||
|
/// History entries for the request
|
||||||
|
History : History list
|
||||||
|
|
||||||
|
/// Note entries for the request
|
||||||
|
Notes : Note list
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Functions to manipulate journal requests
|
||||||
|
module JournalRequest =
|
||||||
|
|
||||||
|
/// Convert a request to the form used for the journal (precomputed values, no notes or history)
|
||||||
|
let ofRequestLite (req : Request) =
|
||||||
|
let lastHistory = req.History |> Array.sortByDescending (fun it -> it.AsOf) |> Array.tryHead
|
||||||
|
// Requests are sorted by the "as of" field in this record; for sorting to work properly, we will put the
|
||||||
|
// largest of the last prayed date, the "snoozed until". or the "show after" date; if none of those are filled,
|
||||||
|
// we will use the last activity date. This will mean that:
|
||||||
|
// - Immediately shown requests will be at the top of the list, in order from least recently prayed to most.
|
||||||
|
// - Non-immediate requests will enter the list as if they were marked as prayed at that time; this will put
|
||||||
|
// them at the bottom of the list.
|
||||||
|
// - Snoozed requests will reappear at the bottom of the list when they return.
|
||||||
|
// - New requests will go to the bottom of the list, but will rise as others are marked as prayed.
|
||||||
|
let lastActivity = lastHistory |> Option.map (fun it -> it.AsOf) |> Option.defaultValue Instant.MinValue
|
||||||
|
let showAfter = defaultArg req.ShowAfter Instant.MinValue
|
||||||
|
let snoozedUntil = defaultArg req.SnoozedUntil Instant.MinValue
|
||||||
|
let lastPrayed =
|
||||||
|
req.History
|
||||||
|
|> Array.sortByDescending (fun it -> it.AsOf)
|
||||||
|
|> Array.filter History.isPrayed
|
||||||
|
|> Array.tryHead
|
||||||
|
|> Option.map (fun it -> it.AsOf)
|
||||||
|
|> Option.defaultValue Instant.MinValue
|
||||||
|
let asOf = List.max [ lastPrayed; showAfter; snoozedUntil ]
|
||||||
|
{ RequestId = req.Id
|
||||||
|
UserId = req.UserId
|
||||||
|
Text = req.History
|
||||||
|
|> Array.filter (fun it -> Option.isSome it.Text)
|
||||||
|
|> Array.sortByDescending (fun it -> it.AsOf)
|
||||||
|
|> Array.tryHead
|
||||||
|
|> Option.map (fun h -> Option.get h.Text)
|
||||||
|
|> Option.defaultValue ""
|
||||||
|
AsOf = if asOf > Instant.MinValue then asOf else lastActivity
|
||||||
|
LastPrayed = if lastPrayed = Instant.MinValue then None else Some lastPrayed
|
||||||
|
LastStatus = match lastHistory with Some h -> h.Status | None -> Created
|
||||||
|
SnoozedUntil = req.SnoozedUntil
|
||||||
|
ShowAfter = req.ShowAfter
|
||||||
|
Recurrence = req.Recurrence
|
||||||
|
History = []
|
||||||
|
Notes = []
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Same as `ofRequestLite`, but with notes and history
|
||||||
|
let ofRequestFull req =
|
||||||
|
{ ofRequestLite req with
|
||||||
|
History = List.ofArray req.History
|
||||||
|
Notes = List.ofArray req.Notes
|
||||||
|
}
|
||||||
582
src/MyPrayerJournal/Handlers.fs
Normal file
582
src/MyPrayerJournal/Handlers.fs
Normal file
@@ -0,0 +1,582 @@
|
|||||||
|
/// HTTP handlers for the myPrayerJournal API
|
||||||
|
[<RequireQualifiedAccess>]
|
||||||
|
module MyPrayerJournal.Handlers
|
||||||
|
|
||||||
|
open Giraffe
|
||||||
|
open Giraffe.Htmx
|
||||||
|
open System
|
||||||
|
|
||||||
|
/// Helper function to be able to split out log on
|
||||||
|
[<AutoOpen>]
|
||||||
|
module private LogOnHelpers =
|
||||||
|
|
||||||
|
open Microsoft.AspNetCore.Authentication
|
||||||
|
|
||||||
|
/// Log on, optionally specifying a redirected URL once authentication is complete
|
||||||
|
let logOn url : HttpHandler = fun next ctx -> task {
|
||||||
|
match url with
|
||||||
|
| Some it ->
|
||||||
|
do! ctx.ChallengeAsync ("Auth0", AuthenticationProperties (RedirectUri = it))
|
||||||
|
return! next ctx
|
||||||
|
| None -> return! challenge "Auth0" next ctx
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// Handlers for error conditions
|
||||||
|
module Error =
|
||||||
|
|
||||||
|
open Microsoft.Extensions.Logging
|
||||||
|
|
||||||
|
/// Handle errors
|
||||||
|
let error (ex : Exception) (log : ILogger) =
|
||||||
|
log.LogError (EventId (), ex, "An unhandled exception has occurred while executing the request.")
|
||||||
|
clearResponse
|
||||||
|
>=> setStatusCode 500
|
||||||
|
>=> setHttpHeader "X-Toast" $"error|||{ex.GetType().Name}: {ex.Message}"
|
||||||
|
>=> text ex.Message
|
||||||
|
|
||||||
|
/// Handle unauthorized actions, redirecting to log on for GETs, otherwise returning a 401 Not Authorized response
|
||||||
|
let notAuthorized : HttpHandler = fun next ctx ->
|
||||||
|
(if ctx.Request.Method = "GET" then logOn None next else setStatusCode 401 earlyReturn) ctx
|
||||||
|
|
||||||
|
/// Handle 404s from the API, sending known URL paths to the Vue app so that they can be handled there
|
||||||
|
let notFound : HttpHandler =
|
||||||
|
setStatusCode 404 >=> text "Not found"
|
||||||
|
|
||||||
|
|
||||||
|
open System.Security.Claims
|
||||||
|
open LiteDB
|
||||||
|
open Microsoft.AspNetCore.Http
|
||||||
|
open NodaTime
|
||||||
|
|
||||||
|
/// Extensions on the HTTP context
|
||||||
|
type HttpContext with
|
||||||
|
|
||||||
|
/// The LiteDB database
|
||||||
|
member this.Db = this.GetService<LiteDatabase> ()
|
||||||
|
|
||||||
|
/// The "sub" for the current user (None if no user is authenticated)
|
||||||
|
member this.CurrentUser =
|
||||||
|
this.User
|
||||||
|
|> Option.ofObj
|
||||||
|
|> Option.map (fun user -> user.Claims |> Seq.tryFind (fun u -> u.Type = ClaimTypes.NameIdentifier))
|
||||||
|
|> Option.flatten
|
||||||
|
|> Option.map (fun claim -> claim.Value)
|
||||||
|
|
||||||
|
/// The current user's ID
|
||||||
|
// NOTE: this may raise if you don't run the request through the requireUser handler first
|
||||||
|
member this.UserId = UserId this.CurrentUser.Value
|
||||||
|
|
||||||
|
/// The system clock
|
||||||
|
member this.Clock = this.GetService<IClock> ()
|
||||||
|
|
||||||
|
/// Get the current instant from the system clock
|
||||||
|
member this.Now = this.Clock.GetCurrentInstant
|
||||||
|
|
||||||
|
/// Get the time zone from the X-Time-Zone header (default UTC)
|
||||||
|
member this.TimeZone =
|
||||||
|
match this.TryGetRequestHeader "X-Time-Zone" with
|
||||||
|
| Some tz ->
|
||||||
|
match this.GetService<IDateTimeZoneProvider>().GetZoneOrNull tz with
|
||||||
|
| null -> DateTimeZone.Utc
|
||||||
|
| zone -> zone
|
||||||
|
| None -> DateTimeZone.Utc
|
||||||
|
|
||||||
|
|
||||||
|
/// Handler helpers
|
||||||
|
[<AutoOpen>]
|
||||||
|
module private Helpers =
|
||||||
|
|
||||||
|
open Microsoft.Extensions.Logging
|
||||||
|
open Microsoft.Net.Http.Headers
|
||||||
|
|
||||||
|
/// Require a user to be logged on
|
||||||
|
let requireUser : HttpHandler =
|
||||||
|
requiresAuthentication Error.notAuthorized
|
||||||
|
|
||||||
|
/// Debug logger
|
||||||
|
let debug (ctx : HttpContext) message =
|
||||||
|
let fac = ctx.GetService<ILoggerFactory> ()
|
||||||
|
let log = fac.CreateLogger "Debug"
|
||||||
|
log.LogInformation message
|
||||||
|
|
||||||
|
/// Return a 201 CREATED response
|
||||||
|
let created =
|
||||||
|
setStatusCode 201
|
||||||
|
|
||||||
|
/// Return a 201 CREATED response with the location header set for the created resource
|
||||||
|
let createdAt url : HttpHandler = fun next ctx ->
|
||||||
|
Successful.CREATED
|
||||||
|
($"{ctx.Request.Scheme}://{ctx.Request.Host.Value}{url}" |> setHttpHeader HeaderNames.Location) next ctx
|
||||||
|
|
||||||
|
/// Return a 303 SEE OTHER response (forces a GET on the redirected URL)
|
||||||
|
let seeOther (url : string) =
|
||||||
|
noResponseCaching >=> setStatusCode 303 >=> setHttpHeader "Location" url
|
||||||
|
|
||||||
|
/// Render a component result
|
||||||
|
let renderComponent nodes : HttpHandler =
|
||||||
|
noResponseCaching
|
||||||
|
>=> fun _ ctx -> backgroundTask {
|
||||||
|
return! ctx.WriteHtmlStringAsync (ViewEngine.RenderView.AsString.htmlNodes nodes)
|
||||||
|
}
|
||||||
|
|
||||||
|
open Views.Layout
|
||||||
|
open System.Threading.Tasks
|
||||||
|
|
||||||
|
/// Create a page rendering context
|
||||||
|
let pageContext (ctx : HttpContext) pageTitle content = backgroundTask {
|
||||||
|
let! hasSnoozed =
|
||||||
|
match ctx.CurrentUser with
|
||||||
|
| Some _ -> Data.hasSnoozed ctx.UserId (ctx.Now ()) ctx.Db
|
||||||
|
| None -> Task.FromResult false
|
||||||
|
return
|
||||||
|
{ IsAuthenticated = Option.isSome ctx.CurrentUser
|
||||||
|
HasSnoozed = hasSnoozed
|
||||||
|
CurrentUrl = ctx.Request.Path.Value
|
||||||
|
PageTitle = pageTitle
|
||||||
|
Content = content
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Composable handler to write a view to the output
|
||||||
|
let writeView view : HttpHandler = fun _ ctx -> backgroundTask {
|
||||||
|
return! ctx.WriteHtmlViewAsync view
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// Hold messages across redirects
|
||||||
|
module Messages =
|
||||||
|
|
||||||
|
/// The messages being held
|
||||||
|
let mutable private messages : Map<UserId, string * string> = Map.empty
|
||||||
|
|
||||||
|
/// Locked update to prevent updates by multiple threads
|
||||||
|
let private upd8 = obj ()
|
||||||
|
|
||||||
|
/// Push a new message into the list
|
||||||
|
let push (ctx : HttpContext) message url = lock upd8 (fun () ->
|
||||||
|
messages <- messages.Add (ctx.UserId, (message, url)))
|
||||||
|
|
||||||
|
/// Add a success message header to the response
|
||||||
|
let pushSuccess ctx message url =
|
||||||
|
push ctx $"success|||%s{message}" url
|
||||||
|
|
||||||
|
/// Pop the messages for the given user
|
||||||
|
let pop userId = lock upd8 (fun () ->
|
||||||
|
let msg = messages.TryFind userId
|
||||||
|
msg |> Option.iter (fun _ -> messages <- messages.Remove userId)
|
||||||
|
msg)
|
||||||
|
|
||||||
|
/// Send a partial result if this is not a full page load (does not append no-cache headers)
|
||||||
|
let partialStatic (pageTitle : string) content : HttpHandler = fun next ctx -> task {
|
||||||
|
let isPartial = ctx.Request.IsHtmx && not ctx.Request.IsHtmxRefresh
|
||||||
|
let! pageCtx = pageContext ctx pageTitle content
|
||||||
|
let view = (match isPartial with true -> partial | false -> view) pageCtx
|
||||||
|
return!
|
||||||
|
(next, ctx)
|
||||||
|
||> match ctx.CurrentUser with
|
||||||
|
| Some _ ->
|
||||||
|
match Messages.pop ctx.UserId with
|
||||||
|
| Some (msg, url) -> setHttpHeader "X-Toast" msg >=> withHxPushUrl url >=> writeView view
|
||||||
|
| None -> writeView view
|
||||||
|
| None -> writeView view
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Send an explicitly non-cached result, rendering as a partial if this is not a full page load
|
||||||
|
let partial pageTitle content =
|
||||||
|
noResponseCaching >=> partialStatic pageTitle content
|
||||||
|
|
||||||
|
/// Add a success message header to the response
|
||||||
|
let withSuccessMessage : string -> HttpHandler =
|
||||||
|
sprintf "success|||%s" >> setHttpHeader "X-Toast"
|
||||||
|
|
||||||
|
/// Hide a modal window when the response is sent
|
||||||
|
let hideModal (name : string) : HttpHandler =
|
||||||
|
setHttpHeader "X-Hide-Modal" name
|
||||||
|
|
||||||
|
|
||||||
|
/// Strongly-typed models for post requests
|
||||||
|
module Models =
|
||||||
|
|
||||||
|
/// An additional note
|
||||||
|
[<CLIMutable; NoComparison; NoEquality>]
|
||||||
|
type NoteEntry =
|
||||||
|
{ /// The notes being added
|
||||||
|
notes : string
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A prayer request
|
||||||
|
[<CLIMutable; NoComparison; NoEquality>]
|
||||||
|
type Request =
|
||||||
|
{ /// The ID of the request
|
||||||
|
requestId : string
|
||||||
|
|
||||||
|
/// Where to redirect after saving
|
||||||
|
returnTo : string
|
||||||
|
|
||||||
|
/// The text of the request
|
||||||
|
requestText : string
|
||||||
|
|
||||||
|
/// The additional status to record
|
||||||
|
status : string option
|
||||||
|
|
||||||
|
/// The recurrence type
|
||||||
|
recurType : string
|
||||||
|
|
||||||
|
/// The recurrence count
|
||||||
|
recurCount : int16 option
|
||||||
|
|
||||||
|
/// The recurrence interval
|
||||||
|
recurInterval : string option
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The date until which a request should not appear in the journal
|
||||||
|
[<CLIMutable; NoComparison; NoEquality>]
|
||||||
|
type SnoozeUntil =
|
||||||
|
{ /// The date (YYYY-MM-DD) at which the request should reappear
|
||||||
|
until : string
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
open MyPrayerJournal.Data.Extensions
|
||||||
|
open NodaTime.Text
|
||||||
|
|
||||||
|
/// Handlers for less-than-full-page HTML requests
|
||||||
|
module Components =
|
||||||
|
|
||||||
|
// GET /components/journal-items
|
||||||
|
let journalItems : HttpHandler = requireUser >=> fun next ctx -> task {
|
||||||
|
let now = ctx.Now ()
|
||||||
|
let shouldBeShown (req : JournalRequest) =
|
||||||
|
match req.SnoozedUntil, req.ShowAfter with
|
||||||
|
| None, None -> true
|
||||||
|
| Some snooze, Some hide when snooze < now && hide < now -> true
|
||||||
|
| Some snooze, _ when snooze < now -> true
|
||||||
|
| _, Some hide when hide < now -> true
|
||||||
|
| _, _ -> false
|
||||||
|
let! journal = Data.journalByUserId ctx.UserId ctx.Db
|
||||||
|
let shown = journal |> List.filter shouldBeShown
|
||||||
|
return! renderComponent [ Views.Journal.journalItems now ctx.TimeZone shown ] next ctx
|
||||||
|
}
|
||||||
|
|
||||||
|
// GET /components/request-item/[req-id]
|
||||||
|
let requestItem reqId : HttpHandler = requireUser >=> fun next ctx -> task {
|
||||||
|
match! Data.tryJournalById (RequestId.ofString reqId) ctx.UserId ctx.Db with
|
||||||
|
| Some req -> return! renderComponent [ Views.Request.reqListItem (ctx.Now ()) ctx.TimeZone req ] next ctx
|
||||||
|
| None -> return! Error.notFound next ctx
|
||||||
|
}
|
||||||
|
|
||||||
|
// GET /components/request/[req-id]/add-notes
|
||||||
|
let addNotes requestId : HttpHandler =
|
||||||
|
requireUser >=> renderComponent (Views.Journal.notesEdit (RequestId.ofString requestId))
|
||||||
|
|
||||||
|
// GET /components/request/[req-id]/notes
|
||||||
|
let notes requestId : HttpHandler = requireUser >=> fun next ctx -> task {
|
||||||
|
let! notes = Data.notesById (RequestId.ofString requestId) ctx.UserId ctx.Db
|
||||||
|
return! renderComponent (Views.Request.notes (ctx.Now ()) ctx.TimeZone (List.ofArray notes)) next ctx
|
||||||
|
}
|
||||||
|
|
||||||
|
// GET /components/request/[req-id]/snooze
|
||||||
|
let snooze requestId : HttpHandler =
|
||||||
|
requireUser >=> renderComponent [ RequestId.ofString requestId |> Views.Journal.snooze ]
|
||||||
|
|
||||||
|
|
||||||
|
/// / URL
|
||||||
|
module Home =
|
||||||
|
|
||||||
|
// GET /
|
||||||
|
let home : HttpHandler =
|
||||||
|
partialStatic "Welcome!" Views.Layout.home
|
||||||
|
|
||||||
|
|
||||||
|
/// /journal URL
|
||||||
|
module Journal =
|
||||||
|
|
||||||
|
// GET /journal
|
||||||
|
let journal : HttpHandler = requireUser >=> fun next ctx -> task {
|
||||||
|
let usr =
|
||||||
|
ctx.User.Claims
|
||||||
|
|> Seq.tryFind (fun c -> c.Type = ClaimTypes.GivenName)
|
||||||
|
|> Option.map (fun c -> c.Value)
|
||||||
|
|> Option.defaultValue "Your"
|
||||||
|
let title = usr |> match usr with "Your" -> sprintf "%s" | _ -> sprintf "%s's"
|
||||||
|
return! partial $"{title} Prayer Journal" (Views.Journal.journal usr) next ctx
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// /legal URLs
|
||||||
|
module Legal =
|
||||||
|
|
||||||
|
// GET /legal/privacy-policy
|
||||||
|
let privacyPolicy : HttpHandler =
|
||||||
|
partialStatic "Privacy Policy" Views.Legal.privacyPolicy
|
||||||
|
|
||||||
|
// GET /legal/terms-of-service
|
||||||
|
let termsOfService : HttpHandler =
|
||||||
|
partialStatic "Terms of Service" Views.Legal.termsOfService
|
||||||
|
|
||||||
|
|
||||||
|
/// /api/request and /request(s) URLs
|
||||||
|
module Request =
|
||||||
|
|
||||||
|
open Cuid
|
||||||
|
|
||||||
|
// GET /request/[req-id]/edit
|
||||||
|
let edit requestId : HttpHandler = requireUser >=> fun next ctx -> task {
|
||||||
|
let returnTo =
|
||||||
|
match ctx.Request.Headers.Referer[0] with
|
||||||
|
| it when it.EndsWith "/active" -> "active"
|
||||||
|
| it when it.EndsWith "/snoozed" -> "snoozed"
|
||||||
|
| _ -> "journal"
|
||||||
|
match requestId with
|
||||||
|
| "new" ->
|
||||||
|
return! partial "Add Prayer Request"
|
||||||
|
(Views.Request.edit (JournalRequest.ofRequestLite Request.empty) returnTo true) next ctx
|
||||||
|
| _ ->
|
||||||
|
match! Data.tryJournalById (RequestId.ofString requestId) ctx.UserId ctx.Db with
|
||||||
|
| Some req ->
|
||||||
|
debug ctx "Found - sending view"
|
||||||
|
return! partial "Edit Prayer Request" (Views.Request.edit req returnTo false) next ctx
|
||||||
|
| None ->
|
||||||
|
debug ctx "Not found - uh oh..."
|
||||||
|
return! Error.notFound next ctx
|
||||||
|
}
|
||||||
|
|
||||||
|
// PATCH /request/[req-id]/prayed
|
||||||
|
let prayed requestId : HttpHandler = requireUser >=> fun next ctx -> task {
|
||||||
|
let db = ctx.Db
|
||||||
|
let userId = ctx.UserId
|
||||||
|
let reqId = RequestId.ofString requestId
|
||||||
|
match! Data.tryRequestById reqId userId db with
|
||||||
|
| Some req ->
|
||||||
|
let now = ctx.Now ()
|
||||||
|
do! Data.addHistory reqId userId { AsOf = now; Status = Prayed; Text = None } db
|
||||||
|
let nextShow =
|
||||||
|
match Recurrence.duration req.Recurrence with
|
||||||
|
| 0L -> None
|
||||||
|
| duration -> Some <| now.Plus (Duration.FromSeconds duration)
|
||||||
|
do! Data.updateShowAfter reqId userId nextShow db
|
||||||
|
do! db.SaveChanges ()
|
||||||
|
return! (withSuccessMessage "Request marked as prayed" >=> Components.journalItems) next ctx
|
||||||
|
| None -> return! Error.notFound next ctx
|
||||||
|
}
|
||||||
|
|
||||||
|
/// POST /request/[req-id]/note
|
||||||
|
let addNote requestId : HttpHandler = requireUser >=> fun next ctx -> task {
|
||||||
|
let db = ctx.Db
|
||||||
|
let userId = ctx.UserId
|
||||||
|
let reqId = RequestId.ofString requestId
|
||||||
|
match! Data.tryRequestById reqId userId db with
|
||||||
|
| Some _ ->
|
||||||
|
let! notes = ctx.BindFormAsync<Models.NoteEntry> ()
|
||||||
|
do! Data.addNote reqId userId { AsOf = ctx.Now (); Notes = notes.notes } db
|
||||||
|
do! db.SaveChanges ()
|
||||||
|
return! (withSuccessMessage "Added Notes" >=> hideModal "notes" >=> created) next ctx
|
||||||
|
| None -> return! Error.notFound next ctx
|
||||||
|
}
|
||||||
|
|
||||||
|
// GET /requests/active
|
||||||
|
let active : HttpHandler = requireUser >=> fun next ctx -> task {
|
||||||
|
let! reqs = Data.journalByUserId ctx.UserId ctx.Db
|
||||||
|
return! partial "Active Requests" (Views.Request.active (ctx.Now ()) ctx.TimeZone reqs) next ctx
|
||||||
|
}
|
||||||
|
|
||||||
|
// GET /requests/snoozed
|
||||||
|
let snoozed : HttpHandler = requireUser >=> fun next ctx -> task {
|
||||||
|
let! reqs = Data.journalByUserId ctx.UserId ctx.Db
|
||||||
|
let now = ctx.Now ()
|
||||||
|
let snoozed = reqs
|
||||||
|
|> List.filter (fun it -> defaultArg (it.SnoozedUntil |> Option.map (fun it -> it > now)) false)
|
||||||
|
return! partial "Snoozed Requests" (Views.Request.snoozed now ctx.TimeZone snoozed) next ctx
|
||||||
|
}
|
||||||
|
|
||||||
|
// GET /requests/answered
|
||||||
|
let answered : HttpHandler = requireUser >=> fun next ctx -> task {
|
||||||
|
let! reqs = Data.answeredRequests ctx.UserId ctx.Db
|
||||||
|
return! partial "Answered Requests" (Views.Request.answered (ctx.Now ()) ctx.TimeZone reqs) next ctx
|
||||||
|
}
|
||||||
|
|
||||||
|
// GET /request/[req-id]/full
|
||||||
|
let getFull requestId : HttpHandler = requireUser >=> fun next ctx -> task {
|
||||||
|
match! Data.tryFullRequestById (RequestId.ofString requestId) ctx.UserId ctx.Db with
|
||||||
|
| Some req -> return! partial "Prayer Request" (Views.Request.full ctx.Clock ctx.TimeZone req) next ctx
|
||||||
|
| None -> return! Error.notFound next ctx
|
||||||
|
}
|
||||||
|
|
||||||
|
// PATCH /request/[req-id]/show
|
||||||
|
let show requestId : HttpHandler = requireUser >=> fun next ctx -> task {
|
||||||
|
let db = ctx.Db
|
||||||
|
let userId = ctx.UserId
|
||||||
|
let reqId = RequestId.ofString requestId
|
||||||
|
match! Data.tryRequestById reqId userId db with
|
||||||
|
| Some _ ->
|
||||||
|
do! Data.updateShowAfter reqId userId None db
|
||||||
|
do! db.SaveChanges ()
|
||||||
|
return! (withSuccessMessage "Request now shown" >=> Components.requestItem requestId) next ctx
|
||||||
|
| None -> return! Error.notFound next ctx
|
||||||
|
}
|
||||||
|
|
||||||
|
// PATCH /request/[req-id]/snooze
|
||||||
|
let snooze requestId : HttpHandler = requireUser >=> fun next ctx -> task {
|
||||||
|
let db = ctx.Db
|
||||||
|
let userId = ctx.UserId
|
||||||
|
let reqId = RequestId.ofString requestId
|
||||||
|
match! Data.tryRequestById reqId userId db with
|
||||||
|
| Some _ ->
|
||||||
|
let! until = ctx.BindFormAsync<Models.SnoozeUntil> ()
|
||||||
|
let date =
|
||||||
|
LocalDatePattern.CreateWithInvariantCulture("yyyy-MM-dd").Parse(until.until).Value
|
||||||
|
.AtStartOfDayInZone(DateTimeZone.Utc)
|
||||||
|
.ToInstant ()
|
||||||
|
do! Data.updateSnoozed reqId userId (Some date) db
|
||||||
|
do! db.SaveChanges ()
|
||||||
|
return!
|
||||||
|
(withSuccessMessage $"Request snoozed until {until.until}"
|
||||||
|
>=> hideModal "snooze"
|
||||||
|
>=> Components.journalItems) next ctx
|
||||||
|
| None -> return! Error.notFound next ctx
|
||||||
|
}
|
||||||
|
|
||||||
|
// PATCH /request/[req-id]/cancel-snooze
|
||||||
|
let cancelSnooze requestId : HttpHandler = requireUser >=> fun next ctx -> task {
|
||||||
|
let db = ctx.Db
|
||||||
|
let userId = ctx.UserId
|
||||||
|
let reqId = RequestId.ofString requestId
|
||||||
|
match! Data.tryRequestById reqId userId db with
|
||||||
|
| Some _ ->
|
||||||
|
do! Data.updateSnoozed reqId userId None db
|
||||||
|
do! db.SaveChanges ()
|
||||||
|
return! (withSuccessMessage "Request unsnoozed" >=> Components.requestItem requestId) next ctx
|
||||||
|
| None -> return! Error.notFound next ctx
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Derive a recurrence from its representation in the form
|
||||||
|
let private parseRecurrence (form : Models.Request) =
|
||||||
|
match form.recurInterval with Some x -> $"{defaultArg form.recurCount 0s} {x}" | None -> "Immediate"
|
||||||
|
|> Recurrence.ofString
|
||||||
|
|
||||||
|
// POST /request
|
||||||
|
let add : HttpHandler = requireUser >=> fun next ctx -> task {
|
||||||
|
let! form = ctx.BindModelAsync<Models.Request> ()
|
||||||
|
let db = ctx.Db
|
||||||
|
let userId = ctx.UserId
|
||||||
|
let now = ctx.Now ()
|
||||||
|
let req =
|
||||||
|
{ Request.empty with
|
||||||
|
Id = Cuid.generate () |> RequestId
|
||||||
|
UserId = userId
|
||||||
|
EnteredOn = now
|
||||||
|
ShowAfter = None
|
||||||
|
Recurrence = parseRecurrence form
|
||||||
|
History = [|
|
||||||
|
{ AsOf = now
|
||||||
|
Status = Created
|
||||||
|
Text = Some form.requestText
|
||||||
|
}
|
||||||
|
|]
|
||||||
|
}
|
||||||
|
Data.addRequest req db
|
||||||
|
do! db.SaveChanges ()
|
||||||
|
Messages.pushSuccess ctx "Added prayer request" "/journal"
|
||||||
|
return! seeOther "/journal" next ctx
|
||||||
|
}
|
||||||
|
|
||||||
|
// PATCH /request
|
||||||
|
let update : HttpHandler = requireUser >=> fun next ctx -> task {
|
||||||
|
let! form = ctx.BindModelAsync<Models.Request> ()
|
||||||
|
let db = ctx.Db
|
||||||
|
let userId = ctx.UserId
|
||||||
|
match! Data.tryJournalById (RequestId.ofString form.requestId) userId db with
|
||||||
|
| Some req ->
|
||||||
|
// update recurrence if changed
|
||||||
|
let recur = parseRecurrence form
|
||||||
|
match recur = req.Recurrence with
|
||||||
|
| true -> ()
|
||||||
|
| false ->
|
||||||
|
do! Data.updateRecurrence req.RequestId userId recur db
|
||||||
|
match recur with
|
||||||
|
| Immediate -> do! Data.updateShowAfter req.RequestId userId None db
|
||||||
|
| _ -> ()
|
||||||
|
// append history
|
||||||
|
let upd8Text = form.requestText.Trim ()
|
||||||
|
let text = if upd8Text = req.Text then None else Some upd8Text
|
||||||
|
do! Data.addHistory req.RequestId userId
|
||||||
|
{ AsOf = ctx.Now (); Status = (Option.get >> RequestAction.ofString) form.status; Text = text } db
|
||||||
|
do! db.SaveChanges ()
|
||||||
|
let nextUrl =
|
||||||
|
match form.returnTo with
|
||||||
|
| "active" -> "/requests/active"
|
||||||
|
| "snoozed" -> "/requests/snoozed"
|
||||||
|
| _ (* "journal" *) -> "/journal"
|
||||||
|
Messages.pushSuccess ctx "Prayer request updated successfully" nextUrl
|
||||||
|
return! seeOther nextUrl next ctx
|
||||||
|
| None -> return! Error.notFound next ctx
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// Handlers for /user URLs
|
||||||
|
module User =
|
||||||
|
|
||||||
|
open Microsoft.AspNetCore.Authentication
|
||||||
|
open Microsoft.AspNetCore.Authentication.Cookies
|
||||||
|
|
||||||
|
// GET /user/log-on
|
||||||
|
let logOn : HttpHandler =
|
||||||
|
logOn (Some "/journal")
|
||||||
|
|
||||||
|
// GET /user/log-off
|
||||||
|
let logOff : HttpHandler = requireUser >=> fun next ctx -> task {
|
||||||
|
do! ctx.SignOutAsync ("Auth0", AuthenticationProperties (RedirectUri = "/"))
|
||||||
|
do! ctx.SignOutAsync CookieAuthenticationDefaults.AuthenticationScheme
|
||||||
|
return! next ctx
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
open Giraffe.EndpointRouting
|
||||||
|
|
||||||
|
/// The routes for myPrayerJournal
|
||||||
|
let routes = [
|
||||||
|
GET_HEAD [ route "/" Home.home ]
|
||||||
|
subRoute "/components/" [
|
||||||
|
GET_HEAD [
|
||||||
|
route "journal-items" Components.journalItems
|
||||||
|
routef "request/%s/add-notes" Components.addNotes
|
||||||
|
routef "request/%s/item" Components.requestItem
|
||||||
|
routef "request/%s/notes" Components.notes
|
||||||
|
routef "request/%s/snooze" Components.snooze
|
||||||
|
]
|
||||||
|
]
|
||||||
|
GET_HEAD [ route "/journal" Journal.journal ]
|
||||||
|
subRoute "/legal/" [
|
||||||
|
GET_HEAD [
|
||||||
|
route "privacy-policy" Legal.privacyPolicy
|
||||||
|
route "terms-of-service" Legal.termsOfService
|
||||||
|
]
|
||||||
|
]
|
||||||
|
subRoute "/request" [
|
||||||
|
GET_HEAD [
|
||||||
|
routef "/%s/edit" Request.edit
|
||||||
|
routef "/%s/full" Request.getFull
|
||||||
|
route "s/active" Request.active
|
||||||
|
route "s/answered" Request.answered
|
||||||
|
route "s/snoozed" Request.snoozed
|
||||||
|
]
|
||||||
|
PATCH [
|
||||||
|
route "" Request.update
|
||||||
|
routef "/%s/cancel-snooze" Request.cancelSnooze
|
||||||
|
routef "/%s/prayed" Request.prayed
|
||||||
|
routef "/%s/show" Request.show
|
||||||
|
routef "/%s/snooze" Request.snooze
|
||||||
|
]
|
||||||
|
POST [
|
||||||
|
route "" Request.add
|
||||||
|
routef "/%s/note" Request.addNote
|
||||||
|
]
|
||||||
|
]
|
||||||
|
subRoute "/user/" [
|
||||||
|
GET_HEAD [
|
||||||
|
route "log-off" User.logOff
|
||||||
|
route "log-on" User.logOn
|
||||||
|
]
|
||||||
|
]
|
||||||
|
]
|
||||||
35
src/MyPrayerJournal/MyPrayerJournal.fsproj
Normal file
35
src/MyPrayerJournal/MyPrayerJournal.fsproj
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>net7.0</TargetFramework>
|
||||||
|
<Version>3.2</Version>
|
||||||
|
<DebugType>embedded</DebugType>
|
||||||
|
<GenerateDocumentationFile>false</GenerateDocumentationFile>
|
||||||
|
<NoWarn>3391</NoWarn>
|
||||||
|
</PropertyGroup>
|
||||||
|
<ItemGroup>
|
||||||
|
<Compile Include="Domain.fs" />
|
||||||
|
<Compile Include="Data.fs" />
|
||||||
|
<Compile Include="Dates.fs" />
|
||||||
|
<Compile Include="Views/Helpers.fs" />
|
||||||
|
<Compile Include="Views/Journal.fs" />
|
||||||
|
<Compile Include="Views/Layout.fs" />
|
||||||
|
<Compile Include="Views/Legal.fs" />
|
||||||
|
<Compile Include="Views/Request.fs" />
|
||||||
|
<Compile Include="Handlers.fs" />
|
||||||
|
<Compile Include="Program.fs" />
|
||||||
|
</ItemGroup>
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="FSharp.SystemTextJson" Version="1.1.23" />
|
||||||
|
<PackageReference Include="FunctionalCuid" Version="1.0.0" />
|
||||||
|
<PackageReference Include="Giraffe" Version="6.0.0" />
|
||||||
|
<PackageReference Include="Giraffe.Htmx" Version="1.9.2" />
|
||||||
|
<PackageReference Include="Giraffe.ViewEngine.Htmx" Version="1.9.2" />
|
||||||
|
<PackageReference Include="LiteDB" Version="5.0.16" />
|
||||||
|
<PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" Version="7.0.5" />
|
||||||
|
<PackageReference Include="NodaTime" Version="3.1.2" />
|
||||||
|
<PackageReference Update="FSharp.Core" Version="7.0.300" />
|
||||||
|
</ItemGroup>
|
||||||
|
<ItemGroup>
|
||||||
|
<Folder Include="wwwroot\" />
|
||||||
|
</ItemGroup>
|
||||||
|
</Project>
|
||||||
169
src/MyPrayerJournal/Program.fs
Normal file
169
src/MyPrayerJournal/Program.fs
Normal file
@@ -0,0 +1,169 @@
|
|||||||
|
module MyPrayerJournal.Api
|
||||||
|
|
||||||
|
open Microsoft.AspNetCore.Builder
|
||||||
|
open Microsoft.AspNetCore.Hosting
|
||||||
|
open System.IO
|
||||||
|
|
||||||
|
/// Configuration functions for the application
|
||||||
|
module Configure =
|
||||||
|
|
||||||
|
/// Configure the content root
|
||||||
|
let contentRoot root =
|
||||||
|
WebApplicationOptions (ContentRootPath = root) |> WebApplication.CreateBuilder
|
||||||
|
|
||||||
|
|
||||||
|
open Microsoft.Extensions.Configuration
|
||||||
|
|
||||||
|
/// Configure the application configuration
|
||||||
|
let appConfiguration (bldr : WebApplicationBuilder) =
|
||||||
|
bldr.Configuration
|
||||||
|
.SetBasePath(bldr.Environment.ContentRootPath)
|
||||||
|
.AddJsonFile("appsettings.json", optional = false, reloadOnChange = true)
|
||||||
|
.AddJsonFile($"appsettings.{bldr.Environment.EnvironmentName}.json", optional = true, reloadOnChange = true)
|
||||||
|
.AddEnvironmentVariables ()
|
||||||
|
|> ignore
|
||||||
|
bldr
|
||||||
|
|
||||||
|
|
||||||
|
open Microsoft.AspNetCore.Server.Kestrel.Core
|
||||||
|
|
||||||
|
/// Configure Kestrel from appsettings.json
|
||||||
|
let kestrel (bldr : WebApplicationBuilder) =
|
||||||
|
let kestrelOpts (ctx : WebHostBuilderContext) (opts : KestrelServerOptions) =
|
||||||
|
(ctx.Configuration.GetSection >> opts.Configure >> ignore) "Kestrel"
|
||||||
|
bldr.WebHost.UseKestrel().ConfigureKestrel kestrelOpts |> ignore
|
||||||
|
bldr
|
||||||
|
|
||||||
|
|
||||||
|
/// Configure the web root directory
|
||||||
|
let webRoot pathSegments (bldr : WebApplicationBuilder) =
|
||||||
|
Array.concat [ [| bldr.Environment.ContentRootPath |]; pathSegments ]
|
||||||
|
|> (Path.Combine >> bldr.WebHost.UseWebRoot >> ignore)
|
||||||
|
bldr
|
||||||
|
|
||||||
|
|
||||||
|
open Microsoft.Extensions.Logging
|
||||||
|
open Microsoft.Extensions.Hosting
|
||||||
|
|
||||||
|
/// Configure logging
|
||||||
|
let logging (bldr : WebApplicationBuilder) =
|
||||||
|
if bldr.Environment.IsDevelopment () then bldr.Logging.AddFilter (fun l -> l > LogLevel.Information) |> ignore
|
||||||
|
bldr.Logging.AddConsole().AddDebug() |> ignore
|
||||||
|
bldr
|
||||||
|
|
||||||
|
|
||||||
|
open Giraffe
|
||||||
|
open LiteDB
|
||||||
|
open Microsoft.AspNetCore.Authentication.Cookies
|
||||||
|
open Microsoft.AspNetCore.Authentication.OpenIdConnect
|
||||||
|
open Microsoft.AspNetCore.Http
|
||||||
|
open Microsoft.Extensions.DependencyInjection
|
||||||
|
open Microsoft.IdentityModel.Protocols.OpenIdConnect
|
||||||
|
open NodaTime
|
||||||
|
open System
|
||||||
|
open System.Text.Json
|
||||||
|
open System.Text.Json.Serialization
|
||||||
|
open System.Threading.Tasks
|
||||||
|
|
||||||
|
/// Configure dependency injection
|
||||||
|
let services (bldr : WebApplicationBuilder) =
|
||||||
|
let sameSite (opts : CookieOptions) =
|
||||||
|
match opts.SameSite, opts.Secure with
|
||||||
|
| SameSiteMode.None, false -> opts.SameSite <- SameSiteMode.Unspecified
|
||||||
|
| _, _ -> ()
|
||||||
|
|
||||||
|
let _ = bldr.Services.AddRouting ()
|
||||||
|
let _ = bldr.Services.AddGiraffe ()
|
||||||
|
let _ = bldr.Services.AddSingleton<IClock> SystemClock.Instance
|
||||||
|
let _ = bldr.Services.AddSingleton<IDateTimeZoneProvider> DateTimeZoneProviders.Tzdb
|
||||||
|
|
||||||
|
let _ =
|
||||||
|
bldr.Services.Configure<CookiePolicyOptions>(fun (opts : CookiePolicyOptions) ->
|
||||||
|
opts.MinimumSameSitePolicy <- SameSiteMode.Unspecified
|
||||||
|
opts.OnAppendCookie <- fun ctx -> sameSite ctx.CookieOptions
|
||||||
|
opts.OnDeleteCookie <- fun ctx -> sameSite ctx.CookieOptions)
|
||||||
|
let _ =
|
||||||
|
bldr.Services.AddAuthentication(fun opts ->
|
||||||
|
opts.DefaultAuthenticateScheme <- CookieAuthenticationDefaults.AuthenticationScheme
|
||||||
|
opts.DefaultSignInScheme <- CookieAuthenticationDefaults.AuthenticationScheme
|
||||||
|
opts.DefaultChallengeScheme <- CookieAuthenticationDefaults.AuthenticationScheme)
|
||||||
|
.AddCookie()
|
||||||
|
.AddOpenIdConnect("Auth0", fun opts ->
|
||||||
|
// Configure OIDC with Auth0 options from configuration
|
||||||
|
let cfg = bldr.Configuration.GetSection "Auth0"
|
||||||
|
opts.Authority <- $"""https://{cfg["Domain"]}/"""
|
||||||
|
opts.ClientId <- cfg["Id"]
|
||||||
|
opts.ClientSecret <- cfg["Secret"]
|
||||||
|
opts.ResponseType <- OpenIdConnectResponseType.Code
|
||||||
|
|
||||||
|
opts.Scope.Clear ()
|
||||||
|
opts.Scope.Add "openid"
|
||||||
|
opts.Scope.Add "profile"
|
||||||
|
|
||||||
|
opts.CallbackPath <- PathString "/user/log-on/success"
|
||||||
|
opts.ClaimsIssuer <- "Auth0"
|
||||||
|
opts.SaveTokens <- true
|
||||||
|
|
||||||
|
opts.Events <- OpenIdConnectEvents ()
|
||||||
|
opts.Events.OnRedirectToIdentityProviderForSignOut <- fun ctx ->
|
||||||
|
let returnTo =
|
||||||
|
match ctx.Properties.RedirectUri with
|
||||||
|
| it when isNull it || it = "" -> ""
|
||||||
|
| redirUri ->
|
||||||
|
let finalRedirUri =
|
||||||
|
match redirUri.StartsWith "/" with
|
||||||
|
| true ->
|
||||||
|
// transform to absolute
|
||||||
|
let request = ctx.Request
|
||||||
|
$"{request.Scheme}://{request.Host.Value}{request.PathBase.Value}{redirUri}"
|
||||||
|
| false -> redirUri
|
||||||
|
Uri.EscapeDataString $"&returnTo={finalRedirUri}"
|
||||||
|
ctx.Response.Redirect $"""https://{cfg["Domain"]}/v2/logout?client_id={cfg["Id"]}{returnTo}"""
|
||||||
|
ctx.HandleResponse ()
|
||||||
|
Task.CompletedTask
|
||||||
|
opts.Events.OnRedirectToIdentityProvider <- fun ctx ->
|
||||||
|
let bldr = UriBuilder ctx.ProtocolMessage.RedirectUri
|
||||||
|
bldr.Scheme <- cfg["Scheme"]
|
||||||
|
bldr.Port <- int cfg["Port"]
|
||||||
|
ctx.ProtocolMessage.RedirectUri <- string bldr
|
||||||
|
Task.CompletedTask)
|
||||||
|
|
||||||
|
let jsonOptions = JsonSerializerOptions ()
|
||||||
|
jsonOptions.Converters.Add (JsonFSharpConverter ())
|
||||||
|
let db = new LiteDatabase (bldr.Configuration.GetConnectionString "db")
|
||||||
|
Data.Startup.ensureDb db
|
||||||
|
let _ = bldr.Services.AddSingleton jsonOptions
|
||||||
|
let _ = bldr.Services.AddSingleton<Json.ISerializer, SystemTextJson.Serializer> ()
|
||||||
|
let _ = bldr.Services.AddSingleton<LiteDatabase> db
|
||||||
|
|
||||||
|
bldr.Build ()
|
||||||
|
|
||||||
|
|
||||||
|
open Giraffe.EndpointRouting
|
||||||
|
|
||||||
|
/// Configure the web application
|
||||||
|
let application (app : WebApplication) =
|
||||||
|
let _ = app.UseStaticFiles ()
|
||||||
|
let _ = app.UseCookiePolicy ()
|
||||||
|
let _ = app.UseRouting ()
|
||||||
|
let _ = app.UseAuthentication ()
|
||||||
|
let _ = app.UseGiraffeErrorHandler Handlers.Error.error
|
||||||
|
let _ = app.UseEndpoints (fun e -> e.MapGiraffeEndpoints Handlers.routes)
|
||||||
|
app
|
||||||
|
|
||||||
|
/// Compose all the configurations into one
|
||||||
|
let webHost pathSegments =
|
||||||
|
contentRoot
|
||||||
|
>> appConfiguration
|
||||||
|
>> kestrel
|
||||||
|
>> webRoot pathSegments
|
||||||
|
>> logging
|
||||||
|
>> services
|
||||||
|
>> application
|
||||||
|
|
||||||
|
|
||||||
|
[<EntryPoint>]
|
||||||
|
let main _ =
|
||||||
|
use host = Configure.webHost [| "wwwroot" |] (Directory.GetCurrentDirectory ())
|
||||||
|
host.Run ()
|
||||||
|
0
|
||||||
42
src/MyPrayerJournal/Views/Helpers.fs
Normal file
42
src/MyPrayerJournal/Views/Helpers.fs
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
/// Internal partial views
|
||||||
|
[<AutoOpen>]
|
||||||
|
module private MyPrayerJournal.Views.Helpers
|
||||||
|
|
||||||
|
open Giraffe.Htmx
|
||||||
|
open Giraffe.ViewEngine
|
||||||
|
open Giraffe.ViewEngine.Htmx
|
||||||
|
open MyPrayerJournal
|
||||||
|
open NodaTime
|
||||||
|
|
||||||
|
/// Create a link that targets the `#top` element and pushes a URL to history
|
||||||
|
let pageLink href attrs =
|
||||||
|
attrs
|
||||||
|
|> List.append [ _href href; _hxBoost; _hxTarget "#top"; _hxSwap HxSwap.InnerHtml; _hxPushUrl "true" ]
|
||||||
|
|> a
|
||||||
|
|
||||||
|
/// Create a Material icon
|
||||||
|
let icon name = span [ _class "material-icons" ] [ str name ]
|
||||||
|
|
||||||
|
/// Create a card when there are no results found
|
||||||
|
let noResults heading link buttonText text =
|
||||||
|
div [ _class "card" ] [
|
||||||
|
h5 [ _class "card-header"] [ str heading ]
|
||||||
|
div [ _class "card-body text-center" ] [
|
||||||
|
p [ _class "card-text" ] text
|
||||||
|
pageLink link [ _class "btn btn-primary" ] [ str buttonText ]
|
||||||
|
]
|
||||||
|
]
|
||||||
|
|
||||||
|
/// Create a date with a span tag, displaying the relative date with the full date/time in the tooltip
|
||||||
|
let relativeDate (date : Instant) now (tz : DateTimeZone) =
|
||||||
|
span [ _title (date.InZone(tz).ToDateTimeOffset().ToString ("f", null)) ] [ Dates.formatDistance now date |> str ]
|
||||||
|
|
||||||
|
/// The version of myPrayerJournal
|
||||||
|
let version =
|
||||||
|
let v = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version
|
||||||
|
seq {
|
||||||
|
string v.Major
|
||||||
|
if v.Minor > 0 then
|
||||||
|
$".{v.Minor}"
|
||||||
|
if v.Revision > 0 then $".{v.Revision}"
|
||||||
|
} |> Seq.reduce (+)
|
||||||
180
src/MyPrayerJournal/Views/Journal.fs
Normal file
180
src/MyPrayerJournal/Views/Journal.fs
Normal file
@@ -0,0 +1,180 @@
|
|||||||
|
/// Views for journal pages and components
|
||||||
|
module MyPrayerJournal.Views.Journal
|
||||||
|
|
||||||
|
open Giraffe.Htmx
|
||||||
|
open Giraffe.ViewEngine
|
||||||
|
open Giraffe.ViewEngine.Accessibility
|
||||||
|
open Giraffe.ViewEngine.Htmx
|
||||||
|
open MyPrayerJournal
|
||||||
|
|
||||||
|
/// Display a card for this prayer request
|
||||||
|
let journalCard now tz req =
|
||||||
|
let reqId = RequestId.toString req.RequestId
|
||||||
|
let spacer = span [] [ rawText " " ]
|
||||||
|
div [ _class "col" ] [
|
||||||
|
div [ _class "card h-100" ] [
|
||||||
|
div [ _class "card-header p-0 d-flex"; _roleToolBar ] [
|
||||||
|
pageLink $"/request/{reqId}/edit" [ _class "btn btn-secondary"; _title "Edit Request" ] [ icon "edit" ]
|
||||||
|
spacer
|
||||||
|
button [ _type "button"
|
||||||
|
_class "btn btn-secondary"
|
||||||
|
_title "Add Notes"
|
||||||
|
_data "bs-toggle" "modal"
|
||||||
|
_data "bs-target" "#notesModal"
|
||||||
|
_hxGet $"/components/request/{reqId}/add-notes"
|
||||||
|
_hxTarget "#notesBody"
|
||||||
|
_hxSwap HxSwap.InnerHtml ] [
|
||||||
|
icon "comment"
|
||||||
|
]
|
||||||
|
spacer
|
||||||
|
button [ _type "button"
|
||||||
|
_class "btn btn-secondary"
|
||||||
|
_title "Snooze Request"
|
||||||
|
_data "bs-toggle" "modal"
|
||||||
|
_data "bs-target" "#snoozeModal"
|
||||||
|
_hxGet $"/components/request/{reqId}/snooze"
|
||||||
|
_hxTarget "#snoozeBody"
|
||||||
|
_hxSwap HxSwap.InnerHtml ] [
|
||||||
|
icon "schedule"
|
||||||
|
]
|
||||||
|
div [ _class "flex-grow-1" ] []
|
||||||
|
button [ _type "button"
|
||||||
|
_class "btn btn-success w-25"
|
||||||
|
_hxPatch $"/request/{reqId}/prayed"
|
||||||
|
_title "Mark as Prayed" ] [
|
||||||
|
icon "done"
|
||||||
|
]
|
||||||
|
]
|
||||||
|
div [ _class "card-body" ] [
|
||||||
|
p [ _class "request-text" ] [ str req.Text ]
|
||||||
|
]
|
||||||
|
div [ _class "card-footer text-end text-muted px-1 py-0" ] [
|
||||||
|
em [] [
|
||||||
|
match req.LastPrayed with
|
||||||
|
| Some dt -> str "last prayed "; relativeDate dt now tz
|
||||||
|
| None -> str "last activity "; relativeDate req.AsOf now tz
|
||||||
|
]
|
||||||
|
]
|
||||||
|
]
|
||||||
|
]
|
||||||
|
|
||||||
|
/// The journal loading page
|
||||||
|
let journal user =
|
||||||
|
article [ _class "container-fluid mt-3" ] [
|
||||||
|
h2 [ _class "pb-3" ] [
|
||||||
|
str user
|
||||||
|
match user with "Your" -> () | _ -> rawText "’s"
|
||||||
|
str " Prayer Journal"
|
||||||
|
]
|
||||||
|
p [ _class "pb-3 text-center" ] [
|
||||||
|
pageLink "/request/new/edit" [ _class "btn btn-primary "] [ icon "add_box"; str " Add a Prayer Request" ]
|
||||||
|
]
|
||||||
|
p [ _hxGet "/components/journal-items"; _hxSwap HxSwap.OuterHtml; _hxTrigger HxTrigger.Load ] [
|
||||||
|
rawText "Loading your prayer journal…"
|
||||||
|
]
|
||||||
|
div [ _id "notesModal"
|
||||||
|
_class "modal fade"
|
||||||
|
_tabindex "-1"
|
||||||
|
_ariaLabelledBy "nodesModalLabel"
|
||||||
|
_ariaHidden "true" ] [
|
||||||
|
div [ _class "modal-dialog modal-dialog-scrollable" ] [
|
||||||
|
div [ _class "modal-content" ] [
|
||||||
|
div [ _class "modal-header" ] [
|
||||||
|
h5 [ _class "modal-title"; _id "nodesModalLabel" ] [ str "Add Notes to Prayer Request" ]
|
||||||
|
button [ _type "button"; _class "btn-close"; _data "bs-dismiss" "modal"; _ariaLabel "Close" ] []
|
||||||
|
]
|
||||||
|
div [ _class "modal-body"; _id "notesBody" ] [ ]
|
||||||
|
div [ _class "modal-footer" ] [
|
||||||
|
button [ _type "button"
|
||||||
|
_id "notesDismiss"
|
||||||
|
_class "btn btn-secondary"
|
||||||
|
_data "bs-dismiss" "modal" ] [
|
||||||
|
str "Close"
|
||||||
|
]
|
||||||
|
]
|
||||||
|
]
|
||||||
|
]
|
||||||
|
]
|
||||||
|
div [ _id "snoozeModal"
|
||||||
|
_class "modal fade"
|
||||||
|
_tabindex "-1"
|
||||||
|
_ariaLabelledBy "snoozeModalLabel"
|
||||||
|
_ariaHidden "true" ] [
|
||||||
|
div [ _class "modal-dialog modal-sm" ] [
|
||||||
|
div [ _class "modal-content" ] [
|
||||||
|
div [ _class "modal-header" ] [
|
||||||
|
h5 [ _class "modal-title"; _id "snoozeModalLabel" ] [ str "Snooze Prayer Request" ]
|
||||||
|
button [ _type "button"; _class "btn-close"; _data "bs-dismiss" "modal"; _ariaLabel "Close" ] []
|
||||||
|
]
|
||||||
|
div [ _class "modal-body"; _id "snoozeBody" ] [ ]
|
||||||
|
div [ _class "modal-footer" ] [
|
||||||
|
button [ _type "button"
|
||||||
|
_id "snoozeDismiss"
|
||||||
|
_class "btn btn-secondary"
|
||||||
|
_data "bs-dismiss" "modal" ] [
|
||||||
|
str "Close"
|
||||||
|
]
|
||||||
|
]
|
||||||
|
]
|
||||||
|
]
|
||||||
|
]
|
||||||
|
]
|
||||||
|
|
||||||
|
/// The journal items
|
||||||
|
let journalItems now tz items =
|
||||||
|
match items |> List.isEmpty with
|
||||||
|
| true ->
|
||||||
|
noResults "No Active Requests" "/request/new/edit" "Add a Request" [
|
||||||
|
rawText "You have no requests to be shown; see the “Active” link above for snoozed or deferred "
|
||||||
|
rawText "requests, and the “Answered” link for answered requests"
|
||||||
|
]
|
||||||
|
| false ->
|
||||||
|
items
|
||||||
|
|> List.map (journalCard now tz)
|
||||||
|
|> section [ _id "journalItems"
|
||||||
|
_class "row row-cols-1 row-cols-md-2 row-cols-lg-3 row-cols-xl-4 g-3"
|
||||||
|
_hxTarget "this"
|
||||||
|
_hxSwap HxSwap.OuterHtml
|
||||||
|
_ariaLabel "Prayer Requests" ]
|
||||||
|
|
||||||
|
/// The notes edit modal body
|
||||||
|
let notesEdit requestId =
|
||||||
|
let reqId = RequestId.toString requestId
|
||||||
|
[ form [ _hxPost $"/request/{reqId}/note" ] [
|
||||||
|
div [ _class "form-floating pb-3" ] [
|
||||||
|
textarea [ _id "notes"
|
||||||
|
_name "notes"
|
||||||
|
_class "form-control"
|
||||||
|
_style "min-height: 8rem;"
|
||||||
|
_placeholder "Notes"
|
||||||
|
_autofocus; _required ] [ ]
|
||||||
|
label [ _for "notes" ] [ str "Notes" ]
|
||||||
|
]
|
||||||
|
p [ _class "text-end" ] [ button [ _type "submit"; _class "btn btn-primary" ] [ str "Add Notes" ] ]
|
||||||
|
]
|
||||||
|
hr [ _style "margin: .5rem -1rem" ]
|
||||||
|
div [ _id "priorNotes" ] [
|
||||||
|
p [ _class "text-center pt-3" ] [
|
||||||
|
button [ _type "button"
|
||||||
|
_class "btn btn-secondary"
|
||||||
|
_hxGet $"/components/request/{reqId}/notes"
|
||||||
|
_hxSwap HxSwap.OuterHtml
|
||||||
|
_hxTarget "#priorNotes" ] [
|
||||||
|
str "Load Prior Notes"
|
||||||
|
]
|
||||||
|
]
|
||||||
|
]
|
||||||
|
]
|
||||||
|
|
||||||
|
/// The snooze edit form
|
||||||
|
let snooze requestId =
|
||||||
|
let today = System.DateTime.Today.ToString "yyyy-MM-dd"
|
||||||
|
form [ _hxPatch $"/request/{RequestId.toString requestId}/snooze"
|
||||||
|
_hxTarget "#journalItems"
|
||||||
|
_hxSwap HxSwap.OuterHtml ] [
|
||||||
|
div [ _class "form-floating pb-3" ] [
|
||||||
|
input [ _type "date"; _id "until"; _name "until"; _class "form-control"; _min today; _required ]
|
||||||
|
label [ _for "until" ] [ str "Until" ]
|
||||||
|
]
|
||||||
|
p [ _class "text-end mb-0" ] [ button [ _type "submit"; _class "btn btn-primary" ] [ str "Snooze" ] ]
|
||||||
|
]
|
||||||
148
src/MyPrayerJournal/Views/Layout.fs
Normal file
148
src/MyPrayerJournal/Views/Layout.fs
Normal file
@@ -0,0 +1,148 @@
|
|||||||
|
/// Layout / home views
|
||||||
|
module MyPrayerJournal.Views.Layout
|
||||||
|
|
||||||
|
open Giraffe.ViewEngine
|
||||||
|
open Giraffe.ViewEngine.Accessibility
|
||||||
|
|
||||||
|
/// The data needed to render a page-level view
|
||||||
|
type PageRenderContext =
|
||||||
|
{ /// Whether the user is authenticated
|
||||||
|
IsAuthenticated : bool
|
||||||
|
|
||||||
|
/// Whether the user has snoozed requests
|
||||||
|
HasSnoozed : bool
|
||||||
|
|
||||||
|
/// The current URL
|
||||||
|
CurrentUrl : string
|
||||||
|
|
||||||
|
/// The title for the page to be rendered
|
||||||
|
PageTitle : string
|
||||||
|
|
||||||
|
/// The content of the page
|
||||||
|
Content : XmlNode
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The home page
|
||||||
|
let home =
|
||||||
|
article [ _class "container mt-3" ] [
|
||||||
|
p [] [ rawText " " ]
|
||||||
|
p [] [
|
||||||
|
str "myPrayerJournal is a place where individuals can record their prayer requests, record that they "
|
||||||
|
str "prayed for them, update them as God moves in the situation, and record a final answer received on "
|
||||||
|
str "that request. It also allows individuals to review their answered prayers."
|
||||||
|
]
|
||||||
|
p [] [
|
||||||
|
str "This site is open and available to the general public. To get started, simply click the "
|
||||||
|
rawText "“Log On” link above, and log on with either a Microsoft or Google account. You can "
|
||||||
|
rawText "also learn more about the site at the “Docs” link, also above."
|
||||||
|
]
|
||||||
|
]
|
||||||
|
|
||||||
|
/// The default navigation bar, which will load the items on page load, and whenever a refresh event occurs
|
||||||
|
let private navBar ctx =
|
||||||
|
nav [ _class "navbar navbar-dark"; _roleNavigation ] [
|
||||||
|
div [ _class "container-fluid" ] [
|
||||||
|
pageLink "/" [ _class "navbar-brand" ] [
|
||||||
|
span [ _class "m" ] [ str "my" ]
|
||||||
|
span [ _class "p" ] [ str "Prayer" ]
|
||||||
|
span [ _class "j" ] [ str "Journal" ]
|
||||||
|
]
|
||||||
|
seq {
|
||||||
|
let navLink (matchUrl : string) =
|
||||||
|
match ctx.CurrentUrl.StartsWith matchUrl with true -> [ _class "is-active-route" ] | false -> []
|
||||||
|
|> pageLink matchUrl
|
||||||
|
if ctx.IsAuthenticated then
|
||||||
|
li [ _class "nav-item" ] [ navLink "/journal" [ str "Journal" ] ]
|
||||||
|
li [ _class "nav-item" ] [ navLink "/requests/active" [ str "Active" ] ]
|
||||||
|
if ctx.HasSnoozed then li [ _class "nav-item" ] [ navLink "/requests/snoozed" [ str "Snoozed" ] ]
|
||||||
|
li [ _class "nav-item" ] [ navLink "/requests/answered" [ str "Answered" ] ]
|
||||||
|
li [ _class "nav-item" ] [ a [ _href "/user/log-off" ] [ str "Log Off" ] ]
|
||||||
|
else li [ _class "nav-item"] [ a [ _href "/user/log-on" ] [ str "Log On" ] ]
|
||||||
|
li [ _class "nav-item" ] [
|
||||||
|
a [ _href "https://docs.prayerjournal.me"; _target "_blank"; _rel "noopener" ] [ str "Docs" ]
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|> List.ofSeq
|
||||||
|
|> ul [ _class "navbar-nav me-auto d-flex flex-row" ]
|
||||||
|
]
|
||||||
|
]
|
||||||
|
|
||||||
|
/// The title tag with the application name appended
|
||||||
|
let titleTag ctx =
|
||||||
|
title [] [ str ctx.PageTitle; rawText " « myPrayerJournal" ]
|
||||||
|
|
||||||
|
/// The HTML `head` element
|
||||||
|
let htmlHead ctx =
|
||||||
|
head [ _lang "en" ] [
|
||||||
|
meta [ _name "viewport"; _content "width=device-width, initial-scale=1" ]
|
||||||
|
meta [ _name "description"; _content "Online prayer journal - free w/Google or Microsoft account" ]
|
||||||
|
titleTag ctx
|
||||||
|
link [ _href "https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css"
|
||||||
|
_rel "stylesheet"
|
||||||
|
_integrity "sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx"
|
||||||
|
_crossorigin "anonymous" ]
|
||||||
|
link [ _href "https://fonts.googleapis.com/icon?family=Material+Icons"; _rel "stylesheet" ]
|
||||||
|
link [ _href "/style/style.css"; _rel "stylesheet" ]
|
||||||
|
]
|
||||||
|
|
||||||
|
/// Element used to display toasts
|
||||||
|
let toaster =
|
||||||
|
div [ _ariaLive "polite"; _ariaAtomic "true"; _id "toastHost" ] [
|
||||||
|
div [ _class "toast-container position-absolute p-3 bottom-0 end-0"; _id "toasts" ] []
|
||||||
|
]
|
||||||
|
|
||||||
|
/// The page's `footer` element
|
||||||
|
let htmlFoot =
|
||||||
|
footer [ _class "container-fluid" ] [
|
||||||
|
p [ _class "text-muted text-end" ] [
|
||||||
|
str $"myPrayerJournal {version}"
|
||||||
|
br []
|
||||||
|
em [] [
|
||||||
|
small [] [
|
||||||
|
pageLink "/legal/privacy-policy" [] [ str "Privacy Policy" ]
|
||||||
|
rawText " • "
|
||||||
|
pageLink "/legal/terms-of-service" [] [ str "Terms of Service" ]
|
||||||
|
rawText " • "
|
||||||
|
a [ _href "https://github.com/bit-badger/myprayerjournal"; _target "_blank"; _rel "noopener" ] [
|
||||||
|
str "Developed"
|
||||||
|
]
|
||||||
|
str " and hosted by "
|
||||||
|
a [ _href "https://bitbadger.solutions"; _target "_blank"; _rel "noopener" ] [
|
||||||
|
str "Bit Badger Solutions"
|
||||||
|
]
|
||||||
|
]
|
||||||
|
]
|
||||||
|
]
|
||||||
|
Htmx.Script.minified
|
||||||
|
script [] [
|
||||||
|
rawText "if (!htmx) document.write('<script src=\"/script/htmx.min.js\"><\/script>')"
|
||||||
|
]
|
||||||
|
script [ _async
|
||||||
|
_src "https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.bundle.min.js"
|
||||||
|
_integrity "sha384-A3rJD856KowSb7dwlZdYEkO39Gagi7vIsF0jrRAoQmDKKtQBHUuLZ9AsSv4jD4Xa"
|
||||||
|
_crossorigin "anonymous" ] []
|
||||||
|
script [] [
|
||||||
|
rawText "setTimeout(function () { "
|
||||||
|
rawText "if (!bootstrap) document.write('<script src=\"/script/bootstrap.bundle.min.js\"><\/script>') "
|
||||||
|
rawText "}, 2000)"
|
||||||
|
]
|
||||||
|
script [ _src "/script/mpj.js" ] []
|
||||||
|
]
|
||||||
|
|
||||||
|
/// Create the full view of the page
|
||||||
|
let view ctx =
|
||||||
|
html [ _lang "en" ] [
|
||||||
|
htmlHead ctx
|
||||||
|
body [] [
|
||||||
|
section [ _id "top"; _ariaLabel "Top navigation" ] [ navBar ctx; main [ _roleMain ] [ ctx.Content ] ]
|
||||||
|
toaster
|
||||||
|
htmlFoot
|
||||||
|
]
|
||||||
|
]
|
||||||
|
|
||||||
|
/// Create a partial view
|
||||||
|
let partial ctx =
|
||||||
|
html [ _lang "en" ] [
|
||||||
|
head [] [ titleTag ctx ]
|
||||||
|
body [] [ navBar ctx; main [ _roleMain ] [ ctx.Content ] ]
|
||||||
|
]
|
||||||
162
src/MyPrayerJournal/Views/Legal.fs
Normal file
162
src/MyPrayerJournal/Views/Legal.fs
Normal file
@@ -0,0 +1,162 @@
|
|||||||
|
/// Views for legal pages
|
||||||
|
module MyPrayerJournal.Views.Legal
|
||||||
|
|
||||||
|
open Giraffe.ViewEngine
|
||||||
|
|
||||||
|
/// View for the "Privacy Policy" page
|
||||||
|
let privacyPolicy =
|
||||||
|
article [ _class "container mt-3" ] [
|
||||||
|
h2 [ _class "mb-2" ] [ str "Privacy Policy" ]
|
||||||
|
h6 [ _class "text-muted pb-3" ] [ str "as of May 21"; sup [] [ str "st"]; str ", 2018" ]
|
||||||
|
p [] [
|
||||||
|
str "The nature of the service is one where privacy is a must. The items below will help you understand "
|
||||||
|
str "the data we collect, access, and store on your behalf as you use this service."
|
||||||
|
]
|
||||||
|
div [ _class "card" ] [
|
||||||
|
div [ _class "list-group list-group-flush" ] [
|
||||||
|
div [ _class "list-group-item"] [
|
||||||
|
h3 [] [ str "Third Party Services" ]
|
||||||
|
p [ _class "card-text" ] [
|
||||||
|
str "myPrayerJournal utilizes a third-party authentication and identity provider. You should "
|
||||||
|
str "familiarize yourself with the privacy policy for "
|
||||||
|
a [ _href "https://auth0.com/privacy"; _target "_blank" ] [ str "Auth0" ]
|
||||||
|
str ", as well as your chosen provider ("
|
||||||
|
a [ _href "https://privacy.microsoft.com/en-us/privacystatement"; _target "_blank" ] [
|
||||||
|
str "Microsoft"
|
||||||
|
]
|
||||||
|
str " or "
|
||||||
|
a [ _href "https://policies.google.com/privacy"; _target "_blank" ] [ str "Google" ]
|
||||||
|
str ")."
|
||||||
|
]
|
||||||
|
]
|
||||||
|
div [ _class "list-group-item" ] [
|
||||||
|
h3 [] [ str "What We Collect" ]
|
||||||
|
h4 [] [ str "Identifying Data" ]
|
||||||
|
ul [] [
|
||||||
|
li [] [
|
||||||
|
str "The only identifying data myPrayerJournal stores is the subscriber "
|
||||||
|
rawText "(“sub”) field from the token we receive from Auth0, once you have "
|
||||||
|
str "signed in through their hosted service. All information is associated with you via "
|
||||||
|
str "this field."
|
||||||
|
]
|
||||||
|
li [] [
|
||||||
|
str "While you are signed in, within your browser, the service has access to your first "
|
||||||
|
str "and last names, along with a URL to the profile picture (provided by your selected "
|
||||||
|
str "identity provider). This information is not transmitted to the server, and is removed "
|
||||||
|
rawText "when “Log Off” is clicked."
|
||||||
|
]
|
||||||
|
]
|
||||||
|
h4 [] [ str "User Provided Data" ]
|
||||||
|
ul [ _class "mb-0" ] [
|
||||||
|
li [] [
|
||||||
|
str "myPrayerJournal stores the information you provide, including the text of prayer "
|
||||||
|
str "requests, updates, and notes; and the date/time when certain actions are taken."
|
||||||
|
]
|
||||||
|
]
|
||||||
|
]
|
||||||
|
div [ _class "list-group-item" ] [
|
||||||
|
h3 [] [ str "How Your Data Is Accessed / Secured" ]
|
||||||
|
ul [ _class "mb-0" ] [
|
||||||
|
li [] [
|
||||||
|
str "Your provided data is returned to you, as required, to display your journal or your "
|
||||||
|
str "answered requests. On the server, it is stored in a controlled-access database."
|
||||||
|
]
|
||||||
|
li [] [
|
||||||
|
str "Your data is backed up, along with other Bit Badger Solutions hosted systems, in a "
|
||||||
|
str "rolling manner; backups are preserved for the prior 7 days, and backups from the 1"
|
||||||
|
sup [] [ str "st" ]
|
||||||
|
str " and 15"
|
||||||
|
sup [] [ str "th" ]
|
||||||
|
str " are preserved for 3 months. These backups are stored in a private cloud data "
|
||||||
|
str "repository."
|
||||||
|
]
|
||||||
|
li [] [
|
||||||
|
str "The data collected and stored is the absolute minimum necessary for the functionality "
|
||||||
|
rawText "of the service. There are no plans to “monetize” this service, and "
|
||||||
|
str "storing the minimum amount of information means that the data we have is not "
|
||||||
|
str "interesting to purchasers (or those who may have more nefarious purposes)."
|
||||||
|
]
|
||||||
|
li [] [
|
||||||
|
str "Access to servers and backups is strictly controlled and monitored for unauthorized "
|
||||||
|
str "access attempts."
|
||||||
|
]
|
||||||
|
]
|
||||||
|
]
|
||||||
|
div [ _class "list-group-item" ] [
|
||||||
|
h3 [] [ str "Removing Your Data" ]
|
||||||
|
p [ _class "card-text" ] [
|
||||||
|
str "At any time, you may choose to discontinue using this service. Both Microsoft and Google "
|
||||||
|
str "provide ways to revoke access from this application. However, if you want your data "
|
||||||
|
str "removed from the database, please contact daniel at bitbadger.solutions (via e-mail, "
|
||||||
|
str "replacing at with @) prior to doing so, to ensure we can determine which subscriber ID "
|
||||||
|
str "belongs to you."
|
||||||
|
]
|
||||||
|
]
|
||||||
|
]
|
||||||
|
]
|
||||||
|
]
|
||||||
|
|
||||||
|
/// View for the "Terms of Service" page
|
||||||
|
let termsOfService =
|
||||||
|
article [ _class "container mt-3" ] [
|
||||||
|
h2 [ _class "mb-2" ] [ str "Terms of Service" ]
|
||||||
|
h6 [ _class "text-muted pb-3"] [ str "as of May 21"; sup [] [ str "st" ]; str ", 2018" ]
|
||||||
|
div [ _class "card" ] [
|
||||||
|
div [ _class "list-group list-group-flush" ] [
|
||||||
|
div [ _class "list-group-item" ] [
|
||||||
|
h3 [] [ str "1. Acceptance of Terms" ]
|
||||||
|
p [ _class "card-text" ] [
|
||||||
|
str "By accessing this web site, you are agreeing to be bound by these Terms and Conditions, "
|
||||||
|
str "and that you are responsible to ensure that your use of this site complies with all "
|
||||||
|
str "applicable laws. Your continued use of this site implies your acceptance of these terms."
|
||||||
|
]
|
||||||
|
]
|
||||||
|
div [ _class "list-group-item" ] [
|
||||||
|
h3 [] [ str "2. Description of Service and Registration" ]
|
||||||
|
p [ _class "card-text" ] [
|
||||||
|
str "myPrayerJournal is a service that allows individuals to enter and amend their prayer "
|
||||||
|
str "requests. It requires no registration by itself, but access is granted based on a "
|
||||||
|
str "successful login with an external identity provider. See "
|
||||||
|
pageLink "/legal/privacy-policy" [] [ str "our privacy policy" ]
|
||||||
|
str " for details on how that information is accessed and stored."
|
||||||
|
]
|
||||||
|
]
|
||||||
|
div [ _class "list-group-item" ] [
|
||||||
|
h3 [] [ str "3. Third Party Services" ]
|
||||||
|
p [ _class "card-text" ] [
|
||||||
|
str "This service utilizes a third-party service provider for identity management. Review the "
|
||||||
|
str "terms of service for "
|
||||||
|
a [ _href "https://auth0.com/terms"; _target "_blank" ] [ str "Auth0"]
|
||||||
|
str ", as well as those for the selected authorization provider ("
|
||||||
|
a [ _href "https://www.microsoft.com/en-us/servicesagreement"; _target "_blank" ] [
|
||||||
|
str "Microsoft"
|
||||||
|
]
|
||||||
|
str " or "
|
||||||
|
a [ _href "https://policies.google.com/terms"; _target "_blank" ] [ str "Google" ]
|
||||||
|
str ")."
|
||||||
|
]
|
||||||
|
]
|
||||||
|
div [ _class "list-group-item" ] [
|
||||||
|
h3 [] [ str "4. Liability" ]
|
||||||
|
p [ _class "card-text" ] [
|
||||||
|
rawText "This service is provided “as is”, and no warranty (express or implied) "
|
||||||
|
str "exists. The service and its developers may not be held liable for any damages that may "
|
||||||
|
str "arise through the use of this service."
|
||||||
|
]
|
||||||
|
]
|
||||||
|
div [ _class "list-group-item" ] [
|
||||||
|
h3 [] [ str "5. Updates to Terms" ]
|
||||||
|
p [ _class "card-text" ] [
|
||||||
|
str "These terms and conditions may be updated at any time, and this service does not have the "
|
||||||
|
str "capability to notify users when these change. The date at the top of the page will be "
|
||||||
|
str "updated when any of the text of these terms is updated."
|
||||||
|
]
|
||||||
|
]
|
||||||
|
]
|
||||||
|
]
|
||||||
|
p [ _class "pt-3" ] [
|
||||||
|
str "You may also wish to review our "
|
||||||
|
pageLink "/legal/privacy-policy" [] [ str "privacy policy" ]
|
||||||
|
str " to learn how we handle your data."
|
||||||
|
]
|
||||||
|
]
|
||||||
270
src/MyPrayerJournal/Views/Request.fs
Normal file
270
src/MyPrayerJournal/Views/Request.fs
Normal file
@@ -0,0 +1,270 @@
|
|||||||
|
/// Views for request pages and components
|
||||||
|
module MyPrayerJournal.Views.Request
|
||||||
|
|
||||||
|
open Giraffe.Htmx
|
||||||
|
open Giraffe.ViewEngine
|
||||||
|
open Giraffe.ViewEngine.Htmx
|
||||||
|
open MyPrayerJournal
|
||||||
|
open NodaTime
|
||||||
|
|
||||||
|
/// Create a request within the list
|
||||||
|
let reqListItem now tz req =
|
||||||
|
let isFuture instant = defaultArg (instant |> Option.map (fun it -> it > now)) false
|
||||||
|
let reqId = RequestId.toString req.RequestId
|
||||||
|
let isAnswered = req.LastStatus = Answered
|
||||||
|
let isSnoozed = isFuture req.SnoozedUntil
|
||||||
|
let isPending = (not isSnoozed) && isFuture req.ShowAfter
|
||||||
|
let btnClass = _class "btn btn-light mx-2"
|
||||||
|
let restoreBtn (link : string) title =
|
||||||
|
button [ btnClass; _hxPatch $"/request/{reqId}/{link}"; _title title ] [ icon "restore" ]
|
||||||
|
div [ _class "list-group-item px-0 d-flex flex-row align-items-start"
|
||||||
|
_hxTarget "this"
|
||||||
|
_hxSwap HxSwap.OuterHtml ] [
|
||||||
|
pageLink $"/request/{reqId}/full" [ btnClass; _title "View Full Request" ] [ icon "description" ]
|
||||||
|
if not isAnswered then pageLink $"/request/{reqId}/edit" [ btnClass; _title "Edit Request" ] [ icon "edit" ]
|
||||||
|
if isSnoozed then restoreBtn "cancel-snooze" "Cancel Snooze"
|
||||||
|
elif isPending then restoreBtn "show" "Show Now"
|
||||||
|
p [ _class "request-text mb-0" ] [
|
||||||
|
str req.Text
|
||||||
|
if isSnoozed || isPending || isAnswered then
|
||||||
|
br []
|
||||||
|
small [ _class "text-muted" ] [
|
||||||
|
if isSnoozed then [ str "Snooze expires "; relativeDate req.SnoozedUntil.Value now tz ]
|
||||||
|
elif isPending then [ str "Request appears next "; relativeDate req.ShowAfter.Value now tz ]
|
||||||
|
else (* isAnswered *) [ str "Answered "; relativeDate req.AsOf now tz ]
|
||||||
|
|> em []
|
||||||
|
]
|
||||||
|
]
|
||||||
|
]
|
||||||
|
|
||||||
|
/// Create a list of requests
|
||||||
|
let reqList now tz reqs =
|
||||||
|
reqs
|
||||||
|
|> List.map (reqListItem now tz)
|
||||||
|
|> div [ _class "list-group" ]
|
||||||
|
|
||||||
|
/// View for Active Requests page
|
||||||
|
let active now tz reqs =
|
||||||
|
article [ _class "container mt-3" ] [
|
||||||
|
h2 [ _class "pb-3" ] [ str "Active Requests" ]
|
||||||
|
if List.isEmpty reqs then
|
||||||
|
noResults "No Active Requests" "/journal" "Return to your journal"
|
||||||
|
[ str "Your prayer journal has no active requests" ]
|
||||||
|
else reqList now tz reqs
|
||||||
|
]
|
||||||
|
|
||||||
|
/// View for Answered Requests page
|
||||||
|
let answered now tz reqs =
|
||||||
|
article [ _class "container mt-3" ] [
|
||||||
|
h2 [ _class "pb-3" ] [ str "Answered Requests" ]
|
||||||
|
if List.isEmpty reqs then
|
||||||
|
noResults "No Answered Requests" "/journal" "Return to your journal" [
|
||||||
|
str "Your prayer journal has no answered requests; once you have marked one as "
|
||||||
|
rawText "“Answered”, it will appear here"
|
||||||
|
]
|
||||||
|
else reqList now tz reqs
|
||||||
|
]
|
||||||
|
|
||||||
|
/// View for Snoozed Requests page
|
||||||
|
let snoozed now tz reqs =
|
||||||
|
article [ _class "container mt-3" ] [
|
||||||
|
h2 [ _class "pb-3" ] [ str "Snoozed Requests" ]
|
||||||
|
reqList now tz reqs
|
||||||
|
]
|
||||||
|
|
||||||
|
/// View for Full Request page
|
||||||
|
let full (clock : IClock) tz (req : Request) =
|
||||||
|
let now = clock.GetCurrentInstant ()
|
||||||
|
let answered =
|
||||||
|
req.History
|
||||||
|
|> Array.filter History.isAnswered
|
||||||
|
|> Array.tryHead
|
||||||
|
|> Option.map (fun x -> x.AsOf)
|
||||||
|
let prayed = (req.History |> Array.filter History.isPrayed |> Array.length).ToString "N0"
|
||||||
|
let daysOpen =
|
||||||
|
let asOf = defaultArg answered now
|
||||||
|
((asOf - (req.History |> Array.filter History.isCreated |> Array.head).AsOf).TotalDays |> int).ToString "N0"
|
||||||
|
let lastText =
|
||||||
|
req.History
|
||||||
|
|> Array.filter (fun h -> Option.isSome h.Text)
|
||||||
|
|> Array.sortByDescending (fun h -> h.AsOf)
|
||||||
|
|> Array.map (fun h -> Option.get h.Text)
|
||||||
|
|> Array.head
|
||||||
|
// The history log including notes (and excluding the final entry for answered requests)
|
||||||
|
let log =
|
||||||
|
let toDisp (h : History) = {| asOf = h.AsOf; text = h.Text; status = RequestAction.toString h.Status |}
|
||||||
|
let all =
|
||||||
|
req.Notes
|
||||||
|
|> Array.map (fun n -> {| asOf = n.AsOf; text = Some n.Notes; status = "Notes" |})
|
||||||
|
|> Array.append (req.History |> Array.map toDisp)
|
||||||
|
|> Array.sortByDescending (fun it -> it.asOf)
|
||||||
|
|> List.ofArray
|
||||||
|
// Skip the first entry for answered requests; that info is already displayed
|
||||||
|
match answered with Some _ -> all.Tail | None -> all
|
||||||
|
article [ _class "container mt-3" ] [
|
||||||
|
div [_class "card" ] [
|
||||||
|
h5 [ _class "card-header" ] [ str "Full Prayer Request" ]
|
||||||
|
div [ _class "card-body" ] [
|
||||||
|
h6 [ _class "card-subtitle text-muted mb-2"] [
|
||||||
|
match answered with
|
||||||
|
| Some date ->
|
||||||
|
str "Answered "
|
||||||
|
date.ToDateTimeOffset().ToString ("D", null) |> str
|
||||||
|
str " ("
|
||||||
|
relativeDate date now tz
|
||||||
|
rawText ") • "
|
||||||
|
| None -> ()
|
||||||
|
rawText $"Prayed %s{prayed} times • Open %s{daysOpen} days"
|
||||||
|
]
|
||||||
|
p [ _class "card-text" ] [ str lastText ]
|
||||||
|
]
|
||||||
|
log
|
||||||
|
|> List.map (fun it ->
|
||||||
|
li [ _class "list-group-item" ] [
|
||||||
|
p [ _class "m-0" ] [
|
||||||
|
str it.status
|
||||||
|
rawText " "
|
||||||
|
small [] [ em [] [ it.asOf.ToDateTimeOffset().ToString ("D", null) |> str ] ]
|
||||||
|
]
|
||||||
|
match it.text with
|
||||||
|
| Some txt -> p [ _class "mt-2 mb-0" ] [ str txt ]
|
||||||
|
| None -> ()
|
||||||
|
])
|
||||||
|
|> ul [ _class "list-group list-group-flush" ]
|
||||||
|
]
|
||||||
|
]
|
||||||
|
|
||||||
|
/// View for the edit request component
|
||||||
|
let edit (req : JournalRequest) returnTo isNew =
|
||||||
|
let cancelLink =
|
||||||
|
match returnTo with
|
||||||
|
| "active" -> "/requests/active"
|
||||||
|
| "snoozed" -> "/requests/snoozed"
|
||||||
|
| _ (* "journal" *) -> "/journal"
|
||||||
|
let recurCount =
|
||||||
|
match req.Recurrence with
|
||||||
|
| Immediate -> None
|
||||||
|
| Hours h -> Some h
|
||||||
|
| Days d -> Some d
|
||||||
|
| Weeks w -> Some w
|
||||||
|
|> Option.map string
|
||||||
|
|> Option.defaultValue ""
|
||||||
|
article [ _class "container" ] [
|
||||||
|
h2 [ _class "pb-3" ] [ (match isNew with true -> "Add" | false -> "Edit") |> strf "%s Prayer Request" ]
|
||||||
|
form [ _hxBoost
|
||||||
|
_hxTarget "#top"
|
||||||
|
_hxPushUrl "true"
|
||||||
|
"/request" |> match isNew with true -> _hxPost | false -> _hxPatch ] [
|
||||||
|
input [ _type "hidden"
|
||||||
|
_name "requestId"
|
||||||
|
_value (match isNew with true -> "new" | false -> RequestId.toString req.RequestId) ]
|
||||||
|
input [ _type "hidden"; _name "returnTo"; _value returnTo ]
|
||||||
|
div [ _class "form-floating pb-3" ] [
|
||||||
|
textarea [ _id "requestText"
|
||||||
|
_name "requestText"
|
||||||
|
_class "form-control"
|
||||||
|
_style "min-height: 8rem;"
|
||||||
|
_placeholder "Enter the text of the request"
|
||||||
|
_autofocus; _required ] [ str req.Text ]
|
||||||
|
label [ _for "requestText" ] [ str "Prayer Request" ]
|
||||||
|
]
|
||||||
|
br []
|
||||||
|
if not isNew then
|
||||||
|
div [ _class "pb-3" ] [
|
||||||
|
label [] [ str "Also Mark As" ]
|
||||||
|
br []
|
||||||
|
div [ _class "form-check form-check-inline" ] [
|
||||||
|
input [ _type "radio"
|
||||||
|
_class "form-check-input"
|
||||||
|
_id "sU"
|
||||||
|
_name "status"
|
||||||
|
_value "Updated"
|
||||||
|
_checked ]
|
||||||
|
label [ _for "sU" ] [ str "Updated" ]
|
||||||
|
]
|
||||||
|
div [ _class "form-check form-check-inline" ] [
|
||||||
|
input [ _type "radio"; _class "form-check-input"; _id "sP"; _name "status"; _value "Prayed" ]
|
||||||
|
label [ _for "sP" ] [ str "Prayed" ]
|
||||||
|
]
|
||||||
|
div [ _class "form-check form-check-inline" ] [
|
||||||
|
input [ _type "radio"; _class "form-check-input"; _id "sA"; _name "status"; _value "Answered" ]
|
||||||
|
label [ _for "sA" ] [ str "Answered" ]
|
||||||
|
]
|
||||||
|
]
|
||||||
|
div [ _class "row" ] [
|
||||||
|
div [ _class "col-12 offset-md-2 col-md-8 offset-lg-3 col-lg-6" ] [
|
||||||
|
p [] [
|
||||||
|
strong [] [ rawText "Recurrence " ]
|
||||||
|
em [ _class "text-muted" ] [ rawText "After prayer, request reappears…" ]
|
||||||
|
]
|
||||||
|
div [ _class "d-flex flex-row flex-wrap justify-content-center align-items-center" ] [
|
||||||
|
div [ _class "form-check mx-2" ] [
|
||||||
|
input [ _type "radio"
|
||||||
|
_class "form-check-input"
|
||||||
|
_id "rI"
|
||||||
|
_name "recurType"
|
||||||
|
_value "Immediate"
|
||||||
|
_onclick "mpj.edit.toggleRecurrence(event)"
|
||||||
|
match req.Recurrence with Immediate -> _checked | _ -> () ]
|
||||||
|
label [ _for "rI" ] [ str "Immediately" ]
|
||||||
|
]
|
||||||
|
div [ _class "form-check mx-2"] [
|
||||||
|
input [ _type "radio"
|
||||||
|
_class "form-check-input"
|
||||||
|
_id "rO"
|
||||||
|
_name "recurType"
|
||||||
|
_value "Other"
|
||||||
|
_onclick "mpj.edit.toggleRecurrence(event)"
|
||||||
|
match req.Recurrence with Immediate -> () | _ -> _checked ]
|
||||||
|
label [ _for "rO" ] [ rawText "Every…" ]
|
||||||
|
]
|
||||||
|
div [ _class "form-floating mx-2"] [
|
||||||
|
input [ _type "number"
|
||||||
|
_class "form-control"
|
||||||
|
_id "recurCount"
|
||||||
|
_name "recurCount"
|
||||||
|
_placeholder "0"
|
||||||
|
_value recurCount
|
||||||
|
_style "width:6rem;"
|
||||||
|
_required
|
||||||
|
match req.Recurrence with Immediate -> _disabled | _ -> () ]
|
||||||
|
label [ _for "recurCount" ] [ str "Count" ]
|
||||||
|
]
|
||||||
|
div [ _class "form-floating mx-2" ] [
|
||||||
|
select [ _class "form-control"
|
||||||
|
_id "recurInterval"
|
||||||
|
_name "recurInterval"
|
||||||
|
_style "width:6rem;"
|
||||||
|
_required
|
||||||
|
match req.Recurrence with Immediate -> _disabled | _ -> () ] [
|
||||||
|
option [ _value "Hours"; match req.Recurrence with Hours _ -> _selected | _ -> () ] [
|
||||||
|
str "hours"
|
||||||
|
]
|
||||||
|
option [ _value "Days"; match req.Recurrence with Days _ -> _selected | _ -> () ] [
|
||||||
|
str "days"
|
||||||
|
]
|
||||||
|
option [ _value "Weeks"; match req.Recurrence with Weeks _ -> _selected | _ -> () ] [
|
||||||
|
str "weeks"
|
||||||
|
]
|
||||||
|
]
|
||||||
|
label [ _form "recurInterval" ] [ str "Interval" ]
|
||||||
|
]
|
||||||
|
]
|
||||||
|
]
|
||||||
|
]
|
||||||
|
div [ _class "text-end pt-3" ] [
|
||||||
|
button [ _class "btn btn-primary me-2"; _type "submit" ] [ icon "save"; str " Save" ]
|
||||||
|
pageLink cancelLink [ _class "btn btn-secondary ms-2" ] [ icon "arrow_back"; str " Cancel" ]
|
||||||
|
]
|
||||||
|
]
|
||||||
|
]
|
||||||
|
|
||||||
|
/// Display a list of notes for a request
|
||||||
|
let notes now tz notes =
|
||||||
|
let toItem (note : Note) =
|
||||||
|
p [] [ small [ _class "text-muted" ] [ relativeDate note.AsOf now tz ]; br []; str note.Notes ]
|
||||||
|
[ p [ _class "text-center" ] [ strong [] [ str "Prior Notes for This Request" ] ]
|
||||||
|
match notes with
|
||||||
|
| [] -> p [ _class "text-center text-muted" ] [ str "There are no prior notes for this request" ]
|
||||||
|
| _ -> yield! notes |> List.map toItem
|
||||||
|
]
|
||||||
@@ -1,4 +1,7 @@
|
|||||||
{
|
{
|
||||||
|
"ConnectionStrings": {
|
||||||
|
"db": "Filename=./mpj.db"
|
||||||
|
},
|
||||||
"Kestrel": {
|
"Kestrel": {
|
||||||
"EndPoints": {
|
"EndPoints": {
|
||||||
"Http": {
|
"Http": {
|
||||||
7
src/MyPrayerJournal/wwwroot/script/bootstrap.bundle.min.js
vendored
Normal file
7
src/MyPrayerJournal/wwwroot/script/bootstrap.bundle.min.js
vendored
Normal file
File diff suppressed because one or more lines are too long
1
src/MyPrayerJournal/wwwroot/script/htmx.min.js
vendored
Normal file
1
src/MyPrayerJournal/wwwroot/script/htmx.min.js
vendored
Normal file
File diff suppressed because one or more lines are too long
104
src/MyPrayerJournal/wwwroot/script/mpj.js
Normal file
104
src/MyPrayerJournal/wwwroot/script/mpj.js
Normal file
@@ -0,0 +1,104 @@
|
|||||||
|
"use strict"
|
||||||
|
|
||||||
|
/** myPrayerJournal script */
|
||||||
|
this.mpj = {
|
||||||
|
/**
|
||||||
|
* Show a message via toast
|
||||||
|
* @param {string} message The message to show
|
||||||
|
*/
|
||||||
|
showToast (message) {
|
||||||
|
const [level, msg] = message.split("|||")
|
||||||
|
|
||||||
|
let header
|
||||||
|
if (level !== "success") {
|
||||||
|
const heading = typ => `<span class="me-auto"><strong>${typ.toUpperCase()}</strong></span>`
|
||||||
|
|
||||||
|
header = document.createElement("div")
|
||||||
|
header.className = "toast-header"
|
||||||
|
header.innerHTML = heading(level === "warning" ? level : "error")
|
||||||
|
|
||||||
|
const close = document.createElement("button")
|
||||||
|
close.type = "button"
|
||||||
|
close.className = "btn-close"
|
||||||
|
close.setAttribute("data-bs-dismiss", "toast")
|
||||||
|
close.setAttribute("aria-label", "Close")
|
||||||
|
header.appendChild(close)
|
||||||
|
}
|
||||||
|
|
||||||
|
const body = document.createElement("div")
|
||||||
|
body.className = "toast-body"
|
||||||
|
body.innerText = msg
|
||||||
|
|
||||||
|
const toastEl = document.createElement("div")
|
||||||
|
toastEl.className = `toast bg-${level === "error" ? "danger" : level} text-white`
|
||||||
|
toastEl.setAttribute("role", "alert")
|
||||||
|
toastEl.setAttribute("aria-live", "assertlive")
|
||||||
|
toastEl.setAttribute("aria-atomic", "true")
|
||||||
|
toastEl.addEventListener("hidden.bs.toast", e => e.target.remove())
|
||||||
|
if (header) toastEl.appendChild(header)
|
||||||
|
|
||||||
|
toastEl.appendChild(body)
|
||||||
|
document.getElementById("toasts").appendChild(toastEl)
|
||||||
|
new bootstrap.Toast(toastEl, { autohide: level === "success" }).show()
|
||||||
|
},
|
||||||
|
/**
|
||||||
|
* Load local version of Bootstrap CSS if the CDN load failed
|
||||||
|
*/
|
||||||
|
ensureCss () {
|
||||||
|
let loaded = false
|
||||||
|
for (let i = 0; !loaded && i < document.styleSheets.length; i++) {
|
||||||
|
loaded = document.styleSheets[i].href.endsWith("bootstrap.min.css")
|
||||||
|
}
|
||||||
|
if (!loaded) {
|
||||||
|
const css = document.createElement("link")
|
||||||
|
css.rel = "stylesheet"
|
||||||
|
css.href = "/style/bootstrap.min.css"
|
||||||
|
document.getElementsByTagName("head")[0].appendChild(css)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
/** Script for the request edit component */
|
||||||
|
edit: {
|
||||||
|
/**
|
||||||
|
* Toggle the recurrence input fields
|
||||||
|
* @param {Event} e The click event
|
||||||
|
*/
|
||||||
|
toggleRecurrence ({ target }) {
|
||||||
|
const isDisabled = target.value === "Immediate"
|
||||||
|
;["recurCount", "recurInterval"].forEach(it => document.getElementById(it).disabled = isDisabled)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
/**
|
||||||
|
* The time zone of the current browser
|
||||||
|
* @type {string}
|
||||||
|
**/
|
||||||
|
timeZone: undefined,
|
||||||
|
/**
|
||||||
|
* Derive the time zone from the current browser
|
||||||
|
*/
|
||||||
|
deriveTimeZone () {
|
||||||
|
try {
|
||||||
|
this.timeZone = (new Intl.DateTimeFormat()).resolvedOptions().timeZone
|
||||||
|
} catch (_) { }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
htmx.on("htmx:afterOnLoad", function (evt) {
|
||||||
|
const hdrs = evt.detail.xhr.getAllResponseHeaders()
|
||||||
|
// Show a message if there was one in the response
|
||||||
|
if (hdrs.indexOf("x-toast") >= 0) {
|
||||||
|
mpj.showToast(evt.detail.xhr.getResponseHeader("x-toast"))
|
||||||
|
}
|
||||||
|
// Hide a modal window if requested
|
||||||
|
if (hdrs.indexOf("x-hide-modal") >= 0) {
|
||||||
|
document.getElementById(evt.detail.xhr.getResponseHeader("x-hide-modal") + "Dismiss").click()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
htmx.on("htmx:configRequest", function (evt) {
|
||||||
|
// Send the user's current time zone so that we can display local time
|
||||||
|
if (mpj.timeZone) {
|
||||||
|
evt.detail.headers["X-Time-Zone"] = mpj.timeZone
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
mpj.deriveTimeZone()
|
||||||
7
src/MyPrayerJournal/wwwroot/style/bootstrap.min.css
vendored
Normal file
7
src/MyPrayerJournal/wwwroot/style/bootstrap.min.css
vendored
Normal file
File diff suppressed because one or more lines are too long
57
src/MyPrayerJournal/wwwroot/style/style.css
Normal file
57
src/MyPrayerJournal/wwwroot/style/style.css
Normal file
@@ -0,0 +1,57 @@
|
|||||||
|
|
||||||
|
nav {
|
||||||
|
background-color: green;
|
||||||
|
}
|
||||||
|
nav .m {
|
||||||
|
font-weight: 100;
|
||||||
|
}
|
||||||
|
nav .p {
|
||||||
|
font-weight: 400;
|
||||||
|
}
|
||||||
|
nav .j {
|
||||||
|
font-weight: 700;
|
||||||
|
}
|
||||||
|
.nav-item a:link,
|
||||||
|
.nav-item a:visited {
|
||||||
|
padding: .5rem 1rem;
|
||||||
|
margin: 0 .5rem;
|
||||||
|
border-radius: .5rem;
|
||||||
|
color: white;
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
.nav-item a:hover {
|
||||||
|
cursor: pointer;
|
||||||
|
background-color: rgba(255, 255, 255, .2);
|
||||||
|
}
|
||||||
|
.nav-item a.is-active-route {
|
||||||
|
border-top-left-radius: 0;
|
||||||
|
border-top-right-radius: 0;
|
||||||
|
border-top: solid 4px rgba(255, 255, 255, .3);
|
||||||
|
}
|
||||||
|
|
||||||
|
form {
|
||||||
|
max-width: 60rem;
|
||||||
|
margin: auto;
|
||||||
|
}
|
||||||
|
.action-cell .material-icons {
|
||||||
|
font-size: 1.1rem ;
|
||||||
|
}
|
||||||
|
.material-icons {
|
||||||
|
vertical-align: bottom;
|
||||||
|
}
|
||||||
|
#toastHost {
|
||||||
|
position: sticky;
|
||||||
|
bottom: 0;
|
||||||
|
}
|
||||||
|
.request-text {
|
||||||
|
white-space: pre-line
|
||||||
|
}
|
||||||
|
|
||||||
|
footer {
|
||||||
|
border-top: solid 1px lightgray;
|
||||||
|
margin: 1rem -1rem 0;
|
||||||
|
padding: 0 1rem;
|
||||||
|
}
|
||||||
|
footer p {
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
@@ -1,275 +0,0 @@
|
|||||||
namespace MyPrayerJournal
|
|
||||||
|
|
||||||
open FSharp.Control.Tasks.V2.ContextInsensitive
|
|
||||||
open Microsoft.EntityFrameworkCore
|
|
||||||
open Microsoft.FSharpLu
|
|
||||||
|
|
||||||
/// Entities for use in the data model for myPrayerJournal
|
|
||||||
[<AutoOpen>]
|
|
||||||
module Entities =
|
|
||||||
|
|
||||||
open FSharp.EFCore.OptionConverter
|
|
||||||
open System.Collections.Generic
|
|
||||||
|
|
||||||
/// Type alias for a Collision-resistant Unique IDentifier
|
|
||||||
type Cuid = string
|
|
||||||
|
|
||||||
/// Request ID is a CUID
|
|
||||||
type RequestId = Cuid
|
|
||||||
|
|
||||||
/// User ID is a string (the "sub" part of the JWT)
|
|
||||||
type UserId = string
|
|
||||||
|
|
||||||
/// History is a record of action taken on a prayer request, including updates to its text
|
|
||||||
type [<CLIMutable; NoComparison; NoEquality>] History =
|
|
||||||
{ /// The ID of the request to which this history entry applies
|
|
||||||
requestId : RequestId
|
|
||||||
/// The time when this history entry was made
|
|
||||||
asOf : int64
|
|
||||||
/// The status for this history entry
|
|
||||||
status : string
|
|
||||||
/// The text of the update, if applicable
|
|
||||||
text : string option
|
|
||||||
}
|
|
||||||
with
|
|
||||||
/// An empty history entry
|
|
||||||
static member empty =
|
|
||||||
{ requestId = ""
|
|
||||||
asOf = 0L
|
|
||||||
status = ""
|
|
||||||
text = None
|
|
||||||
}
|
|
||||||
|
|
||||||
static member configureEF (mb : ModelBuilder) =
|
|
||||||
mb.Entity<History> (
|
|
||||||
fun m ->
|
|
||||||
m.ToTable "history" |> ignore
|
|
||||||
m.HasKey ("requestId", "asOf") |> ignore
|
|
||||||
m.Property(fun e -> e.requestId).IsRequired () |> ignore
|
|
||||||
m.Property(fun e -> e.asOf).IsRequired () |> ignore
|
|
||||||
m.Property(fun e -> e.status).IsRequired() |> ignore
|
|
||||||
m.Property(fun e -> e.text) |> ignore)
|
|
||||||
|> ignore
|
|
||||||
let typ = mb.Model.FindEntityType(typeof<History>)
|
|
||||||
let prop = typ.FindProperty("text")
|
|
||||||
mb.Model.FindEntityType(typeof<History>).FindProperty("text").SetValueConverter (OptionConverter<string> ())
|
|
||||||
|
|
||||||
/// Note is a note regarding a prayer request that does not result in an update to its text
|
|
||||||
and [<CLIMutable; NoComparison; NoEquality>] Note =
|
|
||||||
{ /// The ID of the request to which this note applies
|
|
||||||
requestId : RequestId
|
|
||||||
/// The time when this note was made
|
|
||||||
asOf : int64
|
|
||||||
/// The text of the notes
|
|
||||||
notes : string
|
|
||||||
}
|
|
||||||
with
|
|
||||||
/// An empty note
|
|
||||||
static member empty =
|
|
||||||
{ requestId = ""
|
|
||||||
asOf = 0L
|
|
||||||
notes = ""
|
|
||||||
}
|
|
||||||
|
|
||||||
static member configureEF (mb : ModelBuilder) =
|
|
||||||
mb.Entity<Note> (
|
|
||||||
fun m ->
|
|
||||||
m.ToTable "note" |> ignore
|
|
||||||
m.HasKey ("requestId", "asOf") |> ignore
|
|
||||||
m.Property(fun e -> e.requestId).IsRequired () |> ignore
|
|
||||||
m.Property(fun e -> e.asOf).IsRequired () |> ignore
|
|
||||||
m.Property(fun e -> e.notes).IsRequired () |> ignore)
|
|
||||||
|> ignore
|
|
||||||
|
|
||||||
/// Request is the identifying record for a prayer request
|
|
||||||
and [<CLIMutable; NoComparison; NoEquality>] Request =
|
|
||||||
{ /// The ID of the request
|
|
||||||
requestId : RequestId
|
|
||||||
/// The time this request was initially entered
|
|
||||||
enteredOn : int64
|
|
||||||
/// The ID of the user to whom this request belongs ("sub" from the JWT)
|
|
||||||
userId : string
|
|
||||||
/// The time at which this request should reappear in the user's journal by manual user choice
|
|
||||||
snoozedUntil : int64
|
|
||||||
/// The time at which this request should reappear in the user's journal by recurrence
|
|
||||||
showAfter : int64
|
|
||||||
/// The type of recurrence for this request
|
|
||||||
recurType : string
|
|
||||||
/// How many of the recurrence intervals should occur between appearances in the journal
|
|
||||||
recurCount : int16
|
|
||||||
/// The history entries for this request
|
|
||||||
history : ICollection<History>
|
|
||||||
/// The notes for this request
|
|
||||||
notes : ICollection<Note>
|
|
||||||
}
|
|
||||||
with
|
|
||||||
/// An empty request
|
|
||||||
static member empty =
|
|
||||||
{ requestId = ""
|
|
||||||
enteredOn = 0L
|
|
||||||
userId = ""
|
|
||||||
snoozedUntil = 0L
|
|
||||||
showAfter = 0L
|
|
||||||
recurType = "immediate"
|
|
||||||
recurCount = 0s
|
|
||||||
history = List<History> ()
|
|
||||||
notes = List<Note> ()
|
|
||||||
}
|
|
||||||
|
|
||||||
static member configureEF (mb : ModelBuilder) =
|
|
||||||
mb.Entity<Request> (
|
|
||||||
fun m ->
|
|
||||||
m.ToTable "request" |> ignore
|
|
||||||
m.HasKey(fun e -> e.requestId :> obj) |> ignore
|
|
||||||
m.Property(fun e -> e.requestId).IsRequired () |> ignore
|
|
||||||
m.Property(fun e -> e.enteredOn).IsRequired () |> ignore
|
|
||||||
m.Property(fun e -> e.userId).IsRequired () |> ignore
|
|
||||||
m.Property(fun e -> e.snoozedUntil).IsRequired () |> ignore
|
|
||||||
m.Property(fun e -> e.showAfter).IsRequired () |> ignore
|
|
||||||
m.Property(fun e -> e.recurType).IsRequired() |> ignore
|
|
||||||
m.Property(fun e -> e.recurCount).IsRequired() |> ignore
|
|
||||||
m.HasMany(fun e -> e.history :> IEnumerable<History>)
|
|
||||||
.WithOne()
|
|
||||||
.HasForeignKey(fun e -> e.requestId :> obj)
|
|
||||||
|> ignore
|
|
||||||
m.HasMany(fun e -> e.notes :> IEnumerable<Note>)
|
|
||||||
.WithOne()
|
|
||||||
.HasForeignKey(fun e -> e.requestId :> obj)
|
|
||||||
|> ignore)
|
|
||||||
|> ignore
|
|
||||||
|
|
||||||
/// JournalRequest is the form of a prayer request returned for the request journal display. It also contains
|
|
||||||
/// properties that may be filled for history and notes
|
|
||||||
[<CLIMutable; NoComparison; NoEquality>]
|
|
||||||
type JournalRequest =
|
|
||||||
{ /// The ID of the request
|
|
||||||
requestId : RequestId
|
|
||||||
/// The ID of the user to whom the request belongs
|
|
||||||
userId : string
|
|
||||||
/// The current text of the request
|
|
||||||
text : string
|
|
||||||
/// The last time action was taken on the request
|
|
||||||
asOf : int64
|
|
||||||
/// The last status for the request
|
|
||||||
lastStatus : string
|
|
||||||
/// The time that this request should reappear in the user's journal
|
|
||||||
snoozedUntil : int64
|
|
||||||
/// The time after which this request should reappear in the user's journal by configured recurrence
|
|
||||||
showAfter : int64
|
|
||||||
/// The type of recurrence for this request
|
|
||||||
recurType : string
|
|
||||||
/// How many of the recurrence intervals should occur between appearances in the journal
|
|
||||||
recurCount : int16
|
|
||||||
/// History entries for the request
|
|
||||||
history : History list
|
|
||||||
/// Note entries for the request
|
|
||||||
notes : Note list
|
|
||||||
}
|
|
||||||
with
|
|
||||||
static member configureEF (mb : ModelBuilder) =
|
|
||||||
mb.Query<JournalRequest> (
|
|
||||||
fun m ->
|
|
||||||
m.ToView "journal" |> ignore
|
|
||||||
m.Ignore(fun e -> e.history :> obj) |> ignore
|
|
||||||
m.Ignore(fun e -> e.notes :> obj) |> ignore)
|
|
||||||
|> ignore
|
|
||||||
|
|
||||||
|
|
||||||
open System.Linq
|
|
||||||
|
|
||||||
/// Data context
|
|
||||||
type AppDbContext (opts : DbContextOptions<AppDbContext>) =
|
|
||||||
inherit DbContext (opts)
|
|
||||||
|
|
||||||
[<DefaultValue>]
|
|
||||||
val mutable private history : DbSet<History>
|
|
||||||
[<DefaultValue>]
|
|
||||||
val mutable private notes : DbSet<Note>
|
|
||||||
[<DefaultValue>]
|
|
||||||
val mutable private requests : DbSet<Request>
|
|
||||||
[<DefaultValue>]
|
|
||||||
val mutable private journal : DbQuery<JournalRequest>
|
|
||||||
|
|
||||||
member this.History
|
|
||||||
with get () = this.history
|
|
||||||
and set v = this.history <- v
|
|
||||||
member this.Notes
|
|
||||||
with get () = this.notes
|
|
||||||
and set v = this.notes <- v
|
|
||||||
member this.Requests
|
|
||||||
with get () = this.requests
|
|
||||||
and set v = this.requests <- v
|
|
||||||
member this.Journal
|
|
||||||
with get () = this.journal
|
|
||||||
and set v = this.journal <- v
|
|
||||||
|
|
||||||
override __.OnModelCreating (mb : ModelBuilder) =
|
|
||||||
base.OnModelCreating mb
|
|
||||||
[ History.configureEF
|
|
||||||
Note.configureEF
|
|
||||||
Request.configureEF
|
|
||||||
JournalRequest.configureEF
|
|
||||||
]
|
|
||||||
|> List.iter (fun x -> x mb)
|
|
||||||
|
|
||||||
/// Register a disconnected entity with the context, having the given state
|
|
||||||
member private this.RegisterAs<'TEntity when 'TEntity : not struct> state e =
|
|
||||||
this.Entry<'TEntity>(e).State <- state
|
|
||||||
|
|
||||||
/// Add an entity instance to the context
|
|
||||||
member this.AddEntry e =
|
|
||||||
this.RegisterAs EntityState.Added e
|
|
||||||
|
|
||||||
/// Update the entity instance's values
|
|
||||||
member this.UpdateEntry e =
|
|
||||||
this.RegisterAs EntityState.Modified e
|
|
||||||
|
|
||||||
/// Retrieve all answered requests for the given user
|
|
||||||
member this.AnsweredRequests userId : JournalRequest seq =
|
|
||||||
upcast this.Journal
|
|
||||||
.Where(fun r -> r.userId = userId && r.lastStatus = "Answered")
|
|
||||||
.OrderByDescending(fun r -> r.asOf)
|
|
||||||
|
|
||||||
/// Retrieve the user's current journal
|
|
||||||
member this.JournalByUserId userId : JournalRequest seq =
|
|
||||||
upcast this.Journal
|
|
||||||
.Where(fun r -> r.userId = userId && r.lastStatus <> "Answered")
|
|
||||||
.OrderBy(fun r -> r.showAfter)
|
|
||||||
|
|
||||||
/// Retrieve a request by its ID and user ID
|
|
||||||
member this.TryRequestById reqId userId =
|
|
||||||
task {
|
|
||||||
let! req = this.Requests.AsNoTracking().FirstOrDefaultAsync(fun r -> r.requestId = reqId && r.userId = userId)
|
|
||||||
return Option.fromObject req
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Retrieve notes for a request by its ID and user ID
|
|
||||||
member this.NotesById reqId userId =
|
|
||||||
task {
|
|
||||||
match! this.TryRequestById reqId userId with
|
|
||||||
| Some _ -> return this.Notes.AsNoTracking().Where(fun n -> n.requestId = reqId) |> List.ofSeq
|
|
||||||
| None -> return []
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Retrieve a journal request by its ID and user ID
|
|
||||||
member this.TryJournalById reqId userId =
|
|
||||||
task {
|
|
||||||
let! req = this.Journal.FirstOrDefaultAsync(fun r -> r.requestId = reqId && r.userId = userId)
|
|
||||||
return Option.fromObject req
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Retrieve a request, including its history and notes, by its ID and user ID
|
|
||||||
member this.TryFullRequestById requestId userId =
|
|
||||||
task {
|
|
||||||
match! this.TryJournalById requestId userId with
|
|
||||||
| Some req ->
|
|
||||||
let! fullReq =
|
|
||||||
this.Requests.AsNoTracking()
|
|
||||||
.Include(fun r -> r.history)
|
|
||||||
.Include(fun r -> r.notes)
|
|
||||||
.FirstOrDefaultAsync(fun r -> r.requestId = requestId && r.userId = userId)
|
|
||||||
match Option.fromObject fullReq with
|
|
||||||
| Some _ -> return Some { req with history = List.ofSeq fullReq.history; notes = List.ofSeq fullReq.notes }
|
|
||||||
| None -> return None
|
|
||||||
| None -> return None
|
|
||||||
}
|
|
||||||
@@ -1,321 +0,0 @@
|
|||||||
/// HTTP handlers for the myPrayerJournal API
|
|
||||||
[<RequireQualifiedAccess>]
|
|
||||||
module MyPrayerJournal.Api.Handlers
|
|
||||||
|
|
||||||
open FSharp.Control.Tasks.V2.ContextInsensitive
|
|
||||||
open Giraffe
|
|
||||||
open MyPrayerJournal
|
|
||||||
open System
|
|
||||||
|
|
||||||
/// Handler to return Vue files
|
|
||||||
module Vue =
|
|
||||||
|
|
||||||
/// The application index page
|
|
||||||
let app : HttpHandler = htmlFile "wwwroot/index.html"
|
|
||||||
|
|
||||||
|
|
||||||
/// Handlers for error conditions
|
|
||||||
module Error =
|
|
||||||
|
|
||||||
open Microsoft.Extensions.Logging
|
|
||||||
|
|
||||||
/// Handle errors
|
|
||||||
let error (ex : Exception) (log : ILogger) =
|
|
||||||
log.LogError (EventId(), ex, "An unhandled exception has occurred while executing the request.")
|
|
||||||
clearResponse >=> setStatusCode 500 >=> json ex.Message
|
|
||||||
|
|
||||||
/// Handle 404s from the API, sending known URL paths to the Vue app so that they can be handled there
|
|
||||||
let notFound : HttpHandler =
|
|
||||||
fun next ctx ->
|
|
||||||
[ "/journal"; "/legal"; "/request"; "/user" ]
|
|
||||||
|> List.filter ctx.Request.Path.Value.StartsWith
|
|
||||||
|> List.length
|
|
||||||
|> function
|
|
||||||
| 0 -> (setStatusCode 404 >=> json ([ "error", "not found" ] |> dict)) next ctx
|
|
||||||
| _ -> Vue.app next ctx
|
|
||||||
|
|
||||||
|
|
||||||
/// Handler helpers
|
|
||||||
[<AutoOpen>]
|
|
||||||
module private Helpers =
|
|
||||||
|
|
||||||
open Microsoft.AspNetCore.Http
|
|
||||||
open System.Threading.Tasks
|
|
||||||
open System.Security.Claims
|
|
||||||
|
|
||||||
/// Get the database context from DI
|
|
||||||
let db (ctx : HttpContext) =
|
|
||||||
ctx.GetService<AppDbContext> ()
|
|
||||||
|
|
||||||
/// Get the user's "sub" claim
|
|
||||||
let user (ctx : HttpContext) =
|
|
||||||
ctx.User.Claims |> Seq.tryFind (fun u -> u.Type = ClaimTypes.NameIdentifier)
|
|
||||||
|
|
||||||
/// Get the current user's ID
|
|
||||||
// NOTE: this may raise if you don't run the request through the authorize handler first
|
|
||||||
let userId ctx =
|
|
||||||
((user >> Option.get) ctx).Value
|
|
||||||
|
|
||||||
/// Return a 201 CREATED response
|
|
||||||
let created next ctx =
|
|
||||||
setStatusCode 201 next ctx
|
|
||||||
|
|
||||||
/// The "now" time in JavaScript
|
|
||||||
let jsNow () =
|
|
||||||
DateTime.UtcNow.Subtract(DateTime (1970, 1, 1, 0, 0, 0)).TotalSeconds |> int64 |> (*) 1000L
|
|
||||||
|
|
||||||
/// Handler to return a 403 Not Authorized reponse
|
|
||||||
let notAuthorized : HttpHandler =
|
|
||||||
setStatusCode 403 >=> fun _ _ -> Task.FromResult<HttpContext option> None
|
|
||||||
|
|
||||||
/// Handler to require authorization
|
|
||||||
let authorize : HttpHandler =
|
|
||||||
fun next ctx -> match user ctx with Some _ -> next ctx | None -> notAuthorized next ctx
|
|
||||||
|
|
||||||
/// Flip JSON result so we can pipe into it
|
|
||||||
let asJson<'T> next ctx (o : 'T) =
|
|
||||||
json o next ctx
|
|
||||||
|
|
||||||
|
|
||||||
/// Strongly-typed models for post requests
|
|
||||||
module Models =
|
|
||||||
|
|
||||||
/// A history entry addition (AKA request update)
|
|
||||||
[<CLIMutable>]
|
|
||||||
type HistoryEntry =
|
|
||||||
{ /// The status of the history update
|
|
||||||
status : string
|
|
||||||
/// The text of the update
|
|
||||||
updateText : string
|
|
||||||
}
|
|
||||||
|
|
||||||
/// An additional note
|
|
||||||
[<CLIMutable>]
|
|
||||||
type NoteEntry =
|
|
||||||
{ /// The notes being added
|
|
||||||
notes : string
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Recurrence update
|
|
||||||
[<CLIMutable>]
|
|
||||||
type Recurrence =
|
|
||||||
{ /// The recurrence type
|
|
||||||
recurType : string
|
|
||||||
/// The recurrence cound
|
|
||||||
recurCount : int16
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A prayer request
|
|
||||||
[<CLIMutable>]
|
|
||||||
type Request =
|
|
||||||
{ /// The text of the request
|
|
||||||
requestText : string
|
|
||||||
/// The recurrence type
|
|
||||||
recurType : string
|
|
||||||
/// The recurrence count
|
|
||||||
recurCount : int16
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Reset the "showAfter" property on a request
|
|
||||||
[<CLIMutable>]
|
|
||||||
type Show =
|
|
||||||
{ /// The time after which the request should appear
|
|
||||||
showAfter : int64
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The time until which a request should not appear in the journal
|
|
||||||
[<CLIMutable>]
|
|
||||||
type SnoozeUntil =
|
|
||||||
{ /// The time at which the request should reappear
|
|
||||||
until : int64
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
/// /api/journal URLs
|
|
||||||
module Journal =
|
|
||||||
|
|
||||||
/// GET /api/journal
|
|
||||||
let journal : HttpHandler =
|
|
||||||
authorize
|
|
||||||
>=> fun next ctx ->
|
|
||||||
userId ctx
|
|
||||||
|> (db ctx).JournalByUserId
|
|
||||||
|> asJson next ctx
|
|
||||||
|
|
||||||
|
|
||||||
/// /api/request URLs
|
|
||||||
module Request =
|
|
||||||
|
|
||||||
open NCuid
|
|
||||||
|
|
||||||
/// Ticks per recurrence
|
|
||||||
let private recurrence =
|
|
||||||
[ "immediate", 0L
|
|
||||||
"hours", 3600000L
|
|
||||||
"days", 86400000L
|
|
||||||
"weeks", 604800000L
|
|
||||||
]
|
|
||||||
|> Map.ofList
|
|
||||||
|
|
||||||
/// POST /api/request
|
|
||||||
let add : HttpHandler =
|
|
||||||
authorize
|
|
||||||
>=> fun next ctx ->
|
|
||||||
task {
|
|
||||||
let! r = ctx.BindJsonAsync<Models.Request> ()
|
|
||||||
let db = db ctx
|
|
||||||
let reqId = Cuid.Generate ()
|
|
||||||
let usrId = userId ctx
|
|
||||||
let now = jsNow ()
|
|
||||||
{ Request.empty with
|
|
||||||
requestId = reqId
|
|
||||||
userId = usrId
|
|
||||||
enteredOn = now
|
|
||||||
showAfter = now
|
|
||||||
recurType = r.recurType
|
|
||||||
recurCount = r.recurCount
|
|
||||||
}
|
|
||||||
|> db.AddEntry
|
|
||||||
{ History.empty with
|
|
||||||
requestId = reqId
|
|
||||||
asOf = now
|
|
||||||
status = "Created"
|
|
||||||
text = Some r.requestText
|
|
||||||
}
|
|
||||||
|> db.AddEntry
|
|
||||||
let! _ = db.SaveChangesAsync ()
|
|
||||||
match! db.TryJournalById reqId usrId with
|
|
||||||
| Some req -> return! (setStatusCode 201 >=> json req) next ctx
|
|
||||||
| None -> return! Error.notFound next ctx
|
|
||||||
}
|
|
||||||
|
|
||||||
/// POST /api/request/[req-id]/history
|
|
||||||
let addHistory reqId : HttpHandler =
|
|
||||||
authorize
|
|
||||||
>=> fun next ctx ->
|
|
||||||
task {
|
|
||||||
let db = db ctx
|
|
||||||
match! db.TryRequestById reqId (userId ctx) with
|
|
||||||
| Some req ->
|
|
||||||
let! hist = ctx.BindJsonAsync<Models.HistoryEntry> ()
|
|
||||||
let now = jsNow ()
|
|
||||||
{ History.empty with
|
|
||||||
requestId = reqId
|
|
||||||
asOf = now
|
|
||||||
status = hist.status
|
|
||||||
text = match hist.updateText with null | "" -> None | x -> Some x
|
|
||||||
}
|
|
||||||
|> db.AddEntry
|
|
||||||
match hist.status with
|
|
||||||
| "Prayed" ->
|
|
||||||
db.UpdateEntry { req with showAfter = now + (recurrence.[req.recurType] * int64 req.recurCount) }
|
|
||||||
| _ -> ()
|
|
||||||
let! _ = db.SaveChangesAsync ()
|
|
||||||
return! created next ctx
|
|
||||||
| None -> return! Error.notFound next ctx
|
|
||||||
}
|
|
||||||
|
|
||||||
/// POST /api/request/[req-id]/note
|
|
||||||
let addNote reqId : HttpHandler =
|
|
||||||
authorize
|
|
||||||
>=> fun next ctx ->
|
|
||||||
task {
|
|
||||||
let db = db ctx
|
|
||||||
match! db.TryRequestById reqId (userId ctx) with
|
|
||||||
| Some _ ->
|
|
||||||
let! notes = ctx.BindJsonAsync<Models.NoteEntry> ()
|
|
||||||
{ Note.empty with
|
|
||||||
requestId = reqId
|
|
||||||
asOf = jsNow ()
|
|
||||||
notes = notes.notes
|
|
||||||
}
|
|
||||||
|> db.AddEntry
|
|
||||||
let! _ = db.SaveChangesAsync ()
|
|
||||||
return! created next ctx
|
|
||||||
| None -> return! Error.notFound next ctx
|
|
||||||
}
|
|
||||||
|
|
||||||
/// GET /api/requests/answered
|
|
||||||
let answered : HttpHandler =
|
|
||||||
authorize
|
|
||||||
>=> fun next ctx ->
|
|
||||||
userId ctx
|
|
||||||
|> (db ctx).AnsweredRequests
|
|
||||||
|> asJson next ctx
|
|
||||||
|
|
||||||
/// GET /api/request/[req-id]
|
|
||||||
let get reqId : HttpHandler =
|
|
||||||
authorize
|
|
||||||
>=> fun next ctx ->
|
|
||||||
task {
|
|
||||||
match! (db ctx).TryJournalById reqId (userId ctx) with
|
|
||||||
| Some req -> return! json req next ctx
|
|
||||||
| None -> return! Error.notFound next ctx
|
|
||||||
}
|
|
||||||
|
|
||||||
/// GET /api/request/[req-id]/full
|
|
||||||
let getFull reqId : HttpHandler =
|
|
||||||
authorize
|
|
||||||
>=> fun next ctx ->
|
|
||||||
task {
|
|
||||||
match! (db ctx).TryFullRequestById reqId (userId ctx) with
|
|
||||||
| Some req -> return! json req next ctx
|
|
||||||
| None -> return! Error.notFound next ctx
|
|
||||||
}
|
|
||||||
|
|
||||||
/// GET /api/request/[req-id]/notes
|
|
||||||
let getNotes reqId : HttpHandler =
|
|
||||||
authorize
|
|
||||||
>=> fun next ctx ->
|
|
||||||
task {
|
|
||||||
let! notes = (db ctx).NotesById reqId (userId ctx)
|
|
||||||
return! json notes next ctx
|
|
||||||
}
|
|
||||||
|
|
||||||
/// PATCH /api/request/[req-id]/show
|
|
||||||
let show reqId : HttpHandler =
|
|
||||||
authorize
|
|
||||||
>=> fun next ctx ->
|
|
||||||
task {
|
|
||||||
let db = db ctx
|
|
||||||
match! db.TryRequestById reqId (userId ctx) with
|
|
||||||
| Some req ->
|
|
||||||
let! show = ctx.BindJsonAsync<Models.Show> ()
|
|
||||||
{ req with showAfter = show.showAfter }
|
|
||||||
|> db.UpdateEntry
|
|
||||||
let! _ = db.SaveChangesAsync ()
|
|
||||||
return! setStatusCode 204 next ctx
|
|
||||||
| None -> return! Error.notFound next ctx
|
|
||||||
}
|
|
||||||
|
|
||||||
/// PATCH /api/request/[req-id]/snooze
|
|
||||||
let snooze reqId : HttpHandler =
|
|
||||||
authorize
|
|
||||||
>=> fun next ctx ->
|
|
||||||
task {
|
|
||||||
let db = db ctx
|
|
||||||
match! db.TryRequestById reqId (userId ctx) with
|
|
||||||
| Some req ->
|
|
||||||
let! until = ctx.BindJsonAsync<Models.SnoozeUntil> ()
|
|
||||||
{ req with snoozedUntil = until.until; showAfter = until.until }
|
|
||||||
|> db.UpdateEntry
|
|
||||||
let! _ = db.SaveChangesAsync ()
|
|
||||||
return! setStatusCode 204 next ctx
|
|
||||||
| None -> return! Error.notFound next ctx
|
|
||||||
}
|
|
||||||
|
|
||||||
/// PATCH /api/request/[req-id]/recurrence
|
|
||||||
let updateRecurrence reqId : HttpHandler =
|
|
||||||
authorize
|
|
||||||
>=> fun next ctx ->
|
|
||||||
task {
|
|
||||||
let db = db ctx
|
|
||||||
match! db.TryRequestById reqId (userId ctx) with
|
|
||||||
| Some req ->
|
|
||||||
let! recur = ctx.BindJsonAsync<Models.Recurrence> ()
|
|
||||||
{ req with recurType = recur.recurType; recurCount = recur.recurCount }
|
|
||||||
|> db.UpdateEntry
|
|
||||||
let! _ = db.SaveChangesAsync ()
|
|
||||||
return! setStatusCode 204 next ctx
|
|
||||||
| None -> return! Error.notFound next ctx
|
|
||||||
}
|
|
||||||
@@ -1,33 +0,0 @@
|
|||||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
|
||||||
|
|
||||||
<PropertyGroup>
|
|
||||||
<TargetFramework>netcoreapp2.2</TargetFramework>
|
|
||||||
</PropertyGroup>
|
|
||||||
|
|
||||||
<ItemGroup>
|
|
||||||
<Compile Include="Data.fs" />
|
|
||||||
<Compile Include="Handlers.fs" />
|
|
||||||
<Compile Include="Program.fs" />
|
|
||||||
</ItemGroup>
|
|
||||||
|
|
||||||
<ItemGroup>
|
|
||||||
<PackageReference Include="FSharp.EFCore.OptionConverter" Version="1.0.0" />
|
|
||||||
<PackageReference Include="Giraffe" Version="3.6.0" />
|
|
||||||
<PackageReference Include="Giraffe.TokenRouter" Version="1.0.0" />
|
|
||||||
<PackageReference Include="Microsoft.AspNetCore.App" />
|
|
||||||
<PackageReference Include="Microsoft.FSharpLu" Version="0.10.29" />
|
|
||||||
<PackageReference Include="Microsoft.FSharpLu.Json" Version="0.10.29" />
|
|
||||||
<PackageReference Include="NCuid.NetCore" Version="1.0.1" />
|
|
||||||
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="2.2.0" />
|
|
||||||
<PackageReference Include="TaskBuilder.fs" Version="2.1.0" />
|
|
||||||
</ItemGroup>
|
|
||||||
|
|
||||||
<ItemGroup>
|
|
||||||
<PackageReference Update="FSharp.Core" Version="4.6.2" />
|
|
||||||
</ItemGroup>
|
|
||||||
|
|
||||||
<ItemGroup>
|
|
||||||
<Folder Include="wwwroot\" />
|
|
||||||
</ItemGroup>
|
|
||||||
|
|
||||||
</Project>
|
|
||||||
@@ -1,139 +0,0 @@
|
|||||||
namespace MyPrayerJournal.Api
|
|
||||||
|
|
||||||
open Microsoft.AspNetCore.Builder
|
|
||||||
open Microsoft.AspNetCore.Hosting
|
|
||||||
open System
|
|
||||||
|
|
||||||
/// Configuration functions for the application
|
|
||||||
module Configure =
|
|
||||||
|
|
||||||
open Giraffe
|
|
||||||
open Giraffe.Serialization
|
|
||||||
open Giraffe.TokenRouter
|
|
||||||
open Microsoft.AspNetCore.Authentication.JwtBearer
|
|
||||||
open Microsoft.AspNetCore.Server.Kestrel.Core
|
|
||||||
open Microsoft.EntityFrameworkCore
|
|
||||||
open Microsoft.Extensions.Configuration
|
|
||||||
open Microsoft.Extensions.DependencyInjection
|
|
||||||
open Microsoft.Extensions.Logging
|
|
||||||
open Microsoft.FSharpLu.Json
|
|
||||||
open MyPrayerJournal
|
|
||||||
open Newtonsoft.Json
|
|
||||||
|
|
||||||
/// Set up the configuration for the app
|
|
||||||
let configuration (ctx : WebHostBuilderContext) (cfg : IConfigurationBuilder) =
|
|
||||||
cfg.SetBasePath(ctx.HostingEnvironment.ContentRootPath)
|
|
||||||
.AddJsonFile("appsettings.json", optional = true, reloadOnChange = true)
|
|
||||||
.AddJsonFile(sprintf "appsettings.%s.json" ctx.HostingEnvironment.EnvironmentName)
|
|
||||||
.AddEnvironmentVariables()
|
|
||||||
|> ignore
|
|
||||||
|
|
||||||
/// Configure Kestrel from appsettings.json
|
|
||||||
let kestrel (ctx : WebHostBuilderContext) (opts : KestrelServerOptions) =
|
|
||||||
(ctx.Configuration.GetSection >> opts.Configure >> ignore) "Kestrel"
|
|
||||||
|
|
||||||
/// Custom settings for the JSON serializer (uses compact representation for options and DUs)
|
|
||||||
let jsonSettings =
|
|
||||||
let x = NewtonsoftJsonSerializer.DefaultSettings
|
|
||||||
x.Converters.Add (CompactUnionJsonConverter (true))
|
|
||||||
x.NullValueHandling <- NullValueHandling.Ignore
|
|
||||||
x.MissingMemberHandling <- MissingMemberHandling.Error
|
|
||||||
x.Formatting <- Formatting.Indented
|
|
||||||
x
|
|
||||||
|
|
||||||
/// Configure dependency injection
|
|
||||||
let services (sc : IServiceCollection) =
|
|
||||||
use sp = sc.BuildServiceProvider()
|
|
||||||
let cfg = sp.GetRequiredService<IConfiguration> ()
|
|
||||||
sc.AddGiraffe()
|
|
||||||
.AddAuthentication(
|
|
||||||
/// Use HTTP "Bearer" authentication with JWTs
|
|
||||||
fun opts ->
|
|
||||||
opts.DefaultAuthenticateScheme <- JwtBearerDefaults.AuthenticationScheme
|
|
||||||
opts.DefaultChallengeScheme <- JwtBearerDefaults.AuthenticationScheme)
|
|
||||||
.AddJwtBearer(
|
|
||||||
/// Configure JWT options with Auth0 options from configuration
|
|
||||||
fun opts ->
|
|
||||||
let jwtCfg = cfg.GetSection "Auth0"
|
|
||||||
opts.Authority <- sprintf "https://%s/" jwtCfg.["Domain"]
|
|
||||||
opts.Audience <- jwtCfg.["Id"])
|
|
||||||
|> ignore
|
|
||||||
sc.AddDbContext<AppDbContext>(fun opts -> opts.UseNpgsql(cfg.GetConnectionString "mpj") |> ignore)
|
|
||||||
.AddSingleton<IJsonSerializer>(NewtonsoftJsonSerializer jsonSettings)
|
|
||||||
|> ignore
|
|
||||||
|
|
||||||
/// Routes for the available URLs within myPrayerJournal
|
|
||||||
let webApp =
|
|
||||||
router Handlers.Error.notFound [
|
|
||||||
route "/" Handlers.Vue.app
|
|
||||||
subRoute "/api/" [
|
|
||||||
GET [
|
|
||||||
route "journal" Handlers.Journal.journal
|
|
||||||
subRoute "request" [
|
|
||||||
route "s/answered" Handlers.Request.answered
|
|
||||||
routef "/%s/full" Handlers.Request.getFull
|
|
||||||
routef "/%s/notes" Handlers.Request.getNotes
|
|
||||||
routef "/%s" Handlers.Request.get
|
|
||||||
]
|
|
||||||
]
|
|
||||||
PATCH [
|
|
||||||
subRoute "request" [
|
|
||||||
routef "/%s/recurrence" Handlers.Request.updateRecurrence
|
|
||||||
routef "/%s/show" Handlers.Request.show
|
|
||||||
routef "/%s/snooze" Handlers.Request.snooze
|
|
||||||
]
|
|
||||||
]
|
|
||||||
POST [
|
|
||||||
subRoute "request" [
|
|
||||||
route "" Handlers.Request.add
|
|
||||||
routef "/%s/history" Handlers.Request.addHistory
|
|
||||||
routef "/%s/note" Handlers.Request.addNote
|
|
||||||
]
|
|
||||||
]
|
|
||||||
]
|
|
||||||
]
|
|
||||||
|
|
||||||
/// Configure the web application
|
|
||||||
let application (app : IApplicationBuilder) =
|
|
||||||
let env = app.ApplicationServices.GetService<IHostingEnvironment> ()
|
|
||||||
match env.IsDevelopment () with
|
|
||||||
| true -> app.UseDeveloperExceptionPage ()
|
|
||||||
| false -> app.UseGiraffeErrorHandler Handlers.Error.error
|
|
||||||
|> function
|
|
||||||
| a ->
|
|
||||||
a.UseAuthentication()
|
|
||||||
.UseStaticFiles()
|
|
||||||
.UseGiraffe webApp
|
|
||||||
|> ignore
|
|
||||||
|
|
||||||
/// Configure logging
|
|
||||||
let logging (log : ILoggingBuilder) =
|
|
||||||
let env = log.Services.BuildServiceProvider().GetService<IHostingEnvironment> ()
|
|
||||||
match env.IsDevelopment () with
|
|
||||||
| true -> log
|
|
||||||
| false -> log.AddFilter(fun l -> l > LogLevel.Information)
|
|
||||||
|> function l -> l.AddConsole().AddDebug()
|
|
||||||
|> ignore
|
|
||||||
|
|
||||||
|
|
||||||
module Program =
|
|
||||||
|
|
||||||
open System.IO
|
|
||||||
|
|
||||||
let exitCode = 0
|
|
||||||
|
|
||||||
let CreateWebHostBuilder _ =
|
|
||||||
let contentRoot = Directory.GetCurrentDirectory ()
|
|
||||||
WebHostBuilder()
|
|
||||||
.UseContentRoot(contentRoot)
|
|
||||||
.ConfigureAppConfiguration(Configure.configuration)
|
|
||||||
.UseKestrel(Configure.kestrel)
|
|
||||||
.UseWebRoot(Path.Combine (contentRoot, "wwwroot"))
|
|
||||||
.ConfigureServices(Configure.services)
|
|
||||||
.ConfigureLogging(Configure.logging)
|
|
||||||
.Configure(Action<IApplicationBuilder> Configure.application)
|
|
||||||
|
|
||||||
[<EntryPoint>]
|
|
||||||
let main args =
|
|
||||||
CreateWebHostBuilder(args).Build().Run()
|
|
||||||
exitCode
|
|
||||||
@@ -1,25 +0,0 @@
|
|||||||
|
|
||||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
|
||||||
# Visual Studio 15
|
|
||||||
VisualStudioVersion = 15.0.27703.2035
|
|
||||||
MinimumVisualStudioVersion = 10.0.40219.1
|
|
||||||
Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "MyPrayerJournal.Api", "MyPrayerJournal.Api\MyPrayerJournal.Api.fsproj", "{E0E5240C-00DC-428A-899A-DA4F06625B8A}"
|
|
||||||
EndProject
|
|
||||||
Global
|
|
||||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
|
||||||
Debug|Any CPU = Debug|Any CPU
|
|
||||||
Release|Any CPU = Release|Any CPU
|
|
||||||
EndGlobalSection
|
|
||||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
|
||||||
{E0E5240C-00DC-428A-899A-DA4F06625B8A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
|
||||||
{E0E5240C-00DC-428A-899A-DA4F06625B8A}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
|
||||||
{E0E5240C-00DC-428A-899A-DA4F06625B8A}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
|
||||||
{E0E5240C-00DC-428A-899A-DA4F06625B8A}.Release|Any CPU.Build.0 = Release|Any CPU
|
|
||||||
EndGlobalSection
|
|
||||||
GlobalSection(SolutionProperties) = preSolution
|
|
||||||
HideSolutionNode = FALSE
|
|
||||||
EndGlobalSection
|
|
||||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
|
||||||
SolutionGuid = {7EAB6243-94B3-49A5-BA64-7F01B8BE7CB9}
|
|
||||||
EndGlobalSection
|
|
||||||
EndGlobal
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
> 1%
|
|
||||||
last 2 versions
|
|
||||||
not ie <= 8
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
module.exports = {
|
|
||||||
root: true,
|
|
||||||
env: {
|
|
||||||
node: true
|
|
||||||
},
|
|
||||||
'extends': [
|
|
||||||
'plugin:vue/essential',
|
|
||||||
'@vue/standard'
|
|
||||||
],
|
|
||||||
rules: {
|
|
||||||
'no-console': process.env.NODE_ENV === 'production' ? 'error' : 'off',
|
|
||||||
'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off'
|
|
||||||
},
|
|
||||||
parserOptions: {
|
|
||||||
parser: 'babel-eslint'
|
|
||||||
}
|
|
||||||
}
|
|
||||||
24
src/app/.gitignore
vendored
24
src/app/.gitignore
vendored
@@ -1,24 +0,0 @@
|
|||||||
.DS_Store
|
|
||||||
node_modules
|
|
||||||
/dist
|
|
||||||
|
|
||||||
# local env files
|
|
||||||
.env.local
|
|
||||||
.env.*.local
|
|
||||||
|
|
||||||
# Log files
|
|
||||||
npm-debug.log*
|
|
||||||
yarn-debug.log*
|
|
||||||
yarn-error.log*
|
|
||||||
|
|
||||||
# Editor directories and files
|
|
||||||
.idea
|
|
||||||
.vscode
|
|
||||||
*.suo
|
|
||||||
*.ntvs*
|
|
||||||
*.njsproj
|
|
||||||
*.sln
|
|
||||||
*.sw*
|
|
||||||
|
|
||||||
# Auth0 settings
|
|
||||||
src/auth/auth0-variables.js
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
module.exports = {
|
|
||||||
plugins: {
|
|
||||||
autoprefixer: {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
MIT License
|
|
||||||
|
|
||||||
Copyright (c) 2017 Daniel J. Summers
|
|
||||||
|
|
||||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
||||||
of this software and associated documentation files (the "Software"), to deal
|
|
||||||
in the Software without restriction, including without limitation the rights
|
|
||||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
||||||
copies of the Software, and to permit persons to whom the Software is
|
|
||||||
furnished to do so, subject to the following conditions:
|
|
||||||
|
|
||||||
The above copyright notice and this permission notice shall be included in all
|
|
||||||
copies or substantial portions of the Software.
|
|
||||||
|
|
||||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
||||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
||||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
||||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
||||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
||||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
||||||
SOFTWARE.
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
module.exports = {
|
|
||||||
presets: [
|
|
||||||
'@vue/app'
|
|
||||||
]
|
|
||||||
}
|
|
||||||
33
src/app/composer.json
Normal file
33
src/app/composer.json
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
{
|
||||||
|
"name": "bitbadger/my-prayer-journal",
|
||||||
|
"description": "Minimalist prayer journal to enhance your prayer life",
|
||||||
|
"type": "project",
|
||||||
|
"license": "MIT",
|
||||||
|
"autoload": {
|
||||||
|
"psr-4": {
|
||||||
|
"MyPrayerJournal\\": "lib/",
|
||||||
|
"MyPrayerJournal\\Domain\\": "lib/domain/",
|
||||||
|
"BitBadger\\PgDocuments\\": "lib/documents/"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"authors": [
|
||||||
|
{
|
||||||
|
"name": "Daniel J. Summers",
|
||||||
|
"email": "daniel@bitbadger.solutions"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"require": {
|
||||||
|
"netresearch/jsonmapper": "^4.2",
|
||||||
|
"guzzlehttp/guzzle": "^7.8",
|
||||||
|
"guzzlehttp/psr7": "^2.6",
|
||||||
|
"http-interop/http-factory-guzzle": "^1.2",
|
||||||
|
"auth0/auth0-php": "^8.8",
|
||||||
|
"vlucas/phpdotenv": "^5.5",
|
||||||
|
"visus/cuid2": "^4.0"
|
||||||
|
},
|
||||||
|
"config": {
|
||||||
|
"allow-plugins": {
|
||||||
|
"php-http/discovery": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
2365
src/app/composer.lock
generated
Normal file
2365
src/app/composer.lock
generated
Normal file
File diff suppressed because it is too large
Load Diff
67
src/app/lib/Constants.php
Normal file
67
src/app/lib/Constants.php
Normal file
@@ -0,0 +1,67 @@
|
|||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace MyPrayerJournal;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Constants for use throughout the application
|
||||||
|
*/
|
||||||
|
class Constants
|
||||||
|
{
|
||||||
|
/** @var string The `$_ENV` key for the Auth0 domain configured for myPrayerJournal */
|
||||||
|
const AUTH0_DOMAIN = 'AUTH0_DOMAIN';
|
||||||
|
|
||||||
|
/** @var string The `$_ENV` key for the Auth0 client ID for myPrayerJournal */
|
||||||
|
const AUTH0_CLIENT_ID = 'AUTH0_CLIENT_ID';
|
||||||
|
|
||||||
|
/** @var string The `$_ENV` key for the Auth0 client secret */
|
||||||
|
const AUTH0_CLIENT_SECRET = 'AUTH0_CLIENT_SECRET';
|
||||||
|
|
||||||
|
/** @var string The `$_ENV` key for the Auth0 cookie secret */
|
||||||
|
const AUTH0_COOKIE_SECRET = 'AUTH0_COOKIE_SECRET';
|
||||||
|
|
||||||
|
/** @var string The `$_ENV` key for the base URL for this instance of myPrayerJournal */
|
||||||
|
const BASE_URL = 'AUTH0_BASE_URL';
|
||||||
|
|
||||||
|
/** @var string The Auth0 given name (first name) claim */
|
||||||
|
const CLAIM_GIVEN_NAME = 'given_name';
|
||||||
|
|
||||||
|
/** @var string The Auth0 subscriber (sub) claim */
|
||||||
|
const CLAIM_SUB = 'sub';
|
||||||
|
|
||||||
|
/** @var string The name of the cookie used to persist redirection after Auth0 authentication */
|
||||||
|
const COOKIE_REDIRECT = 'mpjredirect';
|
||||||
|
|
||||||
|
/** @var string the `$_SERVER` key for the HX-Request header */
|
||||||
|
const HEADER_HX_REQUEST = 'HTTP_HX_REQUEST';
|
||||||
|
|
||||||
|
/** @var string The `$_SERVER` key for the HX-History-Restore-Request header */
|
||||||
|
const HEADER_HX_HIST_REQ = 'HTTP_HX_HISTORY_RESTORE_REQUEST';
|
||||||
|
|
||||||
|
/** @var string The `$_SERVER` key for the X-Time-Zone header */
|
||||||
|
const HEADER_USER_TZ = 'HTTP_X_TIME_ZONE';
|
||||||
|
|
||||||
|
/** @var string The `$_REQUEST` key for whether the request was initiated by htmx */
|
||||||
|
const IS_HTMX = 'MPJ_IS_HTMX';
|
||||||
|
|
||||||
|
/** @var string The `$_GET` key for state passed to Auth0 if redirection is required once authenticated */
|
||||||
|
const LOG_ON_STATE = 'state';
|
||||||
|
|
||||||
|
/** @var string The `$_REQUEST` key for the page title for this request */
|
||||||
|
const PAGE_TITLE = 'MPJ_PAGE_TITLE';
|
||||||
|
|
||||||
|
/** @var string The `$_SERVER` key for the current page's relative URI */
|
||||||
|
const REQUEST_URI = 'REQUEST_URI';
|
||||||
|
|
||||||
|
/** @var string The `$_GET` key sent to the log on page if redirection is required once authenticated */
|
||||||
|
const RETURN_URL = 'return_url';
|
||||||
|
|
||||||
|
/** @var string The `$_REQUEST` key for the timezone reference to use for this request */
|
||||||
|
const TIME_ZONE = 'MPJ_TIME_ZONE';
|
||||||
|
|
||||||
|
/** @var string The `$_REQUEST` key for the current user's ID */
|
||||||
|
const USER_ID = 'MPJ_USER_ID';
|
||||||
|
|
||||||
|
/** @var string The `$_REQUEST` key for the current version of myPrayerJournal */
|
||||||
|
const VERSION = 'MPJ_VERSION';
|
||||||
|
}
|
||||||
134
src/app/lib/Data.php
Normal file
134
src/app/lib/Data.php
Normal file
@@ -0,0 +1,134 @@
|
|||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace MyPrayerJournal;
|
||||||
|
|
||||||
|
use BitBadger\PgDocuments\{ Definition, Document, DocumentIndex, Query };
|
||||||
|
use MyPrayerJournal\Domain\{ History, JournalRequest, Note, Request, RequestAction };
|
||||||
|
|
||||||
|
class Data
|
||||||
|
{
|
||||||
|
/** The prayer request table */
|
||||||
|
const REQ_TABLE = 'mpj.request';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ensure the table and index exist
|
||||||
|
*/
|
||||||
|
public static function startUp(): void
|
||||||
|
{
|
||||||
|
Definition::ensureTable(self::REQ_TABLE);
|
||||||
|
Definition::ensureIndex(self::REQ_TABLE, DocumentIndex::Optimized);
|
||||||
|
}
|
||||||
|
|
||||||
|
// /**
|
||||||
|
// * Find a full prayer request by its ID
|
||||||
|
// *
|
||||||
|
// * @param string $reqId The request ID
|
||||||
|
// * @param string $userId The ID of the currently logged-on user
|
||||||
|
// * @return ?Request The request, or null if it is not found
|
||||||
|
// */
|
||||||
|
// public static function findFullRequestById(string $reqId, string $userId): ?Request
|
||||||
|
// {
|
||||||
|
// $req = Document::findById(self::REQ_TABLE, $reqId, Request::class);
|
||||||
|
// return is_null($req) || $req->userId != $userId ? null : $req;
|
||||||
|
// }
|
||||||
|
|
||||||
|
// /**
|
||||||
|
// * Add a history entry to the specified request
|
||||||
|
// *
|
||||||
|
// * @param string $reqId The request ID
|
||||||
|
// * @param string $userId The ID of the currently logged-on user
|
||||||
|
// * @param History $history The history entry to be added
|
||||||
|
// */
|
||||||
|
// public static function addHistory(string $reqId, string $userId, History $history)
|
||||||
|
// {
|
||||||
|
// $req = self::findFullRequestById($reqId, $userId);
|
||||||
|
// if (is_null($req)) throw new \InvalidArgumentException("$reqId not found");
|
||||||
|
// array_unshift($req->history, $history);
|
||||||
|
// Document::updateFull(self::REQ_TABLE, $reqId, $req);
|
||||||
|
// }
|
||||||
|
|
||||||
|
// /**
|
||||||
|
// * Add a note to the specified request
|
||||||
|
// *
|
||||||
|
// * @param string $reqId The request ID
|
||||||
|
// * @param string $userId The ID of the currently logged-on user
|
||||||
|
// * @param Note $note The note to be added
|
||||||
|
// */
|
||||||
|
// public static function addNote(string $reqId, string $userId, Note $note)
|
||||||
|
// {
|
||||||
|
// $req = self::findFullRequestById($reqId, $userId);
|
||||||
|
// if (is_null($req)) throw new \InvalidArgumentException("$reqId not found");
|
||||||
|
// array_unshift($req->notes, $note);
|
||||||
|
// Document::updateFull(self::REQ_TABLE, $reqId, $req);
|
||||||
|
// }
|
||||||
|
|
||||||
|
// /**
|
||||||
|
// * Add a new request
|
||||||
|
// *
|
||||||
|
// * @param Request $req The request to be added
|
||||||
|
// */
|
||||||
|
// public static function addRequest(Request $req)
|
||||||
|
// {
|
||||||
|
// Document::insert(self::REQ_TABLE, $req->id, $req);
|
||||||
|
// }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Map an array of `Request`s to an array of `JournalRequest`s
|
||||||
|
*
|
||||||
|
* @param Request[] $reqs The requests to map
|
||||||
|
* @param bool $full Whether to include history and notes (true) or not (false)
|
||||||
|
* @return JournalRequest[] The journal request objects
|
||||||
|
*/
|
||||||
|
private static function mapToJournalRequest(array $reqs, bool $full): array
|
||||||
|
{
|
||||||
|
return array_map(fn (Request $req) => new JournalRequest($req, $full), $reqs);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get journal requests for the given user by "answered" status
|
||||||
|
*
|
||||||
|
* @param string $userId The ID of the user for whom requests should be retrieved
|
||||||
|
* @param string $op The JSON Path operator to use for comparison (`==` or `<>`)
|
||||||
|
* @return JournalRequest[] The journal request objects
|
||||||
|
*/
|
||||||
|
private static function getJournalByAnswered(string $userId, string $op): array
|
||||||
|
{
|
||||||
|
$sql = sprintf('%s WHERE %s AND %s', Query::selectFromTable(self::REQ_TABLE), Query::whereDataContains('$1'),
|
||||||
|
Query::whereJsonPathMatches('$2'));
|
||||||
|
$params = [
|
||||||
|
Query::jsonbDocParam([ 'userId' => $userId ]),
|
||||||
|
sprintf('$.history[0].status ? (@ %s "%s")', $op, RequestAction::Answered->name)
|
||||||
|
];
|
||||||
|
return self::mapToJournalRequest(
|
||||||
|
Document::customList($sql, $params, Request::class, Document::mapFromJson(...)), true);
|
||||||
|
}
|
||||||
|
|
||||||
|
// /**
|
||||||
|
// * Retrieve all answered requests for this user
|
||||||
|
// *
|
||||||
|
// * @param string $userId The ID of the user for whom answered requests should be retrieved
|
||||||
|
// * @return JournalRequest[] The answered requests
|
||||||
|
// */
|
||||||
|
// public static function getAnsweredRequests(string $userId): array
|
||||||
|
// {
|
||||||
|
// $answered = self::getJournalByAnswered($userId, '==');
|
||||||
|
// usort($answered,
|
||||||
|
// fn (JournalRequest $a, JournalRequest $b) => $a->asOf == $b->asOf ? 0 : ($a->asOf > $b->asOf ? -1 : 1));
|
||||||
|
// return $answered;
|
||||||
|
// }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the user's current prayer request journal
|
||||||
|
*
|
||||||
|
* @param string $userId The ID of the user whose journal should be retrieved
|
||||||
|
* @return JournalRequest[] The journal request objects
|
||||||
|
*/
|
||||||
|
public static function getJournal(string $userId): array
|
||||||
|
{
|
||||||
|
$reqs = self::getJournalByAnswered($userId, '<>');
|
||||||
|
usort($reqs,
|
||||||
|
fn (JournalRequest $a, JournalRequest $b) => $a->asOf == $b->asOf ? 0 : ($a->asOf < $b->asOf ? -1 : 1));
|
||||||
|
return $reqs;
|
||||||
|
}
|
||||||
|
}
|
||||||
63
src/app/lib/Dates.php
Normal file
63
src/app/lib/Dates.php
Normal file
@@ -0,0 +1,63 @@
|
|||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace MyPrayerJournal;
|
||||||
|
|
||||||
|
use DateTimeImmutable, DateTimeInterface, DateTimeZone;
|
||||||
|
|
||||||
|
class Dates
|
||||||
|
{
|
||||||
|
/** Minutes in a day */
|
||||||
|
private const A_DAY = 1_440;
|
||||||
|
|
||||||
|
/** Minutes in two days(-ish) */
|
||||||
|
private const ALMOST_2_DAYS = 2_520;
|
||||||
|
|
||||||
|
/** Minutes in a month */
|
||||||
|
private const A_MONTH = 43_200;
|
||||||
|
|
||||||
|
/** Minutes in two months */
|
||||||
|
private const TWO_MONTHS = 86_400;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get a UTC-referenced current date/time
|
||||||
|
*
|
||||||
|
* @return DateTimeImmutable The current date/time with UTC reference
|
||||||
|
*/
|
||||||
|
public static function now(): DateTimeImmutable
|
||||||
|
{
|
||||||
|
return new DateTimeImmutable(timezone: new DateTimeZone('Etc/UTC'));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Format the distance between two instants in approximate English terms
|
||||||
|
*
|
||||||
|
* @param DateTimeInterface $startOn The starting date/time for the comparison
|
||||||
|
* @param DateTimeInterface $endOn THe ending date/time for the comparison
|
||||||
|
* @return string The formatted interval
|
||||||
|
*/
|
||||||
|
public static function formatDistance(DateTimeInterface $startOn, DateTimeInterface $endOn): string
|
||||||
|
{
|
||||||
|
$diff = $startOn->diff($endOn);
|
||||||
|
$minutes =
|
||||||
|
$diff->i + ($diff->h * 60) + ($diff->d * 60 * 24) + ($diff->m * 60 * 24 * 30) + ($diff->y * 60 * 24 * 365);
|
||||||
|
$months = round($minutes / self::A_MONTH);
|
||||||
|
$years = $months / 12;
|
||||||
|
[ $format, $number ] = match (true) {
|
||||||
|
$minutes < 1 => [ DistanceFormat::LessThanXMinutes, 1 ],
|
||||||
|
$minutes < 45 => [ DistanceFormat::XMinutes, $minutes ],
|
||||||
|
$minutes < 90 => [ DistanceFormat::AboutXHours, 1 ],
|
||||||
|
$minutes < self::A_DAY => [ DistanceFormat::AboutXHours, round($minutes / 60) ],
|
||||||
|
$minutes < self::ALMOST_2_DAYS => [ DistanceFormat::XDays, 1 ],
|
||||||
|
$minutes < self::A_MONTH => [ DistanceFormat::XDays, round($minutes / self::A_DAY) ],
|
||||||
|
$minutes < self::TWO_MONTHS => [ DistanceFormat::AboutXMonths, round($minutes / self::A_MONTH) ],
|
||||||
|
$months < 12 => [ DistanceFormat::XMonths, round($minutes / self::A_MONTH) ],
|
||||||
|
$months % 12 < 3 => [ DistanceFormat::AboutXYears, $years ],
|
||||||
|
$months % 12 < 9 => [ DistanceFormat::OverXYears, $years ],
|
||||||
|
default => [ DistanceFormat::AlmostXYears, $years + 1 ],
|
||||||
|
};
|
||||||
|
|
||||||
|
$relativeWords = sprintf(DistanceFormat::format($format, $number == 1), $number);
|
||||||
|
return $startOn > $endOn ? "$relativeWords ago" : "in $relativeWords";
|
||||||
|
}
|
||||||
|
}
|
||||||
50
src/app/lib/DistanceFormat.php
Normal file
50
src/app/lib/DistanceFormat.php
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace MyPrayerJournal;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The different distance formats supported
|
||||||
|
*/
|
||||||
|
enum DistanceFormat
|
||||||
|
{
|
||||||
|
case LessThanXMinutes;
|
||||||
|
case XMinutes;
|
||||||
|
case AboutXHours;
|
||||||
|
case XHours;
|
||||||
|
case XDays;
|
||||||
|
case AboutXWeeks;
|
||||||
|
case XWeeks;
|
||||||
|
case AboutXMonths;
|
||||||
|
case XMonths;
|
||||||
|
case AboutXYears;
|
||||||
|
case XYears;
|
||||||
|
case OverXYears;
|
||||||
|
case AlmostXYears;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Return the formatting string for the given format and number
|
||||||
|
*
|
||||||
|
* @param DistanceFormat $it The distance format
|
||||||
|
* @param bool $singular If true, returns the singular version; if false (default), returns the plural version
|
||||||
|
* @return string The format string
|
||||||
|
*/
|
||||||
|
public static function format(DistanceFormat $it, bool $singular = false): string
|
||||||
|
{
|
||||||
|
return match ($it) {
|
||||||
|
self::LessThanXMinutes => $singular ? 'less than a minute' : 'less than %d minutes',
|
||||||
|
self::XMinutes => $singular ? 'a minute' : '%d minutes',
|
||||||
|
self::AboutXHours => $singular ? 'about an hour' : 'about %d hours',
|
||||||
|
self::XHours => $singular ? 'an hour' : '%d hours',
|
||||||
|
self::XDays => $singular ? 'a day' : '%d days',
|
||||||
|
self::AboutXWeeks => $singular ? 'about a week' : 'about %d weeks',
|
||||||
|
self::XWeeks => $singular ? 'a week' : '%d weeks',
|
||||||
|
self::AboutXMonths => $singular ? 'about a month' : 'about %d months',
|
||||||
|
self::XMonths => $singular ? 'a month' : '%d months',
|
||||||
|
self::AboutXYears => $singular ? 'about a year' : 'about %d years',
|
||||||
|
self::XYears => $singular ? 'a year' : '%d years',
|
||||||
|
self::OverXYears => $singular ? 'over a year' : 'over %d years',
|
||||||
|
self::AlmostXYears => $singular ? 'almost a year' : 'almost %d years',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
73
src/app/lib/documents/Configuration.php
Normal file
73
src/app/lib/documents/Configuration.php
Normal file
@@ -0,0 +1,73 @@
|
|||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace BitBadger\PgDocuments;
|
||||||
|
|
||||||
|
use PgSql\Connection;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Document table configuration
|
||||||
|
*/
|
||||||
|
class Configuration
|
||||||
|
{
|
||||||
|
/** @var string $connectionString The connection string to use when establishing a database connection */
|
||||||
|
public static string $connectionString = '';
|
||||||
|
|
||||||
|
/** @var ?Connection $pgConn The active connection */
|
||||||
|
private static ?Connection $pgConn = null;
|
||||||
|
|
||||||
|
/** @var ?string $startUp The name of a function to run on first connection to the database */
|
||||||
|
public static ?string $startUp = null;
|
||||||
|
|
||||||
|
/** @var string $keyName The key name for document IDs (default "id") */
|
||||||
|
public static string $keyName = 'id';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ensure that the connection string is set, either explicitly, by environment variables, or with defaults
|
||||||
|
*/
|
||||||
|
private static function ensureConnectionString(): void
|
||||||
|
{
|
||||||
|
if (self::$connectionString == "") {
|
||||||
|
$host = $_ENV['PGDOC_HOST'] ?? 'localhost';
|
||||||
|
$port = $_ENV['PGDOC_PORT'] ?? 5432;
|
||||||
|
$db = $_ENV['PGDOC_DB'] ?? 'postgres';
|
||||||
|
$user = $_ENV['PGDOC_USER'] ?? 'postgres';
|
||||||
|
$pass = $_ENV['PGDOC_PASS'] ?? 'postgres';
|
||||||
|
$opts = $_ENV['PGDOC_OPTS'] ?? '';
|
||||||
|
self::$connectionString = "host=$host port=$port dbname=$db user=$user password=$pass"
|
||||||
|
. ($opts ? " options='$opts'" : '');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A no-op function to force this file to be autoloaded if no explicit configuration is required
|
||||||
|
*/
|
||||||
|
public static function init() { }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the PostgreSQL connection, connecting on first request
|
||||||
|
*
|
||||||
|
* @return Connection The open PostgreSQL connection
|
||||||
|
*/
|
||||||
|
public static function getPgConn(): Connection
|
||||||
|
{
|
||||||
|
if (is_null(self::$pgConn)) {
|
||||||
|
self::ensureConnectionString();
|
||||||
|
self::$pgConn = pg_connect(self::$connectionString);
|
||||||
|
}
|
||||||
|
return self::$pgConn;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Close the PostgreSQL connection if it is open
|
||||||
|
*/
|
||||||
|
public static function closeConn(): void
|
||||||
|
{
|
||||||
|
if (!is_null(self::$pgConn)) {
|
||||||
|
pg_close(self::$pgConn);
|
||||||
|
self::$pgConn = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
require('functions.php');
|
||||||
87
src/app/lib/documents/Definition.php
Normal file
87
src/app/lib/documents/Definition.php
Normal file
@@ -0,0 +1,87 @@
|
|||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace BitBadger\PgDocuments;
|
||||||
|
|
||||||
|
use PgSql\Result;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Methods to define tables and indexes for document tables
|
||||||
|
*/
|
||||||
|
class Definition
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Create a statement to create a document table
|
||||||
|
*
|
||||||
|
* @param string $name The name of the table to create
|
||||||
|
* @return string A `CREATE TABLE` statement for the document table
|
||||||
|
*/
|
||||||
|
public static function createTable(string $name): string
|
||||||
|
{
|
||||||
|
return "CREATE TABLE IF NOT EXISTS $name (data JSONB NOT NULL)";
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a statement to create a key for a document table
|
||||||
|
*
|
||||||
|
* @param string $tableName The table (or schema/table) for which a key should be created
|
||||||
|
* @return string A `CREATE INDEX` statement for a unique key for the document table
|
||||||
|
*/
|
||||||
|
public static function createKey(string $tableName): string
|
||||||
|
{
|
||||||
|
return sprintf('CREATE UNIQUE INDEX IF NOT EXISTS idx_%s_key ON %s ((data -> \'%s\'))',
|
||||||
|
self::extractTable($tableName), $tableName, Configuration::$keyName);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a statement to create an index on a document table
|
||||||
|
*
|
||||||
|
* @param string $name The name of the table for which the index should be created
|
||||||
|
* @param DocumentIndex $type The type of index to create
|
||||||
|
* @return string A `CREATE INDEX` statement for the given table
|
||||||
|
*/
|
||||||
|
public static function createIndex(string $name, DocumentIndex $type): string
|
||||||
|
{
|
||||||
|
return sprintf('CREATE INDEX IF NOT EXISTS idx_%s ON %s USING GIN (data%s)',
|
||||||
|
self::extractTable($name), $name, $type == DocumentIndex::Full ? '' : ' jsonb_path_ops');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ensure the given document table exists
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table
|
||||||
|
*/
|
||||||
|
public static function ensureTable(string $tableName): void
|
||||||
|
{
|
||||||
|
/** @var Result|bool $result */
|
||||||
|
$result = pg_query(pg_conn(), self::createTable($tableName));
|
||||||
|
if ($result) pg_free_result($result);
|
||||||
|
$result = pg_query(pg_conn(), self::createKey($tableName));
|
||||||
|
if ($result) pg_free_result($result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ensure an index on the given document table exists
|
||||||
|
*
|
||||||
|
* @param string $name The name of the table for which the index should be created
|
||||||
|
* @param DocumentIndex $type The type of index to create
|
||||||
|
*/
|
||||||
|
public static function ensureIndex(string $name, DocumentIndex $type): void
|
||||||
|
{
|
||||||
|
/** @var Result|bool $result */
|
||||||
|
$result = pg_query(pg_conn(), self::createIndex($name, $type));
|
||||||
|
if ($result) pg_free_result($result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Extract just the table name from a possible `schema.table` name
|
||||||
|
*
|
||||||
|
* @param string $name The name of the table, possibly including the schema
|
||||||
|
* @return string The table name
|
||||||
|
*/
|
||||||
|
private static function extractTable(string $name): string
|
||||||
|
{
|
||||||
|
$schemaAndTable = explode('.', $name);
|
||||||
|
return end($schemaAndTable);
|
||||||
|
}
|
||||||
|
}
|
||||||
431
src/app/lib/documents/Document.php
Normal file
431
src/app/lib/documents/Document.php
Normal file
@@ -0,0 +1,431 @@
|
|||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace BitBadger\PgDocuments;
|
||||||
|
|
||||||
|
use Exception;
|
||||||
|
use JsonMapper;
|
||||||
|
use PgSql\Result;
|
||||||
|
|
||||||
|
/** Document manipulation functions */
|
||||||
|
class Document
|
||||||
|
{
|
||||||
|
/** JSON Mapper instance to use for creating a domain type instance from a document */
|
||||||
|
private static ?JsonMapper $mapper = null;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Map a domain type from the JSON document retrieved
|
||||||
|
*
|
||||||
|
* @param string $columnName The name of the column from the database
|
||||||
|
* @param array $result An associative array with a single result to be mapped
|
||||||
|
* @param class-string<Type> $className The name of the class onto which the JSON will be mapped
|
||||||
|
* @return Type The domain type
|
||||||
|
*/
|
||||||
|
public static function mapDocFromJson(string $columnName, array $result, string $className): mixed
|
||||||
|
{
|
||||||
|
if (is_null(self::$mapper)) {
|
||||||
|
self::$mapper = new JsonMapper();
|
||||||
|
}
|
||||||
|
|
||||||
|
$mapped = new $className();
|
||||||
|
self::$mapper->map(json_decode($result[$columnName]), $mapped);
|
||||||
|
return $mapped;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Map a domain type from the JSON document retrieved
|
||||||
|
*
|
||||||
|
* @param array $result An associative array with a single result to be mapped
|
||||||
|
* @param class-string<Type> $className The name of the class onto which the JSON will be mapped
|
||||||
|
* @return Type The domain type
|
||||||
|
*/
|
||||||
|
public static function mapFromJson(array $result, string $className): mixed
|
||||||
|
{
|
||||||
|
return self::mapDocFromJson('data', $result, $className);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Execute a document-focused statement that does not return results
|
||||||
|
*
|
||||||
|
* @param string $query The query to be executed
|
||||||
|
* @param array|object $document The array or object representing the document
|
||||||
|
* @throws Exception If the document's ID is null
|
||||||
|
*/
|
||||||
|
private static function executeNonQuery(string $query, array|object $document): void
|
||||||
|
{
|
||||||
|
$docId = is_array($document)
|
||||||
|
? $document[Configuration::$keyName]
|
||||||
|
: get_object_vars($document)[Configuration::$keyName];
|
||||||
|
if (is_null($docId)) throw new Exception('PgDocument: ID cannot be NULL');
|
||||||
|
/** @var Result|bool $result */
|
||||||
|
$result = pg_query_params(pg_conn(), $query, [ $docId, Query::jsonbDocParam($document) ]);
|
||||||
|
if ($result) pg_free_result($result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Insert a document
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table into which a document should be inserted
|
||||||
|
* @param array|object $document The array or object representing the document
|
||||||
|
*/
|
||||||
|
public static function insert(string $tableName, array|object $document): void
|
||||||
|
{
|
||||||
|
self::executeNonQuery(Query::insert($tableName), $document);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Save (upsert) a document
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table into which a document should be inserted
|
||||||
|
* @param array|object $document The array or object representing the document
|
||||||
|
*/
|
||||||
|
public static function save(string $tableName, array|object $document): void
|
||||||
|
{
|
||||||
|
self::executeNonQuery(Query::save($tableName), $document);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Run a count query, returning the `it` parameter of that query as an integer
|
||||||
|
*
|
||||||
|
* @param string $sql The SQL query that will return a count
|
||||||
|
* @param array $params Parameters needed for that query
|
||||||
|
* @return int The count of matching rows for the query
|
||||||
|
*/
|
||||||
|
private static function runCount(string $sql, array $params): int
|
||||||
|
{
|
||||||
|
/** @var Result|bool $result */
|
||||||
|
$result = pg_query_params(pg_conn(), $sql, $params);
|
||||||
|
if (!$result) return -1;
|
||||||
|
$count = intval(pg_fetch_assoc($result)['it']);
|
||||||
|
pg_free_result($result);
|
||||||
|
return $count;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Count all documents in a table
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table in which documents should be counted
|
||||||
|
* @return int The number of documents in the table
|
||||||
|
*/
|
||||||
|
public static function countAll(string $tableName): int
|
||||||
|
{
|
||||||
|
return self::runCount(Query::countAll($tableName), []);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Count documents in a table by JSON containment `@>`
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table in which documents should be counted
|
||||||
|
* @param array|object $criteria The criteria for the JSON containment query
|
||||||
|
* @return int The number of documents in the table matching the JSON containment query
|
||||||
|
*/
|
||||||
|
public static function countByContains(string $tableName, array|object $criteria): int
|
||||||
|
{
|
||||||
|
return self::runCount(Query::countByContains($tableName), [ Query::jsonbDocParam($criteria) ]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Count documents in a table by JSON Path match `@?`
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table in which documents should be counted
|
||||||
|
* @param string $jsonPath The JSON Path to be matched
|
||||||
|
* @return int The number of documents in the table matching the JSON Path
|
||||||
|
*/
|
||||||
|
public static function countByJsonPath(string $tableName, string $jsonPath): int
|
||||||
|
{
|
||||||
|
return self::runCount(Query::countByJsonPath($tableName), [ $jsonPath ]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Run an existence query (returning the `it` parameter of that query)
|
||||||
|
*
|
||||||
|
* @param string $sql The SQL query that will return existence
|
||||||
|
* @param array $params Parameters needed for that query
|
||||||
|
* @return bool The result of the existence query
|
||||||
|
*/
|
||||||
|
private static function runExists(string $sql, array $params): bool
|
||||||
|
{
|
||||||
|
/** @var Result|bool $result */
|
||||||
|
$result = pg_query_params(pg_conn(), $sql, $params);
|
||||||
|
if (!$result) return false;
|
||||||
|
$exists = boolval(pg_fetch_assoc($result)['it']);
|
||||||
|
pg_free_result($result);
|
||||||
|
return $exists;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Determine if a document exists for the given ID
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table in which existence should be checked
|
||||||
|
* @param string $docId The ID of the document whose existence should be checked
|
||||||
|
* @return bool True if the document exists, false if not
|
||||||
|
*/
|
||||||
|
public static function existsById(string $tableName, string $docId): bool
|
||||||
|
{
|
||||||
|
return self::runExists(Query::existsById($tableName), [ $docId ]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Determine if documents exist by JSON containment `@>`
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table in which existence should be checked
|
||||||
|
* @param array|object $criteria The criteria for the JSON containment query
|
||||||
|
* @return bool True if any documents in the table match the JSON containment query, false if not
|
||||||
|
*/
|
||||||
|
public static function existsByContains(string $tableName, array|object $criteria): bool
|
||||||
|
{
|
||||||
|
return self::runExists(Query::existsByContains($tableName), [ Query::jsonbDocParam($criteria) ]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Determine if documents exist by JSON Path match `@?`
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table in which existence should be checked
|
||||||
|
* @param string $jsonPath The JSON Path to be matched
|
||||||
|
* @return bool True if any documents in the table match the JSON Path, false if not
|
||||||
|
*/
|
||||||
|
public static function existsByJsonPath(string $tableName, string $jsonPath): bool
|
||||||
|
{
|
||||||
|
return self::runExists(Query::existsByJsonPath($tableName), [ $jsonPath ]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Run a query, mapping the results to an array of domain type objects
|
||||||
|
*
|
||||||
|
* @param string $sql The query to be run
|
||||||
|
* @param array $params The parameters for the query
|
||||||
|
* @param class-string<Type> $className The type of document to be mapped
|
||||||
|
* @return array<Type> The documents matching the query
|
||||||
|
*/
|
||||||
|
private static function runListQuery(string $sql, array $params, string $className): array
|
||||||
|
{
|
||||||
|
/** @var Result|bool $result */
|
||||||
|
$result = pg_query_params(pg_conn(), $sql, $params);
|
||||||
|
try {
|
||||||
|
if (!$result || pg_result_status($result) == PGSQL_EMPTY_QUERY) return [];
|
||||||
|
return array_map(fn ($it) => self::mapFromJson($it, $className), pg_fetch_all($result));
|
||||||
|
} finally {
|
||||||
|
if ($result) pg_free_result($result);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retrieve all documents in a table
|
||||||
|
*
|
||||||
|
* @param string $tableName The table from which all documents should be retrieved
|
||||||
|
* @param class-string<Type> $className The type of document to be retrieved
|
||||||
|
* @return array<Type> An array of documents
|
||||||
|
*/
|
||||||
|
public static function findAll(string $tableName, string $className): array
|
||||||
|
{
|
||||||
|
return self::runListQuery(Query::selectFromTable($tableName), [], $className);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retrieve a document by its ID
|
||||||
|
*
|
||||||
|
* @param string $tableName The table from which a document should be retrieved
|
||||||
|
* @param string $docId The ID of the document to retrieve
|
||||||
|
* @param class-string<Type> $className The type of document to retrieve
|
||||||
|
* @return Type|null The document, or null if it is not found
|
||||||
|
*/
|
||||||
|
public static function findById(string $tableName, string $docId, string $className): mixed
|
||||||
|
{
|
||||||
|
$results = self::runListQuery(Query::findById($tableName), [ $docId ], $className);
|
||||||
|
return $results ? $results[0] : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retrieve documents in a table via JSON containment `@>`
|
||||||
|
*
|
||||||
|
* @param string $tableName The table from which documents should be retrieved
|
||||||
|
* @param array|object $criteria The criteria for the JSON containment query
|
||||||
|
* @param class-string<Type> $className The type of document to be retrieved
|
||||||
|
* @return array<Type> Documents matching the JSON containment query
|
||||||
|
*/
|
||||||
|
public static function findByContains(string $tableName, array|object $criteria, string $className): array
|
||||||
|
{
|
||||||
|
return self::runListQuery(Query::findByContains($tableName), [ Query::jsonbDocParam($criteria) ], $className);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retrieve the first matching document via JSON containment `@>`
|
||||||
|
*
|
||||||
|
* @param string $tableName The table from which documents should be retrieved
|
||||||
|
* @param array|object $criteria The criteria for the JSON containment query
|
||||||
|
* @param class-string<Type> $className The type of document to be retrieved
|
||||||
|
* @return Type|null The document, or null if none match
|
||||||
|
*/
|
||||||
|
public static function findFirstByContains(string $tableName, array|object $criteria, string $className): mixed
|
||||||
|
{
|
||||||
|
$results = self::runListQuery(Query::findByContains($tableName) . ' LIMIT 1',
|
||||||
|
[ Query::jsonbDocParam($criteria) ], $className);
|
||||||
|
return $results ? $results[0] : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retrieve documents in a table via JSON Path match `@?`
|
||||||
|
*
|
||||||
|
* @param string $tableName The table from which documents should be retrieved
|
||||||
|
* @param string $jsonPath The JSON Path to be matched
|
||||||
|
* @param class-string<Type> $className The type of document to be retrieved
|
||||||
|
* @return array<Type> Documents matching the JSON Path
|
||||||
|
*/
|
||||||
|
public static function findByJsonPath(string $tableName, string $jsonPath, string $className): array
|
||||||
|
{
|
||||||
|
return self::runListQuery(Query::findByJsonPath($tableName), [ $jsonPath ], $className);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retrieve the first matching document via JSON Path match `@?`
|
||||||
|
*
|
||||||
|
* @param string $tableName The table from which documents should be retrieved
|
||||||
|
* @param string $jsonPath The JSON Path to be matched
|
||||||
|
* @param class-string<Type> $className The type of document to be retrieved
|
||||||
|
* @return Type|null The document, or null if none match
|
||||||
|
*/
|
||||||
|
public static function findFirstByJsonPath(string $tableName, string $jsonPath, string $className): mixed
|
||||||
|
{
|
||||||
|
$results = self::runListQuery(Query::findByJsonPath($tableName) . ' LIMIT 1', [ $jsonPath ], $className);
|
||||||
|
return $results ? $results[0] : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Update a full document
|
||||||
|
*
|
||||||
|
* @param string $tableName The table in which the document should be updated
|
||||||
|
* @param array|object $document The document to be updated
|
||||||
|
*/
|
||||||
|
public static function updateFull(string $tableName, array|object $document): void
|
||||||
|
{
|
||||||
|
self::executeNonQuery(Query::updateFull($tableName), $document);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Update a partial document by its ID
|
||||||
|
*
|
||||||
|
* @param string $tableName The table in which the document should be updated
|
||||||
|
* @param array|object $document The partial document to be updated
|
||||||
|
*/
|
||||||
|
public static function updatePartialById(string $tableName, array|object $document): void
|
||||||
|
{
|
||||||
|
self::executeNonQuery(Query::updatePartialById($tableName), $document);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Update partial documents by JSON containment `@>`
|
||||||
|
*
|
||||||
|
* @param string $tableName The table in which documents should be updated
|
||||||
|
* @param array|object $criteria The JSON containment criteria
|
||||||
|
* @param array|object $document The document to be updated
|
||||||
|
*/
|
||||||
|
public static function updatePartialByContains(string $tableName, array|object $criteria,
|
||||||
|
array|object $document): void
|
||||||
|
{
|
||||||
|
/** @var Result|bool $result */
|
||||||
|
$result = pg_query_params(pg_conn(), Query::updatePartialByContains($tableName),
|
||||||
|
[ Query::jsonbDocParam($criteria), Query::jsonbDocParam($document) ]);
|
||||||
|
if ($result) pg_free_result($result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Update partial documents by JSON Path match `@?`
|
||||||
|
*
|
||||||
|
* @param string $tableName The table in which documents should be updated
|
||||||
|
* @param string $jsonPath The JSON Path to be matched
|
||||||
|
* @param array|object $document The document to be updated
|
||||||
|
*/
|
||||||
|
public static function updatePartialByJsonPath(string $tableName, string $jsonPath, array|object $document): void
|
||||||
|
{
|
||||||
|
/** @var Result|bool $result */
|
||||||
|
$result = pg_query_params(pg_conn(), Query::updatePartialByJsonPath($tableName),
|
||||||
|
[ $jsonPath, Query::jsonbDocParam($document) ]);
|
||||||
|
if ($result) pg_free_result($result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Delete a document by its ID
|
||||||
|
*
|
||||||
|
* @param string $tableName The table from which a document should be deleted
|
||||||
|
* @param string $docId The ID of the document to be deleted
|
||||||
|
*/
|
||||||
|
public static function deleteById(string $tableName, string $docId): void
|
||||||
|
{
|
||||||
|
self::executeNonQuery(Query::deleteById($tableName), [ Configuration::$keyName => $docId ]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Delete documents by JSON containment `@>`
|
||||||
|
*
|
||||||
|
* @param string $tableName The table from which documents should be deleted
|
||||||
|
* @param array|object $criteria The criteria for the JSON containment query
|
||||||
|
*/
|
||||||
|
public static function deleteByContains(string $tableName, array|object $criteria): void
|
||||||
|
{
|
||||||
|
/** @var Result|bool $result */
|
||||||
|
$result = pg_query_params(pg_conn(), Query::deleteByContains($tableName), [ Query::jsonbDocParam($criteria) ]);
|
||||||
|
if ($result) pg_free_result($result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Delete documents by JSON Path match `@?`
|
||||||
|
*
|
||||||
|
* @param string $tableName The table from which documents should be deleted
|
||||||
|
* @param string $jsonPath The JSON Path expression to be matched
|
||||||
|
*/
|
||||||
|
public static function deleteByJsonPath(string $tableName, string $jsonPath): void
|
||||||
|
{
|
||||||
|
/** @var Result|bool $result */
|
||||||
|
$result = pg_query_params(pg_conn(), Query::deleteByJsonPath($tableName), [ $jsonPath ]);
|
||||||
|
if ($result) pg_free_result($result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retrieve documents via a custom query and mapping
|
||||||
|
*
|
||||||
|
* @param string $sql The SQL query to execute
|
||||||
|
* @param array $params A positional array of parameters for the SQL query
|
||||||
|
* @param callable $mapFunc A function that expects an associative array and returns a value of the desired type
|
||||||
|
* @param class-string<Type> $className The type of document to be mapped
|
||||||
|
* @return array<Type> The documents matching the query
|
||||||
|
*/
|
||||||
|
public static function customList(string $sql, array $params, string $className, callable $mapFunc): array
|
||||||
|
{
|
||||||
|
/** @var Result|bool $result */
|
||||||
|
$result = pg_query_params(pg_conn(), $sql, $params);
|
||||||
|
try {
|
||||||
|
if (!$result || pg_result_status($result) == PGSQL_EMPTY_QUERY) return [];
|
||||||
|
return array_map(fn ($it) => $mapFunc($it, $className), pg_fetch_all($result));
|
||||||
|
} finally {
|
||||||
|
if ($result) pg_free_result($result);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retrieve a document via a custom query and mapping
|
||||||
|
*
|
||||||
|
* @param string $sql The SQL query to execute ("LIMIT 1" will be appended)
|
||||||
|
* @param array $params A positional array of parameters for the SQL query
|
||||||
|
* @param callable $mapFunc A function that expects an associative array and returns a value of the desired type
|
||||||
|
* @param class-string<Type> $className The type of document to be mapped
|
||||||
|
* @return ?Type The document matching the query, or null if none is found
|
||||||
|
*/
|
||||||
|
public static function customSingle(string $sql, array $params, string $className, callable $mapFunc): mixed
|
||||||
|
{
|
||||||
|
$results = self::customList("$sql LIMIT 1", $params, $className, $mapFunc);
|
||||||
|
return $results ? $results[0] : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Execute a custom query that does not return a result
|
||||||
|
*
|
||||||
|
* @param string $sql The SQL query to execute
|
||||||
|
* @param array $params A positional array of parameters for the SQL query
|
||||||
|
*/
|
||||||
|
public static function customNonQuery(string $sql, array $params): void
|
||||||
|
{
|
||||||
|
/** @var Result|bool $result */
|
||||||
|
$result = pg_query_params(pg_conn(), $sql, $params);
|
||||||
|
if ($result) pg_free_result($result);
|
||||||
|
}
|
||||||
|
}
|
||||||
14
src/app/lib/documents/DocumentIndex.php
Normal file
14
src/app/lib/documents/DocumentIndex.php
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace BitBadger\PgDocuments;
|
||||||
|
|
||||||
|
/** The type of index to generate for the document */
|
||||||
|
enum DocumentIndex
|
||||||
|
{
|
||||||
|
/** A GIN index with standard operations (all operators supported) */
|
||||||
|
case Full;
|
||||||
|
|
||||||
|
/** A GIN index with JSONPath operations (optimized for `@>`, `@?`, `@@` operators) */
|
||||||
|
case Optimized;
|
||||||
|
}
|
||||||
309
src/app/lib/documents/Query.php
Normal file
309
src/app/lib/documents/Query.php
Normal file
@@ -0,0 +1,309 @@
|
|||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace BitBadger\PgDocuments;
|
||||||
|
|
||||||
|
/** Query construction functions */
|
||||||
|
class Query
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Create a `SELECT` clause to retrieve the document data from the given table
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table from which documents should be selected
|
||||||
|
* @return string A `SELECT` clause for the given table
|
||||||
|
*/
|
||||||
|
public static function selectFromTable(string $tableName): string
|
||||||
|
{
|
||||||
|
return "SELECT data FROM $tableName";
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a `WHERE` clause fragment to implement a key check condition
|
||||||
|
*
|
||||||
|
* @param string $paramName The name of the parameter to be replaced when the query is executed
|
||||||
|
* @return string A `WHERE` clause fragment with the named key and parameter
|
||||||
|
*/
|
||||||
|
public static function whereById(string $paramName): string
|
||||||
|
{
|
||||||
|
return sprintf("data -> '%s' = %s", Configuration::$keyName, $paramName);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a `WHERE` clause fragment to implement a @> (JSON contains) condition
|
||||||
|
*
|
||||||
|
* @param string $paramName The name of the parameter for the contains clause
|
||||||
|
* @return string A `WHERE` clause fragment with the named parameter
|
||||||
|
*/
|
||||||
|
public static function whereDataContains(string $paramName): string
|
||||||
|
{
|
||||||
|
return "data @> $paramName";
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a `WHERE` clause fragment to implement a @? (JSON Path match) condition
|
||||||
|
*
|
||||||
|
* @param string $paramName THe name of the parameter for the JSON Path match
|
||||||
|
* @return string A `WHERE` clause fragment with the named parameter
|
||||||
|
*/
|
||||||
|
public static function whereJsonPathMatches(string $paramName): string
|
||||||
|
{
|
||||||
|
return "data @? $paramName::jsonpath";
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a JSONB document parameter
|
||||||
|
*
|
||||||
|
* @param array|object $it The array or object to become a JSONB parameter
|
||||||
|
* @return string The encoded JSON
|
||||||
|
*/
|
||||||
|
public static function jsonbDocParam(array|object $it): string
|
||||||
|
{
|
||||||
|
return json_encode($it);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Query to insert a document
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table into which the document will be inserted
|
||||||
|
* @return string The `INSERT` statement (with `$1` parameter defined for the document)
|
||||||
|
*/
|
||||||
|
public static function insert(string $tableName): string
|
||||||
|
{
|
||||||
|
return sprintf('INSERT INTO %s (data) VALUES ($1)', $tableName);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Query to save a document, inserting it if it does not exist and updating it if it does (AKA "upsert")
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table into which the document will be saved
|
||||||
|
* @return string The `INSERT`/`ON CONFLICT DO UPDATE` statement (with `$1` parameter defined for the document)
|
||||||
|
*/
|
||||||
|
public static function save(string $tableName): string
|
||||||
|
{
|
||||||
|
return sprintf('INSERT INTO %s (data) VALUES ($1) ON CONFLICT (data) DO UPDATE SET data = EXCLUDED.data',
|
||||||
|
$tableName);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Query to count documents in a table
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table for which documents should be counted
|
||||||
|
* @param string $where The condition for which documents should be counted
|
||||||
|
* @return string A `SELECT` statement to obtain the count of documents for the given table
|
||||||
|
*/
|
||||||
|
private static function countQuery(string $tableName, string $where): string
|
||||||
|
{
|
||||||
|
return "SELECT COUNT(*) AS it FROM $tableName WHERE $where";
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Query to count all documents in a table
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table whose rows will be counted
|
||||||
|
* @return string A `SELECT` statement to obtain the count of all documents in the given table
|
||||||
|
*/
|
||||||
|
public static function countAll(string $tableName): string
|
||||||
|
{
|
||||||
|
return self::countQuery($tableName, '1 = 1');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Query to count matching documents using a JSON containment query `@>`
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table from which the count should be obtained
|
||||||
|
* @return string A `SELECT` statement to obtain the count of documents via JSON containment
|
||||||
|
*/
|
||||||
|
public static function countByContains(string $tableName): string
|
||||||
|
{
|
||||||
|
return self::countQuery($tableName, self::whereDataContains('$1'));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Query to count matching documents using a JSON Path match `@?`
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table from which the count should be obtained
|
||||||
|
* @return string A `SELECT` statement to obtain the count of documents via JSON Path match
|
||||||
|
*/
|
||||||
|
public static function countByJsonPath(string $tableName): string
|
||||||
|
{
|
||||||
|
return self::countQuery($tableName, self::whereJsonPathMatches('$1'));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Query to check document existence
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table in which document existence should be checked
|
||||||
|
* @param string $where The criteria for which document existence should be checked
|
||||||
|
* @return string A `SELECT` statement to check document existence for the given criteria
|
||||||
|
*/
|
||||||
|
private static function existsQuery(string $tableName, string $where): string
|
||||||
|
{
|
||||||
|
return "SELECT EXISTS (SELECT 1 FROM $tableName WHERE $where) AS it";
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Query to determine if a document exists for the given ID
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table in which existence should be checked
|
||||||
|
* @return string A `SELECT` statement to check existence of a document by its ID
|
||||||
|
*/
|
||||||
|
public static function existsById(string $tableName): string
|
||||||
|
{
|
||||||
|
return self::existsQuery($tableName, self::whereById('$1'));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Query to determine if documents exist using a JSON containment query `@>`
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table in which existence should be checked
|
||||||
|
* @return string A `SELECT` statement to check existence of a document by JSON containment
|
||||||
|
*/
|
||||||
|
public static function existsByContains(string $tableName): string
|
||||||
|
{
|
||||||
|
return self::existsQuery($tableName, self::whereDataContains('$1'));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Query to determine if documents exist using a JSON Path match `@?`
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table in which existence should be checked
|
||||||
|
* @return string A `SELECT` statement to check existence of a document by JSON Path match
|
||||||
|
*/
|
||||||
|
public static function existsByJsonPath(string $tableName): string
|
||||||
|
{
|
||||||
|
return self::existsQuery($tableName, self::whereJsonPathMatches('$1'));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Query to retrieve a document by its ID
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table from which a document should be retrieved
|
||||||
|
* @return string A `SELECT` statement to retrieve a document by its ID
|
||||||
|
*/
|
||||||
|
public static function findById(string $tableName): string
|
||||||
|
{
|
||||||
|
return sprintf('%s WHERE %s', self::selectFromTable($tableName), self::whereById('$1'));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Query to retrieve documents using a JSON containment query `@>`
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table from which a document should be retrieved
|
||||||
|
* @return string A `SELECT` statement to retrieve documents by JSON containment
|
||||||
|
*/
|
||||||
|
public static function findByContains(string $tableName): string
|
||||||
|
{
|
||||||
|
return sprintf('%s WHERE %s', self::selectFromTable($tableName), self::whereDataContains('$1'));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Query to retrieve documents using a JSON Path match `@?`
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table from which a document should be retrieved
|
||||||
|
* @return string A `SELECT` statement to retrieve a documents by JSON Path match
|
||||||
|
*/
|
||||||
|
public static function findByJsonPath(string $tableName): string
|
||||||
|
{
|
||||||
|
return sprintf('%s WHERE %s', self::selectFromTable($tableName), self::whereJsonPathMatches('$1'));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Query to update a document, replacing the existing document
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table in which a document should be updated
|
||||||
|
* @return string An `UPDATE` statement to update a document by its ID
|
||||||
|
*/
|
||||||
|
public static function updateFull(string $tableName): string
|
||||||
|
{
|
||||||
|
return sprintf('UPDATE %s SET data = $2 WHERE %s', $tableName, self::whereById('$1'));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Query to apply a partial update to a document
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table in which documents should be updated
|
||||||
|
* @param string $where The `WHERE` clause specifying which documents should be updated
|
||||||
|
* @return string An `UPDATE` statement to update a partial document ($1 is ID, $2 is document)
|
||||||
|
*/
|
||||||
|
private static function updatePartial(string $tableName, string $where): string
|
||||||
|
{
|
||||||
|
return sprintf('UPDATE %s SET data = data || $2 WHERE %s', $tableName, $where);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Query to update a document, merging the existing document with the one provided
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table in which a document should be updated
|
||||||
|
* @return string An `UPDATE` statement to update a document by its ID
|
||||||
|
*/
|
||||||
|
public static function updatePartialById(string $tableName): string
|
||||||
|
{
|
||||||
|
return self::updatePartial($tableName, self::whereById('$1'));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Query to update partial documents matching a JSON containment query `@>`
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table in which documents should be updated
|
||||||
|
* @return string An `UPDATE` statement to update documents by JSON containment
|
||||||
|
*/
|
||||||
|
public static function updatePartialByContains(string $tableName): string
|
||||||
|
{
|
||||||
|
return self::updatePartial($tableName, self::whereDataContains('$1'));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Query to update partial documents matching a JSON containment query `@>`
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table in which documents should be updated
|
||||||
|
* @return string An `UPDATE` statement to update documents by JSON Path match
|
||||||
|
*/
|
||||||
|
public static function updatePartialByJsonPath(string $tableName): string
|
||||||
|
{
|
||||||
|
return self::updatePartial($tableName, self::whereJsonPathMatches('$1'));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Query to delete documents
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table from which documents should be deleted
|
||||||
|
* @param string $where The criteria by which documents should be deleted
|
||||||
|
* @return string A `DELETE` statement to delete documents in the specified table
|
||||||
|
*/
|
||||||
|
private static function deleteQuery(string $tableName, string $where): string
|
||||||
|
{
|
||||||
|
return "DELETE FROM $tableName WHERE $where";
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Query to delete a document by its ID
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table from which a document should be deleted
|
||||||
|
* @return string A `DELETE` statement to delete a document by its ID
|
||||||
|
*/
|
||||||
|
public static function deleteById(string $tableName): string
|
||||||
|
{
|
||||||
|
return self::deleteQuery($tableName, self::whereById('$1'));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Query to delete documents using a JSON containment query `@>`
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table from which documents should be deleted
|
||||||
|
* @return string A `DELETE` statement to delete documents by JSON containment
|
||||||
|
*/
|
||||||
|
public static function deleteByContains(string $tableName): string
|
||||||
|
{
|
||||||
|
return self::deleteQuery($tableName, self::whereDataContains('$1'));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Query to delete documents using a JSON Path match `@?`
|
||||||
|
*
|
||||||
|
* @param string $tableName The name of the table from which documents should be deleted
|
||||||
|
* @return string A `DELETE` statement to delete documents by JSON Path match
|
||||||
|
*/
|
||||||
|
public static function deleteByJsonPath(string $tableName): string
|
||||||
|
{
|
||||||
|
return self::deleteQuery($tableName, self::whereJsonPathMatches('$1'));
|
||||||
|
}
|
||||||
|
}
|
||||||
16
src/app/lib/documents/functions.php
Normal file
16
src/app/lib/documents/functions.php
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use BitBadger\PgDocuments\Configuration;
|
||||||
|
use PgSql\Connection;
|
||||||
|
|
||||||
|
if (!function_exists('pg_conn')) {
|
||||||
|
/**
|
||||||
|
* Return the active PostgreSQL connection
|
||||||
|
*
|
||||||
|
* @return Connection The data connection from the configuration
|
||||||
|
*/
|
||||||
|
function pg_conn(): Connection
|
||||||
|
{
|
||||||
|
return Configuration::getPgConn();
|
||||||
|
}
|
||||||
|
}
|
||||||
36
src/app/lib/domain/AsOf.php
Normal file
36
src/app/lib/domain/AsOf.php
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace MyPrayerJournal\Domain;
|
||||||
|
|
||||||
|
use DateTimeImmutable;
|
||||||
|
|
||||||
|
class AsOf
|
||||||
|
{
|
||||||
|
/** The "as of" date/time */
|
||||||
|
public DateTimeImmutable $asOf;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sort an as-of item from oldest to newest
|
||||||
|
*
|
||||||
|
* @param AsOf $a The first item to compare
|
||||||
|
* @param AsOf $b The second item to compare
|
||||||
|
* @return int 0 if they are equal, -1 if A is earlier than B, or 1 if B is earlier than A
|
||||||
|
*/
|
||||||
|
public static function oldestToNewest(AsOf $a, AsOf $b): int
|
||||||
|
{
|
||||||
|
return $a->asOf == $b->asOf ? 0 : ($a->asOf < $b->asOf ? -1 : 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sort an as-of item from newest to oldest
|
||||||
|
*
|
||||||
|
* @param AsOf $a The first item to compare
|
||||||
|
* @param AsOf $b The second item to compare
|
||||||
|
* @return int 0 if they are equal, -1 if B is earlier than A, or 1 if A is earlier than B
|
||||||
|
*/
|
||||||
|
public static function newestToOldest(AsOf $a, AsOf $b): int
|
||||||
|
{
|
||||||
|
return $a->asOf == $b->asOf ? 0 : ($a->asOf > $b->asOf ? -1 : 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
36
src/app/lib/domain/History.php
Normal file
36
src/app/lib/domain/History.php
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace MyPrayerJournal\Domain;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A record of action taken on a prayer request, including updates to its text
|
||||||
|
*/
|
||||||
|
class History extends AsOf
|
||||||
|
{
|
||||||
|
/** The action taken that generated this history entry */
|
||||||
|
public RequestAction $status = RequestAction::Created;
|
||||||
|
|
||||||
|
/** The text of the update, if applicable */
|
||||||
|
public ?string $text = null;
|
||||||
|
|
||||||
|
public function __construct()
|
||||||
|
{
|
||||||
|
$this->asOf = unix_epoch();
|
||||||
|
}
|
||||||
|
|
||||||
|
public function isCreated(): bool
|
||||||
|
{
|
||||||
|
return $this->status == RequestAction::Created;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function isPrayed(): bool
|
||||||
|
{
|
||||||
|
return $this->status == RequestAction::Prayed;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function isAnswered(): bool
|
||||||
|
{
|
||||||
|
return $this->status == RequestAction::Answered;
|
||||||
|
}
|
||||||
|
}
|
||||||
85
src/app/lib/domain/JournalRequest.php
Normal file
85
src/app/lib/domain/JournalRequest.php
Normal file
@@ -0,0 +1,85 @@
|
|||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace MyPrayerJournal\Domain;
|
||||||
|
|
||||||
|
use DateTimeImmutable, DateTimeZone;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A prayer request, along with calculated fields, for use in displaying journal lists
|
||||||
|
*/
|
||||||
|
class JournalRequest extends AsOf
|
||||||
|
{
|
||||||
|
/** The ID of the prayer request */
|
||||||
|
public string $id = '';
|
||||||
|
|
||||||
|
/** The ID of the user to whom the prayer request belongs */
|
||||||
|
public string $userId = '';
|
||||||
|
|
||||||
|
/** The current text of the request */
|
||||||
|
public string $text = '';
|
||||||
|
|
||||||
|
/** The date/time this request was last marked as prayed */
|
||||||
|
public ?DateTimeImmutable $lastPrayed = null;
|
||||||
|
|
||||||
|
/** The last action taken on this request */
|
||||||
|
public RequestAction $lastAction = RequestAction::Created;
|
||||||
|
|
||||||
|
/** When this request will be shown again after having been snoozed */
|
||||||
|
public ?DateTimeImmutable $snoozedUntil = null;
|
||||||
|
|
||||||
|
/** When this request will be show again after a non-immediate recurrence */
|
||||||
|
public ?DateTimeImmutable $showAfter = null;
|
||||||
|
|
||||||
|
/** The type of recurrence for this request */
|
||||||
|
public RecurrenceType $recurrenceType = RecurrenceType::Immediate;
|
||||||
|
|
||||||
|
/** The units for non-immediate recurrence */
|
||||||
|
public ?int $recurrence = null;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The history for this request
|
||||||
|
* @var History[] $history
|
||||||
|
*/
|
||||||
|
public array $history = [];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The notes for this request
|
||||||
|
* @var Note[] $notes
|
||||||
|
*/
|
||||||
|
public array $notes = [];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Constructor
|
||||||
|
*
|
||||||
|
* @param ?Request $req The request off which this journal request should be populated
|
||||||
|
* @param bool $full Whether to include history and notes (true) or exclude them (false)
|
||||||
|
*/
|
||||||
|
public function __construct(?Request $req = null, bool $full = false)
|
||||||
|
{
|
||||||
|
if (is_null($req)) {
|
||||||
|
$this->asOf = unix_epoch();
|
||||||
|
$this->lastPrayed = null;
|
||||||
|
} else {
|
||||||
|
$this->id = $req->id;
|
||||||
|
$this->userId = $req->userId;
|
||||||
|
$this->snoozedUntil = $req->snoozedUntil;
|
||||||
|
$this->showAfter = $req->showAfter;
|
||||||
|
$this->recurrenceType = $req->recurrenceType;
|
||||||
|
$this->recurrence = $req->recurrence;
|
||||||
|
|
||||||
|
usort($req->history, AsOf::newestToOldest(...));
|
||||||
|
$this->asOf = $req->history[array_key_first($req->history)]->asOf;
|
||||||
|
$lastText = array_filter($req->history, fn (History $it) => !is_null($it->text));
|
||||||
|
$this->text = $lastText[array_key_first($lastText)]->text;
|
||||||
|
$lastPrayed = array_filter($req->history, fn (History $it) => $it->isPrayed());
|
||||||
|
if ($lastPrayed) $this->lastPrayed = $lastPrayed[array_key_first($lastPrayed)]->asOf;
|
||||||
|
|
||||||
|
if ($full) {
|
||||||
|
usort($req->notes, AsOf::newestToOldest(...));
|
||||||
|
$this->history = $req->history;
|
||||||
|
$this->notes = $req->notes;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
20
src/app/lib/domain/Note.php
Normal file
20
src/app/lib/domain/Note.php
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace MyPrayerJournal\Domain;
|
||||||
|
|
||||||
|
use DateTimeImmutable, DateTimeZone;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A note entered on a prayer request
|
||||||
|
*/
|
||||||
|
class Note extends AsOf
|
||||||
|
{
|
||||||
|
/** The note */
|
||||||
|
public string $notes = '';
|
||||||
|
|
||||||
|
public function __construct()
|
||||||
|
{
|
||||||
|
$this->asOf = unix_epoch();
|
||||||
|
}
|
||||||
|
}
|
||||||
32
src/app/lib/domain/RecurrenceType.php
Normal file
32
src/app/lib/domain/RecurrenceType.php
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace MyPrayerJournal\Domain;
|
||||||
|
|
||||||
|
use JsonSerializable;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The unit to use when determining when to show a recurring request
|
||||||
|
*/
|
||||||
|
enum RecurrenceType implements JsonSerializable
|
||||||
|
{
|
||||||
|
/** The request should reappear immediately */
|
||||||
|
case Immediate;
|
||||||
|
|
||||||
|
/** The request should reappear after the specified number of hours */
|
||||||
|
case Hours;
|
||||||
|
|
||||||
|
/** The request should reappear after the specified number of days */
|
||||||
|
case Days;
|
||||||
|
|
||||||
|
/** The request should reappear after the specified number of weeks */
|
||||||
|
case Weeks;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Serialize this enum using its name
|
||||||
|
*/
|
||||||
|
public function jsonSerialize(): mixed
|
||||||
|
{
|
||||||
|
return $this->name;
|
||||||
|
}
|
||||||
|
}
|
||||||
52
src/app/lib/domain/Request.php
Normal file
52
src/app/lib/domain/Request.php
Normal file
@@ -0,0 +1,52 @@
|
|||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace MyPrayerJournal\Domain;
|
||||||
|
|
||||||
|
use DateTimeImmutable;
|
||||||
|
use Visus\Cuid2\Cuid2;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A prayer request
|
||||||
|
*/
|
||||||
|
class Request
|
||||||
|
{
|
||||||
|
/** The ID for the request */
|
||||||
|
public string $id;
|
||||||
|
|
||||||
|
/** The date/time the request was originally entered */
|
||||||
|
public DateTimeImmutable $enteredOn;
|
||||||
|
|
||||||
|
/** The ID of the user to whom this request belongs */
|
||||||
|
public string $userId = '';
|
||||||
|
|
||||||
|
/** The date/time the snooze expires for this request */
|
||||||
|
public ?DateTimeImmutable $snoozedUntil = null;
|
||||||
|
|
||||||
|
/** The date/time this request should once again show as defined by recurrence */
|
||||||
|
public ?DateTimeImmutable $showAfter = null;
|
||||||
|
|
||||||
|
/** The type of recurrence for this request */
|
||||||
|
public RecurrenceType $recurrenceType = RecurrenceType::Immediate;
|
||||||
|
|
||||||
|
/** The units which apply to recurrences other than Immediate */
|
||||||
|
public ?int $recurrence = null;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The history for this request
|
||||||
|
* @var History[] $history
|
||||||
|
*/
|
||||||
|
public array $history = [];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The notes for this request
|
||||||
|
* @var Note[] $notes
|
||||||
|
*/
|
||||||
|
public array $notes = [];
|
||||||
|
|
||||||
|
public function __construct()
|
||||||
|
{
|
||||||
|
$this->id = (new Cuid2())->toString();
|
||||||
|
$this->enteredOn = unix_epoch();
|
||||||
|
}
|
||||||
|
}
|
||||||
32
src/app/lib/domain/RequestAction.php
Normal file
32
src/app/lib/domain/RequestAction.php
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace MyPrayerJournal\Domain;
|
||||||
|
|
||||||
|
use JsonSerializable;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* An action that was taken on a request
|
||||||
|
*/
|
||||||
|
enum RequestAction: string implements JsonSerializable
|
||||||
|
{
|
||||||
|
/** The request was entered */
|
||||||
|
case Created = 'Created';
|
||||||
|
|
||||||
|
/** Prayer was recorded for the request */
|
||||||
|
case Prayed = 'Prayed';
|
||||||
|
|
||||||
|
/** The request was updated */
|
||||||
|
case Updated = 'Updated';
|
||||||
|
|
||||||
|
/** The request was marked as answered */
|
||||||
|
case Answered = 'Answered';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Serialize this enum using its name
|
||||||
|
*/
|
||||||
|
public function jsonSerialize(): mixed
|
||||||
|
{
|
||||||
|
return $this->name;
|
||||||
|
}
|
||||||
|
}
|
||||||
108
src/app/lib/start.php
Normal file
108
src/app/lib/start.php
Normal file
@@ -0,0 +1,108 @@
|
|||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
require __DIR__ . '/../vendor/autoload.php';
|
||||||
|
|
||||||
|
error_reporting(E_ALL);
|
||||||
|
ini_set('display_errors', 'On');
|
||||||
|
|
||||||
|
use Auth0\SDK\Auth0;
|
||||||
|
use BitBadger\PgDocuments\Configuration;
|
||||||
|
use DateTimeZone;
|
||||||
|
use Dotenv\Dotenv;
|
||||||
|
use MyPrayerJournal\Constants;
|
||||||
|
|
||||||
|
Dotenv::createImmutable(__DIR__)->load();
|
||||||
|
|
||||||
|
/** @var Auth0 The Auth0 instance to use for the request */
|
||||||
|
$auth0 = new Auth0([
|
||||||
|
'domain' => $_ENV[Constants::AUTH0_DOMAIN],
|
||||||
|
'clientId' => $_ENV[Constants::AUTH0_CLIENT_ID],
|
||||||
|
'clientSecret' => $_ENV[Constants::AUTH0_CLIENT_SECRET],
|
||||||
|
'cookieSecret' => $_ENV[Constants::AUTH0_COOKIE_SECRET]
|
||||||
|
]);
|
||||||
|
|
||||||
|
/** @var ?object The Auth0 session for the current user */
|
||||||
|
$session = $auth0->getCredentials();
|
||||||
|
if (!is_null($session)) $_REQUEST[Constants::USER_ID] = $session->user[Constants::CLAIM_SUB];
|
||||||
|
|
||||||
|
$_REQUEST[Constants::IS_HTMX] = array_key_exists(Constants::HEADER_HX_REQUEST, $_SERVER)
|
||||||
|
&& (!array_key_exists(Constants::HEADER_HX_HIST_REQ, $_SERVER));
|
||||||
|
|
||||||
|
$_REQUEST[Constants::TIME_ZONE] = new DateTimeZone(
|
||||||
|
array_key_exists(Constants::HEADER_USER_TZ, $_SERVER) ? $_SERVER[Constants::HEADER_USER_TZ] : 'Etc/UTC');
|
||||||
|
|
||||||
|
$_REQUEST[Constants::VERSION] = 4;
|
||||||
|
|
||||||
|
Configuration::$startUp = '\MyPrayerJournal\Data::startUp';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Bring in a template
|
||||||
|
*/
|
||||||
|
function template(string $name): void
|
||||||
|
{
|
||||||
|
require_once __DIR__ . "/../templates/$name.php";
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* If a user is not found, either redirect them or fail the request
|
||||||
|
*
|
||||||
|
* @param bool $fail Whether to fail the request (true) or redirect to log on (false - optional, default)
|
||||||
|
*/
|
||||||
|
function require_user(bool $fail = false): void
|
||||||
|
{
|
||||||
|
if (!array_key_exists(Constants::USER_ID, $_REQUEST)) {
|
||||||
|
if ($fail) {
|
||||||
|
http_response_code(403);
|
||||||
|
} else {
|
||||||
|
header(sprintf('Location: /user/log-on?%s=%s', Constants::RETURN_URL, $_SERVER[Constants::REQUEST_URI]));
|
||||||
|
}
|
||||||
|
exit;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Write a bare header for a component result
|
||||||
|
*/
|
||||||
|
function bare_header(): void
|
||||||
|
{
|
||||||
|
echo '<!DOCTYPE html><html lang="en"><head><meta charset="utf8"><title></title></head><body>';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a traditional and htmx link, and apply an active class if the link is active
|
||||||
|
*
|
||||||
|
* @param string $url The URL of the page to be linked
|
||||||
|
* @param array $classNames CSS class names to be applied to the link (optional, default none)
|
||||||
|
* @param bool $checkActive Whether to apply an active class if the route matches (optional, default false)
|
||||||
|
*/
|
||||||
|
function page_link(string $url, array $classNames = [], bool $checkActive = false): void
|
||||||
|
{
|
||||||
|
echo 'href="'. $url . '" hx-get="' . $url . '"';
|
||||||
|
if ($checkActive && str_starts_with($_SERVER[Constants::REQUEST_URI], $url)) {
|
||||||
|
$classNames[] = 'is-active-route';
|
||||||
|
}
|
||||||
|
if (!empty($classNames)) {
|
||||||
|
echo sprintf(' class="%s"', implode(' ', $classNames));
|
||||||
|
}
|
||||||
|
echo ' hx-target="#top" hx-swap="innerHTML" hx-push-url="true"';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Close any open database connection; close the `body` and `html` tags
|
||||||
|
*/
|
||||||
|
function end_request(): void
|
||||||
|
{
|
||||||
|
Configuration::closeConn();
|
||||||
|
echo '</body></html>';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a new instance of the Unix epoch
|
||||||
|
*
|
||||||
|
* @return DateTimeImmutable An immutable date/time as of the Unix epoch
|
||||||
|
*/
|
||||||
|
function unix_epoch(): DateTimeImmutable
|
||||||
|
{
|
||||||
|
return new DateTimeImmutable('1/1/1970', new DateTimeZone('Etc/UTC'));
|
||||||
|
}
|
||||||
@@ -1,33 +0,0 @@
|
|||||||
{
|
|
||||||
"name": "my-prayer-journal",
|
|
||||||
"version": "1.1.0",
|
|
||||||
"description": "myPrayerJournal - Front End",
|
|
||||||
"author": "Daniel J. Summers <daniel@bitbadger.solutions>",
|
|
||||||
"private": true,
|
|
||||||
"scripts": {
|
|
||||||
"serve": "vue-cli-service serve",
|
|
||||||
"build": "vue-cli-service build --modern",
|
|
||||||
"lint": "vue-cli-service lint",
|
|
||||||
"apistart": "cd ../api/MyPrayerJournal.Api && dotnet run",
|
|
||||||
"vue": "vue-cli-service build --modern && cd ../api/MyPrayerJournal.Api && dotnet run"
|
|
||||||
},
|
|
||||||
"dependencies": {
|
|
||||||
"auth0-js": "^9.7.3",
|
|
||||||
"axios": "^0.18.0",
|
|
||||||
"moment": "^2.18.1",
|
|
||||||
"vue": "^2.5.15",
|
|
||||||
"vue-progressbar": "^0.7.3",
|
|
||||||
"vue-router": "^3.0.0",
|
|
||||||
"vue-toast": "^3.1.0",
|
|
||||||
"vuex": "^3.0.1"
|
|
||||||
},
|
|
||||||
"devDependencies": {
|
|
||||||
"@vue/cli-plugin-babel": "^3.0.0",
|
|
||||||
"@vue/cli-plugin-eslint": "^3.0.0",
|
|
||||||
"@vue/cli-service": "^3.0.0",
|
|
||||||
"@vue/eslint-config-standard": "^3.0.0",
|
|
||||||
"pug": "^2.0.1",
|
|
||||||
"pug-plain-loader": "^1.0.0",
|
|
||||||
"vue-template-compiler": "^2.5.17"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
90
src/app/public/components/journal-items.php
Normal file
90
src/app/public/components/journal-items.php
Normal file
@@ -0,0 +1,90 @@
|
|||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
require_once '../../lib/start.php';
|
||||||
|
|
||||||
|
use MyPrayerJournal\{ Constants, Data, Dates };
|
||||||
|
use MyPrayerJournal\Domain\JournalRequest;
|
||||||
|
|
||||||
|
require_user(true);
|
||||||
|
|
||||||
|
$requests = Data::getJournal($_REQUEST[Constants::USER_ID]);
|
||||||
|
|
||||||
|
bare_header();
|
||||||
|
if ($requests) { ?>
|
||||||
|
<section id="journalItems" class="row row-cols-1 row-cols-md-2 row-cols-lg-3 row-cols-xl-4 g-3" hx-target="this"
|
||||||
|
hx-swap="outerHTML" aria-label="Prayer Requests">
|
||||||
|
<p class="mb-3 has-text-centered">
|
||||||
|
<a <?php page_link('/request/edit?new'); ?> class="button is-light">
|
||||||
|
<span class="material-icons">add_box</span> Add a Prayer Request
|
||||||
|
</a>
|
||||||
|
</p><?php
|
||||||
|
array_walk($requests, journal_card(...)); ?>
|
||||||
|
</section><?php
|
||||||
|
} else {
|
||||||
|
$_REQUEST['EMPTY_HEADING'] = 'No Active Requests';
|
||||||
|
$_REQUEST['EMPTY_LINK'] = '/request/edit?new';
|
||||||
|
$_REQUEST['EMPTY_BTN_TXT'] = 'Add a Request';
|
||||||
|
$_REQUEST['EMPTY_TEXT'] = 'You have no requests to be shown; see the “Active” link above for '
|
||||||
|
. 'snoozed or deferred requests, and the “Answered” link for answered requests';
|
||||||
|
template('no_content');
|
||||||
|
}
|
||||||
|
end_request();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Format the activity and relative time
|
||||||
|
*
|
||||||
|
* @param string $activity The activity performed (activity or prayed)
|
||||||
|
* @param DateTimeImmutable $asOf The date/time the activity was performed
|
||||||
|
*/
|
||||||
|
function format_activity(string $activity, DateTimeImmutable $asOf): void
|
||||||
|
{
|
||||||
|
echo sprintf('last %s <span title="%s">%s</span>', $activity,
|
||||||
|
$asOf->setTimezone($_REQUEST[Constants::TIME_ZONE])->format('l, F jS, Y/g:ia T'),
|
||||||
|
Dates::formatDistance(Dates::now(), $asOf));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a card for a prayer request
|
||||||
|
*
|
||||||
|
* @param JournalRequest $req The request for which a card should be generated
|
||||||
|
*/
|
||||||
|
function journal_card(JournalRequest $req): void
|
||||||
|
{
|
||||||
|
$spacer = '<span> </span>'; ?>
|
||||||
|
<div class="col">
|
||||||
|
<div class="card h-100">
|
||||||
|
<div class="card-header p-0 d-flex" role="toolbar">
|
||||||
|
<a <?php page_link("/request/edit?{$req->id}"); ?> class="button btn-secondary" title="Edit Request">
|
||||||
|
<span class="material-icons">edit</span>
|
||||||
|
</a><?php echo $spacer; ?>
|
||||||
|
<button type="button" class="btn btn-secondary" title="Add Notes" data-bs-toggle="modal"
|
||||||
|
data-bs-target="#notesModal" hx-get="/components/request/<?php echo $req->id; ?>/add-notes"
|
||||||
|
hx-target="#notesBody" hx-swap="innerHTML">
|
||||||
|
<span class="material-icons">comment</span>
|
||||||
|
</button><?php echo $spacer; ?>
|
||||||
|
<button type="button" class="btn btn-secondary" title="Snooze Request" data-bs-toggle="modal"
|
||||||
|
data-bs-target="#snoozeModal" hx-get="/components/request/<?php echo $req->id; ?>/snooze"
|
||||||
|
hx-target="#snoozeBody" hx-swap="innerHTML">
|
||||||
|
<span class="material-icons">schedule</span>
|
||||||
|
</button>
|
||||||
|
<div class="flex-grow-1"></div>
|
||||||
|
<a href="/request/prayed?<?php echo $req->id; ?>" class="button btn-success w-25"
|
||||||
|
hx-patch="/request/prayed?<?php echo $req->id; ?>" title="Mark as Prayed">
|
||||||
|
<span class="material-icons">done</span>
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
<div class="card-body">
|
||||||
|
<p class="request-text"><?php echo htmlentities($req->text); ?></p>
|
||||||
|
</div>
|
||||||
|
<div class="card-footer text-end text-muted px-1 py-0">
|
||||||
|
<em><?php
|
||||||
|
[ $activity, $asOf ] = is_null($req->lastPrayed)
|
||||||
|
? [ 'activity', $req->asOf ]
|
||||||
|
: [ 'prayed', $req->lastPrayed ];
|
||||||
|
format_activity($activity, $asOf); ?>
|
||||||
|
</em>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div><?php
|
||||||
|
}
|
||||||
Binary file not shown.
|
Before Width: | Height: | Size: 1.1 KiB |
@@ -1,19 +0,0 @@
|
|||||||
<!DOCTYPE html>
|
|
||||||
<html lang="en">
|
|
||||||
<head>
|
|
||||||
<meta charset="utf-8">
|
|
||||||
<meta http-equiv="X-UA-Compatible" content="IE=edge">
|
|
||||||
<meta name="viewport" content="width=device-width,initial-scale=1.0">
|
|
||||||
<link rel="icon" href="<%= BASE_URL %>favicon.ico">
|
|
||||||
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="preload" as="style">
|
|
||||||
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
|
|
||||||
<title>myPrayerJournal</title>
|
|
||||||
</head>
|
|
||||||
<body>
|
|
||||||
<noscript>
|
|
||||||
<strong>We're sorry but newapp doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
|
|
||||||
</noscript>
|
|
||||||
<div id="app"></div>
|
|
||||||
<!-- built files will be auto injected -->
|
|
||||||
</body>
|
|
||||||
</html>
|
|
||||||
25
src/app/public/index.php
Normal file
25
src/app/public/index.php
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
require_once '../lib/start.php';
|
||||||
|
|
||||||
|
use MyPrayerJournal\Constants;
|
||||||
|
|
||||||
|
$_REQUEST[Constants::PAGE_TITLE] = 'Welcome';
|
||||||
|
|
||||||
|
template('layout/page_header'); ?>
|
||||||
|
<main class="container">
|
||||||
|
<p class="block"> </p>
|
||||||
|
<p class="block">
|
||||||
|
myPrayerJournal is a place where individuals can record their prayer requests, record that they prayed for them,
|
||||||
|
update them as God moves in the situation, and record a final answer received on that request. It also allows
|
||||||
|
individuals to review their answered prayers.
|
||||||
|
</p>
|
||||||
|
<p class="block">
|
||||||
|
This site is open and available to the general public. To get started, simply click the “Log On”
|
||||||
|
link above, and log on with either a Microsoft or Google account. You can also learn more about the site at the
|
||||||
|
“Docs” link, also above.
|
||||||
|
</p>
|
||||||
|
</main><?php
|
||||||
|
template('layout/page_footer');
|
||||||
|
end_request();
|
||||||
20
src/app/public/journal.php
Normal file
20
src/app/public/journal.php
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
require_once '../lib/start.php';
|
||||||
|
|
||||||
|
use MyPrayerJournal\Constants;
|
||||||
|
|
||||||
|
require_user();
|
||||||
|
|
||||||
|
$_REQUEST[Constants::PAGE_TITLE] = "{$session->user[Constants::CLAIM_GIVEN_NAME]}’s Prayer Journal";
|
||||||
|
|
||||||
|
template('layout/page_header'); ?>
|
||||||
|
<main class="container">
|
||||||
|
<h2 class="title"><?php echo $_REQUEST[Constants::PAGE_TITLE]; ?></h2>
|
||||||
|
<p hx-get="/components/journal-items" hx-swap="outerHTML" hx-trigger="load delay:.25s">
|
||||||
|
Loading your prayer journal…
|
||||||
|
</p>
|
||||||
|
</main><?php
|
||||||
|
template('layout/page_footer');
|
||||||
|
end_request();
|
||||||
98
src/app/public/legal/privacy-policy.php
Normal file
98
src/app/public/legal/privacy-policy.php
Normal file
@@ -0,0 +1,98 @@
|
|||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
require_once '../../lib/start.php';
|
||||||
|
|
||||||
|
use MyPrayerJournal\Constants;
|
||||||
|
|
||||||
|
$_REQUEST[Constants::PAGE_TITLE] = 'Privacy Policy';
|
||||||
|
|
||||||
|
template('layout/page_header'); ?>
|
||||||
|
<main class="container">
|
||||||
|
<h2 class="title">Privacy Policy</h2>
|
||||||
|
<h6 class="subtitle">as of May 21<sup>st</sup>, 2018</h6>
|
||||||
|
<p class="mb-3">
|
||||||
|
The nature of the service is one where privacy is a must. The items below will help you understand the data we
|
||||||
|
collect, access, and store on your behalf as you use this service.
|
||||||
|
</p>
|
||||||
|
<div class="card mb-3">
|
||||||
|
<div class="card-header has-background-light">
|
||||||
|
<h3 class="card-header-title">Third Party Services</h3>
|
||||||
|
</div>
|
||||||
|
<p class="card-content">
|
||||||
|
myPrayerJournal utilizes a third-party authentication and identity provider. You should familiarize yourself
|
||||||
|
with the privacy policy for
|
||||||
|
<a href="https://auth0.com/privacy" target="_blank" rel="noopener">Auth0</a>, as well as your chosen
|
||||||
|
provider
|
||||||
|
(<a href="https://privacy.microsoft.com/en-us/privacystatement" target="_blank"
|
||||||
|
rel="noopener">Microsoft</a> or
|
||||||
|
<a href="https://policies.google.com/privacy" target="_blank" rel="noopener">Google</a>).
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div class="card mb-3">
|
||||||
|
<div class="card-header has-background-light">
|
||||||
|
<h3 class="card-header-title">What We Collect</h3>
|
||||||
|
</div>
|
||||||
|
<div class="card-content">
|
||||||
|
<h4 class="subtitle mb-3">Identifying Data</h4>
|
||||||
|
<ul class="mb-3 mx-5">
|
||||||
|
<li>
|
||||||
|
• The only identifying data myPrayerJournal stores is the subscriber (“sub”) field
|
||||||
|
from the token we receive from Auth0, once you have signed in through their hosted service. All
|
||||||
|
information is associated with you via this field.
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
• While you are signed in, within your browser, the service has access to your first and last
|
||||||
|
names, along with a URL to the profile picture (provided by your selected identity provider). This
|
||||||
|
information is not transmitted to the server, and is removed when “Log Off” is clicked.
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<h4 class="subtitle mb-3">User Provided Data</h4>
|
||||||
|
<ul class="mx-5">
|
||||||
|
<li>
|
||||||
|
• myPrayerJournal stores the information you provide, including the text of prayer requests,
|
||||||
|
updates, and notes; and the date/time when certain actions are taken.
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="card mb-3">
|
||||||
|
<div class="card-header has-background-light">
|
||||||
|
<h3 class="card-header-title">How Your Data Is Accessed / Secured</h3>
|
||||||
|
</div>
|
||||||
|
<ul class="card-content">
|
||||||
|
<li>
|
||||||
|
• Your provided data is returned to you, as required, to display your journal or your answered
|
||||||
|
requests. On the server, it is stored in a controlled-access database.
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
• Your data is backed up, along with other Bit Badger Solutions hosted systems, in a rolling
|
||||||
|
manner; backups are preserved for the prior 7 days, and backups from the 1<sup>st</sup> and
|
||||||
|
15<sup>th</sup> are preserved for 3 months. These backups are stored in a private cloud data repository.
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
• The data collected and stored is the absolute minimum necessary for the functionality of the
|
||||||
|
service. There are no plans to “monetize” this service, and storing the minimum amount of
|
||||||
|
information means that the data we have is not interesting to purchasers (or those who may have more
|
||||||
|
nefarious purposes).
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
• Access to servers and backups is strictly controlled and monitored for unauthorized access
|
||||||
|
attempts.
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
<div class="card mb-3">
|
||||||
|
<div class="card-header has-background-light">
|
||||||
|
<h3 class="card-header-title">Removing Your Data</h3>
|
||||||
|
</div>
|
||||||
|
<p class="card-content">
|
||||||
|
At any time, you may choose to discontinue using this service. Both Microsoft and Google provide ways to
|
||||||
|
revoke access from this application. However, if you want your data removed from the database, please
|
||||||
|
contact daniel at bitbadger.solutions (via e-mail, replacing at with @) prior to doing so, to ensure we can
|
||||||
|
determine which subscriber ID belongs to you.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</main><?php
|
||||||
|
template('layout/page_footer');
|
||||||
|
end_request();
|
||||||
73
src/app/public/legal/terms-of-service.php
Normal file
73
src/app/public/legal/terms-of-service.php
Normal file
@@ -0,0 +1,73 @@
|
|||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
require_once '../../lib/start.php';
|
||||||
|
|
||||||
|
use MyPrayerJournal\Constants;
|
||||||
|
|
||||||
|
$_REQUEST[Constants::PAGE_TITLE] = 'Terms of Service';
|
||||||
|
|
||||||
|
template('layout/page_header'); ?>
|
||||||
|
<main class="container">
|
||||||
|
<h2 class="title">Terms of Service</h2>
|
||||||
|
<h6 class="subtitle">as of May 21<sup>st</sup>, 2018</h6>
|
||||||
|
<div class="card mb-3">
|
||||||
|
<div class="card-header has-background-light">
|
||||||
|
<h3 class="card-header-title">1. Acceptance of Terms</h3>
|
||||||
|
</div>
|
||||||
|
<p class="card-content">
|
||||||
|
By accessing this web site, you are agreeing to be bound by these Terms and Conditions, and that you are
|
||||||
|
responsible to ensure that your use of this site complies with all applicable laws. Your continued use of
|
||||||
|
this site implies your acceptance of these terms.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div class="card mb-3">
|
||||||
|
<div class="card-header has-background-light">
|
||||||
|
<h3 class="card-header-title">2. Description of Service and Registration</h3>
|
||||||
|
</div>
|
||||||
|
<p class="card-content">
|
||||||
|
myPrayerJournal is a service that allows individuals to enter and amend their prayer requests. It requires
|
||||||
|
no registration by itself, but access is granted based on a successful login with an external identity
|
||||||
|
provider. See <a <?php page_link('/legal/privacy-policy'); ?>>our privacy policy</a> for details on how that
|
||||||
|
information is accessed and stored.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div class="card mb-3">
|
||||||
|
<div class="card-header has-background-light">
|
||||||
|
<h3 class="card-header-title">3. Third Party Services</h3>
|
||||||
|
</div>
|
||||||
|
<p class="card-content">
|
||||||
|
This service utilizes a third-party service provider for identity management. Review the terms of service
|
||||||
|
for <a href="https://auth0.com/terms" target="_blank" rel="noopener">Auth0</a>, as well as those for the
|
||||||
|
selected authorization provider
|
||||||
|
(<a href="https://www.microsoft.com/en-us/servicesagreement" target="_blank"
|
||||||
|
rel="noopener">Microsoft</a> or
|
||||||
|
<a href="https://policies.google.com/terms" target="_blank" rel="noopener">Google</a>).
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div class="card mb-3">
|
||||||
|
<div class="card-header has-background-light">
|
||||||
|
<h3 class="card-header-title">4. Liability</h3>
|
||||||
|
</div>
|
||||||
|
<p class="card-content">
|
||||||
|
This service is provided “as is”, and no warranty (express or implied) exists. The service and
|
||||||
|
its developers may not be held liable for any damages that may arise through the use of this service.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div class="card mb-3">
|
||||||
|
<div class="card-header has-background-light">
|
||||||
|
<h3 class="card-header-title">5. Updates to Terms</h3>
|
||||||
|
</div>
|
||||||
|
<p class="card-content">
|
||||||
|
These terms and conditions may be updated at any time, and this service does not have the capability to
|
||||||
|
notify users when these change. The date at the top of the page will be updated when any of the text of
|
||||||
|
these terms is updated.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<p>
|
||||||
|
You may also wish to review our <a <?php page_link('/legal/privacy-policy'); ?>>privacy policy</a> to learn how
|
||||||
|
we handle your data.
|
||||||
|
</p>
|
||||||
|
</main><?php
|
||||||
|
template('layout/page_footer');
|
||||||
|
end_request();
|
||||||
104
src/app/public/script/mpj.js
Normal file
104
src/app/public/script/mpj.js
Normal file
@@ -0,0 +1,104 @@
|
|||||||
|
"use strict"
|
||||||
|
|
||||||
|
/** myPrayerJournal script */
|
||||||
|
this.mpj = {
|
||||||
|
/**
|
||||||
|
* Show a message via toast
|
||||||
|
* @param {string} message The message to show
|
||||||
|
*/
|
||||||
|
showToast (message) {
|
||||||
|
const [level, msg] = message.split("|||")
|
||||||
|
|
||||||
|
let header
|
||||||
|
if (level !== "success") {
|
||||||
|
const heading = typ => `<span class="me-auto"><strong>${typ.toUpperCase()}</strong></span>`
|
||||||
|
|
||||||
|
header = document.createElement("div")
|
||||||
|
header.className = "toast-header"
|
||||||
|
header.innerHTML = heading(level === "warning" ? level : "error")
|
||||||
|
|
||||||
|
const close = document.createElement("button")
|
||||||
|
close.type = "button"
|
||||||
|
close.className = "btn-close"
|
||||||
|
close.setAttribute("data-bs-dismiss", "toast")
|
||||||
|
close.setAttribute("aria-label", "Close")
|
||||||
|
header.appendChild(close)
|
||||||
|
}
|
||||||
|
|
||||||
|
const body = document.createElement("div")
|
||||||
|
body.className = "toast-body"
|
||||||
|
body.innerText = msg
|
||||||
|
|
||||||
|
const toastEl = document.createElement("div")
|
||||||
|
toastEl.className = `toast bg-${level === "error" ? "danger" : level} text-white`
|
||||||
|
toastEl.setAttribute("role", "alert")
|
||||||
|
toastEl.setAttribute("aria-live", "assertlive")
|
||||||
|
toastEl.setAttribute("aria-atomic", "true")
|
||||||
|
toastEl.addEventListener("hidden.bs.toast", e => e.target.remove())
|
||||||
|
if (header) toastEl.appendChild(header)
|
||||||
|
|
||||||
|
toastEl.appendChild(body)
|
||||||
|
document.getElementById("toasts").appendChild(toastEl)
|
||||||
|
new bootstrap.Toast(toastEl, { autohide: level === "success" }).show()
|
||||||
|
},
|
||||||
|
/**
|
||||||
|
* Load local version of Bootstrap CSS if the CDN load failed
|
||||||
|
*/
|
||||||
|
ensureCss () {
|
||||||
|
let loaded = false
|
||||||
|
for (let i = 0; !loaded && i < document.styleSheets.length; i++) {
|
||||||
|
loaded = document.styleSheets[i].href.endsWith("bootstrap.min.css")
|
||||||
|
}
|
||||||
|
if (!loaded) {
|
||||||
|
const css = document.createElement("link")
|
||||||
|
css.rel = "stylesheet"
|
||||||
|
css.href = "/style/bootstrap.min.css"
|
||||||
|
document.getElementsByTagName("head")[0].appendChild(css)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
/** Script for the request edit component */
|
||||||
|
edit: {
|
||||||
|
/**
|
||||||
|
* Toggle the recurrence input fields
|
||||||
|
* @param {Event} e The click event
|
||||||
|
*/
|
||||||
|
toggleRecurrence ({ target }) {
|
||||||
|
const isDisabled = target.value === "Immediate"
|
||||||
|
;["recurCount", "recurInterval"].forEach(it => document.getElementById(it).disabled = isDisabled)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
/**
|
||||||
|
* The time zone of the current browser
|
||||||
|
* @type {string}
|
||||||
|
**/
|
||||||
|
timeZone: undefined,
|
||||||
|
/**
|
||||||
|
* Derive the time zone from the current browser
|
||||||
|
*/
|
||||||
|
deriveTimeZone () {
|
||||||
|
try {
|
||||||
|
this.timeZone = (new Intl.DateTimeFormat()).resolvedOptions().timeZone
|
||||||
|
} catch (_) { }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
htmx.on("htmx:afterOnLoad", function (evt) {
|
||||||
|
const hdrs = evt.detail.xhr.getAllResponseHeaders()
|
||||||
|
// Show a message if there was one in the response
|
||||||
|
if (hdrs.indexOf("x-toast") >= 0) {
|
||||||
|
mpj.showToast(evt.detail.xhr.getResponseHeader("x-toast"))
|
||||||
|
}
|
||||||
|
// Hide a modal window if requested
|
||||||
|
if (hdrs.indexOf("x-hide-modal") >= 0) {
|
||||||
|
document.getElementById(evt.detail.xhr.getResponseHeader("x-hide-modal") + "Dismiss").click()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
htmx.on("htmx:configRequest", function (evt) {
|
||||||
|
// Send the user's current time zone so that we can display local time
|
||||||
|
if (mpj.timeZone) {
|
||||||
|
evt.detail.headers["X-Time-Zone"] = mpj.timeZone
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
mpj.deriveTimeZone()
|
||||||
60
src/app/public/style/style.css
Normal file
60
src/app/public/style/style.css
Normal file
@@ -0,0 +1,60 @@
|
|||||||
|
|
||||||
|
nav.navbar.is-dark {
|
||||||
|
background-color: green;
|
||||||
|
|
||||||
|
& .m {
|
||||||
|
font-weight: 100;
|
||||||
|
}
|
||||||
|
& .p {
|
||||||
|
font-weight: 400;
|
||||||
|
}
|
||||||
|
& .j {
|
||||||
|
font-weight: 700;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.nav-item {
|
||||||
|
& a:link,
|
||||||
|
& a:visited {
|
||||||
|
padding: .5rem 1rem;
|
||||||
|
margin: 0 .5rem;
|
||||||
|
border-radius: .5rem;
|
||||||
|
color: white;
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
& a:hover {
|
||||||
|
cursor: pointer;
|
||||||
|
background-color: rgba(255, 255, 255, .2);
|
||||||
|
}
|
||||||
|
& a.is-active-route {
|
||||||
|
border-top-left-radius: 0;
|
||||||
|
border-top-right-radius: 0;
|
||||||
|
border-top: solid 4px rgba(255, 255, 255, .3);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
form {
|
||||||
|
max-width: 60rem;
|
||||||
|
margin: auto;
|
||||||
|
}
|
||||||
|
.action-cell .material-icons {
|
||||||
|
font-size: 1.1rem ;
|
||||||
|
}
|
||||||
|
.material-icons {
|
||||||
|
vertical-align: bottom;
|
||||||
|
}
|
||||||
|
#toastHost {
|
||||||
|
position: sticky;
|
||||||
|
bottom: 0;
|
||||||
|
}
|
||||||
|
.request-text {
|
||||||
|
white-space: pre-line
|
||||||
|
}
|
||||||
|
|
||||||
|
footer {
|
||||||
|
border-top: solid 1px lightgray;
|
||||||
|
margin: 1rem -1rem 0;
|
||||||
|
padding: 0 1rem;
|
||||||
|
|
||||||
|
& p {
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
9
src/app/public/user/log-off.php
Normal file
9
src/app/public/user/log-off.php
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
require_once '../../lib/start.php';
|
||||||
|
|
||||||
|
use MyPrayerJournal\Constants;
|
||||||
|
|
||||||
|
header("Location: {$auth0->logout($_ENV[Constants::BASE_URL])}");
|
||||||
|
exit;
|
||||||
24
src/app/public/user/log-on.php
Normal file
24
src/app/public/user/log-on.php
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
require_once '../../lib/start.php';
|
||||||
|
|
||||||
|
use MyPrayerJournal\Constants;
|
||||||
|
|
||||||
|
$auth0->clear();
|
||||||
|
|
||||||
|
// Check for return URL; if present, store it in a cookie we'll retrieve when we're logged in
|
||||||
|
$nonce = '';
|
||||||
|
if (array_key_exists(Constants::RETURN_URL, $_GET)) {
|
||||||
|
$nonce = urlencode(base64_encode(openssl_random_pseudo_bytes(8)));
|
||||||
|
setcookie(Constants::COOKIE_REDIRECT, "$nonce|{$_GET[Constants::RETURN_URL]}", [
|
||||||
|
'expires' => -1,
|
||||||
|
'secure' => true,
|
||||||
|
'httponly' => true,
|
||||||
|
'samesite' => 'Strict'
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
$params = $nonce ? [ Constants::LOG_ON_STATE => $nonce ] : [];
|
||||||
|
|
||||||
|
header('Location: ' . $auth0->login("{$_ENV[Constants::BASE_URL]}/user/logged-on", $params));
|
||||||
|
exit;
|
||||||
26
src/app/public/user/logged-on.php
Normal file
26
src/app/public/user/logged-on.php
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
require_once '../../lib/start.php';
|
||||||
|
|
||||||
|
use MyPrayerJournal\Constants;
|
||||||
|
|
||||||
|
$auth0->exchange("{$_ENV[Constants::BASE_URL]}/user/logged-on");
|
||||||
|
|
||||||
|
$nextUrl = '/journal';
|
||||||
|
if (array_key_exists(Constants::LOG_ON_STATE, $_GET)) {
|
||||||
|
$nonce = base64_decode(urldecode($_GET[Constants::LOG_ON_STATE]));
|
||||||
|
[$verify, $newNext] = explode('|', $_COOKIE[Constants::COOKIE_REDIRECT]);
|
||||||
|
if ($verify == $nonce && $newNext && str_starts_with($newNext, '/') && !str_starts_with($newNext, '//')) {
|
||||||
|
$nextUrl = $newNext;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
setcookie(Constants::COOKIE_REDIRECT, '', [
|
||||||
|
'expires' => -1,
|
||||||
|
'secure' => true,
|
||||||
|
'httponly' => true,
|
||||||
|
'samesite' => 'Strict'
|
||||||
|
]);
|
||||||
|
header("Location: $nextUrl");
|
||||||
|
exit;
|
||||||
@@ -1,244 +0,0 @@
|
|||||||
<template lang="pug">
|
|
||||||
#app(role='application')
|
|
||||||
navigation
|
|
||||||
#content
|
|
||||||
router-view
|
|
||||||
vue-progress-bar
|
|
||||||
toast(ref='toast')
|
|
||||||
footer.mpj-text-right.mpj-muted-text
|
|
||||||
p
|
|
||||||
| myPrayerJournal v{{ version }}
|
|
||||||
br
|
|
||||||
em: small.
|
|
||||||
#[router-link(:to="{ name: 'PrivacyPolicy' }") Privacy Policy] •
|
|
||||||
#[router-link(:to="{ name: 'TermsOfService' }") Terms of Service] •
|
|
||||||
#[a(href='https://github.com/bit-badger/myprayerjournal' target='_blank') Developed] and hosted by
|
|
||||||
#[a(href='https://bitbadger.solutions' target='_blank') Bit Badger Solutions]
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<script>
|
|
||||||
'use strict'
|
|
||||||
|
|
||||||
import Navigation from './components/common/Navigation.vue'
|
|
||||||
|
|
||||||
import { version } from '../package.json'
|
|
||||||
|
|
||||||
export default {
|
|
||||||
name: 'app',
|
|
||||||
components: {
|
|
||||||
Navigation
|
|
||||||
},
|
|
||||||
data () {
|
|
||||||
return {}
|
|
||||||
},
|
|
||||||
mounted () {
|
|
||||||
this.$refs.toast.setOptions({ position: 'bottom right' })
|
|
||||||
},
|
|
||||||
computed: {
|
|
||||||
toast () {
|
|
||||||
return this.$refs.toast
|
|
||||||
},
|
|
||||||
version () {
|
|
||||||
return version.endsWith('.0') ? version.substr(0, version.length - 2) : version
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<style>
|
|
||||||
html, body {
|
|
||||||
background-color: whitesmoke;
|
|
||||||
font-family: -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Oxygen-Sans,Ubuntu,Cantarell,"Helvetica Neue",sans-serif;
|
|
||||||
font-size: 1rem;
|
|
||||||
}
|
|
||||||
body {
|
|
||||||
padding-top: 50px;
|
|
||||||
margin: 0;
|
|
||||||
}
|
|
||||||
h1, h2, h3, h4, h5 {
|
|
||||||
font-weight: 500;
|
|
||||||
margin-top: 0;
|
|
||||||
}
|
|
||||||
h1 {
|
|
||||||
font-size: 2.5rem;
|
|
||||||
}
|
|
||||||
h2 {
|
|
||||||
font-size: 2rem;
|
|
||||||
}
|
|
||||||
h3 {
|
|
||||||
font-size: 1.75rem;
|
|
||||||
}
|
|
||||||
h4 {
|
|
||||||
font-size: 1.5rem;
|
|
||||||
}
|
|
||||||
h5 {
|
|
||||||
font-size: 1.25rem;
|
|
||||||
}
|
|
||||||
p {
|
|
||||||
margin-bottom: 0;
|
|
||||||
}
|
|
||||||
input, textarea, select {
|
|
||||||
border-radius: .25rem;
|
|
||||||
font-size: 1rem;
|
|
||||||
}
|
|
||||||
textarea {
|
|
||||||
font-family: "SFMono-Regular",Consolas,"Liberation Mono",Menlo,Courier,monospace;
|
|
||||||
}
|
|
||||||
input, select {
|
|
||||||
font-family: inherit;
|
|
||||||
}
|
|
||||||
button,
|
|
||||||
a[role="button"] {
|
|
||||||
border: solid 1px #050;
|
|
||||||
border-radius: .5rem;
|
|
||||||
background-color: rgb(235, 235, 235);
|
|
||||||
padding: .25rem;
|
|
||||||
font-size: 1rem;
|
|
||||||
}
|
|
||||||
a[role="button"]:link,
|
|
||||||
a[role="button"]:visited {
|
|
||||||
color: black;
|
|
||||||
}
|
|
||||||
button.primary,
|
|
||||||
a[role="button"].primary {
|
|
||||||
background-color: white;
|
|
||||||
border-width: 3px;
|
|
||||||
}
|
|
||||||
button:hover,
|
|
||||||
a[role="button"]:hover {
|
|
||||||
cursor: pointer;
|
|
||||||
background-color: #050;
|
|
||||||
color: white;
|
|
||||||
text-decoration: none;
|
|
||||||
}
|
|
||||||
label {
|
|
||||||
font-variant: small-caps;
|
|
||||||
font-size: 1.1rem;
|
|
||||||
}
|
|
||||||
label.normal {
|
|
||||||
font-variant: unset;
|
|
||||||
font-size: unset;
|
|
||||||
}
|
|
||||||
footer {
|
|
||||||
border-top: solid 1px lightgray;
|
|
||||||
margin-top: 1rem;
|
|
||||||
padding: 0 1rem;
|
|
||||||
}
|
|
||||||
footer p {
|
|
||||||
margin: 0;
|
|
||||||
}
|
|
||||||
a:link, a:visited {
|
|
||||||
color: #050;
|
|
||||||
text-decoration: none;
|
|
||||||
}
|
|
||||||
a:hover {
|
|
||||||
text-decoration: underline;
|
|
||||||
}
|
|
||||||
.mpj-main-content {
|
|
||||||
max-width: 60rem;
|
|
||||||
margin: auto;
|
|
||||||
}
|
|
||||||
.mpj-main-content-wide {
|
|
||||||
margin: .5rem;
|
|
||||||
}
|
|
||||||
@media screen and (max-width: 21rem) {
|
|
||||||
.mpj-main-content-wide {
|
|
||||||
margin: 0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
.mpj-request-text {
|
|
||||||
white-space: pre-line;
|
|
||||||
}
|
|
||||||
.mpj-request-list p {
|
|
||||||
border-top: solid 1px lightgray;
|
|
||||||
}
|
|
||||||
.mpj-request-list p:first-child {
|
|
||||||
border-top: none;
|
|
||||||
}
|
|
||||||
.mpj-request-log {
|
|
||||||
width: 100%;
|
|
||||||
}
|
|
||||||
.mpj-request-log thead th {
|
|
||||||
border-top: solid 1px lightgray;
|
|
||||||
border-bottom: solid 2px lightgray;
|
|
||||||
text-align: left;
|
|
||||||
}
|
|
||||||
.mpj-request-log tbody td {
|
|
||||||
border-bottom: dotted 1px lightgray;
|
|
||||||
vertical-align: top;
|
|
||||||
}
|
|
||||||
.mpj-bg {
|
|
||||||
background-image: -webkit-gradient(linear, left top, left bottom, from(#050), to(whitesmoke));
|
|
||||||
background-image: -webkit-linear-gradient(top, #050, whitesmoke);
|
|
||||||
background-image: -moz-linear-gradient(top, #050, whitesmoke);
|
|
||||||
background-image: linear-gradient(to bottom, #050, whitesmoke);
|
|
||||||
}
|
|
||||||
.mpj-text-center {
|
|
||||||
text-align: center;
|
|
||||||
}
|
|
||||||
.mpj-text-nowrap {
|
|
||||||
white-space: nowrap;
|
|
||||||
}
|
|
||||||
.mpj-text-right {
|
|
||||||
text-align: right;
|
|
||||||
}
|
|
||||||
.mpj-muted-text {
|
|
||||||
color: rgba(0, 0, 0, .6);
|
|
||||||
}
|
|
||||||
.mpj-narrow {
|
|
||||||
max-width: 40rem;
|
|
||||||
margin: auto;
|
|
||||||
}
|
|
||||||
.mpj-skinny {
|
|
||||||
max-width: 20rem;
|
|
||||||
margin: auto;
|
|
||||||
}
|
|
||||||
.mpj-full-width {
|
|
||||||
width: 100%;
|
|
||||||
}
|
|
||||||
.mpj-modal {
|
|
||||||
position: fixed;
|
|
||||||
z-index: 8;
|
|
||||||
left: 0;
|
|
||||||
top: 0;
|
|
||||||
width: 100%;
|
|
||||||
height: 100%;
|
|
||||||
overflow: auto;
|
|
||||||
background-color: rgba(0, 0, 0, .4);
|
|
||||||
}
|
|
||||||
.mpj-modal-content {
|
|
||||||
background-color: whitesmoke;
|
|
||||||
border: solid 1px #050;
|
|
||||||
border-radius: .5rem;
|
|
||||||
animation-name: animatetop;
|
|
||||||
animation-duration: 0.4s;
|
|
||||||
padding: 1rem;
|
|
||||||
margin-top: 4rem;
|
|
||||||
}
|
|
||||||
@keyframes animatetop {
|
|
||||||
from {
|
|
||||||
top: -300px;
|
|
||||||
opacity: 0;
|
|
||||||
}
|
|
||||||
to {
|
|
||||||
top: 0;
|
|
||||||
opacity: 1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
.mpj-modal-content header {
|
|
||||||
margin: -1rem -1rem .5rem;
|
|
||||||
border-radius: .4rem;
|
|
||||||
}
|
|
||||||
.mpj-modal-content header h5 {
|
|
||||||
color: white;
|
|
||||||
margin: 0;
|
|
||||||
padding: 1rem;
|
|
||||||
}
|
|
||||||
.mpj-margin {
|
|
||||||
margin-left: 1rem;
|
|
||||||
margin-right: 1rem;
|
|
||||||
}
|
|
||||||
.material-icons {
|
|
||||||
vertical-align: middle;
|
|
||||||
}
|
|
||||||
</style>
|
|
||||||
@@ -1,98 +0,0 @@
|
|||||||
'use strict'
|
|
||||||
|
|
||||||
import axios from 'axios'
|
|
||||||
|
|
||||||
const http = axios.create({
|
|
||||||
baseURL: `${location.protocol}//${location.host}/api/`
|
|
||||||
})
|
|
||||||
|
|
||||||
/**
|
|
||||||
* API access for myPrayerJournal
|
|
||||||
*/
|
|
||||||
export default {
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Set the bearer token for all future requests
|
|
||||||
* @param {string} token The token to use to identify the user to the server
|
|
||||||
*/
|
|
||||||
setBearer: token => { http.defaults.headers.common['authorization'] = `Bearer ${token}` },
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Remove the bearer token
|
|
||||||
*/
|
|
||||||
removeBearer: () => delete http.defaults.headers.common['authorization'],
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Add a note for a prayer request
|
|
||||||
* @param {string} requestId The Id of the request to which the note applies
|
|
||||||
* @param {string} notes The notes to be added
|
|
||||||
*/
|
|
||||||
addNote: (requestId, notes) => http.post(`request/${requestId}/note`, { notes }),
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Add a new prayer request
|
|
||||||
* @param {string} requestText The text of the request to be added
|
|
||||||
* @param {string} recurType The type of recurrence for this request
|
|
||||||
* @param {number} recurCount The number of intervals of recurrence
|
|
||||||
*/
|
|
||||||
addRequest: (requestText, recurType, recurCount) => http.post('request', { requestText, recurType, recurCount }),
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get all answered requests, along with the text they had when it was answered
|
|
||||||
*/
|
|
||||||
getAnsweredRequests: () => http.get('requests/answered'),
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get a prayer request (full; includes all history and notes)
|
|
||||||
* @param {string} requestId The Id of the request to retrieve
|
|
||||||
*/
|
|
||||||
getFullRequest: requestId => http.get(`request/${requestId}/full`),
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get past notes for a prayer request
|
|
||||||
* @param {string} requestId The Id of the request for which notes should be retrieved
|
|
||||||
*/
|
|
||||||
getNotes: requestId => http.get(`request/${requestId}/notes`),
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get a prayer request (journal-style; only latest update)
|
|
||||||
* @param {string} requestId The Id of the request to retrieve
|
|
||||||
*/
|
|
||||||
getRequest: requestId => http.get(`request/${requestId}`),
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Get all prayer requests and their most recent updates
|
|
||||||
*/
|
|
||||||
journal: () => http.get('journal'),
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Show a request after the given date (used for "show now")
|
|
||||||
* @param {string} requestId The ID of the request which should be shown
|
|
||||||
* @param {number} showAfter The ticks after which the request should be shown
|
|
||||||
*/
|
|
||||||
showRequest: (requestId, showAfter) => http.patch(`request/${requestId}/show`, { showAfter }),
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Snooze a request until the given time
|
|
||||||
* @param {string} requestId The ID of the prayer request to be snoozed
|
|
||||||
* @param {number} until The ticks until which the request should be snoozed
|
|
||||||
*/
|
|
||||||
snoozeRequest: (requestId, until) => http.patch(`request/${requestId}/snooze`, { until }),
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Update recurrence for a prayer request
|
|
||||||
* @param {string} requestId The ID of the prayer request for which recurrence is being updated
|
|
||||||
* @param {string} recurType The type of recurrence to set
|
|
||||||
* @param {number} recurCount The number of recurrence intervals to set
|
|
||||||
*/
|
|
||||||
updateRecurrence: (requestId, recurType, recurCount) =>
|
|
||||||
http.patch(`request/${requestId}/recurrence`, { recurType, recurCount }),
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Update a prayer request
|
|
||||||
* @param {string} requestId The ID of the request to be updated
|
|
||||||
* @param {string} status The status of the update
|
|
||||||
* @param {string} updateText The text of the update (optional)
|
|
||||||
*/
|
|
||||||
updateRequest: (requestId, status, updateText) => http.post(`request/${requestId}/history`, { status, updateText })
|
|
||||||
}
|
|
||||||
@@ -1,138 +0,0 @@
|
|||||||
'use strict'
|
|
||||||
|
|
||||||
import auth0 from 'auth0-js'
|
|
||||||
|
|
||||||
import AUTH_CONFIG from './auth0-variables'
|
|
||||||
import mutations from '@/store/mutation-types'
|
|
||||||
|
|
||||||
var tokenRenewalTimeout
|
|
||||||
|
|
||||||
export default class AuthService {
|
|
||||||
constructor () {
|
|
||||||
this.login = this.login.bind(this)
|
|
||||||
this.setSession = this.setSession.bind(this)
|
|
||||||
this.logout = this.logout.bind(this)
|
|
||||||
this.isAuthenticated = this.isAuthenticated.bind(this)
|
|
||||||
}
|
|
||||||
|
|
||||||
auth0 = new auth0.WebAuth({
|
|
||||||
domain: AUTH_CONFIG.domain,
|
|
||||||
clientID: AUTH_CONFIG.clientId,
|
|
||||||
redirectUri: AUTH_CONFIG.appDomain + AUTH_CONFIG.callbackUrl,
|
|
||||||
audience: `https://${AUTH_CONFIG.domain}/userinfo`,
|
|
||||||
responseType: 'token id_token',
|
|
||||||
scope: 'openid profile email'
|
|
||||||
})
|
|
||||||
|
|
||||||
login () {
|
|
||||||
this.auth0.authorize()
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Promisified parseHash function
|
|
||||||
*/
|
|
||||||
parseHash () {
|
|
||||||
return new Promise((resolve, reject) => {
|
|
||||||
this.auth0.parseHash((err, authResult) => {
|
|
||||||
if (err) {
|
|
||||||
reject(err)
|
|
||||||
} else {
|
|
||||||
resolve(authResult)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Promisified userInfo function
|
|
||||||
*
|
|
||||||
* @param token The auth token from the login result
|
|
||||||
*/
|
|
||||||
userInfo (token) {
|
|
||||||
return new Promise((resolve, reject) => {
|
|
||||||
this.auth0.client.userInfo(token, (err, user) => {
|
|
||||||
if (err) {
|
|
||||||
reject(err)
|
|
||||||
} else {
|
|
||||||
resolve(user)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
handleAuthentication (store, router) {
|
|
||||||
this.parseHash()
|
|
||||||
.then(authResult => {
|
|
||||||
if (authResult && authResult.accessToken && authResult.idToken) {
|
|
||||||
this.setSession(authResult)
|
|
||||||
this.userInfo(authResult.accessToken)
|
|
||||||
.then(user => {
|
|
||||||
store.commit(mutations.USER_LOGGED_ON, user)
|
|
||||||
router.replace('/journal')
|
|
||||||
})
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.catch(err => {
|
|
||||||
router.replace('/')
|
|
||||||
console.log(err)
|
|
||||||
alert(`Error: ${err.error}. Check the console for further details.`)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
scheduleRenewal () {
|
|
||||||
let expiresAt = JSON.parse(localStorage.getItem('expires_at'))
|
|
||||||
let delay = expiresAt - Date.now()
|
|
||||||
if (delay > 0) {
|
|
||||||
tokenRenewalTimeout = setTimeout(() => {
|
|
||||||
this.renewToken()
|
|
||||||
}, delay)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
setSession (authResult) {
|
|
||||||
// Set the time that the access token will expire at
|
|
||||||
let expiresAt = JSON.stringify(
|
|
||||||
authResult.expiresIn * 1000 + new Date().getTime()
|
|
||||||
)
|
|
||||||
localStorage.setItem('access_token', authResult.accessToken)
|
|
||||||
localStorage.setItem('id_token', authResult.idToken)
|
|
||||||
localStorage.setItem('expires_at', expiresAt)
|
|
||||||
this.scheduleRenewal()
|
|
||||||
}
|
|
||||||
|
|
||||||
renewToken () {
|
|
||||||
console.log('attempting renewal...')
|
|
||||||
this.auth0.renewAuth(
|
|
||||||
{
|
|
||||||
audience: `https://${AUTH_CONFIG.domain}/userinfo`,
|
|
||||||
redirectUri: `${AUTH_CONFIG.appDomain}/static/silent.html`,
|
|
||||||
usePostMessage: true
|
|
||||||
},
|
|
||||||
(err, result) => {
|
|
||||||
if (err) {
|
|
||||||
console.log(err)
|
|
||||||
} else {
|
|
||||||
this.setSession(result)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
logout (store, router) {
|
|
||||||
// Clear access token and ID token from local storage
|
|
||||||
clearTimeout(tokenRenewalTimeout)
|
|
||||||
localStorage.removeItem('access_token')
|
|
||||||
localStorage.removeItem('id_token')
|
|
||||||
localStorage.removeItem('expires_at')
|
|
||||||
localStorage.setItem('user_profile', JSON.stringify({}))
|
|
||||||
// navigate to the home route
|
|
||||||
store.commit(mutations.USER_LOGGED_OFF)
|
|
||||||
router.replace('/')
|
|
||||||
}
|
|
||||||
|
|
||||||
isAuthenticated () {
|
|
||||||
// Check whether the current time is past the access token's expiry time
|
|
||||||
let expiresAt = JSON.parse(localStorage.getItem('expires_at'))
|
|
||||||
return new Date().getTime() < expiresAt
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
<template lang="pug">
|
|
||||||
article.mpj-main-content(role='main')
|
|
||||||
page-title(title='Welcome!'
|
|
||||||
hideOnPage='true')
|
|
||||||
p
|
|
||||||
p.
|
|
||||||
myPrayerJournal is a place where individuals can record their prayer requests, record that they prayed for them,
|
|
||||||
update them as God moves in the situation, and record a final answer received on that request. It will also allow
|
|
||||||
individuals to review their answered prayers.
|
|
||||||
p.
|
|
||||||
This site is currently in beta, but it is open and available to the general public. To get started, simply click
|
|
||||||
the “Log On” link above, and log on with either a Microsoft or Google account. You can also learn more
|
|
||||||
about the site at the “Docs” link, also above.
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<script>
|
|
||||||
'use strict'
|
|
||||||
|
|
||||||
export default {
|
|
||||||
name: 'home'
|
|
||||||
}
|
|
||||||
</script>
|
|
||||||
@@ -1,72 +0,0 @@
|
|||||||
<template lang="pug">
|
|
||||||
article.mpj-main-content-wide(role='main')
|
|
||||||
page-title(:title='title')
|
|
||||||
p(v-if='isLoadingJournal') Loading your prayer journal...
|
|
||||||
template(v-else)
|
|
||||||
.mpj-text-center
|
|
||||||
router-link(:to="{ name: 'EditRequest', params: { id: 'new' } }"
|
|
||||||
role='button').
|
|
||||||
#[md-icon(icon='add_box')] Add a New Request
|
|
||||||
br
|
|
||||||
.mpj-journal(v-if='journal.length > 0')
|
|
||||||
request-card(v-for='request in journal'
|
|
||||||
:key='request.requestId'
|
|
||||||
:request='request'
|
|
||||||
:events='eventBus'
|
|
||||||
:toast='toast')
|
|
||||||
p.text-center(v-else): em.
|
|
||||||
No requests found; click the “Add a New Request” button to add one
|
|
||||||
notes-edit(:events='eventBus'
|
|
||||||
:toast='toast')
|
|
||||||
snooze-request(:events='eventBus'
|
|
||||||
:toast='toast')
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<script>
|
|
||||||
'use strict'
|
|
||||||
|
|
||||||
import Vue from 'vue'
|
|
||||||
import { mapState } from 'vuex'
|
|
||||||
|
|
||||||
import NotesEdit from './request/NotesEdit'
|
|
||||||
import RequestCard from './request/RequestCard'
|
|
||||||
import SnoozeRequest from './request/SnoozeRequest'
|
|
||||||
|
|
||||||
import actions from '@/store/action-types'
|
|
||||||
|
|
||||||
export default {
|
|
||||||
name: 'journal',
|
|
||||||
components: {
|
|
||||||
NotesEdit,
|
|
||||||
RequestCard,
|
|
||||||
SnoozeRequest
|
|
||||||
},
|
|
||||||
data () {
|
|
||||||
return {
|
|
||||||
eventBus: new Vue()
|
|
||||||
}
|
|
||||||
},
|
|
||||||
computed: {
|
|
||||||
title () {
|
|
||||||
return `${this.user.given_name}’s Prayer Journal`
|
|
||||||
},
|
|
||||||
toast () {
|
|
||||||
return this.$parent.$refs.toast
|
|
||||||
},
|
|
||||||
...mapState(['user', 'journal', 'isLoadingJournal'])
|
|
||||||
},
|
|
||||||
async created () {
|
|
||||||
await this.$store.dispatch(actions.LOAD_JOURNAL, this.$Progress)
|
|
||||||
this.toast.showToast(`Loaded ${this.journal.length} prayer requests`, { theme: 'success' })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<style>
|
|
||||||
.mpj-journal {
|
|
||||||
display: flex;
|
|
||||||
flex-flow: row wrap;
|
|
||||||
justify-content: center;
|
|
||||||
align-items: flex-start;
|
|
||||||
}
|
|
||||||
</style>
|
|
||||||
@@ -1,55 +0,0 @@
|
|||||||
<script>
|
|
||||||
'use strict'
|
|
||||||
|
|
||||||
import moment from 'moment'
|
|
||||||
|
|
||||||
export default {
|
|
||||||
name: 'date-from-now',
|
|
||||||
props: {
|
|
||||||
tag: {
|
|
||||||
type: String,
|
|
||||||
default: 'span'
|
|
||||||
},
|
|
||||||
value: {
|
|
||||||
type: Number,
|
|
||||||
default: 0
|
|
||||||
},
|
|
||||||
interval: {
|
|
||||||
type: Number,
|
|
||||||
default: 10000
|
|
||||||
}
|
|
||||||
},
|
|
||||||
data () {
|
|
||||||
return {
|
|
||||||
fromNow: moment(this.value).fromNow(),
|
|
||||||
intervalId: null
|
|
||||||
}
|
|
||||||
},
|
|
||||||
computed: {
|
|
||||||
actual () {
|
|
||||||
return moment(this.value).format('LLLL')
|
|
||||||
}
|
|
||||||
},
|
|
||||||
mounted () {
|
|
||||||
this.intervalId = setInterval(this.updateFromNow, this.interval)
|
|
||||||
this.$watch('value', this.updateFromNow)
|
|
||||||
},
|
|
||||||
beforeDestroy () {
|
|
||||||
clearInterval(this.intervalId)
|
|
||||||
},
|
|
||||||
methods: {
|
|
||||||
updateFromNow () {
|
|
||||||
let newFromNow = moment(this.value).fromNow()
|
|
||||||
if (newFromNow !== this.fromNow) this.fromNow = newFromNow
|
|
||||||
}
|
|
||||||
},
|
|
||||||
render (createElement) {
|
|
||||||
return createElement(this.tag, {
|
|
||||||
domProps: {
|
|
||||||
title: this.actual,
|
|
||||||
innerText: this.fromNow
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
</script>
|
|
||||||
@@ -1,15 +0,0 @@
|
|||||||
<template lang="pug">
|
|
||||||
i.material-icons(v-html='icon')
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<script>
|
|
||||||
export default {
|
|
||||||
name: 'md-icon',
|
|
||||||
props: {
|
|
||||||
icon: {
|
|
||||||
type: String,
|
|
||||||
required: true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
</script>
|
|
||||||
@@ -1,96 +0,0 @@
|
|||||||
<template lang="pug">
|
|
||||||
nav.mpj-top-nav.mpj-bg(role='menubar')
|
|
||||||
router-link.title(:to="{ name: 'Home' }"
|
|
||||||
role='menuitem')
|
|
||||||
span(style='font-weight:100;') my
|
|
||||||
span(style='font-weight:600;') Prayer
|
|
||||||
span(style='font-weight:700;') Journal
|
|
||||||
router-link(v-if='isAuthenticated'
|
|
||||||
:to="{ name: 'Journal' }"
|
|
||||||
role='menuitem') Journal
|
|
||||||
router-link(v-if='isAuthenticated'
|
|
||||||
:to="{ name: 'ActiveRequests' }"
|
|
||||||
role='menuitem') Active
|
|
||||||
router-link(v-if='hasSnoozed'
|
|
||||||
:to="{ name: 'SnoozedRequests' }"
|
|
||||||
role='menuitem') Snoozed
|
|
||||||
router-link(v-if='isAuthenticated'
|
|
||||||
:to="{ name: 'AnsweredRequests' }"
|
|
||||||
role='menuitem') Answered
|
|
||||||
a(v-if='isAuthenticated'
|
|
||||||
href='#'
|
|
||||||
role='menuitem'
|
|
||||||
@click.stop='logOff()') Log Off
|
|
||||||
a(v-if='!isAuthenticated'
|
|
||||||
href='#'
|
|
||||||
role='menuitem'
|
|
||||||
@click.stop='logOn()') Log On
|
|
||||||
a(href='https://docs.prayerjournal.me'
|
|
||||||
target='_blank'
|
|
||||||
role='menuitem'
|
|
||||||
@click.stop='') Docs
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<script>
|
|
||||||
'use strict'
|
|
||||||
|
|
||||||
import { mapState } from 'vuex'
|
|
||||||
|
|
||||||
import AuthService from '@/auth/AuthService'
|
|
||||||
|
|
||||||
export default {
|
|
||||||
name: 'navigation',
|
|
||||||
data () {
|
|
||||||
return {
|
|
||||||
auth0: new AuthService()
|
|
||||||
}
|
|
||||||
},
|
|
||||||
computed: {
|
|
||||||
hasSnoozed () {
|
|
||||||
return this.isAuthenticated &&
|
|
||||||
Array.isArray(this.journal) &&
|
|
||||||
this.journal.filter(req => req.snoozedUntil > Date.now()).length > 0
|
|
||||||
},
|
|
||||||
...mapState([ 'journal', 'isAuthenticated' ])
|
|
||||||
},
|
|
||||||
methods: {
|
|
||||||
logOn () {
|
|
||||||
this.auth0.login()
|
|
||||||
},
|
|
||||||
logOff () {
|
|
||||||
this.auth0.logout(this.$store, this.$router)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<style>
|
|
||||||
.mpj-top-nav {
|
|
||||||
position: fixed;
|
|
||||||
display: flex;
|
|
||||||
flex-flow: row wrap;
|
|
||||||
align-items: center;
|
|
||||||
top: 0;
|
|
||||||
left: 0;
|
|
||||||
width: 100%;
|
|
||||||
padding-left: .5rem;
|
|
||||||
min-height: 50px;
|
|
||||||
}
|
|
||||||
.mpj-top-nav a:link,
|
|
||||||
.mpj-top-nav a:visited {
|
|
||||||
text-decoration: none;
|
|
||||||
color: rgba(255, 255, 255, .75);
|
|
||||||
padding-left: 1rem;
|
|
||||||
}
|
|
||||||
.mpj-top-nav a:link.router-link-active,
|
|
||||||
.mpj-top-nav a:visited.router-link-active,
|
|
||||||
.mpj-top-nav a:hover {
|
|
||||||
color: white;
|
|
||||||
}
|
|
||||||
.mpj-top-nav .title {
|
|
||||||
font-size: 1.25rem;
|
|
||||||
color: white;
|
|
||||||
padding-left: 1.25rem;
|
|
||||||
padding-right: 1.25rem;
|
|
||||||
}
|
|
||||||
</style>
|
|
||||||
@@ -1,35 +0,0 @@
|
|||||||
<template lang="pug">
|
|
||||||
h2.mpj-page-title(v-if='!hideOnPage'
|
|
||||||
v-html='title')
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<script>
|
|
||||||
export default {
|
|
||||||
name: 'page-title',
|
|
||||||
props: {
|
|
||||||
title: {
|
|
||||||
type: String,
|
|
||||||
required: true
|
|
||||||
},
|
|
||||||
hideOnPage: {
|
|
||||||
type: Boolean,
|
|
||||||
default: false
|
|
||||||
}
|
|
||||||
},
|
|
||||||
watch: {
|
|
||||||
title () {
|
|
||||||
document.title = `${this.title.replace('’', "'")} « myPrayerJournal`
|
|
||||||
}
|
|
||||||
},
|
|
||||||
created () {
|
|
||||||
document.title = `${this.title.replace('’', "'")} « myPrayerJournal`
|
|
||||||
}
|
|
||||||
}
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<style scoped>
|
|
||||||
.mpj-page-title {
|
|
||||||
border-bottom: solid 1px lightgray;
|
|
||||||
margin-bottom: 20px;
|
|
||||||
}
|
|
||||||
</style>
|
|
||||||
@@ -1,54 +0,0 @@
|
|||||||
<template lang="pug">
|
|
||||||
article
|
|
||||||
page-title(title='Privacy Policy')
|
|
||||||
p: small: em (as of May 21, 2018)
|
|
||||||
p.
|
|
||||||
The nature of the service is one where privacy is a must. The items below will help you understand the data we
|
|
||||||
collect, access, and store on your behalf as you use this service.
|
|
||||||
hr
|
|
||||||
h3 Third Party Services
|
|
||||||
p.
|
|
||||||
myPrayerJournal utilizes a third-party authentication and identity provider. You should familiarize yourself with
|
|
||||||
the privacy policy for #[a(href='https://auth0.com/privacy' target='_blank') Auth0], as well as your chosen provider
|
|
||||||
(#[a(href='https://privacy.microsoft.com/en-us/privacystatement' target='_blank') Microsoft] or
|
|
||||||
#[a(href='https://policies.google.com/privacy' target='_blank') Google]).
|
|
||||||
hr
|
|
||||||
h3 What We Collect
|
|
||||||
h4 Identifying Data
|
|
||||||
ul
|
|
||||||
li.
|
|
||||||
The only identifying data myPrayerJournal stores is the subscriber (“sub”) field from the token we
|
|
||||||
receive from Auth0, once you have signed in through their hosted service. All information is associated with you
|
|
||||||
via this field.
|
|
||||||
li.
|
|
||||||
While you are signed in, within your browser, the service has access to your first and last names, along with a
|
|
||||||
URL to the profile picture (provided by your selected identity provider). This information is not transmitted to
|
|
||||||
the server, and is removed when “Log Off” is clicked.
|
|
||||||
h4 User Provided Data
|
|
||||||
ul
|
|
||||||
li.
|
|
||||||
myPrayerJournal stores the information you provide, including the text of prayer requests, updates, and notes;
|
|
||||||
and the date/time when certain actions are taken.
|
|
||||||
hr
|
|
||||||
h3 How Your Data Is Accessed / Secured
|
|
||||||
ul
|
|
||||||
li.
|
|
||||||
Your provided data is returned to you, as required, to display your journal or your answered requests.
|
|
||||||
On the server, it is stored in a controlled-access database.
|
|
||||||
li.
|
|
||||||
Your data is backed up, along with other Bit Badger Solutions hosted systems, in a rolling manner; backups are
|
|
||||||
preserved for the prior 7 days, and backups from the 1st and 15th are preserved for 3 months. These backups are
|
|
||||||
stored in a private cloud data repository.
|
|
||||||
li.
|
|
||||||
The data collected and stored is the absolute minimum necessary for the functionality of the service. There are
|
|
||||||
no plans to “monetize” this service, and storing the minimum amount of information means that the
|
|
||||||
data we have is not interesting to purchasers (or those who may have more nefarious purposes).
|
|
||||||
li Access to servers and backups is strictly controlled and monitored for unauthorized access attempts.
|
|
||||||
hr
|
|
||||||
h3 Removing Your Data
|
|
||||||
p.
|
|
||||||
At any time, you may choose to discontinue using this service. Both Microsoft and Google provide ways to revoke
|
|
||||||
access from this application. However, if you want your data removed from the database, please contact daniel at
|
|
||||||
bitbadger.solutions (via e-mail, replacing at with @) prior to doing so, to ensure we can determine which
|
|
||||||
subscriber ID belongs to you.
|
|
||||||
</template>
|
|
||||||
@@ -1,35 +0,0 @@
|
|||||||
<template lang="pug">
|
|
||||||
article
|
|
||||||
page-title(title='Terms of Service')
|
|
||||||
p: small: em (as of May 21, 2018)
|
|
||||||
h3 1. Acceptance of Terms
|
|
||||||
p.
|
|
||||||
By accessing this web site, you are agreeing to be bound by these Terms and Conditions, and that you are
|
|
||||||
responsible to ensure that your use of this site complies with all applicable laws. Your continued use of this
|
|
||||||
site implies your acceptance of these terms.
|
|
||||||
h3 2. Description of Service and Registration
|
|
||||||
p.
|
|
||||||
myPrayerJournal is a service that allows individuals to enter and amend their prayer requests. It requires no
|
|
||||||
registration by itself, but access is granted based on a successful login with an external identity provider. See
|
|
||||||
#[router-link(:to="{ name: 'PrivacyPolicy' }") our privacy policy] for details on how that information is accessed
|
|
||||||
and stored.
|
|
||||||
h3 3. Third Party Services
|
|
||||||
p.
|
|
||||||
This service utilizes a third-party service provider for identity management. Review the terms of service for
|
|
||||||
#[a(href='https://auth0.com/terms' target='_blank') Auth0], as well as those for the selected authorization
|
|
||||||
provider (#[a(href='https://www.microsoft.com/en-us/servicesagreement' target='_blank') Microsoft] or
|
|
||||||
#[a(href='https://policies.google.com/terms' target='_blank') Google]).
|
|
||||||
h3 4. Liability
|
|
||||||
p.
|
|
||||||
This service is provided "as is", and no warranty (express or implied) exists. The service and its developers may
|
|
||||||
not be held liable for any damages that may arise through the use of this service.
|
|
||||||
h3 5. Updates to Terms
|
|
||||||
p.
|
|
||||||
These terms and conditions may be updated at any time, and this service does not have the capability to notify
|
|
||||||
users when these change. The date at the top of the page will be updated when any of the text of these terms is
|
|
||||||
updated.
|
|
||||||
hr
|
|
||||||
p.
|
|
||||||
You may also wish to review our #[router-link(:to="{ name: 'PrivacyPolicy' }") privacy policy] to learn how we
|
|
||||||
handle your data.
|
|
||||||
</template>
|
|
||||||
@@ -1,59 +0,0 @@
|
|||||||
<template lang="pug">
|
|
||||||
article.mpj-main-content(role='main')
|
|
||||||
page-title(title='Active Requests')
|
|
||||||
div(v-if='loaded').mpj-request-list
|
|
||||||
p.mpj-text-center(v-if='requests.length === 0'): em.
|
|
||||||
No active requests found; return to #[router-link(:to='{ name: "Journal" } ') your journal]
|
|
||||||
request-list-item(v-for='req in requests'
|
|
||||||
:key='req.requestId'
|
|
||||||
:request='req'
|
|
||||||
:toast='toast')
|
|
||||||
p(v-else) Loading journal...
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<script>
|
|
||||||
'use strict'
|
|
||||||
|
|
||||||
import { mapState } from 'vuex'
|
|
||||||
|
|
||||||
import RequestListItem from '@/components/request/RequestListItem'
|
|
||||||
|
|
||||||
import actions from '@/store/action-types'
|
|
||||||
|
|
||||||
export default {
|
|
||||||
name: 'active-requests',
|
|
||||||
components: {
|
|
||||||
RequestListItem
|
|
||||||
},
|
|
||||||
data () {
|
|
||||||
return {
|
|
||||||
requests: [],
|
|
||||||
loaded: false
|
|
||||||
}
|
|
||||||
},
|
|
||||||
computed: {
|
|
||||||
toast () {
|
|
||||||
return this.$parent.$refs.toast
|
|
||||||
},
|
|
||||||
...mapState(['journal', 'isLoadingJournal'])
|
|
||||||
},
|
|
||||||
created () {
|
|
||||||
this.$on('requestUnsnoozed', this.ensureJournal)
|
|
||||||
this.$on('requestNowShown', this.ensureJournal)
|
|
||||||
},
|
|
||||||
methods: {
|
|
||||||
async ensureJournal () {
|
|
||||||
if (!Array.isArray(this.journal)) {
|
|
||||||
this.loaded = false
|
|
||||||
await this.$store.dispatch(actions.LOAD_JOURNAL, this.$Progress)
|
|
||||||
}
|
|
||||||
this.requests = this.journal
|
|
||||||
.sort((a, b) => a.showAfter - b.showAfter)
|
|
||||||
this.loaded = true
|
|
||||||
}
|
|
||||||
},
|
|
||||||
async mounted () {
|
|
||||||
await this.ensureJournal()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
</script>
|
|
||||||
@@ -1,52 +0,0 @@
|
|||||||
<template lang="pug">
|
|
||||||
article.mpj-main-content(role='main')
|
|
||||||
page-title(title='Answered Requests')
|
|
||||||
div(v-if='loaded').mpj-request-list
|
|
||||||
p.text-center(v-if='requests.length === 0'): em.
|
|
||||||
No answered requests found; once you have marked one as “Answered”, it will appear here
|
|
||||||
request-list-item(v-for='req in requests'
|
|
||||||
:key='req.requestId'
|
|
||||||
:request='req'
|
|
||||||
:toast='toast')
|
|
||||||
p(v-else) Loading answered requests...
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<script>
|
|
||||||
'use strict'
|
|
||||||
|
|
||||||
import api from '@/api'
|
|
||||||
|
|
||||||
import RequestListItem from '@/components/request/RequestListItem'
|
|
||||||
|
|
||||||
export default {
|
|
||||||
name: 'answered-requests',
|
|
||||||
components: {
|
|
||||||
RequestListItem
|
|
||||||
},
|
|
||||||
data () {
|
|
||||||
return {
|
|
||||||
requests: [],
|
|
||||||
loaded: false
|
|
||||||
}
|
|
||||||
},
|
|
||||||
computed: {
|
|
||||||
toast () {
|
|
||||||
return this.$parent.$refs.toast
|
|
||||||
}
|
|
||||||
},
|
|
||||||
async mounted () {
|
|
||||||
this.$Progress.start()
|
|
||||||
try {
|
|
||||||
const reqs = await api.getAnsweredRequests()
|
|
||||||
this.requests = reqs.data
|
|
||||||
this.$Progress.finish()
|
|
||||||
} catch (err) {
|
|
||||||
console.error(err)
|
|
||||||
this.toast.showToast('Error loading requests; check console for details', { theme: 'danger' })
|
|
||||||
this.$Progress.fail()
|
|
||||||
} finally {
|
|
||||||
this.loaded = true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
</script>
|
|
||||||
@@ -1,204 +0,0 @@
|
|||||||
<template lang="pug">
|
|
||||||
article.mpj-main-content(role='main')
|
|
||||||
page-title(:title='title')
|
|
||||||
.mpj-narrow
|
|
||||||
label(for='request_text')
|
|
||||||
| Prayer Request
|
|
||||||
br
|
|
||||||
textarea(v-model='form.requestText'
|
|
||||||
:rows='10'
|
|
||||||
@blur='trimText()'
|
|
||||||
autofocus).mpj-full-width
|
|
||||||
br
|
|
||||||
template(v-if='!isNew')
|
|
||||||
label Also Mark As
|
|
||||||
br
|
|
||||||
label.normal
|
|
||||||
input(v-model='form.status'
|
|
||||||
type='radio'
|
|
||||||
name='status'
|
|
||||||
value='Updated')
|
|
||||||
| Updated
|
|
||||||
|
|
|
||||||
label.normal
|
|
||||||
input(v-model='form.status'
|
|
||||||
type='radio'
|
|
||||||
name='status'
|
|
||||||
value='Prayed')
|
|
||||||
| Prayed
|
|
||||||
|
|
|
||||||
label.normal
|
|
||||||
input(v-model='form.status'
|
|
||||||
type='radio'
|
|
||||||
name='status'
|
|
||||||
value='Answered')
|
|
||||||
| Answered
|
|
||||||
br
|
|
||||||
label Recurrence
|
|
||||||
|
|
|
||||||
em.mpj-muted-text After prayer, request reappears...
|
|
||||||
br
|
|
||||||
label.normal
|
|
||||||
input(v-model='form.recur.typ'
|
|
||||||
type='radio'
|
|
||||||
name='recur'
|
|
||||||
value='immediate')
|
|
||||||
| Immediately
|
|
||||||
|
|
|
||||||
label.normal
|
|
||||||
input(v-model='form.recur.typ'
|
|
||||||
type='radio'
|
|
||||||
name='recur'
|
|
||||||
value='other')
|
|
||||||
| Every...
|
|
||||||
input(v-model='form.recur.count'
|
|
||||||
type='number'
|
|
||||||
:disabled='!showRecurrence').mpj-recur-count
|
|
||||||
select(v-model='form.recur.other'
|
|
||||||
:disabled='!showRecurrence').mpj-recur-type
|
|
||||||
option(value='hours') hours
|
|
||||||
option(value='days') days
|
|
||||||
option(value='weeks') weeks
|
|
||||||
.mpj-text-right
|
|
||||||
button(:disabled='!isValidRecurrence'
|
|
||||||
@click.stop='saveRequest()').primary.
|
|
||||||
#[md-icon(icon='save')] Save
|
|
||||||
|
|
|
||||||
button(@click.stop='goBack()').
|
|
||||||
#[md-icon(icon='arrow_back')] Cancel
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<script>
|
|
||||||
'use strict'
|
|
||||||
|
|
||||||
import { mapState } from 'vuex'
|
|
||||||
|
|
||||||
import actions from '@/store/action-types'
|
|
||||||
|
|
||||||
export default {
|
|
||||||
name: 'edit-request',
|
|
||||||
props: {
|
|
||||||
id: {
|
|
||||||
type: String,
|
|
||||||
required: true
|
|
||||||
}
|
|
||||||
},
|
|
||||||
data () {
|
|
||||||
return {
|
|
||||||
title: 'Edit Prayer Request',
|
|
||||||
isNew: false,
|
|
||||||
form: {
|
|
||||||
requestId: '',
|
|
||||||
requestText: '',
|
|
||||||
status: 'Updated',
|
|
||||||
recur: {
|
|
||||||
typ: 'immediate',
|
|
||||||
other: '',
|
|
||||||
count: ''
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
computed: {
|
|
||||||
isValidRecurrence () {
|
|
||||||
if (this.form.recur.typ === 'immediate') return true
|
|
||||||
const count = Number.parseInt(this.form.recur.count)
|
|
||||||
if (isNaN(count) || this.form.recur.other === '') return false
|
|
||||||
if (this.form.recur.other === 'hours' && count > (365 * 24)) return false
|
|
||||||
if (this.form.recur.other === 'days' && count > 365) return false
|
|
||||||
if (this.form.recur.other === 'weeks' && count > 52) return false
|
|
||||||
return true
|
|
||||||
},
|
|
||||||
showRecurrence () {
|
|
||||||
return this.form.recur.typ !== 'immediate'
|
|
||||||
},
|
|
||||||
toast () {
|
|
||||||
return this.$parent.$refs.toast
|
|
||||||
},
|
|
||||||
...mapState(['journal'])
|
|
||||||
},
|
|
||||||
async mounted () {
|
|
||||||
await this.ensureJournal()
|
|
||||||
if (this.id === 'new') {
|
|
||||||
this.title = 'Add Prayer Request'
|
|
||||||
this.isNew = true
|
|
||||||
this.form.requestId = ''
|
|
||||||
this.form.requestText = ''
|
|
||||||
this.form.status = 'Created'
|
|
||||||
this.form.recur.typ = 'immediate'
|
|
||||||
this.form.recur.other = ''
|
|
||||||
this.form.recur.count = ''
|
|
||||||
} else {
|
|
||||||
this.title = 'Edit Prayer Request'
|
|
||||||
this.isNew = false
|
|
||||||
if (this.journal.length === 0) {
|
|
||||||
await this.$store.dispatch(actions.LOAD_JOURNAL, this.$Progress)
|
|
||||||
}
|
|
||||||
const req = this.journal.filter(r => r.requestId === this.id)[0]
|
|
||||||
this.form.requestId = this.id
|
|
||||||
this.form.requestText = req.text
|
|
||||||
this.form.status = 'Updated'
|
|
||||||
if (req.recurType === 'immediate') {
|
|
||||||
this.form.recur.typ = 'immediate'
|
|
||||||
this.form.recur.other = ''
|
|
||||||
this.form.recur.count = ''
|
|
||||||
} else {
|
|
||||||
this.form.recur.typ = 'other'
|
|
||||||
this.form.recur.other = req.recurType
|
|
||||||
this.form.recur.count = req.recurCount
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
methods: {
|
|
||||||
goBack () {
|
|
||||||
this.$router.go(-1)
|
|
||||||
},
|
|
||||||
trimText () {
|
|
||||||
this.form.requestText = this.form.requestText.trim()
|
|
||||||
},
|
|
||||||
async ensureJournal () {
|
|
||||||
if (!Array.isArray(this.journal)) {
|
|
||||||
await this.$store.dispatch(actions.LOAD_JOURNAL, this.$Progress)
|
|
||||||
}
|
|
||||||
},
|
|
||||||
async saveRequest () {
|
|
||||||
if (this.isNew) {
|
|
||||||
await this.$store.dispatch(actions.ADD_REQUEST, {
|
|
||||||
progress: this.$Progress,
|
|
||||||
requestText: this.form.requestText,
|
|
||||||
recurType: this.form.recur.typ === 'immediate' ? 'immediate' : this.form.recur.other,
|
|
||||||
recurCount: this.form.recur.typ === 'immediate' ? 0 : Number.parseInt(this.form.recur.count)
|
|
||||||
})
|
|
||||||
this.toast.showToast('New prayer request added', { theme: 'success' })
|
|
||||||
} else {
|
|
||||||
await this.$store.dispatch(actions.UPDATE_REQUEST, {
|
|
||||||
progress: this.$Progress,
|
|
||||||
requestId: this.form.requestId,
|
|
||||||
updateText: this.form.requestText,
|
|
||||||
status: this.form.status,
|
|
||||||
recurType: this.form.recur.typ === 'immediate' ? 'immediate' : this.form.recur.other,
|
|
||||||
recurCount: this.form.recur.typ === 'immediate' ? 0 : Number.parseInt(this.form.recur.count)
|
|
||||||
})
|
|
||||||
if (this.form.status === 'Answered') {
|
|
||||||
this.toast.showToast('Request updated and removed from active journal', { theme: 'success' })
|
|
||||||
} else {
|
|
||||||
this.toast.showToast('Request updated', { theme: 'success' })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
this.goBack()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<style>
|
|
||||||
.mpj-recur-count {
|
|
||||||
width: 3rem;
|
|
||||||
border-top-right-radius: 0;
|
|
||||||
border-bottom-right-radius: 0;
|
|
||||||
}
|
|
||||||
.mpj-recur-type {
|
|
||||||
border-top-left-radius: 0;
|
|
||||||
border-bottom-left-radius: 0;
|
|
||||||
}
|
|
||||||
</style>
|
|
||||||
@@ -1,91 +0,0 @@
|
|||||||
<template lang="pug">
|
|
||||||
article.mpj-main-content(role='main')
|
|
||||||
page-title(title='Full Prayer Request')
|
|
||||||
template(v-if='request')
|
|
||||||
p
|
|
||||||
span(v-if='isAnswered') Answered {{ formatDate(answered) }} (#[date-from-now(:value='answered')])
|
|
||||||
small: em.mpj-muted-text prayed {{ prayedCount }} times, open {{ openDays }} days
|
|
||||||
p.mpj-request-text {{ lastText }}
|
|
||||||
br
|
|
||||||
table.mpj-request-log
|
|
||||||
thead
|
|
||||||
tr
|
|
||||||
th Action
|
|
||||||
th Update / Notes
|
|
||||||
tbody
|
|
||||||
tr(v-for='item in log' :key='item.asOf')
|
|
||||||
td {{ item.status }} on #[span.mpj-text-nowrap {{ formatDate(item.asOf) }}]
|
|
||||||
td(v-if='item.text').mpj-request-text {{ item.text }}
|
|
||||||
td(v-else)
|
|
||||||
p(v-else) Loading request...
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<script>
|
|
||||||
'use strict'
|
|
||||||
|
|
||||||
import moment from 'moment'
|
|
||||||
|
|
||||||
import api from '@/api'
|
|
||||||
|
|
||||||
const asOfDesc = (a, b) => b.asOf - a.asOf
|
|
||||||
|
|
||||||
export default {
|
|
||||||
name: 'full-request',
|
|
||||||
props: {
|
|
||||||
id: {
|
|
||||||
type: String,
|
|
||||||
required: true
|
|
||||||
}
|
|
||||||
},
|
|
||||||
data () {
|
|
||||||
return {
|
|
||||||
request: null
|
|
||||||
}
|
|
||||||
},
|
|
||||||
computed: {
|
|
||||||
answered () {
|
|
||||||
return this.request.history.find(hist => hist.status === 'Answered').asOf
|
|
||||||
},
|
|
||||||
isAnswered () {
|
|
||||||
return this.request.history.filter(hist => hist.status === 'Answered').length > 0
|
|
||||||
},
|
|
||||||
lastText () {
|
|
||||||
return this.request.history
|
|
||||||
.filter(hist => hist.text)
|
|
||||||
.sort(asOfDesc)[0].text
|
|
||||||
},
|
|
||||||
log () {
|
|
||||||
const allHistory = (this.request.notes || [])
|
|
||||||
.map(note => ({ asOf: note.asOf, text: note.notes, status: 'Notes' }))
|
|
||||||
.concat(this.request.history)
|
|
||||||
.sort(asOfDesc)
|
|
||||||
// Skip the first entry for answered requests; that info is already displayed
|
|
||||||
return this.isAnswered ? allHistory.slice(1) : allHistory
|
|
||||||
},
|
|
||||||
openDays () {
|
|
||||||
const asOf = this.isAnswered ? this.answered : Date.now()
|
|
||||||
return Math.floor(
|
|
||||||
(asOf - this.request.history.find(hist => hist.status === 'Created').asOf) / 1000 / 60 / 60 / 24)
|
|
||||||
},
|
|
||||||
prayedCount () {
|
|
||||||
return this.request.history.filter(hist => hist.status === 'Prayed').length
|
|
||||||
}
|
|
||||||
},
|
|
||||||
async mounted () {
|
|
||||||
this.$Progress.start()
|
|
||||||
try {
|
|
||||||
const req = await api.getFullRequest(this.id)
|
|
||||||
this.request = req.data
|
|
||||||
this.$Progress.finish()
|
|
||||||
} catch (e) {
|
|
||||||
console.log(e)
|
|
||||||
this.$Progress.fail()
|
|
||||||
}
|
|
||||||
},
|
|
||||||
methods: {
|
|
||||||
formatDate (asOf) {
|
|
||||||
return moment(asOf).format('LL')
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
</script>
|
|
||||||
@@ -1,114 +0,0 @@
|
|||||||
<template lang="pug">
|
|
||||||
.mpj-modal(v-show='notesVisible')
|
|
||||||
.mpj-modal-content.mpj-narrow
|
|
||||||
header.mpj-bg
|
|
||||||
h5 Add Notes to Prayer Request
|
|
||||||
label
|
|
||||||
| Notes
|
|
||||||
br
|
|
||||||
textarea(v-model='form.notes'
|
|
||||||
:rows='10'
|
|
||||||
@blur='trimText()').mpj-full-width
|
|
||||||
.mpj-text-right
|
|
||||||
button(@click='saveNotes()').primary.
|
|
||||||
#[md-icon(icon='save')] Save
|
|
||||||
|
|
|
||||||
button(@click='closeDialog()').
|
|
||||||
#[md-icon(icon='undo')] Cancel
|
|
||||||
hr
|
|
||||||
div(v-if='hasPriorNotes')
|
|
||||||
p.mpj-text-center: strong Prior Notes for This Request
|
|
||||||
.mpj-note-list
|
|
||||||
p(v-for='note in priorNotes'
|
|
||||||
:key='note.asOf')
|
|
||||||
small.mpj-muted-text: date-from-now(:value='note.asOf')
|
|
||||||
br
|
|
||||||
span.mpj-request-text {{ note.notes }}
|
|
||||||
div(v-else-if='noPriorNotes').mpj-text-center.mpj-muted-text There are no prior notes for this request
|
|
||||||
div(v-else).mpj-text-center
|
|
||||||
button(@click='loadNotes()').
|
|
||||||
#[md-icon(icon='cloud_download')] Load Prior Notes
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<script>
|
|
||||||
'use strict'
|
|
||||||
|
|
||||||
import api from '@/api'
|
|
||||||
|
|
||||||
export default {
|
|
||||||
name: 'notes-edit',
|
|
||||||
props: {
|
|
||||||
toast: { required: true },
|
|
||||||
events: { required: true }
|
|
||||||
},
|
|
||||||
data () {
|
|
||||||
return {
|
|
||||||
notesVisible: false,
|
|
||||||
form: {
|
|
||||||
requestId: '',
|
|
||||||
notes: ''
|
|
||||||
},
|
|
||||||
priorNotes: [],
|
|
||||||
priorNotesLoaded: false
|
|
||||||
}
|
|
||||||
},
|
|
||||||
computed: {
|
|
||||||
hasPriorNotes () {
|
|
||||||
return this.priorNotesLoaded && this.priorNotes.length > 0
|
|
||||||
},
|
|
||||||
noPriorNotes () {
|
|
||||||
return this.priorNotesLoaded && this.priorNotes.length === 0
|
|
||||||
}
|
|
||||||
},
|
|
||||||
created () {
|
|
||||||
this.events.$on('notes', this.openDialog)
|
|
||||||
},
|
|
||||||
methods: {
|
|
||||||
closeDialog () {
|
|
||||||
this.form.requestId = ''
|
|
||||||
this.form.notes = ''
|
|
||||||
this.priorNotes = []
|
|
||||||
this.priorNotesLoaded = false
|
|
||||||
this.notesVisible = false
|
|
||||||
},
|
|
||||||
async loadNotes () {
|
|
||||||
this.$Progress.start()
|
|
||||||
try {
|
|
||||||
const notes = await api.getNotes(this.form.requestId)
|
|
||||||
this.priorNotes = notes.data
|
|
||||||
this.$Progress.finish()
|
|
||||||
} catch (e) {
|
|
||||||
console.error(e)
|
|
||||||
this.$Progress.fail()
|
|
||||||
} finally {
|
|
||||||
this.priorNotesLoaded = true
|
|
||||||
}
|
|
||||||
},
|
|
||||||
openDialog (request) {
|
|
||||||
this.form.requestId = request.requestId
|
|
||||||
this.notesVisible = true
|
|
||||||
},
|
|
||||||
async saveNotes () {
|
|
||||||
this.$Progress.start()
|
|
||||||
try {
|
|
||||||
await api.addNote(this.form.requestId, this.form.notes)
|
|
||||||
this.$Progress.finish()
|
|
||||||
this.toast.showToast('Added notes', { theme: 'success' })
|
|
||||||
this.closeDialog()
|
|
||||||
} catch (e) {
|
|
||||||
console.error(e)
|
|
||||||
this.$Progress.fail()
|
|
||||||
}
|
|
||||||
},
|
|
||||||
trimText () {
|
|
||||||
this.form.notes = this.form.notes.trim()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<style>
|
|
||||||
.mpj-note-list p {
|
|
||||||
border-top: dotted 1px lightgray;
|
|
||||||
}
|
|
||||||
</style>
|
|
||||||
@@ -1,93 +0,0 @@
|
|||||||
<template lang="pug">
|
|
||||||
.mpj-request-card(v-if='shouldDisplay')
|
|
||||||
header.mpj-card-header(role='toolbar').
|
|
||||||
#[button(@click='markPrayed()' title='Pray').primary: md-icon(icon='done')]
|
|
||||||
#[button(@click.stop='showEdit()' title='Edit'): md-icon(icon='edit')]
|
|
||||||
#[button(@click.stop='showNotes()' title='Add Notes'): md-icon(icon='comment')]
|
|
||||||
#[button(@click.stop='snooze()' title='Snooze Request'): md-icon(icon='schedule')]
|
|
||||||
div
|
|
||||||
p.card-text.mpj-request-text
|
|
||||||
| {{ request.text }}
|
|
||||||
p.as-of.mpj-text-right: small.mpj-muted-text: em
|
|
||||||
= '(last activity '
|
|
||||||
date-from-now(:value='request.asOf')
|
|
||||||
| )
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<script>
|
|
||||||
'use strict'
|
|
||||||
|
|
||||||
import actions from '@/store/action-types'
|
|
||||||
|
|
||||||
export default {
|
|
||||||
name: 'request-card',
|
|
||||||
props: {
|
|
||||||
request: { required: true },
|
|
||||||
toast: { required: true },
|
|
||||||
events: { required: true }
|
|
||||||
},
|
|
||||||
computed: {
|
|
||||||
shouldDisplay () {
|
|
||||||
const now = Date.now()
|
|
||||||
return Math.max(now, this.request.showAfter, this.request.snoozedUntil) === now
|
|
||||||
}
|
|
||||||
},
|
|
||||||
methods: {
|
|
||||||
async markPrayed () {
|
|
||||||
await this.$store.dispatch(actions.UPDATE_REQUEST, {
|
|
||||||
progress: this.$Progress,
|
|
||||||
requestId: this.request.requestId,
|
|
||||||
status: 'Prayed',
|
|
||||||
updateText: ''
|
|
||||||
})
|
|
||||||
this.toast.showToast('Request marked as prayed', { theme: 'success' })
|
|
||||||
},
|
|
||||||
showEdit () {
|
|
||||||
this.$router.push({ name: 'EditRequest', params: { id: this.request.requestId } })
|
|
||||||
},
|
|
||||||
showNotes () {
|
|
||||||
this.events.$emit('notes', this.request)
|
|
||||||
},
|
|
||||||
snooze () {
|
|
||||||
this.events.$emit('snooze', this.request.requestId)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<style>
|
|
||||||
.mpj-request-card {
|
|
||||||
border: solid 1px darkgray;
|
|
||||||
border-radius: 5px;
|
|
||||||
width: 20rem;
|
|
||||||
margin: .5rem;
|
|
||||||
}
|
|
||||||
@media screen and (max-width: 20rem) {
|
|
||||||
.mpj-request-card {
|
|
||||||
width: 100%;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
.mpj-card-header {
|
|
||||||
display: flex;
|
|
||||||
flex-flow: row;
|
|
||||||
justify-content: center;
|
|
||||||
background-image: -webkit-gradient(linear, left top, left bottom, from(lightgray), to(whitesmoke));
|
|
||||||
background-image: -webkit-linear-gradient(top, lightgray, whitesmoke);
|
|
||||||
background-image: -moz-linear-gradient(top, lightgray, whitesmoke);
|
|
||||||
background-image: linear-gradient(to bottom, lightgray, whitesmoke);
|
|
||||||
}
|
|
||||||
.mpj-card-header button {
|
|
||||||
margin: .25rem;
|
|
||||||
padding: 0 .25rem;
|
|
||||||
}
|
|
||||||
.mpj-card-header button .material-icons {
|
|
||||||
font-size: 1.3rem;
|
|
||||||
}
|
|
||||||
.mpj-request-card .card-text {
|
|
||||||
margin-left: 1rem;
|
|
||||||
margin-right: 1rem;
|
|
||||||
}
|
|
||||||
.mpj-request-card .as-of {
|
|
||||||
margin-right: .25rem;
|
|
||||||
}
|
|
||||||
</style>
|
|
||||||
@@ -1,86 +0,0 @@
|
|||||||
<template lang="pug">
|
|
||||||
p.mpj-request-text
|
|
||||||
| {{ request.text }}
|
|
||||||
br
|
|
||||||
br
|
|
||||||
button(@click='viewFull'
|
|
||||||
title='View Full Request').
|
|
||||||
#[md-icon(icon='description')] View Full Request
|
|
||||||
|
|
|
||||||
template(v-if='!isAnswered')
|
|
||||||
button(@click='editRequest'
|
|
||||||
title='Edit Request').
|
|
||||||
#[md-icon(icon='edit')] Edit Request
|
|
||||||
|
|
|
||||||
template(v-if='isSnoozed')
|
|
||||||
button(@click='cancelSnooze()').
|
|
||||||
#[md-icon(icon='restore')] Cancel Snooze
|
|
||||||
|
|
|
||||||
template(v-if='isPending')
|
|
||||||
button(@click='showNow()').
|
|
||||||
#[md-icon(icon='restore')] Show Now
|
|
||||||
br(v-if='isSnoozed || isPending || isAnswered')
|
|
||||||
small(v-if='isSnoozed').mpj-muted-text: em.
|
|
||||||
Snooze expires #[date-from-now(:value='request.snoozedUntil')]
|
|
||||||
small(v-if='isPending').mpj-muted-text: em.
|
|
||||||
Request scheduled to reappear #[date-from-now(:value='request.showAfter')]
|
|
||||||
small(v-if='isAnswered').mpj-muted-text: em.
|
|
||||||
Answered #[date-from-now(:value='request.asOf')]
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<script>
|
|
||||||
'use strict'
|
|
||||||
|
|
||||||
import actions from '@/store/action-types'
|
|
||||||
|
|
||||||
export default {
|
|
||||||
name: 'request-list-item',
|
|
||||||
props: {
|
|
||||||
request: { required: true },
|
|
||||||
toast: { required: true }
|
|
||||||
},
|
|
||||||
data () {
|
|
||||||
return {}
|
|
||||||
},
|
|
||||||
computed: {
|
|
||||||
answered () {
|
|
||||||
return this.request.history.find(hist => hist.status === 'Answered').asOf
|
|
||||||
},
|
|
||||||
isAnswered () {
|
|
||||||
return this.request.lastStatus === 'Answered'
|
|
||||||
},
|
|
||||||
isPending () {
|
|
||||||
return !this.isSnoozed && this.request.showAfter > Date.now()
|
|
||||||
},
|
|
||||||
isSnoozed () {
|
|
||||||
return this.request.snoozedUntil > Date.now()
|
|
||||||
}
|
|
||||||
},
|
|
||||||
methods: {
|
|
||||||
async cancelSnooze () {
|
|
||||||
await this.$store.dispatch(actions.SNOOZE_REQUEST, {
|
|
||||||
progress: this.$Progress,
|
|
||||||
requestId: this.request.requestId,
|
|
||||||
until: 0
|
|
||||||
})
|
|
||||||
this.toast.showToast('Request un-snoozed', { theme: 'success' })
|
|
||||||
this.$parent.$emit('requestUnsnoozed')
|
|
||||||
},
|
|
||||||
editRequest () {
|
|
||||||
this.$router.push({ name: 'EditRequest', params: { id: this.request.requestId } })
|
|
||||||
},
|
|
||||||
async showNow () {
|
|
||||||
await this.$store.dispatch(actions.SHOW_REQUEST_NOW, {
|
|
||||||
progress: this.$Progress,
|
|
||||||
requestId: this.request.requestId,
|
|
||||||
showAfter: Date.now()
|
|
||||||
})
|
|
||||||
this.toast.showToast('Recurrence skipped; request now shows in journal', { theme: 'success' })
|
|
||||||
this.$parent.$emit('requestNowShown')
|
|
||||||
},
|
|
||||||
viewFull () {
|
|
||||||
this.$router.push({ name: 'FullRequest', params: { id: this.request.requestId } })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
</script>
|
|
||||||
@@ -1,71 +0,0 @@
|
|||||||
<template lang="pug">
|
|
||||||
.mpj-modal(v-show='snoozeVisible')
|
|
||||||
.mpj-modal-content.mpj-skinny
|
|
||||||
header.mpj-bg
|
|
||||||
h5 Snooze Prayer Request
|
|
||||||
p.mpj-text-center
|
|
||||||
label
|
|
||||||
= 'Until '
|
|
||||||
input(v-model='form.snoozedUntil'
|
|
||||||
type='date'
|
|
||||||
autofocus)
|
|
||||||
br
|
|
||||||
.mpj-text-right
|
|
||||||
button.primary(:disabled='!isValid'
|
|
||||||
@click='snoozeRequest()').
|
|
||||||
#[md-icon(icon='snooze')] Snooze
|
|
||||||
|
|
|
||||||
button(@click='closeDialog()').
|
|
||||||
#[md-icon(icon='undo')] Cancel
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<script>
|
|
||||||
'use strict'
|
|
||||||
|
|
||||||
import actions from '@/store/action-types'
|
|
||||||
|
|
||||||
export default {
|
|
||||||
name: 'snooze-request',
|
|
||||||
props: {
|
|
||||||
toast: { required: true },
|
|
||||||
events: { required: true }
|
|
||||||
},
|
|
||||||
data () {
|
|
||||||
return {
|
|
||||||
snoozeVisible: false,
|
|
||||||
form: {
|
|
||||||
requestId: '',
|
|
||||||
snoozedUntil: ''
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
created () {
|
|
||||||
this.events.$on('snooze', this.openDialog)
|
|
||||||
},
|
|
||||||
computed: {
|
|
||||||
isValid () {
|
|
||||||
return !isNaN(Date.parse(this.form.snoozedUntil))
|
|
||||||
}
|
|
||||||
},
|
|
||||||
methods: {
|
|
||||||
closeDialog () {
|
|
||||||
this.form.requestId = ''
|
|
||||||
this.form.snoozedUntil = ''
|
|
||||||
this.snoozeVisible = false
|
|
||||||
},
|
|
||||||
openDialog (requestId) {
|
|
||||||
this.form.requestId = requestId
|
|
||||||
this.snoozeVisible = true
|
|
||||||
},
|
|
||||||
async snoozeRequest () {
|
|
||||||
await this.$store.dispatch(actions.SNOOZE_REQUEST, {
|
|
||||||
progress: this.$Progress,
|
|
||||||
requestId: this.form.requestId,
|
|
||||||
until: Date.parse(this.form.snoozedUntil)
|
|
||||||
})
|
|
||||||
this.toast.showToast(`Request snoozed until ${this.form.snoozedUntil}`, { theme: 'success' })
|
|
||||||
this.closeDialog()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
</script>
|
|
||||||
@@ -1,59 +0,0 @@
|
|||||||
<template lang="pug">
|
|
||||||
article.mpj-main-content(role='main')
|
|
||||||
page-title(title='Snoozed Requests')
|
|
||||||
div(v-if='loaded').mpj-request-list
|
|
||||||
p.mpj-text-center(v-if='requests.length === 0'): em.
|
|
||||||
No snoozed requests found; return to #[router-link(:to='{ name: "Journal" } ') your journal]
|
|
||||||
request-list-item(v-for='req in requests'
|
|
||||||
:key='req.requestId'
|
|
||||||
:request='req'
|
|
||||||
:toast='toast')
|
|
||||||
p(v-else) Loading journal...
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<script>
|
|
||||||
'use strict'
|
|
||||||
|
|
||||||
import { mapState } from 'vuex'
|
|
||||||
|
|
||||||
import actions from '@/store/action-types'
|
|
||||||
|
|
||||||
import RequestListItem from '@/components/request/RequestListItem'
|
|
||||||
|
|
||||||
export default {
|
|
||||||
name: 'snoozed-requests',
|
|
||||||
components: {
|
|
||||||
RequestListItem
|
|
||||||
},
|
|
||||||
data () {
|
|
||||||
return {
|
|
||||||
requests: [],
|
|
||||||
loaded: false
|
|
||||||
}
|
|
||||||
},
|
|
||||||
computed: {
|
|
||||||
toast () {
|
|
||||||
return this.$parent.$refs.toast
|
|
||||||
},
|
|
||||||
...mapState(['journal', 'isLoadingJournal'])
|
|
||||||
},
|
|
||||||
created () {
|
|
||||||
this.$on('requestUnsnoozed', this.ensureJournal)
|
|
||||||
},
|
|
||||||
methods: {
|
|
||||||
async ensureJournal () {
|
|
||||||
if (!Array.isArray(this.journal)) {
|
|
||||||
this.loaded = false
|
|
||||||
await this.$store.dispatch(actions.LOAD_JOURNAL, this.$Progress)
|
|
||||||
}
|
|
||||||
this.requests = this.journal
|
|
||||||
.filter(req => req.snoozedUntil > Date.now())
|
|
||||||
.sort((a, b) => a.snoozedUntil - b.snoozedUntil)
|
|
||||||
this.loaded = true
|
|
||||||
}
|
|
||||||
},
|
|
||||||
async mounted () {
|
|
||||||
await this.ensureJournal()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
</script>
|
|
||||||
@@ -1,20 +0,0 @@
|
|||||||
<template lang="pug">
|
|
||||||
article.mpj-main-content(role='main')
|
|
||||||
pageTitle(title='Logging On')
|
|
||||||
p Logging you on...
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<script>
|
|
||||||
'use strict'
|
|
||||||
|
|
||||||
import AuthService from '@/auth/AuthService'
|
|
||||||
|
|
||||||
export default {
|
|
||||||
name: 'log-on',
|
|
||||||
created () {
|
|
||||||
this.$Progress.start()
|
|
||||||
new AuthService().handleAuthentication(this.$store, this.$router)
|
|
||||||
// Auth service redirects to dashboard, which restarts the progress bar
|
|
||||||
}
|
|
||||||
}
|
|
||||||
</script>
|
|
||||||
@@ -1,36 +0,0 @@
|
|||||||
import Vue from 'vue'
|
|
||||||
import VueProgressBar from 'vue-progressbar'
|
|
||||||
import VueToast from 'vue-toast'
|
|
||||||
|
|
||||||
import 'vue-toast/dist/vue-toast.min.css'
|
|
||||||
|
|
||||||
import App from './App'
|
|
||||||
import router from './router'
|
|
||||||
import store from './store'
|
|
||||||
import DateFromNow from './components/common/DateFromNow'
|
|
||||||
import MaterialDesignIcon from './components/common/MaterialDesignIcon'
|
|
||||||
import PageTitle from './components/common/PageTitle'
|
|
||||||
|
|
||||||
Vue.config.productionTip = false
|
|
||||||
|
|
||||||
Vue.use(VueProgressBar, {
|
|
||||||
color: 'yellow',
|
|
||||||
failedColor: 'red',
|
|
||||||
height: '5px',
|
|
||||||
transition: {
|
|
||||||
speed: '0.2s',
|
|
||||||
opacity: '0.6s',
|
|
||||||
termination: 1000
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
Vue.component('date-from-now', DateFromNow)
|
|
||||||
Vue.component('md-icon', MaterialDesignIcon)
|
|
||||||
Vue.component('page-title', PageTitle)
|
|
||||||
Vue.component('toast', VueToast)
|
|
||||||
|
|
||||||
new Vue({
|
|
||||||
router,
|
|
||||||
store,
|
|
||||||
render: h => h(App)
|
|
||||||
}).$mount('#app')
|
|
||||||
@@ -1,83 +0,0 @@
|
|||||||
'use strict'
|
|
||||||
|
|
||||||
import Vue from 'vue'
|
|
||||||
import Router from 'vue-router'
|
|
||||||
|
|
||||||
import ActiveRequests from '@/components/request/ActiveRequests'
|
|
||||||
import AnsweredRequests from '@/components/request/AnsweredRequests'
|
|
||||||
import EditRequest from '@/components/request/EditRequest'
|
|
||||||
import FullRequest from '@/components/request/FullRequest'
|
|
||||||
import Home from '@/components/Home'
|
|
||||||
import Journal from '@/components/Journal'
|
|
||||||
import LogOn from '@/components/user/LogOn'
|
|
||||||
import PrivacyPolicy from '@/components/legal/PrivacyPolicy'
|
|
||||||
import SnoozedRequests from '@/components/request/SnoozedRequests'
|
|
||||||
import TermsOfService from '@/components/legal/TermsOfService'
|
|
||||||
|
|
||||||
Vue.use(Router)
|
|
||||||
|
|
||||||
export default new Router({
|
|
||||||
mode: 'history',
|
|
||||||
base: process.env.BASE_URL,
|
|
||||||
scrollBehavior (to, from, savedPosition) {
|
|
||||||
if (savedPosition) {
|
|
||||||
return savedPosition
|
|
||||||
} else {
|
|
||||||
return { x: 0, y: 0 }
|
|
||||||
}
|
|
||||||
},
|
|
||||||
routes: [
|
|
||||||
{
|
|
||||||
path: '/',
|
|
||||||
name: 'Home',
|
|
||||||
component: Home
|
|
||||||
},
|
|
||||||
{
|
|
||||||
path: '/journal',
|
|
||||||
name: 'Journal',
|
|
||||||
component: Journal
|
|
||||||
},
|
|
||||||
{
|
|
||||||
path: '/legal/privacy-policy',
|
|
||||||
name: 'PrivacyPolicy',
|
|
||||||
component: PrivacyPolicy
|
|
||||||
},
|
|
||||||
{
|
|
||||||
path: '/legal/terms-of-service',
|
|
||||||
name: 'TermsOfService',
|
|
||||||
component: TermsOfService
|
|
||||||
},
|
|
||||||
{
|
|
||||||
path: '/request/:id/edit',
|
|
||||||
name: 'EditRequest',
|
|
||||||
component: EditRequest,
|
|
||||||
props: true
|
|
||||||
},
|
|
||||||
{
|
|
||||||
path: '/request/:id/full',
|
|
||||||
name: 'FullRequest',
|
|
||||||
component: FullRequest,
|
|
||||||
props: true
|
|
||||||
},
|
|
||||||
{
|
|
||||||
path: '/requests/active',
|
|
||||||
name: 'ActiveRequests',
|
|
||||||
component: ActiveRequests
|
|
||||||
},
|
|
||||||
{
|
|
||||||
path: '/requests/answered',
|
|
||||||
name: 'AnsweredRequests',
|
|
||||||
component: AnsweredRequests
|
|
||||||
},
|
|
||||||
{
|
|
||||||
path: '/requests/snoozed',
|
|
||||||
name: 'SnoozedRequests',
|
|
||||||
component: SnoozedRequests
|
|
||||||
},
|
|
||||||
{
|
|
||||||
path: '/user/log-on',
|
|
||||||
name: 'LogOn',
|
|
||||||
component: LogOn
|
|
||||||
}
|
|
||||||
]
|
|
||||||
})
|
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
'use strict'
|
|
||||||
|
|
||||||
export default {
|
|
||||||
/** Action to add a prayer request (pass request text) */
|
|
||||||
ADD_REQUEST: 'add-request',
|
|
||||||
/** Action to load the user's prayer journal */
|
|
||||||
LOAD_JOURNAL: 'load-journal',
|
|
||||||
/** Action to update a request */
|
|
||||||
UPDATE_REQUEST: 'update-request',
|
|
||||||
/** Action to skip the remaining recurrence period */
|
|
||||||
SHOW_REQUEST_NOW: 'show-request-now',
|
|
||||||
/** Action to snooze a request */
|
|
||||||
SNOOZE_REQUEST: 'snooze-request'
|
|
||||||
}
|
|
||||||
@@ -1,148 +0,0 @@
|
|||||||
'use strict'
|
|
||||||
|
|
||||||
import Vue from 'vue'
|
|
||||||
import Vuex from 'vuex'
|
|
||||||
|
|
||||||
import api from '@/api'
|
|
||||||
import AuthService from '@/auth/AuthService'
|
|
||||||
|
|
||||||
import mutations from './mutation-types'
|
|
||||||
import actions from './action-types'
|
|
||||||
|
|
||||||
Vue.use(Vuex)
|
|
||||||
|
|
||||||
const auth0 = new AuthService()
|
|
||||||
|
|
||||||
const logError = function (error) {
|
|
||||||
if (error.response) {
|
|
||||||
// The request was made and the server responded with a status code
|
|
||||||
// that falls out of the range of 2xx
|
|
||||||
console.log(error.response.data)
|
|
||||||
console.log(error.response.status)
|
|
||||||
console.log(error.response.headers)
|
|
||||||
} else if (error.request) {
|
|
||||||
// The request was made but no response was received
|
|
||||||
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
|
|
||||||
// http.ClientRequest in node.js
|
|
||||||
console.log(error.request)
|
|
||||||
} else {
|
|
||||||
// Something happened in setting up the request that triggered an Error
|
|
||||||
console.log('Error', error.message)
|
|
||||||
}
|
|
||||||
console.log(error.config)
|
|
||||||
}
|
|
||||||
|
|
||||||
export default new Vuex.Store({
|
|
||||||
state: {
|
|
||||||
user: JSON.parse(localStorage.getItem('user_profile') || '{}'),
|
|
||||||
isAuthenticated: (() => {
|
|
||||||
auth0.scheduleRenewal()
|
|
||||||
if (auth0.isAuthenticated()) {
|
|
||||||
api.setBearer(localStorage.getItem('id_token'))
|
|
||||||
}
|
|
||||||
return auth0.isAuthenticated()
|
|
||||||
})(),
|
|
||||||
journal: {},
|
|
||||||
isLoadingJournal: false
|
|
||||||
},
|
|
||||||
mutations: {
|
|
||||||
[mutations.LOADING_JOURNAL] (state, flag) {
|
|
||||||
state.isLoadingJournal = flag
|
|
||||||
},
|
|
||||||
[mutations.LOADED_JOURNAL] (state, journal) {
|
|
||||||
state.journal = journal
|
|
||||||
},
|
|
||||||
[mutations.REQUEST_ADDED] (state, newRequest) {
|
|
||||||
state.journal.push(newRequest)
|
|
||||||
},
|
|
||||||
[mutations.REQUEST_UPDATED] (state, request) {
|
|
||||||
let jrnl = state.journal.filter(it => it.requestId !== request.requestId)
|
|
||||||
if (request.lastStatus !== 'Answered') jrnl.push(request)
|
|
||||||
state.journal = jrnl
|
|
||||||
},
|
|
||||||
[mutations.USER_LOGGED_OFF] (state) {
|
|
||||||
state.user = {}
|
|
||||||
api.removeBearer()
|
|
||||||
state.isAuthenticated = false
|
|
||||||
},
|
|
||||||
[mutations.USER_LOGGED_ON] (state, user) {
|
|
||||||
localStorage.setItem('user_profile', JSON.stringify(user))
|
|
||||||
state.user = user
|
|
||||||
api.setBearer(localStorage.getItem('id_token'))
|
|
||||||
state.isAuthenticated = true
|
|
||||||
}
|
|
||||||
},
|
|
||||||
actions: {
|
|
||||||
async [actions.ADD_REQUEST] ({ commit }, { progress, requestText, recurType, recurCount }) {
|
|
||||||
progress.start()
|
|
||||||
try {
|
|
||||||
const newRequest = await api.addRequest(requestText, recurType, recurCount)
|
|
||||||
commit(mutations.REQUEST_ADDED, newRequest.data)
|
|
||||||
progress.finish()
|
|
||||||
} catch (err) {
|
|
||||||
logError(err)
|
|
||||||
progress.fail()
|
|
||||||
}
|
|
||||||
},
|
|
||||||
async [actions.LOAD_JOURNAL] ({ commit }, progress) {
|
|
||||||
commit(mutations.LOADED_JOURNAL, {})
|
|
||||||
progress.start()
|
|
||||||
commit(mutations.LOADING_JOURNAL, true)
|
|
||||||
api.setBearer(localStorage.getItem('id_token'))
|
|
||||||
try {
|
|
||||||
const jrnl = await api.journal()
|
|
||||||
commit(mutations.LOADED_JOURNAL, jrnl.data)
|
|
||||||
progress.finish()
|
|
||||||
} catch (err) {
|
|
||||||
logError(err)
|
|
||||||
progress.fail()
|
|
||||||
} finally {
|
|
||||||
commit(mutations.LOADING_JOURNAL, false)
|
|
||||||
}
|
|
||||||
},
|
|
||||||
async [actions.UPDATE_REQUEST] ({ commit, state }, { progress, requestId, status, updateText, recurType, recurCount }) {
|
|
||||||
progress.start()
|
|
||||||
try {
|
|
||||||
let oldReq = (state.journal.filter(req => req.requestId === requestId) || [])[0] || {}
|
|
||||||
if (status !== 'Updated' || oldReq.text !== updateText) {
|
|
||||||
await api.updateRequest(requestId, status, updateText)
|
|
||||||
}
|
|
||||||
if (status === 'Updated' && (oldReq.recurType !== recurType || oldReq.recurCount !== recurCount)) {
|
|
||||||
await api.updateRecurrence(requestId, recurType, recurCount)
|
|
||||||
}
|
|
||||||
const request = await api.getRequest(requestId)
|
|
||||||
commit(mutations.REQUEST_UPDATED, request.data)
|
|
||||||
progress.finish()
|
|
||||||
} catch (err) {
|
|
||||||
logError(err)
|
|
||||||
progress.fail()
|
|
||||||
}
|
|
||||||
},
|
|
||||||
async [actions.SHOW_REQUEST_NOW] ({ commit }, { progress, requestId, showAfter }) {
|
|
||||||
progress.start()
|
|
||||||
try {
|
|
||||||
await api.showRequest(requestId, showAfter)
|
|
||||||
const request = await api.getRequest(requestId)
|
|
||||||
commit(mutations.REQUEST_UPDATED, request.data)
|
|
||||||
progress.finish()
|
|
||||||
} catch (err) {
|
|
||||||
logError(err)
|
|
||||||
progress.fail()
|
|
||||||
}
|
|
||||||
},
|
|
||||||
async [actions.SNOOZE_REQUEST] ({ commit }, { progress, requestId, until }) {
|
|
||||||
progress.start()
|
|
||||||
try {
|
|
||||||
await api.snoozeRequest(requestId, until)
|
|
||||||
const request = await api.getRequest(requestId)
|
|
||||||
commit(mutations.REQUEST_UPDATED, request.data)
|
|
||||||
progress.finish()
|
|
||||||
} catch (err) {
|
|
||||||
logError(err)
|
|
||||||
progress.fail()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
getters: {},
|
|
||||||
modules: {}
|
|
||||||
})
|
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
'use strict'
|
|
||||||
|
|
||||||
export default {
|
|
||||||
/** Mutation for when the user's prayer journal is being loaded */
|
|
||||||
LOADING_JOURNAL: 'loading-journal',
|
|
||||||
/** Mutation for when the user's prayer journal has been loaded */
|
|
||||||
LOADED_JOURNAL: 'journal-loaded',
|
|
||||||
/** Mutation for adding a new prayer request (pass text) */
|
|
||||||
REQUEST_ADDED: 'request-added',
|
|
||||||
/** Mutation to replace a prayer request at the top of the current journal */
|
|
||||||
REQUEST_UPDATED: 'request-updated',
|
|
||||||
/** Mutation for logging a user off */
|
|
||||||
USER_LOGGED_OFF: 'user-logged-off',
|
|
||||||
/** Mutation for logging a user on (pass user) */
|
|
||||||
USER_LOGGED_ON: 'user-logged-on'
|
|
||||||
}
|
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
<!DOCTYPE html>
|
|
||||||
<html>
|
|
||||||
<head>
|
|
||||||
<meta charset="utf-8">
|
|
||||||
<script src="https://cdn.auth0.com/js/auth0/8.9/auth0.min.js"></script>
|
|
||||||
<script>
|
|
||||||
var webAuth = new auth0.WebAuth({
|
|
||||||
domain: 'djs-consulting.auth0.com',
|
|
||||||
clientID: 'Of2s0RQCQ3mt3dwIkOBY5h85J9sXbF2n',
|
|
||||||
scope: 'openid profile email',
|
|
||||||
responseType: 'token id_token',
|
|
||||||
redirectUri: location.protocol + '//' + location.host + '/static/silent.html'
|
|
||||||
})
|
|
||||||
</script>
|
|
||||||
<script>
|
|
||||||
webAuth.parseHash(window.location.hash, function (err, response) {
|
|
||||||
parent.postMessage(err || response, location.protocol + '//' + location.host);
|
|
||||||
})
|
|
||||||
</script>
|
|
||||||
</head>
|
|
||||||
<body></body>
|
|
||||||
</html>
|
|
||||||
21
src/app/templates/layout/page_footer.php
Normal file
21
src/app/templates/layout/page_footer.php
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
<?php
|
||||||
|
use MyPrayerJournal\Constants; ?>
|
||||||
|
</section><?php
|
||||||
|
if (!$_REQUEST[Constants::IS_HTMX]) { ?>
|
||||||
|
<footer class="container-fluid mx-1">
|
||||||
|
<p class="text-muted has-text-right">
|
||||||
|
myPrayerJournal <?php echo $_REQUEST[Constants::VERSION]; ?><br>
|
||||||
|
<em><small>
|
||||||
|
<a <?php page_link('/legal/privacy-policy'); ?>>Privacy Policy</a> •
|
||||||
|
<a <?php page_link('/legal/terms-of-service'); ?>>Terms of Service</a> •
|
||||||
|
<a href="https://github.com/bit-badger/myprayerjournal" target="_blank" rel="noopener">Developed</a>
|
||||||
|
and hosted by
|
||||||
|
<a href="https://bitbadger.solutions" target="_blank" rel="noopener">Bit Badger Solutions</a>
|
||||||
|
</small></em>
|
||||||
|
</p>
|
||||||
|
</footer>
|
||||||
|
<script src="https://unpkg.com/htmx.org@1.9.4"
|
||||||
|
integrity="sha384-zUfuhFKKZCbHTY6aRR46gxiqszMk5tcHjsVFxnUo8VMus4kHGVdIYVbOYYNlKmHV"
|
||||||
|
crossorigin="anonymous"></script>
|
||||||
|
<script src="/script/mpj.js"></script><?php
|
||||||
|
}
|
||||||
50
src/app/templates/layout/page_header.php
Normal file
50
src/app/templates/layout/page_header.php
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
<?php
|
||||||
|
use BitBadger\PgDocuments\Document;
|
||||||
|
use MyPrayerJournal\{ Constants, Data };
|
||||||
|
|
||||||
|
$isLoggedOn = array_key_exists('MPJ_USER_ID', $_REQUEST);
|
||||||
|
$hasSnoozed = false;
|
||||||
|
if ($isLoggedOn) {
|
||||||
|
$hasSnoozed = Document::countByJsonPath(Data::REQ_TABLE, '$.snoozedUntil ? (@ == "0")') > 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
$theTitle = array_key_exists(Constants::PAGE_TITLE, $_REQUEST) ? "{$_REQUEST[Constants::PAGE_TITLE]} « " : ''; ?>
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf8">
|
||||||
|
<title><?php echo $theTitle; ?>myPrayerJournal</title><?php
|
||||||
|
if (!$_REQUEST[Constants::IS_HTMX]) { ?>
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.9.4/css/bulma.min.css"
|
||||||
|
integrity="sha512-HqxHUkJM0SYcbvxUw5P60SzdOTy/QVwA1JJrvaXJv4q7lmbDZCmZaqz01UPOaQveoxfYRv1tHozWGPMcuTBuvQ=="
|
||||||
|
crossorigin="anonymous" referrerpolicy="no-referrer">
|
||||||
|
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
|
||||||
|
<link href="/style/style.css" rel="stylesheet"><?php
|
||||||
|
} ?>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<section id="top" aria-label="top navigation">
|
||||||
|
<nav class="navbar is-dark has-shadow" role="navigation" aria-label="main navigation">
|
||||||
|
<div class="navbar-brand">
|
||||||
|
<a <?php page_link('/'); ?> class="navbar-item">
|
||||||
|
<span class="m">my</span><span class="p">Prayer</span><span class="j">Journal</span>
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
<div class="navbar-menu">
|
||||||
|
<div class="navbar-start"><?php
|
||||||
|
if ($isLoggedOn) { ?>
|
||||||
|
<a <?php page_link('/journal', ['navbar-item'], true); ?>>Journal</a>
|
||||||
|
<a <?php page_link('/requests/active', ['navbar-item'], true); ?>>Active</a><?php
|
||||||
|
if ($hasSnoozed) { ?>
|
||||||
|
<a <?php page_link('/requests/snoozed', ['navbar-item'], true); ?>>Snoozed</a><?php
|
||||||
|
} ?>
|
||||||
|
<a <?php page_link('/requests/answered', ['navbar-item'], true); ?>>Answered</a>
|
||||||
|
<a href="/user/log-off" class="navbar-item">Log Off</a><?php
|
||||||
|
} else { ?>
|
||||||
|
<a href="/user/log-on" class="navbar-item">Log On</a><?php
|
||||||
|
} ?>
|
||||||
|
<a href="https://docs.prayerjournal.me" class="navbar-item" target="_blank" rel="noopener">Docs</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</nav>
|
||||||
10
src/app/templates/no_content.php
Normal file
10
src/app/templates/no_content.php
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
<div class="card mb-3">
|
||||||
|
<div class="card-header has-background-light">
|
||||||
|
<h5 class="card-header-title"><?php echo $_REQUEST['EMPTY_HEADING']; ?></h5>
|
||||||
|
</div>
|
||||||
|
<div class="card-content has-text-centered">
|
||||||
|
<p class="mb-5"><?php echo $_REQUEST['EMPTY_TEXT']; ?></p>
|
||||||
|
<a <?php page_link($_REQUEST['EMPTY_LINK']); ?>
|
||||||
|
class="button is-link"><?php echo $_REQUEST['EMPTY_BTN_TXT']; ?></a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user