30 Commits

Author SHA1 Message Date
ff34bb9743 Add live-beta note 2024-06-26 18:41:41 -04:00
61127676a2 Update to beta2 of doc lib 2024-06-25 15:55:14 -04:00
5beeee4819 Use option for req-by-ID 2024-06-23 17:09:56 -04:00
a2feaff4da Clean up .NET artifacts 2024-06-23 16:39:35 -04:00
e121701250 Remove F# app / GitHub pages docs 2024-06-23 16:36:56 -04:00
20ad50928a Move files, complete PHP migration
The application works the same way as the F# version
2024-06-23 16:35:55 -04:00
9421bb2035 Add cancel snooze
- Add common request validation function
2024-06-23 06:58:47 -04:00
d6e8cf66cc Finish req list, add snoozed list 2024-06-22 22:48:31 -04:00
2369827033 Notes / snooze, update data migration
- WIP on finishing out request list
2024-06-22 20:23:37 -04:00
3ebb03d470 Adapt relative date logic from F# version 2024-06-22 18:13:45 -04:00
b759c3494e First cut of Add / Edit / Active / Answered pages
- Centralized UI between UI and Layout classes
2024-06-22 16:58:33 -04:00
0b7fa77247 Journal renders correctly 2024-06-22 12:30:26 -04:00
4ea55d4d25 Migrate v3 data; WIP on journal items 2024-06-21 23:22:56 -04:00
4aa6e832c7 Add Auth0, partial support 2024-06-21 19:01:12 -04:00
41853a7645 WIP on vanilla PHP framework 2024-06-20 23:06:31 -04:00
24c503385e Merge pull request 'Version 3.4' (#78) from 3.4 into main
Reviewed-on: #78
2024-06-07 23:37:08 +00:00
b393a86bb5 Configure id field 2024-06-07 19:35:17 -04:00
8ee3c6b483 Add documentation and handler (#77) 2024-06-07 12:04:00 -04:00
b07532ab50 Update Dockerfile to .NET 8 (#75)
- Update deps
- Implement newer doc library
2024-06-06 23:07:57 -04:00
b3f62c2586 WIP on update to .NET 8 (#75) 2024-06-06 22:49:57 -04:00
20dcaf6e1b Remove LiteDB/PostgreSQL migration util 2023-10-09 22:19:34 -04:00
b9d81fb7aa Convert Data Storage to PostgreSQL Documents (#74) 2023-10-09 22:15:38 -04:00
3df5c71d81 Update deps; move to .NET 7
- Update local htmx to v1.9.2
- Get version from assembly
2023-05-23 21:14:08 -04:00
c697001736 Merge pull request #73 from bit-badger/dependabot/nuget/src/MyPrayerJournal/LiteDB-5.0.13
Bump LiteDB from 5.0.12 to 5.0.13 in /src/MyPrayerJournal
2023-05-23 20:11:51 -04:00
dependabot[bot]
6c28cfc1ec Bump LiteDB from 5.0.12 to 5.0.13 in /src/MyPrayerJournal
Bumps [LiteDB](https://github.com/mbdavid/LiteDB) from 5.0.12 to 5.0.13.
- [Release notes](https://github.com/mbdavid/LiteDB/releases)
- [Commits](https://github.com/mbdavid/LiteDB/compare/v5.0.12...v5.0.13)

---
updated-dependencies:
- dependency-name: LiteDB
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-02-24 16:37:59 +00:00
8702723e01 Fix request ID generation (#72)
- Bump version
2022-08-23 08:36:17 -04:00
d621ede7bb Version 3.1 (#71)
- Fix request sorting
- Send time zone, so request actions are displayed in local time
- Make recurrence a true DU
- Tweak the data store representation of a few other fields
2022-07-30 17:02:58 -04:00
a826275510 Add NuGet packages for htmx extensions 2021-11-11 19:17:14 -05:00
2a86e41fe3 Add JetBrains link
Also fix typo
2021-11-03 10:52:42 -04:00
babc77bbd0 Remove v2/v3 migration project 2021-10-26 19:50:51 -04:00
69 changed files with 4205 additions and 2550 deletions

255
.gitignore vendored
View File

@@ -1,256 +1,7 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
# Visual Studio 2015 cache/options directory
.vs/
.vscode/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# DNX
project.lock.json
artifacts/
*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# TODO: Comment the next line if you want to checkin your web deploy settings
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/packages/*
# except build/, which is used as an MSBuild target.
!**/packages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/packages/repositories.config
# NuGet v3's project.json files produces more ignoreable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.pfx
*.publishsettings
node_modules/
orleans.codegen.cs
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
# SQL Server files
*.mdf
*.ldf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# JetBrains Rider # JetBrains Rider
.idea/ .idea/
*.sln.iml *.sln.iml
# Ionide VSCode extension # PHP ignore files
.ionide src/vendor
src/.env

View File

@@ -6,6 +6,6 @@ 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://prayerjournal.me/docs>.

View File

@@ -1 +0,0 @@
docs.prayerjournal.me

View File

@@ -1 +0,0 @@
theme: jekyll-theme-architect

View File

@@ -1,55 +0,0 @@
# Documentation
## About myPrayerJournal
Journaling has a long history; it helps people remember what happened, and the act of writing helps people think about what happened and process it. A prayer journal is not a new concept; it helps you keep track of the requests for which you've prayed, you can use it to pray over things repeatedly, and you can write the result when the answer comes _(or it was "no")_.
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.
## Finding the Site
The application is at <https://prayerjournal.me>.
## Signing Up
myPrayerJournal uses login services using Google or Microsoft accounts. The only information the application stores in its database is your user Id token it receives from these services, so there are no permissions you should have to accept from these provider other than establishing that you can log on with that account. Because of this, you'll want to pick the same one each time; the tokens between the two accounts are different, even if you use the same e-mail address to log on to both.
## Your Prayer Journal
Your current requests will be presented in columns (usually three, but it could be more or less, depending on the size of your screen or device). Each request is in its own card, and the buttons at the top of each card apply to that request. The last line of each request also tells you how long it has been since anything has been done on that request. Any time you see something like "a few minutes ago," you can hover over that to see the actual date/time the action was taken.
## Adding a Request
To add a request, click the "Add a New Request" button at the top of your journal. Then, enter the text of the request as you see fit; there is no right or wrong way, and you are the only person who will see the text you enter. When you save the request, it will go to the bottom of the list of requests.
## Setting Request Recurrence
When you add or update a request, you can choose whether requests go to the bottom of the journal once they have been marked "Prayed" or whether they will reappear after a delay. You can set recurrence in terms of hours, days, or weeks, but it cannot be longer than 365 days. If you decide you want a request to reappear sooner, you can skip the current delay; click the "Active" menu link, find the request in the list (likely near the bottom), and click the "Show Now" button.
## Praying for Requests
The first button for each request has a checkmark icon; clicking this button will mark the request as "Prayed" and move it to the bottom of the list (or off, if you've set a recurrence period for the request). This allows you, if you're praying through your requests, to start at the top left (with the request that it's been the longest since you've prayed) and click the button as you pray; when the request move below or away, the next-least-recently-prayed request will take the top spot.
## Editing Requests
The second button for each request has a pencil icon. This allows you to edit the text of the request, pretty much the same way you entered it; it starts with the current text, and you can add to it, modify it, or completely replace it. By default, updates will go in with an "Updated" status; you have the option to also mark this update as "Prayed" or "Answered." Answered requests will drop off the journal list.
## Adding Notes
The third button for each request has an icon that looks like a speech bubble with lines on it; this lets you record notes about the request. If there is something you want to record that doesn't change the text of the request, this is the place to do it. For example, you may be praying for a long-term health issue, and that person tells you that their status is the same; or, you may want to record something God said to you while you were praying for that request.
## Snoozing Requests
There may be a time where a request does not need to appear. The fourth button, with the clock icon, allows you to snooze requests until the day you specify. Additionally, if you have any snoozed requests, a "Snoozed" menu item will appear next to the "Journal" one; this page allows you to see what requests are snoozed, and return them to your journal by canceling the snooze.
## Viewing a Request and Its History
myPrayerJournal tracks all of the actions related to a request; from the "Active" and "Answered" menu links (and "Snoozed", if it's showing), there is a "View Full Request" button. That page will show the current text of the request; how many times it has been marked as prayed; how long it has been an active request; and a log of all updates, prayers, and notes you have recorded. That log is listed from most recent to least recent; if you want to read it chronologically, just press the "End" key on your keyboard and read it from the bottom up.
The "Active" link will show all requests that have not yet been marked answered, including snoozed and recurring requests. If requests are snoozed, or in a recurrence period off the journal, there will be a button where you can return the request to the list (either "Cancel Snooze" or "Show Now"). The "Answered" link shows all requests that have been marked answered. The "Snoozed" link just shows snoozed requests.
## Final Notes
- If you encounter errors, please [file an issue on GitHub](https://github.com/bit-badger/myPrayerJournal/issues) with as much detail as possible. You can also provide suggestions, or browse the list of currently open issues.
- Prayer requests and their history are securely backed up nightly along with other Bit Badger Solutions data.
- Prayer changes things - most of all, the one doing the praying. I pray that this tool enables you to deepen and strengthen your prayer life.

View File

@@ -1,3 +0,0 @@
#!/snap/bin/pwsh
Set-Location src/MyPrayerJournal
dotnet publish -c Release -r linux-x64 -p:PublishSingleFile=true --self-contained false

9
src/Caddyfile Normal file
View File

@@ -0,0 +1,9 @@
{
frankenphp
order php_server before file_server
}
http://localhost:3000 {
root * ./public
try_files {path} {path}.php
php_server
}

17
src/Dockerfile Normal file
View File

@@ -0,0 +1,17 @@
FROM mcr.microsoft.com/dotnet/sdk:8.0-alpine AS build
WORKDIR /mpj
COPY ./MyPrayerJournal/MyPrayerJournal.fsproj ./
RUN dotnet restore
COPY ./MyPrayerJournal ./
RUN dotnet publish -c Release -r linux-x64
RUN rm bin/Release/net8.0/linux-x64/publish/appsettings.*.json || true
FROM mcr.microsoft.com/dotnet/aspnet:8.0-alpine as final
WORKDIR /app
RUN apk add --no-cache icu-libs
ENV DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=false
COPY --from=build /mpj/bin/Release/net8.0/linux-x64/publish/ ./
EXPOSE 80
CMD [ "dotnet", "/app/MyPrayerJournal.dll" ]

View File

@@ -1,22 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<Compile Include="Program.fs" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="FSharp.Data" Version="4.2.3" />
<PackageReference Include="LiteDB" Version="5.0.11" />
<PackageReference Include="NodaTime" Version="3.0.9" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\MyPrayerJournal\MyPrayerJournal.fsproj" />
</ItemGroup>
</Project>

View File

@@ -1,57 +0,0 @@
open FSharp.Data
open FSharp.Data.CsvExtensions
open LiteDB
open MyPrayerJournal.Domain
open NodaTime
module Subdocs =
open FSharp.Data.JsonExtensions
let history json =
match JsonValue.Parse json with
| JsonValue.Array hist ->
hist
|> Array.map (fun h ->
{ asOf = (h?asOf.AsInteger64 >> Instant.FromUnixTimeMilliseconds) ()
status = h?status.AsString () |> RequestAction.ofString
text = match h?text.AsString () with "" -> None | txt -> Some txt
})
|> List.ofArray
| _ -> []
let notes json =
match JsonValue.Parse json with
| JsonValue.Array notes ->
notes
|> Array.map (fun n ->
{ asOf = (n?asOf.AsInteger64 >> Instant.FromUnixTimeMilliseconds) ()
notes = n?notes.AsString ()
})
|> List.ofArray
| _ -> []
let oldData = CsvFile.Load("data.csv")
let db = new LiteDatabase("Filename=./mpj.db")
MyPrayerJournal.Data.Startup.ensureDb db
let migrated =
oldData.Rows
|> Seq.map (fun r ->
{ id = r["@id"].Replace ("Requests/", "") |> RequestId.ofString
enteredOn = (r?enteredOn.AsInteger64 >> Instant.FromUnixTimeMilliseconds) ()
userId = UserId r?userId
snoozedUntil = (r?snoozedUntil.AsInteger64 >> Instant.FromUnixTimeMilliseconds) ()
showAfter = (r?showAfter.AsInteger64 >> Instant.FromUnixTimeMilliseconds) ()
recurType = r?recurType |> Recurrence.ofString
recurCount = (r?recurCount.AsInteger >> int16) ()
history = Subdocs.history r?history
notes = Subdocs.notes r?notes
})
|> db.GetCollection<Request>("request").Insert
db.Checkpoint ()
printfn $"Migrated {migrated} requests"

View File

@@ -1,5 +0,0 @@
## LiteDB database file
*.db
## Development settings
appsettings.Development.json

View File

@@ -1,209 +0,0 @@
module MyPrayerJournal.Data
open LiteDB
open NodaTime
open System
open System.Threading.Tasks
// fsharplint:disable MemberNames
/// LiteDB extensions
[<AutoOpen>]
module Extensions =
/// Extensions on the LiteDatabase class
type LiteDatabase with
/// The Request collection
member this.requests
with get () = 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 =
/// Map a history entry to BSON
let historyToBson (hist : History) : BsonValue =
let doc = BsonDocument ()
doc["asOf"] <- hist.asOf.ToUnixTimeMilliseconds ()
doc["status"] <- RequestAction.toString hist.status
doc["text"] <- match hist.text with Some t -> t | None -> ""
upcast doc
/// Map a BSON document to a history entry
let historyFromBson (doc : BsonValue) =
{ asOf = Instant.FromUnixTimeMilliseconds doc["asOf"].AsInt64
status = RequestAction.ofString doc["status"].AsString
text = match doc["text"].AsString with "" -> None | txt -> Some txt
}
/// Map a note entry to BSON
let noteToBson (note : Note) : BsonValue =
let doc = BsonDocument ()
doc["asOf"] <- note.asOf.ToUnixTimeMilliseconds ()
doc["notes"] <- note.notes
upcast doc
/// Map a BSON document to a note entry
let noteFromBson (doc : BsonValue) =
{ asOf = Instant.FromUnixTimeMilliseconds doc["asOf"].AsInt64
notes = doc["notes"].AsString
}
/// Map a request to its BSON representation
let requestToBson req : BsonValue =
let doc = BsonDocument ()
doc["_id"] <- RequestId.toString req.id
doc["enteredOn"] <- req.enteredOn.ToUnixTimeMilliseconds ()
doc["userId"] <- UserId.toString req.userId
doc["snoozedUntil"] <- req.snoozedUntil.ToUnixTimeMilliseconds ()
doc["showAfter"] <- req.showAfter.ToUnixTimeMilliseconds ()
doc["recurType"] <- Recurrence.toString req.recurType
doc["recurCount"] <- BsonValue req.recurCount
doc["history"] <- BsonArray (req.history |> List.map historyToBson |> Seq.ofList)
doc["notes"] <- BsonArray (req.notes |> List.map noteToBson |> Seq.ofList)
upcast doc
/// Map a BSON document to a request
let requestFromBson (doc : BsonValue) =
{ id = RequestId.ofString doc["_id"].AsString
enteredOn = Instant.FromUnixTimeMilliseconds doc["enteredOn"].AsInt64
userId = UserId doc["userId"].AsString
snoozedUntil = Instant.FromUnixTimeMilliseconds doc["snoozedUntil"].AsInt64
showAfter = Instant.FromUnixTimeMilliseconds doc["showAfter"].AsInt64
recurType = Recurrence.ofString doc["recurType"].AsString
recurCount = int16 doc["recurCount"].AsInt32
history = doc["history"].AsArray |> Seq.map historyFromBson |> List.ofSeq
notes = doc["notes"].AsArray |> Seq.map noteFromBson |> List.ofSeq
}
/// Set up the mapping
let register () =
BsonMapper.Global.RegisterType<Request>(
Func<Request, BsonValue> requestToBson, Func<BsonValue, Request> requestFromBson)
/// 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 = 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 = note :: req.notes }
| None -> invalidOp $"{RequestId.toString reqId} not found"
}
/// Add a request
let addRequest (req : Request) (db : LiteDatabase) =
db.requests.Insert req |> ignore
// FIXME: make a common function here
/// Retrieve all answered requests for the given user
let answeredRequests userId (db : LiteDatabase) = backgroundTask {
let! reqs = db.requests.Find (Query.EQ ("userId", UserId.toString userId)) |> toListAsync
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 : LiteDatabase) = backgroundTask {
let! jrnl = db.requests.Find (Query.EQ ("userId", UserId.toString userId)) |> toListAsync
return
jrnl
|> 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 -> r.snoozedUntil > now)
}
/// 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 recurCount db = backgroundTask {
match! tryFullRequestById reqId userId db with
| Some req -> do! doUpdate db { req with recurType = recurType; recurCount = recurCount }
| 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"
}

View File

@@ -1,78 +0,0 @@
/// 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
/// Convert from a JavaScript "ticks" value to a date/time
let fromJs ticks = DateTime.UnixEpoch + TimeSpan.FromTicks (ticks * 10_000L)
let formatDistance (startDate : Instant) (endDate : 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 = startDate - endDate
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 startDate > endDate with true -> sprintf "%s ago" | false -> sprintf "in %s"

View File

@@ -1,213 +0,0 @@
[<AutoOpen>]
/// The data model for myPrayerJournal
module MyPrayerJournal.Domain
// fsharplint:disable RecordFieldNames
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 =
| Immediate
| Hours
| Days
| Weeks
/// Functions to manipulate recurrences
module Recurrence =
/// Create a string representation of a recurrence
let toString =
function
| Immediate -> "Immediate"
| Hours -> "Hours"
| Days -> "Days"
| Weeks -> "Weeks"
/// Create a recurrence value from a string
let ofString =
function
| "Immediate" -> Immediate
| "Hours" -> Hours
| "Days" -> Days
| "Weeks" -> Weeks
| 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 x =
(match x with
| Immediate -> 0L
| Hours -> oneHour
| Days -> oneHour * 24L
| Weeks -> oneHour * 24L * 7L)
/// The action taken on a request as part of a history entry
type RequestAction =
| Created
| Prayed
| Updated
| Answered
/// 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
}
/// 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
/// The time at which this request should reappear in the user's journal by recurrence
showAfter : Instant
/// The type of recurrence for this request
recurType : Recurrence
/// How many of the recurrence intervals should occur between appearances in the journal
recurCount : int16
/// The history entries for this request
history : History list
/// The notes for this request
notes : Note list
}
with
/// An empty request
static member empty =
{ id = Cuid.generate () |> RequestId
enteredOn = Instant.MinValue
userId = UserId ""
snoozedUntil = Instant.MinValue
showAfter = Instant.MinValue
recurType = Immediate
recurCount = 0s
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 status for the request
lastStatus : RequestAction
/// The time that this request should reappear in the user's journal
snoozedUntil : Instant
/// The time after which this request should reappear in the user's journal by configured recurrence
showAfter : Instant
/// The type of recurrence for this request
recurType : Recurrence
/// 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
}
/// 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 hist = req.history |> List.sortByDescending (fun it -> it.asOf) |> List.tryHead
{ requestId = req.id
userId = req.userId
text = req.history
|> List.filter (fun it -> Option.isSome it.text)
|> List.sortByDescending (fun it -> it.asOf)
|> List.tryHead
|> Option.map (fun h -> Option.get h.text)
|> Option.defaultValue ""
asOf = match hist with Some h -> h.asOf | None -> Instant.MinValue
lastStatus = match hist with Some h -> h.status | None -> Created
snoozedUntil = req.snoozedUntil
showAfter = req.showAfter
recurType = req.recurType
recurCount = req.recurCount
history = []
notes = []
}
/// Same as `ofRequestLite`, but with notes and history
let ofRequestFull req =
{ ofRequestLite req with
history = req.history
notes = req.notes
}
/// 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}"
/// 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

View File

@@ -1,603 +0,0 @@
/// HTTP handlers for the myPrayerJournal API
[<RequireQualifiedAccess>]
module MyPrayerJournal.Handlers
// fsharplint:disable RecordFieldNames
open Giraffe
open Giraffe.Htmx
open Microsoft.AspNetCore.Authentication
open Microsoft.AspNetCore.Http
open System
open System.Security.Claims
open NodaTime
/// Helper function to be able to split out log on
[<AutoOpen>]
module private LogOnHelpers =
/// Log on, optionally specifying a redirected URL once authentication is complete
let logOn url : HttpHandler =
fun next ctx -> backgroundTask {
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
open System.Threading.Tasks
/// 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" (sprintf "error|||%s: %s" (ex.GetType().Name) ex.Message)
>=> text ex.Message
/// Handle unauthorized actions, redirecting to log on for GETs, otherwise returning a 401 Not Authorized reponse
let notAuthorized : HttpHandler =
fun next ctx ->
(next, ctx)
||> match ctx.Request.Method with
| "GET" -> logOn None
| _ -> setStatusCode 401 >=> fun _ _ -> Task.FromResult<HttpContext option> None
/// 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"
/// Handler helpers
[<AutoOpen>]
module private Helpers =
open LiteDB
open Microsoft.Extensions.Logging
open Microsoft.Net.Http.Headers
let debug (ctx : HttpContext) message =
let fac = ctx.GetService<ILoggerFactory>()
let log = fac.CreateLogger "Debug"
log.LogInformation message
/// Get the LiteDB database
let db (ctx : HttpContext) = ctx.GetService<LiteDatabase>()
/// Get the user's "sub" claim
let user (ctx : HttpContext) =
ctx.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)
/// Get the current user's ID
// NOTE: this may raise if you don't run the request through the requiresAuthentication handler first
let userId ctx =
(user >> Option.get) ctx |> UserId
/// Get the system clock
let clock (ctx : HttpContext) =
ctx.GetService<IClock> ()
/// Get the current instant
let now ctx =
(clock ctx).GetCurrentInstant ()
/// 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 ->
(sprintf "%s://%s%s" ctx.Request.Scheme ctx.Request.Host.Value url |> setHttpHeader HeaderNames.Location
>=> created) 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 next ctx -> backgroundTask {
return! ctx.WriteHtmlStringAsync (ViewEngine.RenderView.AsString.htmlNodes nodes)
}
open Views.Layout
/// Create a page rendering context
let pageContext (ctx : HttpContext) pageTitle content = backgroundTask {
let! hasSnoozed = backgroundTask {
match user ctx with
| Some _ -> return! Data.hasSnoozed (userId ctx) (now ctx) (db ctx)
| None -> return false
}
return {
isAuthenticated = (user >> Option.isSome) ctx
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 next ctx -> backgroundTask {
return! ctx.WriteHtmlViewAsync view
}
/// Hold messages across redirects
module Messages =
/// The messages being held
let mutable private messages : Map<string, (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 message url = lock upd8 (fun () ->
messages <- messages.Add (ctx |> (user >> Option.get), (message, url)))
/// Add a success message header to the response
let pushSuccess ctx message url =
push ctx (sprintf "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 -> backgroundTask {
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 user ctx with
| Some u ->
match Messages.pop u with
| Some (msg, url) -> setHttpHeader "X-Toast" msg >=> withHxPush 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 =
requiresAuthentication Error.notAuthorized
>=> fun next ctx -> backgroundTask {
let now = now ctx
let! jrnl = Data.journalByUserId (userId ctx) (db ctx)
let shown = jrnl |> List.filter (fun it -> now > it.snoozedUntil && now > it.showAfter)
return! renderComponent [ Views.Journal.journalItems now shown ] next ctx
}
// GET /components/request-item/[req-id]
let requestItem reqId : HttpHandler =
requiresAuthentication Error.notAuthorized
>=> fun next ctx -> backgroundTask {
match! Data.tryJournalById (RequestId.ofString reqId) (userId ctx) (db ctx) with
| Some req -> return! renderComponent [ Views.Request.reqListItem (now ctx) req ] next ctx
| None -> return! Error.notFound next ctx
}
// GET /components/request/[req-id]/add-notes
let addNotes requestId : HttpHandler =
requiresAuthentication Error.notAuthorized
>=> renderComponent (Views.Journal.notesEdit (RequestId.ofString requestId))
// GET /components/request/[req-id]/notes
let notes requestId : HttpHandler =
requiresAuthentication Error.notAuthorized
>=> fun next ctx -> backgroundTask {
let! notes = Data.notesById (RequestId.ofString requestId) (userId ctx) (db ctx)
return! renderComponent (Views.Request.notes (now ctx) notes) next ctx
}
// GET /components/request/[req-id]/snooze
let snooze requestId : HttpHandler =
requiresAuthentication Error.notAuthorized
>=> 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 =
requiresAuthentication Error.notAuthorized
>=> fun next ctx -> backgroundTask {
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 (sprintf "%s Prayer Journal" title) (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 =
// GET /request/[req-id]/edit
let edit requestId : HttpHandler =
requiresAuthentication Error.notAuthorized
>=> fun next ctx -> backgroundTask {
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) (userId ctx) (db ctx) 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 =
requiresAuthentication Error.notAuthorized
>=> fun next ctx -> backgroundTask {
let db = db ctx
let usrId = userId ctx
let reqId = RequestId.ofString requestId
match! Data.tryRequestById reqId usrId db with
| Some req ->
let now = now ctx
do! Data.addHistory reqId usrId { asOf = now; status = Prayed; text = None } db
let nextShow =
match Recurrence.duration req.recurType with
| 0L -> Instant.MinValue
| duration -> now.Plus (Duration.FromSeconds (duration * int64 req.recurCount))
do! Data.updateShowAfter reqId usrId 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 =
requiresAuthentication Error.notAuthorized
>=> fun next ctx -> backgroundTask {
let db = db ctx
let usrId = userId ctx
let reqId = RequestId.ofString requestId
match! Data.tryRequestById reqId usrId db with
| Some _ ->
let! notes = ctx.BindFormAsync<Models.NoteEntry> ()
do! Data.addNote reqId usrId { asOf = now ctx; 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 =
requiresAuthentication Error.notAuthorized
>=> fun next ctx -> backgroundTask {
let! reqs = Data.journalByUserId (userId ctx) (db ctx)
return! partial "Active Requests" (Views.Request.active (now ctx) reqs) next ctx
}
// GET /requests/snoozed
let snoozed : HttpHandler =
requiresAuthentication Error.notAuthorized
>=> fun next ctx -> backgroundTask {
let! reqs = Data.journalByUserId (userId ctx) (db ctx)
let now = now ctx
let snoozed = reqs |> List.filter (fun it -> it.snoozedUntil > now)
return! partial "Active Requests" (Views.Request.snoozed now snoozed) next ctx
}
// GET /requests/answered
let answered : HttpHandler =
requiresAuthentication Error.notAuthorized
>=> fun next ctx -> backgroundTask {
let! reqs = Data.answeredRequests (userId ctx) (db ctx)
return! partial "Answered Requests" (Views.Request.answered (now ctx) reqs) next ctx
}
// GET /api/request/[req-id]
let get requestId : HttpHandler =
requiresAuthentication Error.notAuthorized
>=> fun next ctx -> backgroundTask {
match! Data.tryJournalById (RequestId.ofString requestId) (userId ctx) (db ctx) with
| Some req -> return! json req next ctx
| None -> return! Error.notFound next ctx
}
// GET /request/[req-id]/full
let getFull requestId : HttpHandler =
requiresAuthentication Error.notAuthorized
>=> fun next ctx -> backgroundTask {
match! Data.tryFullRequestById (RequestId.ofString requestId) (userId ctx) (db ctx) with
| Some req -> return! partial "Prayer Request" (Views.Request.full (clock ctx) req) next ctx
| None -> return! Error.notFound next ctx
}
// PATCH /request/[req-id]/show
let show requestId : HttpHandler =
requiresAuthentication Error.notAuthorized
>=> fun next ctx -> backgroundTask {
let db = db ctx
let usrId = userId ctx
let reqId = RequestId.ofString requestId
match! Data.tryRequestById reqId usrId db with
| Some _ ->
do! Data.updateShowAfter reqId usrId Instant.MinValue 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 =
requiresAuthentication Error.notAuthorized
>=> fun next ctx -> backgroundTask {
let db = db ctx
let usrId = userId ctx
let reqId = RequestId.ofString requestId
match! Data.tryRequestById reqId usrId 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 usrId 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 =
requiresAuthentication Error.notAuthorized
>=> fun next ctx -> backgroundTask {
let db = db ctx
let usrId = userId ctx
let reqId = RequestId.ofString requestId
match! Data.tryRequestById reqId usrId db with
| Some _ ->
do! Data.updateSnoozed reqId usrId Instant.MinValue db
do! db.saveChanges ()
return! (withSuccessMessage "Request unsnoozed" >=> Components.requestItem requestId) next ctx
| None -> return! Error.notFound next ctx
}
/// Derive a recurrence and interval from its primitive representation in the form
let private parseRecurrence (form : Models.Request) =
(Recurrence.ofString (match form.recurInterval with Some x -> x | _ -> "Immediate"),
defaultArg form.recurCount (int16 0))
// POST /request
let add : HttpHandler =
requiresAuthentication Error.notAuthorized
>=> fun next ctx -> backgroundTask {
let! form = ctx.BindModelAsync<Models.Request> ()
let db = db ctx
let usrId = userId ctx
let now = now ctx
let (recur, interval) = parseRecurrence form
let req =
{ Request.empty with
userId = usrId
enteredOn = now
showAfter = Instant.MinValue
recurType = recur
recurCount = interval
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 =
requiresAuthentication Error.notAuthorized
>=> fun next ctx -> backgroundTask {
let! form = ctx.BindModelAsync<Models.Request> ()
let db = db ctx
let usrId = userId ctx
match! Data.tryJournalById (RequestId.ofString form.requestId) usrId db with
| Some req ->
// update recurrence if changed
let (recur, interval) = parseRecurrence form
match recur = req.recurType && interval = req.recurCount with
| true -> ()
| false ->
do! Data.updateRecurrence req.requestId usrId recur interval db
match recur with
| Immediate -> do! Data.updateShowAfter req.requestId usrId Instant.MinValue db
| _ -> ()
// append history
let upd8Text = form.requestText.Trim ()
let text = match upd8Text = req.text with true -> None | false -> Some upd8Text
do! Data.addHistory req.requestId usrId
{ asOf = now ctx; 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.Cookies
// GET /user/log-on
let logOn : HttpHandler =
logOn (Some "/journal")
// GET /user/log-off
let logOff : HttpHandler =
requiresAuthentication Error.notAuthorized
>=> 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
]
]
]

View File

@@ -1,33 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Version>3.0.0.0</Version>
</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="0.17.4" />
<PackageReference Include="FunctionalCuid" Version="1.0.0" />
<PackageReference Include="Giraffe" Version="5.0.0" />
<PackageReference Include="LiteDB" Version="5.0.11" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.OpenIdConnect" Version="5.0.10" />
<PackageReference Include="NodaTime" Version="3.0.9" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="../../../Giraffe.Htmx/src/Htmx/Giraffe.Htmx.fsproj" />
<ProjectReference Include="../../../Giraffe.Htmx/src/ViewEngine.Htmx/Giraffe.ViewEngine.Htmx.fsproj" />
</ItemGroup>
<ItemGroup>
<Folder Include="wwwroot\" />
</ItemGroup>
</Project>

View File

@@ -1,181 +0,0 @@
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) =
match bldr.Environment.IsDevelopment () with
| true -> ()
| false -> 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
| _, _ -> ()
bldr.Services
.AddRouting()
.AddGiraffe()
.AddSingleton<IClock>(SystemClock.Instance)
.Configure<CookiePolicyOptions>(
fun (opts : CookiePolicyOptions) ->
opts.MinimumSameSitePolicy <- SameSiteMode.Unspecified
opts.OnAppendCookie <- fun ctx -> sameSite ctx.CookieOptions
opts.OnDeleteCookie <- fun ctx -> sameSite ctx.CookieOptions)
.AddAuthentication(
/// Use HTTP "Bearer" authentication with JWTs
fun opts ->
opts.DefaultAuthenticateScheme <- CookieAuthenticationDefaults.AuthenticationScheme
opts.DefaultSignInScheme <- CookieAuthenticationDefaults.AuthenticationScheme
opts.DefaultChallengeScheme <- CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie()
.AddOpenIdConnect("Auth0",
/// Configure OIDC with Auth0 options from configuration
fun opts ->
let cfg = bldr.Configuration.GetSection "Auth0"
opts.Authority <- sprintf "https://%s/" 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
sprintf "%s://%s%s%s" request.Scheme request.Host.Value request.PathBase.Value redirUri
| false -> redirUri
Uri.EscapeDataString finalRedirUri |> sprintf "&returnTo=%s"
sprintf "https://%s/v2/logout?client_id=%s%s" cfg["Domain"] cfg["Id"] returnTo
|> ctx.Response.Redirect
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
)
|> ignore
let jsonOptions = JsonSerializerOptions ()
jsonOptions.Converters.Add (JsonFSharpConverter ())
let db = new LiteDatabase (bldr.Configuration.GetConnectionString "db")
Data.Startup.ensureDb db
bldr.Services.AddSingleton(jsonOptions)
.AddSingleton<Json.ISerializer, SystemTextJson.Serializer>()
.AddSingleton<LiteDatabase> db
|> ignore
bldr.Build ()
open Giraffe.EndpointRouting
/// Configure the web application
let application (app : WebApplication) =
// match app.Environment.IsDevelopment () with
// | true -> app.UseDeveloperExceptionPage ()
// | false -> app.UseGiraffeErrorHandler Handlers.Error.error
// |> ignore
app
.UseStaticFiles()
.UseCookiePolicy()
.UseRouting()
.UseAuthentication()
.UseGiraffeErrorHandler(Handlers.Error.error)
.UseEndpoints (fun e -> e.MapGiraffeEndpoints Handlers.routes |> ignore)
|> ignore
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

View File

@@ -1,27 +0,0 @@
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:61905",
"sslPort": 0
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"MyPrayerJournal.Api": {
"commandName": "Project",
"launchBrowser": true,
"applicationUrl": "http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

View File

@@ -1,31 +0,0 @@
/// Internal partial views
[<AutoOpen>]
module private MyPrayerJournal.Views.Helpers
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 ]
|> 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 =
span [ _title (date.ToDateTimeOffset().ToString ("f", null)) ] [ Dates.formatDistance now date |> str ]

View File

@@ -1,177 +0,0 @@
/// Views for journal pages and components
module MyPrayerJournal.Views.Journal
open Giraffe.ViewEngine
open Giraffe.ViewEngine.Accessibility
open Giraffe.ViewEngine.Htmx
open MyPrayerJournal
/// Display a card for this prayer request
let journalCard now req =
let reqId = RequestId.toString req.requestId
let spacer = span [] [ rawText "&nbsp;" ]
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 [] [ str "last activity "; relativeDate req.asOf now ]
]
]
]
/// The journal loading page
let journal user = article [ _class "container-fluid mt-3" ] [
h2 [ _class "pb-3" ] [
str user
match user with "Your" -> () | _ -> rawText "&rsquo;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&hellip;"
]
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 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 &ldquo;Active&rdquo; link above for snoozed or deferred "
rawText "requests, and the &ldquo;Answered&rdquo; link for answered requests"
]
| false ->
items
|> List.map (journalCard now)
|> 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
]
/// 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" ] ]
]

View File

@@ -1,151 +0,0 @@
/// Layout / home views
module MyPrayerJournal.Views.Layout
// fsharplint:disable RecordFieldNames
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 "&nbsp;" ]
p [] [
str "myPrayerJournal is a place where individuals can record their prayer requests, record that they prayed for "
str "them, update them as God moves in the situation, and record a final answer received on that request. It also "
str "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 "&ldquo;Log On&rdquo; link above, and log on with either a Microsoft or Google account. You can also "
rawText "learn more about the site at the &ldquo;Docs&rdquo; 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
match ctx.isAuthenticated with
| true ->
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" ] ]
| false -> 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 " &#xab; 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.0.2/dist/css/bootstrap.min.css"
_rel "stylesheet"
_integrity "sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"
_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 v3"
br []
em [] [
small [] [
pageLink "/legal/privacy-policy" [] [ str "Privacy Policy" ]
rawText " &bull; "
pageLink "/legal/terms-of-service" [] [ str "Terms of Service" ]
rawText " &bull; "
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" ]
]
]
]
script [
_src "https://unpkg.com/htmx.org@1.5.0"
_integrity "sha384-oGA+prIp5Vchu6we2YkI51UtVzN9Jpx2Z7PnR1I78PnZlN8LkrCT4lqqqmDkyrvI"
_crossorigin "anonymous"
] []
script [] [
rawText "if (!htmx) document.write('<script src=\"/script/htmx-1.5.0.min.js\"><\/script>')"
]
script [
_async
_src "https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"
_integrity "sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"
_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" ] [ 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 ] ]
]

View File

@@ -1,153 +0,0 @@
/// 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 the data "
str "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 familiarize "
str "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 [] [
rawText "The only identifying data myPrayerJournal stores is the subscriber (&ldquo;sub&rdquo;) field from "
str "the token we receive from Auth0, once you have signed in through their hosted service. All "
str "information is associated with you via this field."
]
li [] [
str "While you are signed in, within your browser, the service has access to your first and last names, "
str "along with a URL to the profile picture (provided by your selected identity provider). This "
rawText "information is not transmitted to the server, and is removed when &ldquo;Log Off&rdquo; is "
str "clicked."
]
]
h4 [] [ str "User Provided Data" ]
ul [ _class "mb-0" ] [
li [] [
str "myPrayerJournal stores the information you provide, including the text of prayer requests, updates, "
str "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 answered "
str "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 rolling manner; "
str "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 repository."
]
li [] [
str "The data collected and stored is the absolute minimum necessary for the functionality of the service. "
rawText "There are no plans to &ldquo;monetize&rdquo; this service, and storing the minimum amount of "
str "information means that the data we have is not interesting to purchasers (or those who may have more "
str "nefarious purposes)."
]
li [] [
str "Access to servers and backups is strictly controlled and monitored for unauthorized 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 provide ways "
str "to revoke access from this application. However, if you want your data removed from the database, "
str "please contact daniel at bitbadger.solutions (via e-mail, replacing at with @) prior to doing so, to "
str "ensure we can determine which subscriber ID 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, and that you "
str "are responsible to ensure that your use of this site complies with all applicable laws. Your continued "
str "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 requests. It "
str "requires no registration by itself, but access is granted based on a successful login with an external "
str "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 terms of "
str "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 &ldquo;as is&rdquo;, and no warranty (express or implied) exists. The "
str "service and its developers may not be held liable for any damages that may arise through the use of "
str "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 capability to "
str "notify users when these change. The date at the top of the page will be updated when any of the text of "
str "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."
]
]

View File

@@ -1,268 +0,0 @@
/// Views for request pages and components
module MyPrayerJournal.Views.Request
open Giraffe.ViewEngine
open Giraffe.ViewEngine.Htmx
open MyPrayerJournal
open NodaTime
open System
/// Create a request within the list
let reqListItem now req =
let reqId = RequestId.toString req.requestId
let isAnswered = req.lastStatus = Answered
let isSnoozed = req.snoozedUntil > now
let isPending = (not isSnoozed) && req.showAfter > now
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" ]
match isAnswered with
| true -> ()
| false -> pageLink $"/request/{reqId}/edit" [ btnClass; _title "Edit Request" ] [ icon "edit" ]
match true with
| _ when isSnoozed -> restoreBtn "cancel-snooze" "Cancel Snooze"
| _ when isPending -> restoreBtn "show" "Show Now"
| _ -> ()
p [ _class "request-text mb-0" ] [
str req.text
match isSnoozed || isPending || isAnswered with
| true ->
br []
small [ _class "text-muted" ] [
match () with
| _ when isSnoozed -> [ str "Snooze expires "; relativeDate req.snoozedUntil now ]
| _ when isPending -> [ str "Request appears next "; relativeDate req.showAfter now ]
| _ (* isAnswered *) -> [ str "Answered "; relativeDate req.asOf now ]
|> em []
]
| false -> ()
]
]
/// Create a list of requests
let reqList now reqs =
reqs
|> List.map (reqListItem now)
|> div [ _class "list-group" ]
/// View for Active Requests page
let active now reqs = article [ _class "container mt-3" ] [
h2 [ _class "pb-3" ] [ str "Active Requests" ]
match reqs |> List.isEmpty with
| true ->
noResults "No Active Requests" "/journal" "Return to your journal"
[ str "Your prayer journal has no active requests" ]
| false -> reqList now reqs
]
/// View for Answered Requests page
let answered now reqs = article [ _class "container mt-3" ] [
h2 [ _class "pb-3" ] [ str "Answered Requests" ]
match reqs |> List.isEmpty with
| true ->
noResults "No Active Requests" "/journal" "Return to your journal" [
rawText "Your prayer journal has no answered requests; once you have marked one as &ldquo;Answered&rdquo;, "
str "it will appear here"
]
| false -> reqList now reqs
]
/// View for Snoozed Requests page
let snoozed now reqs = article [ _class "container mt-3" ] [
h2 [ _class "pb-3" ] [ str "Snoozed Requests" ]
reqList now reqs
]
/// View for Full Request page
let full (clock : IClock) (req : Request) =
let now = clock.GetCurrentInstant ()
let answered =
req.history
|> List.filter RequestAction.isAnswered
|> List.tryHead
|> Option.map (fun x -> x.asOf)
let prayed = (req.history |> List.filter RequestAction.isPrayed |> List.length).ToString "N0"
let daysOpen =
let asOf = defaultArg answered now
((asOf - (req.history |> List.filter RequestAction.isCreated |> List.head).asOf).TotalDays |> int).ToString "N0"
let lastText =
req.history
|> List.filter (fun h -> Option.isSome h.text)
|> List.sortByDescending (fun h -> h.asOf)
|> List.map (fun h -> Option.get h.text)
|> List.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
|> List.map (fun n -> {| asOf = n.asOf; text = Some n.notes; status = "Notes" |})
|> List.append (req.history |> List.map toDisp)
|> List.sortByDescending (fun it -> it.asOf)
// Skip the first entry for answered requests; that info is already displayed
match answered with Some _ -> all |> List.skip 1 | 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
rawText ") &bull; "
| None -> ()
sprintf "Prayed %s times &bull; Open %s days" prayed daysOpen |> rawText
]
p [ _class "card-text" ] [ str lastText ]
]
log
|> List.map (fun it -> li [ _class "list-group-item" ] [
p [ _class "m-0" ] [
str it.status
rawText "&nbsp; "
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"
article [ _class "container" ] [
h2 [ _class "pb-3" ] [ (match isNew with true -> "Add" | false -> "Edit") |> strf "%s Prayer Request" ]
form [
_hxBoost
_hxTarget "#top"
_hxPushUrl
"/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 []
match isNew with
| true -> ()
| false ->
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 &nbsp; " ]
em [ _class "text-muted" ] [ rawText "After prayer, request reappears&hellip;" ]
]
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.recurType 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.recurType with Immediate -> () | _ -> _checked
]
label [ _for "rO" ] [ rawText "Every&hellip;" ]
]
div [ _class "form-floating mx-2"] [
input [
_type "number"
_class "form-control"
_id "recurCount"
_name "recurCount"
_placeholder "0"
_value (string req.recurCount)
_style "width:6rem;"
_required
match req.recurType 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.recurType with Immediate -> _disabled | _ -> ()
] [
option [ _value "Hours"; match req.recurType with Hours -> _selected | _ -> () ] [ str "hours" ]
option [ _value "Days"; match req.recurType with Days -> _selected | _ -> () ] [ str "days" ]
option [ _value "Weeks"; match req.recurType 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 notes =
let toItem (note : Note) =
p [] [ small [ _class "text-muted" ] [ relativeDate note.asOf now ]; 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
]

View File

@@ -1,12 +0,0 @@
{
"ConnectionStrings": {
"db": "Filename=./mpj.db"
},
"Kestrel": {
"EndPoints": {
"Http": {
"Url": "http://localhost:3000"
}
}
}
}

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

27
src/composer.json Normal file
View File

@@ -0,0 +1,27 @@
{
"name": "bit-badger/my-prayer-journal",
"minimum-stability": "beta",
"require": {
"php": ">=8.2",
"ext-pdo": "*",
"ext-sqlite3": "*",
"bit-badger/pdo-document": "^1",
"guzzlehttp/guzzle": "^7.8",
"guzzlehttp/psr7": "^2.6",
"http-interop/http-factory-guzzle": "^1.2",
"auth0/auth0-php": "^8.11",
"vlucas/phpdotenv": "^5.6"
},
"autoload": {
"psr-4": {
"MyPrayerJournal\\": "lib/",
"MyPrayerJournal\\Domain\\": "lib/Domain",
"MyPrayerJournal\\UI\\": "lib/UI"
}
},
"config": {
"allow-plugins": {
"php-http/discovery": true
}
}
}

2347
src/composer.lock generated Normal file

File diff suppressed because it is too large Load Diff

56
src/convert-from-v3.php Normal file
View File

@@ -0,0 +1,56 @@
<?php declare(strict_types=1);
use BitBadger\PDODocument\{AutoId, Configuration, Custom, Definition, Document, Mode};
use BitBadger\PDODocument\Mapper\ArrayMapper;
use MyPrayerJournal\Domain\{History, Note, Recurrence, RecurrencePeriod, Request, RequestAction};
use MyPrayerJournal\Table;
require 'start.php';
echo 'Retrieving v3 requests...' . PHP_EOL;
Configuration::resetPDO();
Configuration::$pdoDSN = 'pgsql:host=localhost;user=mpj;password=devpassword;dbname=mpj';
$reqs = Custom::array('SELECT data FROM mpj.request', [], new ArrayMapper());
echo 'Found ' . sizeof($reqs) . ' requests; migrating to v4...' . PHP_EOL;
Configuration::resetPDO();
Configuration::$mode = Mode::SQLite;
Configuration::$pdoDSN = 'sqlite:./data/mpj.db';
Configuration::$autoId = AutoId::RandomString;
Configuration::$idStringLength = 12;
Definition::ensureTable(Table::REQUEST);
/** Convert dates to the same format */
function convertDate(string $date): string
{
return (new DateTimeImmutable($date))->format('c');
}
foreach ($reqs as $reqJson) {
$req = json_decode($reqJson['data']);
$recurParts = explode(' ', $req->recurrence);
$recurPeriod = RecurrencePeriod::from(end($recurParts));
$recur = match ($recurPeriod) {
RecurrencePeriod::Immediate => new Recurrence(RecurrencePeriod::Immediate),
default => new Recurrence($recurPeriod, (int)$recurParts[0])
};
Document::insert(Table::REQUEST, new Request(
enteredOn: convertDate($req->enteredOn),
userId: $req->userId,
snoozedUntil: property_exists($req, 'snoozedUntil') ? convertDate($req->snoozedUntil) : null,
showAfter: property_exists($req, 'showAfter') ? convertDate($req->showAfter) : null,
recurrence: $recur,
history: array_map(fn(stdClass $hist) =>
new History(
asOf: convertDate($hist->asOf),
action: RequestAction::from($hist->status),
text: property_exists($hist, 'text') ? $hist->text : null),
$req->history),
notes: array_map(fn(stdClass $note) =>
new Note(convertDate($note->asOf), $note->notes), $req->notes ?? [])));
}
echo PHP_EOL . 'done' . PHP_EOL;

88
src/lib/Auth.php Normal file
View File

@@ -0,0 +1,88 @@
<?php declare(strict_types=1);
namespace MyPrayerJournal;
use Auth0\SDK\Auth0;
use Auth0\SDK\Exception\ConfigurationException;
/**
* myPrayerJournal-specific authorization functions
*/
class Auth
{
/** @var Auth0|null The Auth0 client to use for requests (initialized on first use) */
private static ?Auth0 $auth0 = null;
/**
* Get the current Auth0 client
*
* @return Auth0 The current Auth0 client
*/
public static function client(): Auth0
{
if (is_null(self::$auth0)) {
self::$auth0 = new Auth0([
'domain' => $_ENV['AUTH0_DOMAIN'],
'clientId' => $_ENV['AUTH0_CLIENT_ID'],
'clientSecret' => $_ENV['AUTH0_CLIENT_SECRET'],
'cookieSecret' => $_ENV['AUTH0_COOKIE_SECRET']
]);
}
return self::$auth0;
}
/**
* Get the logged on user information
*
* @return array|null The user information (null if no user is logged on)
*/
public static function user(): ?array
{
return self::client()->getUser();
}
/**
* Initiate a log on with Auth0
*
* @throws ConfigurationException If the Auth0 client is not configured correctly
*/
public static function logOn(): never
{
$params = match (true) {
$_SERVER['PHP_SELF'] <> '/user/log-on.php' => ['redirectUri' => $_SERVER['PHP_SELF']],
default => []
};
self::client()->clear();
header('Location: ' . self::client()->login($_ENV['AUTH0_BASE_URL'] . '/user/log-on/success', $params));
exit;
}
/**
* Log off from this application and Auth0
*
* @throws ConfigurationException If the Auth0 client is not configured correctly
*/
public static function logOff(): never
{
session_destroy();
header('Location: ' . self::client()->logout($_ENV['AUTH0_BASE_URL']));
exit;
}
/**
* Require a user be logged on
*
* @param bool $redirect Whether to redirect to log on if there is not a user logged on
* @return void If it returns, there is a user logged on; if not, we will be redirected to log on
* @throws ConfigurationException If the Auth0 client is not configured correctly
*/
public static function requireUser(bool $redirect = true): void
{
if (is_null(self::user())) {
if ($redirect) self::logOn();
http_response_code(403);
die('Not Authorized');
}
}
}

View File

@@ -0,0 +1,25 @@
<?php declare(strict_types=1);
namespace MyPrayerJournal\Domain;
use JsonSerializable;
/**
* A record of an action taken on a request
*/
class History implements JsonSerializable
{
/**
* @param string $asOf The date/time this entry was made
* @param RequestAction $action The action taken for this history entry
* @param string|null $text The text for this history entry (optional)
*/
public function __construct(public string $asOf, public RequestAction $action, public ?string $text = null) { }
public function jsonSerialize(): mixed
{
$values = ['asOf' => $this->asOf, 'action' => $this->action->value];
if (isset($this->text)) $values['text'] = $this->text;
return $values;
}
}

30
src/lib/Domain/Note.php Normal file
View File

@@ -0,0 +1,30 @@
<?php declare(strict_types=1);
namespace MyPrayerJournal\Domain;
use BitBadger\PDODocument\DocumentException;
/**
* A note entered on a prayer request
*/
class Note
{
/**
* @param string $asOf The date/time this note was recorded
* @param string $text The text of the note
*/
public function __construct(public string $asOf, public string $text) { }
/**
* Retrieve notes for a given request
*
* @param string $id The ID of the request for which notes should be retrieved
* @return array|Note[] The notes for the request, or an empty array if the request was not found
* @throws DocumentException If any is encountered
*/
public static function byRequestId(string $id): array
{
$req = Request::byId($id);
return $req->isDefined() ? $req->get()->notes : [];
}
}

View File

@@ -0,0 +1,41 @@
<?php declare(strict_types=1);
namespace MyPrayerJournal\Domain;
use DateInterval;
use JsonSerializable;
/**
* The recurrence for a prayer request
*/
class Recurrence implements JsonSerializable
{
/**
* @param RecurrencePeriod $period The recurrence period
* @param int|null $interval How many of the periods will pass before the request is visible again
*/
public function __construct(public RecurrencePeriod $period, public ?int $interval = null) { }
/**
* Get the date/time interval for this recurrence
*
* @return DateInterval The interval matching the recurrence
*/
public function interval(): DateInterval
{
$period = match ($this->period) {
RecurrencePeriod::Immediate => 'T0S',
RecurrencePeriod::Hours => "T{$this->interval}H",
RecurrencePeriod::Days => "{$this->interval}D",
RecurrencePeriod::Weeks => ($this->interval * 7) . 'D'
};
return new DateInterval("P$period");
}
public function jsonSerialize(): mixed
{
$values = ['period' => $this->period->value];
if (isset($this->interval)) $values['interval'] = $this->interval;
return $values;
}
}

View File

@@ -0,0 +1,21 @@
<?php declare(strict_types=1);
namespace MyPrayerJournal\Domain;
/**
* The type of recurrence a request can have
*/
enum RecurrencePeriod: string
{
/** Requests, once prayed, are available again immediately */
case Immediate = 'Immediate';
/** Requests, once prayed, appear again in a number of hours */
case Hours = 'Hours';
/** Requests, once prayed, appear again in a number of days */
case Days = 'Days';
/** Requests, once prayed, appear again in a number of weeks */
case Weeks = 'Weeks';
}

203
src/lib/Domain/Request.php Normal file
View File

@@ -0,0 +1,203 @@
<?php declare(strict_types=1);
namespace MyPrayerJournal\Domain;
use BitBadger\PDODocument\{Custom, DocumentException, DocumentList, Find};
use BitBadger\PDODocument\Mapper\DocumentMapper;
use DateTimeImmutable;
use Exception;
use JsonSerializable;
use MyPrayerJournal\Table;
use PhpOption\{None, Option};
/**
* A prayer request
*/
class Request implements JsonSerializable
{
/**
* @param string $id The ID for the request
* @param string $enteredOn The date/time this request was originally entered
* @param string $userId The ID of the user to whom this request belongs
* @param string|null $snoozedUntil The date/time the snooze expires for this request (null = not snoozed)
* @param string|null $showAfter The date/time the current recurrence period is over (null = immediate)
* @param Recurrence $recurrence The recurrence for this request
* @param History[] $history The history of this request
* @param Note[] $notes Notes regarding this request
* @throws Exception If the ID generation fails
*/
public function __construct(public string $id = '', public string $enteredOn = '', public string $userId = '',
public ?string $snoozedUntil = null, public ?string $showAfter = null,
public Recurrence $recurrence = new Recurrence(RecurrencePeriod::Immediate),
public array $history = [], public array $notes = []) { }
/**
* Get the current text for this request
*
* @return string The most recent text for the request
*/
public function currentText(): string
{
foreach ($this->history as $hist) if (isset($hist->text)) return $hist->text;
return '';
}
/**
* Get the date/time this request was last marked as prayed
*
* @return string|null The date/time this request was last marked as prayed
*/
public function lastPrayed(): ?string
{
foreach ($this->history as $hist) if ($hist->action == RequestAction::Prayed) return $hist->asOf;
return null;
}
/**
* Has this request been answered?
*
* @return bool True if the request is answered, false if not
*/
public function isAnswered(): bool
{
return $this->history[0]->action == RequestAction::Answered;
}
/**
* Is this request currently snoozed?
*
* @return bool True if the request is snoozed, false if not
* @throws Exception If the snoozed until date/time is not valid
*/
public function isSnoozed(): bool
{
return isset($this->snoozedUntil) && new DateTimeImmutable($this->snoozedUntil) > new DateTimeImmutable('now');
}
/**
* Is this request currently not shown due to recurrence?
*
* @return bool True if the request is pending, false if not
* @throws Exception If the snoozed or show-after date/times are not valid
*/
public function isPending(): bool
{
return !$this->isSnoozed()
&& isset($this->showAfter)
&& new DateTimeImmutable($this->showAfter) > new DateTimeImmutable('now');
}
public function jsonSerialize(): mixed
{
$values = [
'id' => $this->id,
'enteredOn' => $this->enteredOn,
'userId' => $this->userId,
'recurrence' => $this->recurrence,
'history' => $this->history,
'notes' => $this->notes
];
if (isset($this->snoozedUntil)) $values['snoozedUntil'] = $this->snoozedUntil;
if (isset($this->showAfter)) $values['showAfter'] = $this->showAfter;
return $values;
}
/**
* Find a request by its ID
*
* @param string $id The ID of the request
* @return Option<Request> The request (if it is found and belongs to the current user)
* @throws DocumentException If any is encountered
*/
public static function byId(string $id): Option
{
$req = Find::byId(Table::REQUEST, $id, self::class);
return ($req->getOrElse(new Request('x'))->userId == $_SESSION['user_id']) ? $req : None::create();
}
/**
* Get the user's active journal requests
*
* @return DocumentList<Request> The requests for the user's journal
* @throws DocumentException If any is encountered
*/
public static function forJournal(): DocumentList
{
$table = Table::REQUEST;
return Custom::list(<<<SQL
SELECT data, (
SELECT h.value->>'asOf' as_of
FROM $table i LEFT JOIN json_each(i.data, '$.history') h
WHERE r.data->>'id' = i.data->>'id' AND h.value->>'action' = 'Prayed'
LIMIT 1) last_prayed
FROM $table r
WHERE data->>'userId' = :userId
AND data->>'$.history[0].action' <> 'Answered'
AND (data->>'snoozedUntil' IS NULL OR data->>'snoozedUntil' < datetime('now'))
AND (data->>'showAfter' IS NULL OR data->>'showAfter' < datetime('now'))
ORDER BY coalesce(last_prayed, data->>'snoozedUntil', data->>'showAfter', data->>'$.history[0].asOf')
SQL, [':userId' => $_SESSION['user_id']], new DocumentMapper(self::class));
}
/**
* Get either the user's active or answered requests
*
* @param bool $active True to retrieve active requests, false to retrieve answered requests
* @param bool $snoozed True to retrieve only snoozed requests
* @return DocumentList<Request> The requests matching the criteria
* @throws DocumentException If any is encountered
*/
private static function forUser(bool $active = true, bool $snoozed = false): DocumentList
{
$table = Table::REQUEST;
$op = $active ? '<>' : '=';
$extra = $snoozed ? "AND datetime(data->>'snoozedUntil') > datetime('now')" : '';
$order = $active
? "coalesce(data->>'snoozedUntil', data->>'showAfter', last_prayed, data->>'$.history[0].asOf')"
: "data->>'$.history[0].asOf' DESC";
return Custom::list(<<<SQL
SELECT data, (
SELECT h.value->>'asOf' as_of
FROM $table i LEFT JOIN json_each(i.data, '$.history') h
WHERE r.data->>'id' = i.data->>'id' AND h.value->>'action' = 'Prayed'
LIMIT 1) last_prayed
FROM $table r
WHERE data->>'userId' = :userId
AND data->>'$.history[0].action' $op 'Answered' $extra
ORDER BY $order
SQL, [':userId' => $_SESSION['user_id']], new DocumentMapper(self::class));
}
/**
* Get a list of active requests for a user
*
* @return DocumentList<Request> The user's active requests
* @throws DocumentException If any is encountered
*/
public static function active(): DocumentList
{
return self::forUser();
}
/**
* Get a list of answered requests for a user
*
* @return DocumentList<Request> The user's answered requests
* @throws DocumentException If any is encountered
*/
public static function answered(): DocumentList
{
return self::forUser(false);
}
/**
* Get a list of snoozed requests for a user
*
* @return DocumentList<Request> The user's snoozed requests
* @throws DocumentException If any is encountered
*/
public static function snoozed(): DocumentList
{
return self::forUser(snoozed: true);
}
}

View File

@@ -0,0 +1,21 @@
<?php declare(strict_types=1);
namespace MyPrayerJournal\Domain;
/**
* An action taken on a prayer request
*/
enum RequestAction: string
{
/** The request was created */
case Created = 'Created';
/** The request was marked as having been prayed for */
case Prayed = 'Prayed';
/** The request was updated */
case Updated = 'Updated';
/** The request was marked as answered */
case Answered = 'Answered';
}

12
src/lib/Table.php Normal file
View File

@@ -0,0 +1,12 @@
<?php declare(strict_types=1);
namespace MyPrayerJournal;
/**
* Constants for table names
*/
class Table
{
/** @var string The prayer request table used by myPrayerJournal */
const REQUEST = 'request';
}

175
src/lib/UI/Component.php Normal file
View File

@@ -0,0 +1,175 @@
<?php declare(strict_types=1);
namespace MyPrayerJournal\UI;
use BitBadger\PDODocument\{DocumentException, DocumentList};
use DateTimeImmutable;
use DateTimeZone;
use Exception;
use MyPrayerJournal\Domain\Request;
/**
* User interface building blocks
*/
class Component
{
/**
* Generate a material icon
*
* @param string $name The name of the material icon
* @return string The material icon wrapped in a `span` tag
*/
public static function icon(string $name): string {
return "<span class=material-icons>$name</span>";
}
/**
* Render the journal items for the current user
*
* @throws DocumentException If any is encountered
*/
public static function journal(): void
{
Layout::bareHead();
$reqs = Request::forJournal();
if ($reqs->hasItems()) { ?>
<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"><?php
$spacer = '<span>&nbsp;</span>';
foreach ($reqs->items() as /** @var Request $req */ $req) { ?>
<div class=col>
<div class="card h-100">
<div class="card-header p-0 d-flex" role=toolbar>
<?=self::pageLink("/request/edit?id=$req->id", self::icon('edit'),
['class' => 'btn btn-secondary', 'title' => 'Edit Request'])?>
<?=$spacer?>
<button type=button class="btn btn-secondary" title="Add Notes" data-bs-toggle=modal
data-bs-target=#notesModal hx-get="/components/request/add-note?id=<?=$req->id?>"
hx-target=#notesBody hx-swap=innerHTML><?=self::icon('comment');?></button>
<?=$spacer?>
<button type=button class="btn btn-secondary" title="Snooze Request" data-bs-toggle=modal
data-bs-target=#snoozeModal hx-get="/components/request/snooze?id=<?=$req->id?>"
hx-target=#snoozeBody hx-swap=innerHTML><?=self::icon('schedule');?></button>
<div class=flex-grow-1></div>
<button type=button class="btn btn-success w-25" hx-patch="/request/prayed?id=<?=$req->id?>"
title="Mark as Prayed"><?=self::icon('done');?></button>
</div>
<div class=card-body>
<p class=request-text><?=htmlentities($req->currentText());?>
</div>
<div class="card-footer text-end text-muted px-1 py-0">
<em><?php
$lastPrayed = $req->lastPrayed();
echo 'last ' . (is_null($lastPrayed) ? 'activity': 'prayed') . ' '
. self::relativeDate($lastPrayed ?? $req->history[0]->asOf); ?>
</em>
</div>
</div>
</div><?php
} ?>
</section><?php
} else {
Component::noResults('No Active Requests', '/request/edit?id=new', 'Add a Request', <<<'TEXT'
You have no requests to be shown; see the &ldquo;Active&rdquo; link above for snoozed or deferred
requests, and the &ldquo;Answered&rdquo; link for answered requests
TEXT);
}
Layout::bareFoot();
}
/**
* Create a card when there are no results found
*/
public static function noResults(string $heading, string $link, string $buttonText, string $text): void
{ ?>
<div class=card>
<h5 class=card-header><?=$heading?></h5>
<div class="card-body text-center">
<p class=card-text><?=$text?></p>
<?=self::pageLink($link, $buttonText, ['class' => 'btn btn-primary'])?>
</div>
</div><?php
}
/**
* Create a link to a page within myPrayerJournal
*
* @param string $href The URL for the link
* @param string $text The text for the link
* @param array $attrs Any additional attributes that should be placed on the `a` tag
*/
public static function pageLink(string $href, string $text, array $attrs = []): string
{
$extraAttrs = array_reduce(array_keys($attrs),
fn($acc, $key) => $acc . sprintf(' %s="%s"', $key, $attrs[$key]), '');
return sprintf('<a href="%s" hx-get="%s" hx-target=#top hx-swap=innerHTML hx-push-url=true%s>%s</a>', $href,
$href, $extraAttrs, $text);
}
/**
* Create a relative date with a tooltip with the actual date/time
*
* @return string The HTML for the relative date
* @throws Exception If the date/time cannot be parsed
*/
public static function relativeDate(string $date): string
{
$parsed = new DateTimeImmutable($date);
$inZone = $parsed->setTimezone(new DateTimeZone($_REQUEST['time_zone']));
return sprintf('<span title="%s">%s</span>', date_format($inZone, 'l, F j, Y \a\t g:ia T'),
RelativeDate::between('now', $parsed));
}
/**
* Render a request list item
*
* @param Request $req The request on which the list items should be based
* @throws Exception If date/time values cannot be parsed
*/
public static function requestItem(Request $req): void
{
$btnClass = "btn btn-light mx-2";
$restoreBtn = fn(string $id, string $link, string $title) => sprintf(
'<button class="%s" hx-patch="/request/%s?id=%s" title="%s" hx-target=#req-%s hx-swap=outerHTML>%s</button>',
$btnClass, $link, $id, htmlspecialchars($title), $id, self::icon('restore')); ?>
<div class="list-group-item px-0 d-flex flex-row align-items-start" id=req-<?=$req->id?>><?php
echo self::pageLink("/request/full?id=$req->id", self::icon('description'),
['class' => $btnClass, 'title' => 'View Full Request']);
if (!$req->isAnswered()) {
echo self::pageLink("/request/edit?id=$req->id", self::icon('edit'),
['class' => $btnClass, 'title' => 'Edit Request']);
}
if ($req->isSnoozed()) {
echo $restoreBtn($req->id, 'cancel-snooze', 'Cancel Snooze');
} elseif ($req->isPending()) {
echo $restoreBtn($req->id, 'show', 'Show Now');
}
echo '<p class="request-text mb-0">' . $req->currentText();
if ($req->isSnoozed() || $req->isPending() || $req->isAnswered()) { ?>
<br>
<small class=text-muted><em><?php
if ($req->isSnoozed()) {
echo 'Snooze expires ' . self::relativeDate($req->snoozedUntil);
} elseif ($req->isPending()) {
echo 'Request appears next ' . self::relativeDate($req->showAfter);
} else {
echo 'Answered ' . self::relativeDate($req->history[0]->asOf);
} ?>
</em></small><?php
} ?>
</div><?php
}
/**
* Render the given list of requests
*
* @param DocumentList<Request> $reqs The list of requests to render
* @throws Exception If date/time instances are not valid
*/
public static function requestList(DocumentList $reqs): void
{
echo '<div class=list-group>';
foreach ($reqs->items() as $req) self::requestItem($req);
echo '</div>';
}
}

180
src/lib/UI/Layout.php Normal file
View File

@@ -0,0 +1,180 @@
<?php declare(strict_types=1);
namespace MyPrayerJournal\UI;
use BitBadger\PDODocument\Custom;
use BitBadger\PDODocument\Mapper\ExistsMapper;
use MyPrayerJournal\Table;
class Layout
{
/**
* Generate the heading for a bare result
*/
public static function bareHead(): void
{
echo '<!DOCTYPE html><html lang=en><head><title></title></head><body>';
}
/**
* Generate the end of a bare result
*/
public static function bareFoot(): void
{
echo '</body></html>';
}
/**
* Is this an htmx request?
*
* @return bool True if this is an htmx request, false if not
*/
private static function isHtmx(): bool
{
return key_exists('HTTP_HX_REQUEST', $_SERVER) && !key_exists('HTTP_HX_HISTORY_RESTORE_REQUEST', $_SERVER);
}
/**
* Create the `DOCTYPE` declaration, `html`, and `head` tags for the page
*
* @param string $title The title of the page
*/
public static function htmlHead(string $title): void
{
if (self::isHtmx()) {
echo "<!DOCTYPE html><html lang=en><head lang=en><title>$title &#xab; myPrayerJournal</title></head>";
} else {
echo <<<HEAD
<!DOCTYPE html>
<html lang=en>
<head>
<meta name=viewport content="width=device-width, initial-scale=1">
<meta name=description content="Online prayer journal - free w/Google or Microsoft account">
<meta name=htmx-config content='{"historyCacheSize":0}'>
<title>$title &#xab; myPrayerJournal</title>
<link href=https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css rel=stylesheet
integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN"
crossorigin=anonymous>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel=stylesheet>
<link href=/style/style.css rel=stylesheet>
</head>
HEAD;
}
}
private static function navLink(string $url, string $text): void
{
$classAttr = match (true) {
str_starts_with($_SERVER['PHP_SELF'], $url) => ['class' => 'is-active-route'],
default => []
};
echo '<li class=nav-item>' . Component::pageLink($url, $text, $classAttr);
}
/**
* The default navigation bar, which will load the items on page load, and whenever a refresh event occurs
*/
public static function navBar(): void
{
$table = Table::REQUEST;
$hasSnoozed = key_exists('user_id', $_SESSION)
? Custom::scalar(<<<SQL
SELECT EXISTS (
SELECT 1 FROM $table
WHERE data->>'userId' = :userId AND datetime(data->>'snoozedUntil') > datetime('now'))
SQL, [':userId' => $_SESSION['user_id']], new ExistsMapper())
: false; ?>
<nav class="navbar navbar-dark" role="navigation">
<div class=container-fluid>
<?=Component::pageLink('/',
'<span class=m>my</span><span class=p>Prayer</span><span class=j>Journal</span>',
['class' => 'navbar-brand'])?>
<ul class="navbar-nav me-auto d-flex flex-row"><?php
if (key_exists('user_id', $_SESSION)) {
self::navLink('/journal', 'Journal');
self::navLink('/requests/active', 'Active');
if ($hasSnoozed) self::navLink('/requests/snoozed', 'Snoozed');
self::navLink('/requests/answered', 'Answered'); ?>
<li class=nav-item><a href=/user/log-off>Log Off</a><?php
} else { ?>
<li class=nav-item><a href=/user/log-on>Log On</a><?php
}
self::navLink('/docs', 'Docs'); ?>
</ul>
</div>
</nav><?php
}
/**
* Drop .0 or .0.0 from the end of the version to format it for display
*
* @return string The version of the application for user display
*/
private static function displayVersion(): string {
[$major, $minor, $rev] = explode('.', MPJ_VERSION);
$minor = $minor == '0' ? '' : ".$minor";
$rev = match (true) {
$rev == '0' => '',
str_starts_with($rev, '0-') => substr($rev, 1),
default => ".$rev"
};
return "v$major$minor$rev";
}
/**
* Create the footer
*/
public static function htmlFoot(): void
{ ?>
<footer class=container-fluid>
<p class="text-muted text-end">
myPrayerJournal <?=self::displayVersion();?><br>
<em><small>
<?=Component::pageLink('/legal/privacy-policy', 'Privacy Policy')?> &bull;
<?=Component::pageLink('/legal/terms-of-service', 'Terms of Service')?> &bull;
<a href=https://git.bitbadger.solutions/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>
<script src=https://unpkg.com/htmx.org@2.0.0 crossorigin=anonymous
integrity="sha384-wS5l5IKJBvK6sPTKa2WZ1js3d947pvWXbPJ1OmWfEuxLgeHcEbjUUA5i9V5ZkpCw"></script>
<script>if (!htmx) document.write('<script src=\"/script/htmx.min.js\"><\/script>')</script>
<script async src=https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js
integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL"
crossorigin=anonymous></script>
<script>
setTimeout(function () {
if (!bootstrap) document.write('<script src=\"/script/bootstrap.bundle.min.js\"><\/script>')
}, 2000)
</script>
<script src=/script/mpj.js></script>
</footer><?php
}
/**
* Generate the heading for a full or partial page result
*
* @param string $title The title of the page
*/
public static function pageHead(string $title): void
{
self::htmlHead($title);
echo '<body>';
if (!self::isHtmx()) echo '<section id=top aria-label="Top navigation">';
self::navBar();
echo '<main role=main>';
}
/**
* Generate the end of the page for a full or partial page result
*/
public static function pageFoot(): void
{
echo '</main>';
if (!self::isHtmx()) {
echo '</section>';
self::htmlFoot();
}
echo '</body></html>';
}
}

View File

@@ -0,0 +1,66 @@
<?php declare(strict_types=1);
namespace MyPrayerJournal\UI;
use DateTimeImmutable;
use Exception;
/**
* A type of relative date, along with the formatting strings
*/
enum RelativeDate: string
{
case LessThanXMinutes = 'less than a minute|less than %d minutes';
case XMinutes = 'a minute|%d minutes';
case AboutXHours = 'about an hour|about %d hours';
case XHours = 'an hour|%d hours';
case XDays = 'a day|%d days';
case AboutXWeeks = 'about a week|about %d weeks';
case XWeeks = 'a week|%d weeks';
case AboutXMonths = 'about a month|about %d months';
case XMonths = 'a month|%d months';
case AboutXYears = 'about a year|about %d years';
case XYears = 'a year|%d years';
case OverXYears = 'over a year|over %d years';
case AlmostXYears = 'almost a year|almost %d years';
// Many thanks to date-fns (https://date-fns.org) for this logic
/**
* Format the distance between two dates
*
* @param string|DateTimeImmutable $from The starting date/time
* @param string|DateTimeImmutable $to The ending date/time
* @return string The distance between two dates
* @throws Exception If date/time objects cannot be created
*/
public static function between(string|DateTimeImmutable $from, string|DateTimeImmutable $to): string
{
$aDay = 1_440.0;
$almost2Days = 2_520.0;
$aMonth = 43_200.0;
$twoMonths = 86_400.0;
$dtFrom = is_string($from) ? new DateTimeImmutable($from) : $from;
$dtTo = is_string($to) ? new DateTimeImmutable($to) : $to;
$minutes = abs($dtFrom->getTimestamp() - $dtTo->getTimestamp()) / 60;
$months = round($minutes / $aMonth);
$years = round($months / 12);
[$type, $number] = match (true) {
$minutes < 1.0 => [RelativeDate::LessThanXMinutes, 1],
$minutes < 45.0 => [RelativeDate::XMinutes, round($minutes)],
$minutes < 90.0 => [RelativeDate::AboutXHours, 1],
$minutes < $aDay => [RelativeDate::AboutXHours, round($minutes / 60)],
$minutes < $almost2Days => [RelativeDate::XDays, 1],
$minutes < $aMonth => [RelativeDate::XDays, round($minutes / $aDay)],
$minutes < $twoMonths => [RelativeDate::AboutXMonths, round($minutes / $aMonth)],
$months < 12 => [RelativeDate::XMonths, round($minutes / $aMonth)],
$months % 12 < 3 => [RelativeDate::AboutXYears, $years],
$months % 12 < 9 => [RelativeDate::OverXYears, $years],
default => [RelativeDate::AlmostXYears, $years]
};
[$singular, $plural] = explode('|', $type->value);
$value = $number == 1 ? $singular : sprintf($plural, $number);
return $dtFrom > $dtTo ? "$value ago" : "in $value";
}
}

View File

@@ -0,0 +1,11 @@
<?php declare(strict_types=1);
use MyPrayerJournal\Auth;
use MyPrayerJournal\UI\Component;
if ($_SERVER['REQUEST_METHOD'] <> 'GET') not_found();
require '../../start.php';
Auth::requireUser(false);
Component::journal();

View File

@@ -0,0 +1,24 @@
<?php declare(strict_types=1);
use MyPrayerJournal\UI\Layout;
require '../../../start.php';
$req = validate_request($_GET['id'], ['GET'], false);
Layout::bareHead(); ?>
<form hx-post="/request/note?id=<?=$req->id?>">
<div class="form-floating pb-3">
<textarea id=notes name=notes class=form-control style="min-height: 8rem;" placeholder=Notes autofocus
required></textarea>
<label for=notes>Notes</label>
</div>
<p class=text-end><button type=submit class="btn btn-primary">Add Notes</button>
</form>
<hr style="margin: .5rem -1rem">
<div id=priorNotes>
<p class="text-center pt-3">
<button type=button class="btn btn-secondary" hx-get="/components/request/notes?id=<?=$req->id?>"
hx-swap=outerHTML hx-target=#priorNotes>Load Prior Notes</button>
</div><?php
Layout::bareFoot();

View File

@@ -0,0 +1,19 @@
<?php declare(strict_types=1);
use MyPrayerJournal\UI\{Component, Layout};
require '../../../start.php';
$req = validate_request($_GET['id'], ['GET'], false);
Layout::bareHead();?>
<p class=text-center><strong>Prior Notes for This Request</strong><?php
if (sizeof($req->notes) > 0) {
foreach ($req->notes as $note) { ?>
<p><small class=text-muted><?=Component::relativeDate($note->asOf)?></small><br>
<?=htmlentities($note->text)?><?php
}
} else { ?>
<p class="text-center text-muted">There are no prior notes for this request<?php
}
Layout::bareFoot();

View File

@@ -0,0 +1,18 @@
<?php declare(strict_types=1);
use MyPrayerJournal\UI\Layout;
require '../../../start.php';
$req = validate_request($_GET['id'], ['GET'], false);
Layout::bareHead(); ?>
<form hx-patch="/request/snooze?id=<?=$req->id?>" hx-target=#journalItems hx-swap=outerHTML>
<div class="form-floating pb-3">
<input type=date id=until name=until class=form-control
min="<?=(new DateTimeImmutable('now'))->format('Y-m-d')?>" required>
<label for=until>Until</label>
</div>
<p class="text-end mb-0"><button type=submit class="btn btn-primary">Snooze</button>
</form><?php
Layout::bareFoot();

102
src/public/docs.php Normal file
View File

@@ -0,0 +1,102 @@
<?php declare(strict_types=1);
use MyPrayerJournal\UI\Layout;
require '../start.php';
if ($_SERVER['REQUEST_METHOD'] <> 'GET') not_found();
Layout::pageHead('Documentation'); ?>
<article class="container mt-3">
<h2 class=mb-3>Documentation</h2>
<h3 class="mb-3 mt-4">About myPrayerJournal</h3>
<p>Journaling has a long history; it helps people remember what happened, and the act of writing helps people think
about what happened and process it. A prayer journal is not a new concept; it helps you keep track of the
requests for which you&rsquo;ve prayed, you can use it to pray over things repeatedly, and you can write the
result when the answer comes <em>(or it was &ldquo;no&rdquo;)</em>.
<p>myPrayerJournal was borne of out of a personal desire
<a href=https://daniel.summershome.org target=_blank rel=noopener>Daniel</a> had to have something that would
help him with his prayer life. When it&rsquo;s time to pray, it&rsquo;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&rsquo;ve prayed for a request, or running out of room to
write another update on one.
<h3 class="mb-3 mt-4">Signing Up</h3>
<p>myPrayerJournal uses login services using Google or Microsoft accounts. The only information the application
stores in its database is your user ID token it receives from these services, so there are no permissions you
should have to accept from these provider other than establishing that you can log on with that account. Because
of this, you&rsquo;ll want to pick the same one each time; the tokens between the two accounts are different,
even if you use the same e-mail address to log on to both.
<h3 class="mb-3 mt-4">Your Prayer Journal</h3>
<p>Your current requests will be presented in columns (usually three, but it could be more or less, depending on the
size of your screen or device). Each request is in its own card, and the buttons at the top of each card apply
to that request. The last line of each request also tells you how long it has been since anything has been done
on that request. Any time you see something like &ldquo;a few minutes ago,&rdquo; you can hover over that to see
the actual date/time the action was taken.
<h3 class="mb-3 mt-4">Adding a Request</h3>
<p>To add a request, click the &ldquo;Add a New Request&rdquo; button at the top of your journal. Then, enter the
text of the request as you see fit; there is no right or wrong way, and you are the only person who will see the
text you enter. When you save the request, it will go to the bottom of the list of requests.
<h3 class="mb-3 mt-4">Setting Request Recurrence</h3>
<p>When you add or update a request, you can choose whether requests go to the bottom of the journal once they have
been marked &ldquo;Prayed&rdquo; or whether they will reappear after a delay. You can set recurrence in terms of
hours, days, or weeks, but it cannot be longer than 365 days. If you decide you want a request to reappear
sooner, you can skip the current delay; click the &ldquo;Active&rdquo; menu link, find the request in the list
(likely near the bottom), and click the &ldquo;Show Now&rdquo; button.
<h3 class="mb-3 mt-4">Praying for Requests</h3>
<p>The first button for each request has a checkmark icon; clicking this button will mark the request as
&ldquo;Prayed&rdquo; and move it to the bottom of the list (or off, if you&rsquo;ve set a recurrence period for
the request). This allows you, if you&rsquo;re praying through your requests, to start at the top left (with the
request that it&rsquo;s been the longest since you&rsquo;ve prayed) and click the button as you pray; when the
request move below or away, the next-least-recently-prayed request will take the top spot.
<h3 class="mb-3 mt-4">Editing Requests</h3>
<p>The second button for each request has a pencil icon. This allows you to edit the text of the request, pretty
much the same way you entered it; it starts with the current text, and you can add to it, modify it, or
completely replace it. By default, updates will go in with an &ldquo;Updated&rdquo; status; you have the option
to also mark this update as &ldquo;Prayed&rdquo; or &ldquo;Answered&rdquo;. Answered requests will drop off the
journal list.
<h3 class="mb-3 mt-4">Adding Notes</h3>
<p>The third button for each request has an icon that looks like a speech bubble with lines on it; this lets you
record notes about the request. If there is something you want to record that doesn&rsquo;t change the text of
the request, this is the place to do it. For example, you may be praying for a long-term health issue, and that
person tells you that their status is the same; or, you may want to record something God said to you while you
were praying for that request."
<h3 class="mb-3 mt-4">Snoozing Requests</h3>
<p>There may be a time when a request does not need to appear. The fourth button, with the clock icon, allows you to
snooze requests until the day you specify. Additionally, if you have any snoozed requests, a
&ldquo;Snoozed&rdquo; menu item will appear next to the &ldquo;Journal&rdquo; one; this page allows you to see
what requests are snoozed, and return them to your journal by canceling the snooze.
<h3 class="mb-3 mt-4">Viewing a Request and Its History</h3>
<p>myPrayerJournal tracks all actions related to a request; from the &ldquo;Active&rdquo; and &ldquo;Answered&rdquo;
menu links (and &ldquo;Snoozed&rdquo;, if it&rsquo;s showing), there is a &ldquo;View Full Request&rdquo;
button. That page will show the current text of the request; how many times it has been marked as prayed; how
long it has been an active request; and a log of all updates, prayers, and notes you have recorded. That log is
listed from most recent to least recent; if you want to read it chronologically, press the &ldquo;End&rdquo; key
on your keyboard and read it from the bottom up.
<p>The &ldquo;Active&rdquo; link will show all requests that have not yet been marked answered, including snoozed
and recurring requests. If requests are snoozed, or in a recurrence period off the journal, there will be a
button where you can return the request to the list (either &ldquo;Cancel Snooze&rdquo; or &ldquo;Show
Now&rdquo;). The &ldquo;Answered&rdquo; link shows all requests that have been marked answered. The
&ldquo;Snoozed&rdquo; link only shows snoozed requests.
<h3 id=notes class="mb-3 mt-4">Final Notes</h3>
<ul>
<li>If you encounter errors, please
<a href=https://git.bitbadger.solutions/bit-badger/myPrayerJournal/issues target=_blank rel=noopener>file an
issue</a> (or <a href="mailto:daniel@bitbadger.solutions?subject=myPrayerJournal+Issue">e-mail Daniel</a> if
you do not have an account on that server) with as much detail as possible. You can also provide
suggestions, or browse the list of currently open issues.
<li>Prayer requests and their history are securely backed up nightly along with other Bit Badger Solutions data.
<li>Prayer changes things - most of all, the one doing the praying. I pray that this tool enables you to deepen
and strengthen your prayer life.
</ul>
</article><?php
Layout::pageFoot();

21
src/public/index.php Normal file
View File

@@ -0,0 +1,21 @@
<?php declare(strict_types=1);
use MyPrayerJournal\UI\Component;use MyPrayerJournal\UI\Layout;
require '../start.php';
if ($_SERVER['REQUEST_METHOD'] <> 'GET') not_found();
Layout::pageHead('Welcome'); ?>
<article class="container mt-3">
<p>&nbsp;
<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 also allows
individuals to review their answered prayers.
<p>This site is open and available for anyone who wants to use it. To get started, simply click the &ldquo;Log
On&rdquo; link above, and log on with either a Microsoft or Google account. You can also learn more about the
site at the &ldquo;Docs&rdquo; link, also above.
<hr>
<p><em>This is an in-progress upgrade from v3 to v4; if you encounter errors, see
<?=Component::pageLink('/docs#notes', 'the documentation')?> on reporting them.</em>
</article><?php
Layout::pageFoot();

51
src/public/journal.php Normal file
View File

@@ -0,0 +1,51 @@
<?php declare(strict_types=1);
use MyPrayerJournal\Auth;
use MyPrayerJournal\UI\{Component, Layout};
require '../start.php';
if ($_SERVER['REQUEST_METHOD'] <> 'GET') not_found();
Auth::requireUser();
$user = Auth::user();
$name = $user['given_name'] ?? 'Your';
Layout::pageHead('Journal'); ?>
<article class="container-fluid mt-3">
<h2 class=pb-3><?=$name?><?=$name == 'Your' ? '' : '&rsquo;s'?> Prayer Journal</h2>
<p class="pb-3 text-center">
<?=Component::pageLink('/request/edit?id=new', Component::icon('add_box') . ' Add a Prayer Request',
['class' => 'btn btn-primary'])?>
<p hx-get=/components/journal-items hx-swap=outerHTML hx-trigger=load hx-target=this>
Loading your prayer journal&hellip;
<div id=notesModal class="modal fade" tabindex=-1 aria-labelledby=nodesModalLabel aria-hidden=true>
<div class="modal-dialog modal-dialog-scrollable">
<div class=modal-content>
<div class=modal-header>
<h5 class=modal-title id=nodesModalLabel>Add Notes to Prayer Request</h5>
<button type=button class=btn-close data-bs-dismiss=modal aria-label=Close></button>
</div>
<div class=modal-body id=notesBody></div>
<div class=modal-footer>
<button type=button id=notesDismiss class="btn btn-secondary" data-bs-dismiss=modal>Close</button>
</div>
</div>
</div>
</div>
<div id=snoozeModal class="modal fade" tabindex=-1 aria-labelledby=snoozeModalLabel aria-hidden=true>
<div class="modal-dialog modal-sm">
<div class=modal-content>
<div class=modal-header>
<h5 class=modal-title id=snoozeModalLabel>Snooze Prayer Request</h5>
<button type=button class=btn-close data-bs-dismiss=modal aria-label=Close></button>
</div>
<div class=modal-body id=snoozeBody></div>
<div class=modal-footer>
<button type=button id=snoozeDismiss class="btn btn-secondary" data-bs-dismiss=modal>Close</button>
</div>
</div>
</div>
</div>
</article><?php
Layout::pageFoot();

View File

@@ -0,0 +1,72 @@
<?php declare(strict_types=1);
use MyPrayerJournal\UI\Layout;
require '../../start.php';
if ($_SERVER['REQUEST_METHOD'] <> 'GET') not_found();
Layout::pageHead('Privacy Policy'); ?>
<article class="container mt-3">
<h2 class=mb-2>Privacy Policy</h2>
<h6 class="text-muted pb-3">as of May 21<sup>st</sup>, 2018</h6>
<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.
<div class=card>
<div class="list-group list-group-flush">
<div class=list-group-item>
<h3>Third Party Services</h3>
<p class=card-text>
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>).
</div>
<div class=list-group-item>
<h3>What We Collect</h3>
<h4>Identifying Data</h4>
<ul>
<li>The only identifying data myPrayerJournal stores is the subscriber (&ldquo;sub&rdquo;) 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 &ldquo;Log Off&rdquo; is
clicked.
</ul>
<h4>User Provided Data</h4>
<ul class=mb-0>
<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.
</ul>
</div>
<div class=list-group-item>
<h3>How Your Data Is Accessed / Secured</h3>
<ul class=mb-0>
<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 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>The data collected and stored is the absolute minimum necessary for the functionality of the
service. There are no plans to &ldquo;monetize&rdquo; 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.
</ul>
</div>
<div class=list-group-item>
<h3>Removing Your Data</h3>
<p class=card-text>
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.
</div>
</div>
</div>
</article><?php
Layout::pageFoot();

View File

@@ -0,0 +1,59 @@
<?php declare(strict_types=1);
use MyPrayerJournal\UI\{Component, Layout};
require '../../start.php';
if ($_SERVER['REQUEST_METHOD'] <> 'GET') not_found();
Layout::pageHead('Terms of Service'); ?>
<article class="container mt-3">
<h2 class=mb-2>Terms of Service</h2>
<h6 class="text-muted pb-3">as of May 21<sup>st</sup>, 2018</h6>
<div class=card>
<div class="list-group list-group-flush">
<div class=list-group-item>
<h3>1. Acceptance of Terms</h3>
<p class=card-text>
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.
</div>
<div class=list-group-item>
<h3>2. Description of Service and Registration</h3>
<p class=card-text>
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
<?=Component::pageLink('/legal/privacy-policy', 'our privacy policy')?> for details on how that
information is accessed and stored.
</div>
<div class=list-group-item>
<h3>3. Third Party Services</h3>
<p class=card-text>
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>).
</div>
<div class=list-group-item>
<h3>4. Liability</h3>
<p class=card-text>
This service is provided &ldquo;as is&rdquo;, 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.
</div>
<div class=list-group-item>
<h3>5. Updates to Terms</h3>
<p class=card-text>
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."
</div>
</div>
</div>
<p class=pt-3>
You may also wish to review our <?=Component::pageLink('/legal/privacy-policy', 'privacy policy')?> to learn how
we handle your data.
</article><?php
Layout::pageFoot();

View File

@@ -0,0 +1,17 @@
<?php declare(strict_types=1);
use BitBadger\PDODocument\RemoveFields;
use MyPrayerJournal\Table;
use MyPrayerJournal\UI\{Component, Layout};
require '../../start.php';
$req = validate_request($_GET['id'], ['PATCH'], false);
RemoveFields::byId(Table::REQUEST, $req->id, ['snoozedUntil']);
$req->snoozedUntil = null;
// TODO: message
Layout::bareHead();
Component::requestItem($req);
Layout::bareFoot();

107
src/public/request/edit.php Normal file
View File

@@ -0,0 +1,107 @@
<?php declare(strict_types=1);
use MyPrayerJournal\Auth;
use MyPrayerJournal\Domain\{RecurrencePeriod, Request, RequestAction};
use MyPrayerJournal\UI\{Component, Layout};
require '../../start.php';
if ($_SERVER['REQUEST_METHOD'] <> 'GET') not_found();
Auth::requireUser();
$isNew = $_GET['id'] == 'new';
$req = match ($isNew) {
true => new Request('new'),
false => Request::byId($_GET['id'])->getOrCall(not_found(...))
};
$cancelLink = match (true) {
str_ends_with($_SERVER['HTTP_REFERER'] ?? '', 'active') => '/requests/active',
str_ends_with($_SERVER['HTTP_REFERER'] ?? '', 'snoozed') => '/requests/snoozed',
default => '/journal'
};
$action = $_GET['id'] == 'new' ? 'Add' : 'Edit';
Layout::pageHead("$action Prayer Request");?>
<article class=container>
<h2 class=pb-3><?=$action?> Prayer Request</h2>
<form <?=$isNew ? 'hx-post' : 'hx-patch'?>=/request/save hx-target=#top hx-push-url=true>
<input type=hidden name=requestId value=<?=$req->id?>>
<input type=hidden name=returnTo value=<?=$cancelLink?>>
<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><?=$req->currentText()?></textarea>
<label for=requestText>Prayer Request</label>
</div><br><?php
if (!$isNew) { ?>
<div class=pb-3>
<label>Also Mark As</label><br>
<div class="form-check form-check-inline">
<input type=radio class=form-check-input id=sU name=status value=<?=RequestAction::Updated->value?>
checked>
<label for=sU>Updated</label>
</div>
<div class="form-check form-check-inline">
<input type=radio class=form-check-input id=sP name=status value=<?=RequestAction::Prayed->value?>>
<label for=sP>Prayed</label>
</div>
<div class="form-check form-check-inline">
<input type=radio class=form-check-input id=sA name=status
value=<?=RequestAction::Answered->value?>>
<label for=sA>Answered</label>
</div>
</div><?php
} ?>
<div class=row">
<div class="col-12 offset-md-2 col-md-8 offset-lg-3 col-lg-6">
<p><strong>Recurrence &nbsp;</strong> <em class=text-muted>After prayer, request reappears&hellip;</em>
<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=<?=RecurrencePeriod::Immediate->value?>
onclick="mpj.edit.toggleRecurrence(event)"<?php
if ($req->recurrence->period == RecurrencePeriod::Immediate) echo ' checked'; ?>>
<label for=rI>Immediately</label>
</div>
<div class="form-check mx-2">
<input type=radio class=form-check-input id=rO name=recurType value=Other
onclick="mpj.edit.toggleRecurrence(event)"<?php
if ($req->recurrence->period <> RecurrencePeriod::Immediate) echo ' checked'; ?>>
<label for=rO>Every&hellip;</label>
</div>
<div class="form-floating mx-2">
<input type=number class=form-control id=recurCount name=recurCount placeholder=0 required
value=<?=$req->recurrence->interval ?? 0?> style="width:6rem;"<?php
if ($req->recurrence->period == RecurrencePeriod::Immediate) echo ' disabled'; ?>>
<label for=recurCount>Count</label>
</div>
<div class="form-floating mx-2">
<select class=form-control id=recurInterval name=recurInterval style="width:6rem;" required<?php
if ($req->recurrence->period == RecurrencePeriod::Immediate) echo ' disabled'; ?>>
<option value=<?=RecurrencePeriod::Hours->value?><?php
if ($req->recurrence->period == RecurrencePeriod::Hours) echo ' selected'; ?>>
hours
</option>
<option value=<?=RecurrencePeriod::Days->value?><?php
if ($req->recurrence->period == RecurrencePeriod::Days) echo ' selected'; ?>>
days
</option>
<option value=<?=RecurrencePeriod::Weeks->value?><?php
if ($req->recurrence->period == RecurrencePeriod::Weeks) echo ' selected'; ?>>
weeks
</option>
</select>
<label for=recurInterval>Interval</label>
</div>
</div>
</div>
</div>
<div class="text-end pt-3">
<button class="btn btn-primary me-2" type=submit><?=Component::icon('save');?> Save</button>
<?=Component::pageLink($cancelLink, Component::icon('arrow_back') . ' Cancel',
['class' => 'btn btn-secondary ms-2'])?>
</div>
</form>
</article><?php
Layout::pageFoot();

View File

@@ -0,0 +1,46 @@
<?php declare(strict_types=1);
use MyPrayerJournal\Domain\{History, Note, RequestAction};
use MyPrayerJournal\UI\{Layout, RelativeDate};
require '../../start.php';
$req = validate_request($_GET['id'], ['GET']);
$answered = $req->isAnswered() ? new DateTimeImmutable($req->history[0]->asOf) : null;
$prayed = sizeof(array_filter($req->history, fn(History $hist) => $hist->action == RequestAction::Prayed));
$daysOpen =
(($answered ?? new DateTimeImmutable('now'))->getTimestamp()
- (new DateTimeImmutable(end($req->history)->asOf))->getTimestamp()) / 86400;
$logs = array_merge(
array_map(fn(Note $note) => [new DateTimeImmutable($note->asOf), 'Notes', $note->text], $req->notes),
array_map(fn(History $hist) => [new DateTimeImmutable($hist->asOf), $hist->action->value, $hist->text ?? ''],
$req->history));
usort($logs, fn($a, $b) => $a[0] > $b[0] ? -1 : 1);
if ($req->isAnswered()) array_shift($logs);
Layout::pageHead('Full Request');?>
<article class="container mt-3">
<div class=card>
<h5 class=card-header>Full Prayer Request</h5>
<div class=card-body>
<h6 class="card-subtitle text-muted mb-2"><?php
if (!is_null($answered)) { ?>
Answered <?=$answered->format('F j, Y')?>
(<?= RelativeDate::between('now', $req->history[0]->asOf);?>) &bull;<?php
} ?>
Prayed <?=number_format($prayed)?> times &bull; Open <?=number_format($daysOpen)?> days
</h6>
<p class=card-text><?=htmlentities($req->currentText())?>
</div>
<ul class="list-group list-group-flush"><?php
foreach ($logs as $log) { ?>
<li class=list-group-item>
<p class=m-0><?=$log[1]?>&nbsp; <small><em><?=$log[0]->format('F j, Y')?></em></small><?php
if ($log[2] <> '') echo '<p class="mt-2 mb-0">' . htmlentities($log[2]);
} ?>
</ul>
</div>
</article><?php
Layout::pageFoot();

View File

@@ -0,0 +1,15 @@
<?php declare(strict_types=1);
use BitBadger\PDODocument\Patch;
use MyPrayerJournal\Domain\Note;
use MyPrayerJournal\Table;
require '../../start.php';
$req = validate_request($_GET['id'], ['POST'], false);
array_unshift($req->notes, new Note((new DateTimeImmutable('now'))->format('c'), $_POST['notes']));
Patch::byId(Table::REQUEST, $req->id, ['notes' => $req->notes]);
hide_modal('notes');
http_response_code(202);

View File

@@ -0,0 +1,21 @@
<?php declare(strict_types=1);
use BitBadger\PDODocument\Patch;
use MyPrayerJournal\Domain\{History, RecurrencePeriod, RequestAction};
use MyPrayerJournal\Table;
use MyPrayerJournal\UI\Component;
require '../../start.php';
$req = validate_request($_GET['id'], ['PATCH'], false);
$now = new DateTimeImmutable('now');
array_unshift($req->history, new History($now->format('c'), RequestAction::Prayed));
$patch = ['history' => $req->history];
if ($req->recurrence->period <> RecurrencePeriod::Immediate) {
$patch['showAfter'] = $now->add($req->recurrence->interval())->format('c');
}
Patch::byId(Table::REQUEST, $req->id, $patch);
Component::journal();

View File

@@ -0,0 +1,46 @@
<?php declare(strict_types=1);
use BitBadger\PDODocument\{Document, Patch, RemoveFields};
use MyPrayerJournal\{Auth, Table};
use MyPrayerJournal\Domain\{History, Recurrence, RecurrencePeriod, Request, RequestAction};
require '../../start.php';
if ($_SERVER['REQUEST_METHOD'] <> 'POST' && $_SERVER['REQUEST_METHOD'] <> 'PATCH') not_found();
Auth::requireUser(false);
$now = new DateTimeImmutable('now');
$recurrence = new Recurrence(RecurrencePeriod::from($_POST['recurType'] ?? $_PATCH['recurType']));
if ($recurrence->period <> RecurrencePeriod::Immediate) {
$recurrence->interval = (int)($_POST['recurCount'] ?? $_PATCH['recurCount']);
}
switch ($_SERVER['REQUEST_METHOD']) {
case 'POST':
Document::insert(Table::REQUEST, new Request(
enteredOn: $now->format('c'),
userId: $_SESSION['user_id'],
recurrence: $recurrence,
history: [new History($now->format('c'), RequestAction::Created, $_POST['requestText'])]));
//Messages.pushSuccess ctx "Added prayer request" "/journal"
see_other('/journal');
case 'PATCH':
$req = Request::byId($_PATCH['requestId'])->getOrCall(not_found(...));
$patch = [];
// update recurrence if changed
if ($recurrence != $req->recurrence) {
$patch['recurrence'] = $recurrence;
if ($recurrence->period == RecurrencePeriod::Immediate) {
RemoveFields::byId(Table::REQUEST, $req->id, ['showAfter']);
}
}
// append history
$upd8Text = trim($_PATCH['requestText']);
$text = $upd8Text == '' || $upd8Text == $req->currentText() ? null : $upd8Text;
array_unshift($req->history, new History($now->format('c'), RequestAction::from($_PATCH['status']), $text));
$patch['history'] = $req->history;
Patch::byId(Table::REQUEST, $req->id, $patch);
//Messages.pushSuccess ctx "Prayer request updated successfully" nextUrl
see_other($_PATCH['returnTo']);
}

View File

@@ -0,0 +1,17 @@
<?php declare(strict_types=1);
use BitBadger\PDODocument\RemoveFields;
use MyPrayerJournal\Table;
use MyPrayerJournal\UI\{Component, Layout};
require '../../start.php';
$req = validate_request($_GET['id'], ['PATCH'], false);
RemoveFields::byId(Table::REQUEST, $req->id, ['showAfter']);
$req->showAfter = null;
// TODO: message
Layout::bareHead();
Component::requestItem($req);
Layout::bareFoot();

View File

@@ -0,0 +1,18 @@
<?php declare(strict_types=1);
use BitBadger\PDODocument\Patch;
use MyPrayerJournal\Table;
use MyPrayerJournal\UI\Component;
require '../../start.php';
$req = validate_request($_GET['id'], ['PATCH'], false);
$until = (new DateTimeImmutable($_PATCH['until'] . 'T00:00:00', new DateTimeZone($_REQUEST['time_zone'])))
->setTimezone(new DateTimeZone('Etc/UTC'));
Patch::byId(Table::REQUEST, $req->id, ['snoozedUntil' => $until->format('c')]);
// TODO: message
hide_modal('snooze');
Component::journal();

View File

@@ -0,0 +1,24 @@
<?php declare(strict_types=1);
use MyPrayerJournal\Auth;
use MyPrayerJournal\Domain\Request;
use MyPrayerJournal\UI\{Component, Layout};
require '../../start.php';
if ($_SERVER['REQUEST_METHOD'] <> 'GET') not_found();
Auth::requireUser();
$reqs = Request::active();
Layout::pageHead('Active Requests'); ?>
<article class="container mt-3">
<h2 class=pb-3>Active Requests</h2><?php
if ($reqs->hasItems()) {
Component::requestList($reqs);
} else {
Component::noResults('No Active Requests', '/journal', 'Return to your journal',
'Your prayer journal has no active requests');
} ?>
</article><?php
Layout::pageFoot();

View File

@@ -0,0 +1,26 @@
<?php declare(strict_types=1);
use MyPrayerJournal\Auth;
use MyPrayerJournal\Domain\Request;
use MyPrayerJournal\UI\{Component, Layout};
require '../../start.php';
if ($_SERVER['REQUEST_METHOD'] <> 'GET') not_found();
Auth::requireUser();
$reqs = Request::answered();
Layout::pageHead('Answered Requests'); ?>
<article class="container mt-3">
<h2 class=pb-3>Answered Requests</h2><?php
if ($reqs->hasItems()) {
Component::requestList($reqs);
} else {
Component::noResults('No Answered Requests', '/journal', 'Return to your journal', <<<'TEXT'
Your prayer journal has no answered requests; once you have marked one as &ldquo;Answered&rdquo;, it will
appear here
TEXT);
} ?>
</article><?php
Layout::pageFoot();

View File

@@ -0,0 +1,24 @@
<?php declare(strict_types=1);
use MyPrayerJournal\Auth;
use MyPrayerJournal\Domain\Request;
use MyPrayerJournal\UI\{Component, Layout};
require '../../start.php';
if ($_SERVER['REQUEST_METHOD'] <> 'GET') not_found();
Auth::requireUser();
$reqs = Request::snoozed();
Layout::pageHead('Snoozed Requests'); ?>
<article class="container mt-3">
<h2 class=pb-3>Snoozed Requests</h2><?php
if ($reqs->hasItems()) {
Component::requestList($reqs);
} else {
Component::noResults('No Snoozed Requests', '/journal', 'Return to your journal',
'Your prayer journal has no snoozed requests');
} ?>
</article><?php
Layout::pageFoot();

File diff suppressed because one or more lines are too long

1
src/public/script/htmx.min.js vendored Normal file

File diff suppressed because one or more lines are too long

View File

@@ -1,7 +1,7 @@
"use strict" "use strict"
/** myPrayerJournal script */ /** myPrayerJournal script */
const mpj = { this.mpj = {
/** /**
* Show a message via toast * Show a message via toast
* @param {string} message The message to show * @param {string} message The message to show
@@ -66,6 +66,19 @@ const mpj = {
const isDisabled = target.value === "Immediate" const isDisabled = target.value === "Immediate"
;["recurCount", "recurInterval"].forEach(it => document.getElementById(it).disabled = isDisabled) ;["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 (_) { }
} }
} }
@@ -80,3 +93,12 @@ htmx.on("htmx:afterOnLoad", function (evt) {
document.getElementById(evt.detail.xhr.getResponseHeader("x-hide-modal") + "Dismiss").click() 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()

View File

@@ -0,0 +1,8 @@
<?php declare(strict_types=1);
use MyPrayerJournal\Auth;
require '../../start.php';
if ($_SERVER['REQUEST_METHOD'] <> 'GET') not_found();
Auth::logOff();

View File

@@ -0,0 +1,8 @@
<?php declare(strict_types=1);
use MyPrayerJournal\Auth;
require '../../start.php';
if ($_SERVER['REQUEST_METHOD'] <> 'GET') not_found();
Auth::logOn();

View File

@@ -0,0 +1,11 @@
<?php declare(strict_types=1);
use MyPrayerJournal\Auth;
require '../../../start.php';
Auth::client()->exchange($_ENV['AUTH0_BASE_URL'] . '/user/log-on/success');
// TODO: get the possible redirect URL
header('Location: /journal');
exit();

86
src/start.php Normal file
View File

@@ -0,0 +1,86 @@
<?php declare(strict_types=1);
use Auth0\SDK\Exception\ConfigurationException;
use BitBadger\PDODocument\{AutoId, Configuration, Definition, DocumentException, Mode};
use Dotenv\Dotenv;
use MyPrayerJournal\{Auth, Table};
use MyPrayerJournal\Domain\Request;
require __DIR__ . '/vendor/autoload.php';
/** The version of this application */
const MPJ_VERSION = '4.0.0-alpha1';
(Dotenv::createImmutable(__DIR__))->load();
if (php_sapi_name() != 'cli') {
session_start();
$auth0_user = Auth::user();
if (!is_null($auth0_user)) {
$_SESSION['user_id'] = $auth0_user['sub'];
}
$_REQUEST['time_zone'] = $_SERVER['HTTP_X_TIME_ZONE'] ?? 'Etc/UTC';
}
Configuration::$pdoDSN = 'sqlite:' . implode(DIRECTORY_SEPARATOR, [__DIR__, 'data', 'mpj.db']);
Configuration::$mode = Mode::SQLite;
Configuration::$autoId = AutoId::RandomString;
Configuration::$idStringLength = 12;
Definition::ensureTable(Table::REQUEST);
Definition::ensureFieldIndex(Table::REQUEST, 'user', ['userId']);
$_PATCH = [];
if ($_SERVER['REQUEST_METHOD'] ?? '' == 'PATCH') parse_str(file_get_contents('php://input'), $_PATCH);
/**
* Return a 404 and exit
*/
function not_found(): never
{
http_response_code(404);
die('Not found');
}
/**
* Return a 303 redirect ("see other" - redirects to a GET)
*
* @param string $url The URL to which the browser should be redirected
*/
function see_other(string $url): never
{
header('Location: ' . (str_starts_with($url, 'http') ? '/' : $url));
http_response_code(303);
exit;
}
/**
* Add a header that instructs the browser to close an open modal dialog
*
* @param string $name The name of the dialog to be closed
*/
function hide_modal(string $name): void
{
header("X-Hide-Modal: $name");
}
/**
* Validate the user, HTTP method, and request
*
* @param string $id The ID of the prayer request to retrieve
* @param array $methods The allowable HTTP methods
* @param bool $redirect Whether to redirect not-logged-on users (optional, defaults to true)
* @return Request The request (failures will not return)
* @throws ConfigurationException If any is encountered
* @throws DocumentException If any is encountered
*/
function validate_request(string $id, array $methods, bool $redirect = true): Request
{
if (sizeof(array_filter($methods, fn($it) => $_SERVER['REQUEST_METHOD'] == $it)) == 0) not_found();
Auth::requireUser($redirect);
return Request::byId($id)->getOrCall(not_found(...));
}