142 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
997279783f Version 3 (#67) 2021-10-26 19:39:58 -04:00
77c85f516c Version 3 2021-10-26 19:38:45 -04:00
ca622aa4b7 Merge branch 'master' of https://github.com/bit-badger/myPrayerJournal 2021-10-26 19:22:54 -04:00
cce4f17cd8 Update to .NET 5 (#48); update deps 2021-06-19 14:08:49 -04:00
0bf73e49c9 Merge pull request #61 from bit-badger/dependabot/npm_and_yarn/src/app/yargs-parser-5.0.1
Bump yargs-parser from 5.0.0 to 5.0.1 in /src/app
2021-06-19 13:29:57 -04:00
a84d54c095 Merge pull request #60 from bit-badger/dependabot/npm_and_yarn/src/app/ws-6.2.2
Bump ws from 6.2.1 to 6.2.2 in /src/app
2021-06-19 13:29:28 -04:00
dependabot[bot]
68f4a1b9b2 Bump ws from 6.2.1 to 6.2.2 in /src/app
Bumps [ws](https://github.com/websockets/ws) from 6.2.1 to 6.2.2.
- [Release notes](https://github.com/websockets/ws/releases)
- [Commits](https://github.com/websockets/ws/commits)

---
updated-dependencies:
- dependency-name: ws
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2021-06-19 17:29:13 +00:00
23ccd3ac67 Merge pull request #59 from bit-badger/dependabot/npm_and_yarn/src/app/dns-packet-1.3.4
Bump dns-packet from 1.3.1 to 1.3.4 in /src/app
2021-06-19 13:28:26 -04:00
d4823c15f7 Merge pull request #58 from bit-badger/dependabot/npm_and_yarn/src/app/browserslist-4.16.6
Bump browserslist from 4.11.1 to 4.16.6 in /src/app
2021-06-19 13:27:51 -04:00
fc01e79337 Merge pull request #57 from bit-badger/dependabot/npm_and_yarn/src/app/hosted-git-info-2.8.9
Bump hosted-git-info from 2.8.8 to 2.8.9 in /src/app
2021-06-19 13:27:15 -04:00
fa9c902af7 Merge pull request #56 from bit-badger/dependabot/npm_and_yarn/src/app/url-parse-1.5.1
Bump url-parse from 1.4.7 to 1.5.1 in /src/app
2021-06-19 13:26:34 -04:00
dependabot[bot]
ed762ea03e Bump yargs-parser from 5.0.0 to 5.0.1 in /src/app
Bumps [yargs-parser](https://github.com/yargs/yargs-parser) from 5.0.0 to 5.0.1.
- [Release notes](https://github.com/yargs/yargs-parser/releases)
- [Changelog](https://github.com/yargs/yargs-parser/blob/v5.0.1/CHANGELOG.md)
- [Commits](https://github.com/yargs/yargs-parser/compare/v5.0.0...v5.0.1)

---
updated-dependencies:
- dependency-name: yargs-parser
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2021-06-19 17:26:25 +00:00
3675af3dca Merge pull request #55 from bit-badger/dependabot/npm_and_yarn/src/app/y18n-3.2.2
Bump y18n from 3.2.1 to 3.2.2 in /src/app
2021-06-19 13:25:41 -04:00
dependabot[bot]
1830e01ad6 Bump dns-packet from 1.3.1 to 1.3.4 in /src/app
Bumps [dns-packet](https://github.com/mafintosh/dns-packet) from 1.3.1 to 1.3.4.
- [Release notes](https://github.com/mafintosh/dns-packet/releases)
- [Changelog](https://github.com/mafintosh/dns-packet/blob/master/CHANGELOG.md)
- [Commits](https://github.com/mafintosh/dns-packet/compare/v1.3.1...v1.3.4)

Signed-off-by: dependabot[bot] <support@github.com>
2021-05-27 07:41:55 +00:00
dependabot[bot]
ffe057d7ee Bump browserslist from 4.11.1 to 4.16.6 in /src/app
Bumps [browserslist](https://github.com/browserslist/browserslist) from 4.11.1 to 4.16.6.
- [Release notes](https://github.com/browserslist/browserslist/releases)
- [Changelog](https://github.com/browserslist/browserslist/blob/main/CHANGELOG.md)
- [Commits](https://github.com/browserslist/browserslist/compare/4.11.1...4.16.6)

Signed-off-by: dependabot[bot] <support@github.com>
2021-05-24 23:59:12 +00:00
dependabot[bot]
bafdfb1af5 Bump hosted-git-info from 2.8.8 to 2.8.9 in /src/app
Bumps [hosted-git-info](https://github.com/npm/hosted-git-info) from 2.8.8 to 2.8.9.
- [Release notes](https://github.com/npm/hosted-git-info/releases)
- [Changelog](https://github.com/npm/hosted-git-info/blob/v2.8.9/CHANGELOG.md)
- [Commits](https://github.com/npm/hosted-git-info/compare/v2.8.8...v2.8.9)

Signed-off-by: dependabot[bot] <support@github.com>
2021-05-09 23:16:11 +00:00
dependabot[bot]
3d907e9569 Bump url-parse from 1.4.7 to 1.5.1 in /src/app
Bumps [url-parse](https://github.com/unshiftio/url-parse) from 1.4.7 to 1.5.1.
- [Release notes](https://github.com/unshiftio/url-parse/releases)
- [Commits](https://github.com/unshiftio/url-parse/compare/1.4.7...1.5.1)

Signed-off-by: dependabot[bot] <support@github.com>
2021-05-07 10:02:02 +00:00
dependabot[bot]
c8ef6e8714 Bump y18n from 3.2.1 to 3.2.2 in /src/app
Bumps [y18n](https://github.com/yargs/y18n) from 3.2.1 to 3.2.2.
- [Release notes](https://github.com/yargs/y18n/releases)
- [Changelog](https://github.com/yargs/y18n/blob/master/CHANGELOG.md)
- [Commits](https://github.com/yargs/y18n/commits)

Signed-off-by: dependabot[bot] <support@github.com>
2021-03-30 13:23:51 +00:00
266243423c Update deps 2021-03-09 11:45:54 -05:00
92a493251a Merge pull request #50 from bit-badger/dependabot/npm_and_yarn/src/app/axios-0.21.1
Bump axios from 0.19.2 to 0.21.1 in /src/app
2021-03-09 10:46:35 -05:00
c7c63d01f8 Merge pull request #54 from bit-badger/dependabot/npm_and_yarn/src/app/lodash-4.17.21
Bump lodash from 4.17.15 to 4.17.21 in /src/app
2021-03-09 10:45:19 -05:00
dependabot[bot]
62a18a8b09 Bump axios from 0.19.2 to 0.21.1 in /src/app
Bumps [axios](https://github.com/axios/axios) from 0.19.2 to 0.21.1.
- [Release notes](https://github.com/axios/axios/releases)
- [Changelog](https://github.com/axios/axios/blob/v0.21.1/CHANGELOG.md)
- [Commits](https://github.com/axios/axios/compare/v0.19.2...v0.21.1)

Signed-off-by: dependabot[bot] <support@github.com>
2021-03-09 15:45:18 +00:00
d1a9eb62c3 Merge pull request #49 from bit-badger/dependabot/npm_and_yarn/src/app/highlight.js-9.18.5
Bump highlight.js from 9.18.1 to 9.18.5 in /src/app
2021-03-09 10:44:11 -05:00
407222d06a Merge pull request #47 from bit-badger/dependabot/npm_and_yarn/src/app/node-fetch-2.6.1
Bump node-fetch from 2.6.0 to 2.6.1 in /src/app
2021-03-09 10:43:29 -05:00
044283709c Merge pull request #46 from bit-badger/dependabot/npm_and_yarn/src/app/http-proxy-1.18.1
Bump http-proxy from 1.18.0 to 1.18.1 in /src/app
2021-03-09 10:43:04 -05:00
dependabot[bot]
be86fbfcba Bump highlight.js from 9.18.1 to 9.18.5 in /src/app
Bumps [highlight.js](https://github.com/highlightjs/highlight.js) from 9.18.1 to 9.18.5.
- [Release notes](https://github.com/highlightjs/highlight.js/releases)
- [Changelog](https://github.com/highlightjs/highlight.js/blob/9.18.5/CHANGES.md)
- [Commits](https://github.com/highlightjs/highlight.js/compare/9.18.1...9.18.5)

Signed-off-by: dependabot[bot] <support@github.com>
2021-03-09 15:42:51 +00:00
dependabot[bot]
63b3037ede Bump lodash from 4.17.15 to 4.17.21 in /src/app
Bumps [lodash](https://github.com/lodash/lodash) from 4.17.15 to 4.17.21.
- [Release notes](https://github.com/lodash/lodash/releases)
- [Commits](https://github.com/lodash/lodash/compare/4.17.15...4.17.21)

Signed-off-by: dependabot[bot] <support@github.com>
2021-03-09 15:42:15 +00:00
d239b16d33 Merge pull request #43 from bit-badger/dependabot/npm_and_yarn/src/app/websocket-extensions-0.1.4
Bump websocket-extensions from 0.1.3 to 0.1.4 in /src/app
2021-03-09 10:41:56 -05:00
a9ab0446c4 Merge pull request #52 from bit-badger/dependabot/npm_and_yarn/src/app/pug-3.0.1
Bump pug from 2.0.4 to 3.0.1 in /src/app
2021-03-09 10:39:59 -05:00
366ed2ed2f Merge pull request #53 from bit-badger/dependabot/npm_and_yarn/src/app/elliptic-6.5.4
Bump elliptic from 6.5.2 to 6.5.4 in /src/app
2021-03-09 10:39:29 -05:00
dependabot[bot]
fb304c26b6 Bump elliptic from 6.5.2 to 6.5.4 in /src/app
Bumps [elliptic](https://github.com/indutny/elliptic) from 6.5.2 to 6.5.4.
- [Release notes](https://github.com/indutny/elliptic/releases)
- [Commits](https://github.com/indutny/elliptic/compare/v6.5.2...v6.5.4)

Signed-off-by: dependabot[bot] <support@github.com>
2021-03-09 00:56:03 +00:00
dependabot[bot]
7b11e70e76 Bump pug from 2.0.4 to 3.0.1 in /src/app
Bumps [pug](https://github.com/pugjs/pug) from 2.0.4 to 3.0.1.
- [Release notes](https://github.com/pugjs/pug/releases)
- [Commits](https://github.com/pugjs/pug/compare/pug@2.0.4...pug@3.0.1)

Signed-off-by: dependabot[bot] <support@github.com>
2021-03-03 02:54:57 +00:00
dependabot[bot]
f50a8ae83e Bump node-fetch from 2.6.0 to 2.6.1 in /src/app
Bumps [node-fetch](https://github.com/bitinn/node-fetch) from 2.6.0 to 2.6.1.
- [Release notes](https://github.com/bitinn/node-fetch/releases)
- [Changelog](https://github.com/node-fetch/node-fetch/blob/master/docs/CHANGELOG.md)
- [Commits](https://github.com/bitinn/node-fetch/compare/v2.6.0...v2.6.1)

Signed-off-by: dependabot[bot] <support@github.com>
2020-09-12 05:25:20 +00:00
dependabot[bot]
aa0864416f Bump http-proxy from 1.18.0 to 1.18.1 in /src/app
Bumps [http-proxy](https://github.com/http-party/node-http-proxy) from 1.18.0 to 1.18.1.
- [Release notes](https://github.com/http-party/node-http-proxy/releases)
- [Changelog](https://github.com/http-party/node-http-proxy/blob/master/CHANGELOG.md)
- [Commits](https://github.com/http-party/node-http-proxy/compare/1.18.0...1.18.1)

Signed-off-by: dependabot[bot] <support@github.com>
2020-09-07 11:51:40 +00:00
dependabot[bot]
05a1b7adda Bump websocket-extensions from 0.1.3 to 0.1.4 in /src/app
Bumps [websocket-extensions](https://github.com/faye/websocket-extensions-node) from 0.1.3 to 0.1.4.
- [Release notes](https://github.com/faye/websocket-extensions-node/releases)
- [Changelog](https://github.com/faye/websocket-extensions-node/blob/master/CHANGELOG.md)
- [Commits](https://github.com/faye/websocket-extensions-node/compare/0.1.3...0.1.4)

Signed-off-by: dependabot[bot] <support@github.com>
2020-06-06 13:17:04 +00:00
Daniel J. Summers
f833598cdd Fix progress bar style 2020-05-21 08:05:03 -05:00
Daniel J. Summers
dfd1c59554 Fix tryJournalById function (#42)
Also update .NET deps
2020-04-23 10:07:23 -05:00
Daniel J. Summers
83b70073e9 Update deps 2020-04-11 08:51:14 -05:00
dependabot[bot]
11025cc39a Bump auth0-js from 9.12.2 to 9.13.2 in /src/app (#40) 2020-04-11 13:37:32 +00:00
Daniel J. Summers
fb908a1cef Update to .NET Core 3.1 (#39)
Also catch dependencies up to latest
2020-03-07 18:30:21 -06:00
Daniel J. Summers
6a6f7b35c7 Reverse notes ordering, make scrollable (#32) 2019-10-14 10:50:50 -05:00
715df08cbe Migrate API to .NET Core 3.0 (#31)
Migrate API to .NET Core 3.0 (fixes #30)
2019-09-28 08:42:58 -05:00
Daniel J. Summers
ac8b39fff9 Update version 2019-09-26 21:22:14 -05:00
Daniel J. Summers
2bf54136ca Fix journal ordering fix (#28 again) 2019-09-26 20:46:08 -05:00
Daniel J. Summers
0709cabea1 Fix journal ordering (#28) 2019-09-10 06:08:19 -05:00
Daniel J. Summers
cbd9114599 Update deps
fixes security for eslint-utils, which isn't part of the published package; no same-day point-plusone release required
2019-09-02 19:39:51 -05:00
Daniel J. Summers
097ee2deb4 Remove v2 migration program 2019-09-02 19:07:51 -05:00
fa78e86de6 myPrayerJournal v2 (#27)
App changes:
* Move to Vue Material for UI components
* Convert request cards to true material design cards, separating the "pray" button from the others and improved highlighting of the current request
* Centralize Auth0 integration in one place; modify the Vuex store to rely on it entirely, and add a Vue mixin to make it accessible by any component

API changes:
* Change backing data store to RavenDB
* Evolve domain models (using F# discriminated unions, and JSON converters for storage) to make invalid states unrepresentable
* Incorporate the FunctionalCuid library
* Create a functional pipeline for app configuration instead of chaining `IWebHostBuilder` calls

Bug fixes:
* Set showAfter to 0 for immediately recurring requests (#26)
2019-09-02 19:01:26 -05:00
Daniel J. Summers
ce588b6a43 dep update for lodash CVE 2019-07-12 19:34:26 -05:00
Daniel J. Summers
57cd17c734 Fixed broken pray button 2019-07-07 07:08:42 -05:00
Daniel J. Summers
42615dae82 Update recurrence before status (#25); version bump 2019-07-05 20:34:38 -05:00
Daniel J. Summers
68b650e31d Updated dependencies 2019-05-31 20:29:57 -05:00
Daniel J. Summers
d738321dc0 Use FSharpLu for JSON serialization (#24) 2019-02-23 13:59:32 -06:00
Daniel J. Summers
8995097d68 Updated to .NET Core 2.2 (#23)
Also updated API and app deps
2019-02-23 10:59:23 -06:00
Daniel J. Summers
4310fb91fa Updated deps 2019-01-29 20:52:38 -06:00
Daniel J. Summers
c0def7623f Updated docs link to new subdomain 2018-09-09 21:08:22 -05:00
Daniel J. Summers
ab8fab51c5 Create CNAME 2018-09-07 17:43:59 -05:00
Daniel J. Summers
96717ae7c4 Delete CNAME 2018-09-07 17:43:43 -05:00
Daniel J. Summers
b11ff0ff3d Create CNAME 2018-09-07 16:41:38 -05:00
Daniel J. Summers
6486763297 Delete CNAME 2018-09-07 16:41:23 -05:00
Daniel J. Summers
e94e28880b Create CNAME 2018-09-07 16:39:43 -05:00
Daniel J. Summers
16c3a9fd44 Updated docs for 1.0! 2018-08-21 20:53:44 -05:00
Daniel J. Summers
473359c645 Sort journal by appearance time (#21) 2018-08-21 20:44:39 -05:00
Daniel J. Summers
334710065c Upgrade to Vue CLI 3 / Webpack 4 (#22)
Fixes #19
2018-08-21 20:39:41 -05:00
Daniel J. Summers
ee9326d7a5 Updated docs for recurrence (#16) 2018-08-18 20:12:30 -05:00
Daniel J. Summers
2c34650ceb Completed recurrence work (#16)
Requests can now:
- be entered with recurrence
- be updated with recurrence
- manually skip recurrence period

Also did an app-wide clean-up to ensure that everything is done the same way in all places
2018-08-18 19:32:48 -05:00
Daniel J. Summers
9f1e258180 Added recurrence to new request add/edit page (#16)
still need to get the actual non-immediate recurrence stuff to work correctly
2018-08-18 13:46:03 -05:00
Daniel J. Summers
0c21e6c1c0 Unsnooze works; #20 is complete
also:
- wrapped up some other stylings
- snoozed requests still show in the journal; this logic will change with recurrence work, so that bug is deferred
2018-08-18 11:07:30 -05:00
Daniel J. Summers
a6144f67ec Converted notes modal (#20) 2018-08-18 09:13:38 -05:00
Daniel J. Summers
e351fe5b56 Active request page (#16)
Also:
- refactored snoozed and answered list pages to use a common list format
- reworked the URLs to make them more consistent
- eliminated current "full" API endpoint, and renamed existing "complete" endpoint to "full"
2018-08-17 22:12:14 -05:00
Daniel J. Summers
d3aff4a110 Add/Edit request works
No longer a modal (#20)
2018-08-17 20:59:57 -05:00
Daniel J. Summers
c0dd6b5dd6 A few more minor tweaks 2018-08-16 22:09:39 -05:00
Daniel J. Summers
5bba499251 -BootstrapVue -VueAwesome
- All non-modals no longer reference Bootstrap or Font Awesome (#20)
- Removed "full request" button from journal page (#16)
- Added role attributes in many places
2018-08-16 21:57:54 -05:00
Daniel J. Summers
96f2f2f7e0 Added recurrence SQL; updated API
API should support recurrence (#16); also updated for new F# match! statement
2018-08-14 21:01:21 -05:00
Daniel J. Summers
2bf3bc4865 Working toward hosting
Seeing different behavior when this is sitting behind nginx; working toward a solution
2018-08-07 08:17:56 -05:00
Daniel J. Summers
95175d2c57 Merge branch 'master' of https://github.com/bit-badger/myPrayerJournal 2018-08-06 21:30:45 -05:00
Daniel J. Summers
3f71d75a99 Restoring ignored file changes
Also deleted a file I missed
2018-08-06 21:30:11 -05:00
Daniel J. Summers
8becb8cea4 F# API (#18)
- API is now F# / Giraffe / EF Core
- Snoozed requests are complete #17
- Updated doc links in preparation for transfer to Bit Badger Solutions organization's repository
2018-08-06 21:21:28 -05:00
Daniel J. Summers
d1fd5f68e7 Added snooze icon to journal
#17
2018-06-18 21:05:04 -05:00
Daniel J. Summers
d0ea7cf3c6 Added "snoozedUntil" column to API
Also added a "snooze" route (working on #17 )
2018-06-18 20:25:00 -05:00
Daniel J. Summers
05990d537a Version bump 2018-06-14 18:31:51 -05:00
Daniel J. Summers
67cdd5a9b0 Update tooltip on date changed
Bound long date to computed property (addresses #15 )
2018-06-14 18:21:14 -05:00
Daniel J. Summers
650bda6bc5 Version bump; remove logging 2018-05-27 19:46:55 -05:00
Daniel J. Summers
6424cde1b6 Merge branch 'go-backend' 2018-05-27 19:39:21 -05:00
Daniel J. Summers
d429d6c9ac Merged Go API changes 2018-05-27 19:38:37 -05:00
Daniel J. Summers
91daa387cb Misc final tweaks
- Handle notes being nil
- Distinguish between request not found, error retrieving notes, and no notes for present request
- Minor UI tweaks to use smart quotes
2018-05-27 19:26:52 -05:00
Daniel J. Summers
d57e2e863a Remove JavaScript API files 2018-05-27 18:02:31 -05:00
Daniel J. Summers
9de713fc6a Fixed "answered" API error 2018-05-27 18:00:37 -05:00
Daniel J. Summers
79ced40470 Most API features now work
- Switched from Vestigo to ozzo-routing in a misguided attempt to get JSON to parse as a form; not switching back at this point
- Fixed error with request SQL for individual requests
- Parsing JSON body works now

Still need to handle "no rows found" for journal/answered lists; this isn't an error for new users
2018-05-26 22:18:26 -05:00
Daniel J. Summers
bad430fc37 GDPR update; version bump
- added Terms of Service and Privacy Policy
- updated deps
- fixed vue-bootstrap warning
2018-05-26 11:59:30 -05:00
Daniel J. Summers
d5a783304e updated API deps 2018-05-20 22:08:59 -05:00
Daniel J. Summers
a429a2d6c9 GDPR update; version bump
- added Terms of Service and Privacy Policy
- updated deps
- fixed vue-bootstrap warning
2018-05-19 23:22:44 -05:00
Daniel J. Summers
2b6f7c63d0 route handler translation 2018-03-31 22:13:26 -05:00
Daniel J. Summers
419c181eff Authorization works (yay)
The journal page once again loads as it should; now to migrate the remaining routes
2018-03-31 19:58:44 -05:00
Daniel J. Summers
9637b38a3f Static files now served; auth is broken 2018-03-24 13:37:18 -05:00
Daniel J. Summers
59b5574b16 Switched to vestigo router
Also moved db reference to data module; it now starts, but doesn't serve index.html for root yet
2018-03-22 22:11:38 -05:00
Daniel J. Summers
b248f7ca7f minor tweaks towards JWTs
time box expired before completing this; one of these days...
2018-03-20 20:26:02 -05:00
Daniel J. Summers
8d84bdb2e6 app/API build adjustments; get user from ctx 2018-03-12 23:14:16 -05:00
Daniel J. Summers
b7406bd827 More work on auth and req ctx 2018-03-12 21:44:43 -05:00
Daniel J. Summers
d92ac4430e Split routes, router, and handlers into different files 2018-03-11 22:38:13 -05:00
Daniel J. Summers
0cde2fb6db Merge updated deps/build files 2018-03-11 20:57:25 -05:00
Daniel J. Summers
943492f175 Updated Auth0 and other deps #13; version bump 2018-03-10 22:50:39 -06:00
Daniel J. Summers
df76385d6a Added previously-ignored Vue build files
Those globs will git you...
2018-03-10 22:22:10 -06:00
Daniel J. Summers
8c801ea49f Interim commit; started work on routes 2018-01-18 11:29:01 -06:00
Daniel J. Summers
0807aa300a Data and structures converted 2018-01-17 23:00:26 -06:00
Daniel J. Summers
8d8d112fff Updated front page text (#12) 2017-10-23 22:04:34 -05:00
Daniel J. Summers
6c4061e07d Updated docs/README; version bump
So long alpha - hello, beta!
2017-10-23 21:40:58 -05:00
Daniel J. Summers
9cdb505bb1 Renamed RequestListItem to RequestCard 2017-10-23 21:22:29 -05:00
Daniel J. Summers
40d765fb92 Journal is more mobile-friendly (#11)
Also:
- Updated deps
- Ensure the date is wrapped as a whole on the Answered Request page
2017-10-23 21:19:39 -05:00
Daniel J. Summers
56dee71377 Updated dox for #9; version bump 2017-10-23 05:53:30 -05:00
Daniel J. Summers
3c3f0a7981 Finished answered request layout (#9)
Also:
- rearranged API calls to be in alphabetical order (except the bearer
stuff at the top)
- modified the API base URL and Auth0 renewal URLs to be derived from
the browser's location (localhost / prod both work now with no change)
2017-10-22 22:50:26 -05:00
Daniel J. Summers
a1ce40ee83 Get version from package.json (#10)
...that was easy.
2017-10-19 15:11:51 -05:00
104 changed files with 4347 additions and 11256 deletions

258
.gitignore vendored
View File

@@ -1,259 +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
.idea/
*.sln.iml
# Compiled files / application
src/api/public/index.html
src/api/public/static
src/api/appsettings.json
build/
# PHP ignore files
src/vendor
src/.env

View File

@@ -1,7 +1,11 @@
# myPrayerJournal
## 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")_.
This is borne of out of a personal desire I had to have something that would help me with my 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.
It is still a work-in-progress (WIP), but is available for public preview at <https://prayerjournal.me>.
## Further Reading
The documentation for the site is at <https://prayerjournal.me/docs>.

View File

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

View File

@@ -1,45 +0,0 @@
# Documentation
## Caveats
_myPrayerJournal is currently alpha software. There likely will be errors, the way things work may change, and parts of the application are unfinished or need polish. I **will** do my best to not lose any data, though; it is backed up the way other Bit Badger Solutions sites have their data backed up. Throughout this document, current gotchas will be called out with italic text, like this notice._
## 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 three columns (or one, if you're using a mobile phone). Each request is in its own card, and the buttons at the bottom 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.
## 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. 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 goes to the bottom of the list, 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 piece of paper with writing; 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.
## Viewing a Request and Its History
myPrayerJournal tracks all of the actions related to a request; the fourth button, with the magnifying glass icon, will show you the entire history, including the text as it changed, and all the times "Prayed" was recorded.
## Answered Requests
Next to "Journal" on the top navigation is the word "Answered." This page lists all answered requests, from most recent to least recent, along with the text of the request at the time it was marked as answered. It will also show you when it was marked answered. The button with the magnifying class at the words "Show Full Request" behave the same way as the paragraph immediately preceding this describes. _(This will likely change before a 0.9.x release, but this gives at least some way to find and review answered requests.)_
## Known Issues
See [the GitHub issues list](https://github.com/danieljsummers/myPrayerJournal/issues) for the most up-to-date list.

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,35 +0,0 @@
'use strict'
const chalk = require('chalk')
const { env } = require('./appsettings.json') // process.env.NODE_ENV || 'dev'
if ('dev' === env) require('babel-register')
const src = (env === 'dev') ? './src' : './build'
const app = require(`${src}/index`).default
const db = require(`${src}/db`).default
const fullEnv = ('dev' === env) ? 'Development' : 'Production'
const { port } = require('./appsettings.json')
/**
* Log a start-up message for the app
* @param {string} status The status to display
*/
const startupMsg = (status) => {
console.log(chalk`{reset myPrayerJournal ${status} | Port: {bold ${port}} | Mode: {bold ${fullEnv}}}`)
}
// Ensure the database exists before starting up
db.verify()
.then(() => app.listen(port, () => startupMsg('ready')))
.catch(err => {
console.log(chalk`\n{reset {bgRed.white.bold || Error connecting to PostgreSQL }}`)
for (let key of Object.keys(err)) {
console.log(chalk`${key}: {reset {bold ${err[key]}}}`)
}
console.log('')
startupMsg('failed')
})

View File

@@ -1,12 +0,0 @@
'use strict'
import fs from 'fs'
/**
* Read and parse a JSON file
* @param {string} path The path to the file
* @param {string} encoding The encoding of the file (defaults to UTF-8)
* @return {*} The parsed contents of the file
*/
export default (path, encoding = 'utf-8') =>
JSON.parse(fs.readFileSync(path, encoding))

View File

@@ -1,45 +0,0 @@
{
"name": "my-prayer-journal-api",
"private": true,
"version": "0.8.4",
"description": "Server API for myPrayerJournal",
"main": "index.js",
"author": "Daniel J. Summers <daniel@bitbadger.solutions>",
"license": "MIT",
"dependencies": {
"chalk": "^2.1.0",
"cuid": "^1.3.8",
"jwks-rsa-koa": "^1.1.3",
"koa": "^2.3.0",
"koa-bodyparser": "^4.2.0",
"koa-jwt": "^3.2.2",
"koa-router": "^7.2.1",
"koa-send": "^4.1.0",
"koa-static": "^4.0.1",
"pg": "^7.3.0"
},
"scripts": {
"start": "node app.js",
"build": "babel src -d build",
"vue": "cd ../app && node build/build.js prod && cd ../api && node app.js"
},
"devDependencies": {
"babel": "^6.23.0",
"babel-cli": "^6.26.0",
"babel-preset-env": "^1.6.0",
"babel-register": "^6.26.0",
"koa-morgan": "^1.0.1"
},
"babel": {
"presets": [
[
"env",
{
"targets": {
"node": "current"
}
}
]
]
}
}

View File

@@ -1,108 +0,0 @@
'use strict'
import { Pool } from 'pg'
/**
* SQL to check the existence of a table in the mpj schema
* @param {string} table The name of the table whose existence should be checked
*/
const tableSql = table => `SELECT 1 FROM pg_tables WHERE schemaname='mpj' AND tablename='${table}'`
/**
* SQL to determine if an index exists
* @param {string} table The name of the table which the given index indexes
* @param {string} index The name of the index
*/
const indexSql = (table, index) =>
`SELECT 1 FROM pg_indexes WHERE schemaname='mpj' AND tablename='${table}' AND indexname='${index}'`
const ddl = [
{
name: 'myPrayerJournal Schema',
check: `SELECT 1 FROM pg_namespace WHERE nspname='mpj'`,
fix: `
CREATE SCHEMA mpj;
COMMENT ON SCHEMA mpj IS 'myPrayerJournal data'`
},
{
name: 'request Table',
check: tableSql('request'),
fix: `
CREATE TABLE mpj.request (
"requestId" varchar(25) PRIMARY KEY,
"enteredOn" bigint NOT NULL,
"userId" varchar(100) NOT NULL);
COMMENT ON TABLE mpj.request IS 'Requests'`
},
{
name: 'history Table',
check: tableSql('history'),
fix: `
CREATE TABLE mpj.history (
"requestId" varchar(25) NOT NULL REFERENCES mpj.request,
"asOf" bigint NOT NULL,
"status" varchar(25),
"text" text,
PRIMARY KEY ("requestId", "asOf"));
COMMENT ON TABLE mpj.history IS 'Request update history'`
},
{
name: 'note Table',
check: tableSql('note'),
fix: `
CREATE TABLE mpj.note (
"requestId" varchar(25) NOT NULL REFERENCES mpj.request,
"asOf" bigint NOT NULL,
"notes" text NOT NULL,
PRIMARY KEY ("requestId", "asOf"));
COMMENT ON TABLE mpj.note IS 'Notes regarding a request'`
},
{
name: 'request.userId Index',
check: indexSql('request', 'idx_request_userId'),
fix: `
CREATE INDEX "idx_request_userId" ON mpj.request ("userId");
COMMENT ON INDEX "idx_request_userId" IS 'Requests are retrieved by user'`
},
{
name: 'journal View',
check: `SELECT 1 FROM pg_views WHERE schemaname='mpj' AND viewname='journal'`,
fix: `
CREATE VIEW mpj.journal AS
SELECT
request."requestId",
request."userId",
(SELECT "text"
FROM mpj.history
WHERE history."requestId" = request."requestId"
AND "text" IS NOT NULL
ORDER BY "asOf" DESC
LIMIT 1) AS "text",
(SELECT "asOf"
FROM mpj.history
WHERE history."requestId" = request."requestId"
ORDER BY "asOf" DESC
LIMIT 1) AS "asOf",
(SELECT "status"
FROM mpj.history
WHERE history."requestId" = request."requestId"
ORDER BY "asOf" DESC
LIMIT 1) AS "lastStatus"
FROM mpj.request;
COMMENT ON VIEW mpj.journal IS 'Requests with latest text'`
}
]
export default function (query) {
return {
/**
* Ensure that the database schema, tables, and indexes exist
*/
ensureDatabase: async () => {
for (let item of ddl) {
const result = await query(item.check, [])
if (1 > result.rowCount) await query(item.fix, [])
}
}
}
}

View File

@@ -1,27 +0,0 @@
'use strict'
import { Pool, types } from 'pg'
import appConfig from '../../appsettings.json'
import ddl from './ddl'
import request from './request'
/** Pooled PostgreSQL instance */
const pool = new Pool(appConfig.pgPool)
// Return "bigint" (int8) instances as number instead of strings
// ref: https://github.com/brianc/node-pg-types
types.setTypeParser(20, val => parseInt(val))
/**
* Run a SQL query
* @param {string} text The SQL command
* @param {*[]} params The parameters for the query
*/
const query = (text, params) => pool.query(text, params)
export default {
query: query,
request: request(pool),
verify: ddl(query).ensureDatabase
}

View File

@@ -1,188 +0,0 @@
'use strict'
import { Pool } from 'pg'
import cuid from 'cuid'
const currentRequestSql = `
SELECT "requestId", "text", "asOf", "lastStatus"
FROM mpj.journal`
const journalSql = `${currentRequestSql}
WHERE "userId" = $1
AND "lastStatus" <> 'Answered'`
const requestNotFound = {
requestId: '',
text: 'Not Found',
asOf: 0
}
export default function (pool) {
/**
* Retrieve basic information about a single request
* @param {string} requestId The Id of the request to retrieve
* @param {string} userId The Id of the user to whom the request belongs
*/
let retrieveRequest = (requestId, userId) =>
pool.query(`
SELECT "requestId", "enteredOn"
FROM mpj.request
WHERE "requestId" = $1
AND "userId" = $2`,
[ requestId, userId ])
return {
/**
* Add a history entry for this request
* @param {string} userId The Id of the user to whom this request belongs
* @param {string} requestId The Id of the request to which the update applies
* @param {string} status The status for this history entry
* @param {string} updateText The updated text for the request (pass blank if no update)
* @return {number} 404 if the request is not found or does not belong to the given user, 204 if successful
*/
addHistory: async (userId, requestId, status, updateText) => {
const req = retrieveRequest(requestId, userId)
if (req.rowCount === 0) {
return 404
}
await pool.query(`
INSERT INTO mpj.history
("requestId", "asOf", "status", "text")
VALUES
($1, $2, $3, NULLIF($4, ''))`,
[ requestId, Date.now(), status, updateText ])
return 204
},
/**
* Add a new prayer request
* @param {string} userId The Id of the user
* @param {string} requestText The text of the request
* @return The created request
*/
addNew: async (userId, requestText) => {
const id = cuid()
const enteredOn = Date.now()
return (async () => {
const client = await pool.connect()
try {
await client.query('BEGIN')
await client.query(
'INSERT INTO mpj.request ("requestId", "enteredOn", "userId") VALUES ($1, $2, $3)',
[ id, enteredOn, userId ])
await client.query(
`INSERT INTO mpj.history ("requestId", "asOf", "status", "text") VALUES ($1, $2, 'Created', $3)`,
[ id, enteredOn, requestText ])
await client.query('COMMIT')
} catch (e) {
await client.query('ROLLBACK')
throw e
} finally {
client.release()
}
return { requestId: id, text: requestText, asOf: enteredOn, lastStatus: 'Created' }
})().catch(e => {
console.error(e.stack)
return { requestId: '', text: 'error', asOf: 0, lastStatus: 'Errored' }
})
},
/**
* Add a note about a prayer request
* @param {string} userId The Id of the user to whom the request belongs
* @param {string} requestId The Id of the request to which the note applies
* @param {string} note The notes to add
* @return {number} 404 if the request is not found or does not belong to the given user, 204 if successful
*/
addNote: async (userId, requestId, note) => {
const req = retrieveRequest(requestId, userId)
if (req.rowCount === 0) {
return 404
}
await pool.query(`
INSERT INTO mpj.note
("requestId", "asOf", "notes")
VALUES
($1, $2, $3)`,
[ requestId, Date.now(), note ])
return 204
},
/**
* Get all answered requests with their text as of the "Answered" status
* @param {string} userId The Id of the user for whom requests should be retrieved
* @return All requests
*/
answered: async (userId) =>
(await pool.query(`${currentRequestSql}
WHERE "userId" = $1
AND "lastStatus" = 'Answered'
ORDER BY "asOf" DESC`,
[ userId ])).rows,
/**
* Get the "current" version of a request by its Id
* @param {string} requestId The Id of the request to retrieve
* @param {string} userId The Id of the user to which the request belongs
* @return The request, or a request-like object indicating that the request was not found
*/
byId: async (userId, requestId) => {
const reqs = await pool.query(`${currentRequestSql}
WHERE "requestId" = $1
AND "userId" = $2`,
[ requestId, userId ])
return (0 < reqs.rowCount) ? reqs.rows[0] : requestNotFound
},
/**
* Get a prayer request, including its full history, by its Id
* @param {string} userId The Id of the user to which the request belongs
* @param {string} requestId The Id of the request to retrieve
* @return The request, or a request-like object indicating that the request was not found
*/
fullById: async (userId, requestId) => {
const reqResults = await retrieveRequest(requestId, userId)
if (0 === reqResults.rowCount) {
return requestNotFound
}
const req = reqResults.rows[0]
const history = await pool.query(`
SELECT "asOf", "status", COALESCE("text", '') AS "text"
FROM mpj.history
WHERE "requestId" = $1
ORDER BY "asOf"`,
[ requestId ])
req.history = history.rows
return req
},
/**
* Get the current requests for a user (i.e., their complete current journal)
* @param {string} userId The Id of the user
* @return The requests that make up the current journal
*/
journal: async userId => (await pool.query(`${journalSql} ORDER BY "asOf"`, [ userId ])).rows,
/**
* Get the notes for a request, most recent first
* @param {string} userId The Id of the user to whom the request belongs
* @param {string} requestId The Id of the request whose notes should be retrieved
* @return The notes for the request
*/
notesById: async (userId, requestId) => {
const reqResults = await retrieveRequest(requestId, userId)
if (0 === reqResults.rowCount) {
return requestNotFound
}
const notes = await pool.query(`
SELECT "asOf", "notes"
FROM mpj.note
WHERE "requestId" = $1
ORDER BY "asOf" DESC`,
[ requestId ])
return notes.rows
}
}
}

View File

@@ -1,36 +0,0 @@
'use strict'
import Koa from 'koa'
import bodyParser from 'koa-bodyparser'
import morgan from 'koa-morgan'
import send from 'koa-send'
import serveFrom from 'koa-static'
import appConfig from '../appsettings.json'
import router from './routes'
/** Koa app */
const app = new Koa()
if (appConfig.env === 'dev') app.use(morgan('dev'))
export default app
// Serve the Vue files from /public
.use(serveFrom('public'))
// Parse the body into ctx.request.body, if present
.use(bodyParser())
// Tie in all the routes
.use(router.routes())
.use(router.allowedMethods())
// Send the index.html file for what would normally get a 404
.use(async (ctx, next) => {
if (ctx.url.indexOf('/api') === -1) {
try {
await send(ctx, 'index.html', { root: __dirname + '/../public/' })
}
catch (err) {
return await next(err)
}
}
return await next()
})

View File

@@ -1,39 +0,0 @@
'use strict'
import jwt from 'koa-jwt'
import jwksRsa from 'jwks-rsa-koa'
import Router from 'koa-router'
import appConfig from '../../appsettings.json'
import journal from './journal'
import request from './request'
/** Authentication middleware to verify the access token against the Auth0 JSON Web Key Set */
const checkJwt = jwt({
// Dynamically provide a signing key
// based on the kid in the header and
// the singing keys provided by the JWKS endpoint.
secret: jwksRsa.koaJwt2Key({
cache: true,
rateLimit: true,
jwksRequestsPerMinute: 5,
jwksUri: `https://${appConfig.auth0.domain}/.well-known/jwks.json`
}),
// Validate the audience and the issuer.
audience: appConfig.auth0.clientId,
issuer: `https://${appConfig.auth0.domain}/`,
algorithms: ['RS256']
})
/** /api/journal routes */
const journalRoutes = journal(checkJwt)
/** /api/request routes */
const requestRoutes = request(checkJwt)
/** Combined router */
const router = new Router({ prefix: '/api' })
router.use('/journal', journalRoutes.routes(), journalRoutes.allowedMethods())
router.use('/request', requestRoutes.routes(), requestRoutes.allowedMethods())
export default router

View File

@@ -1,16 +0,0 @@
'use strict'
import Router from 'koa-router'
import db from '../db'
const router = new Router()
export default function (checkJwt) {
router.get('/', checkJwt, async (ctx, next) => {
const reqs = await db.request.journal(ctx.state.user.sub)
ctx.body = reqs
return await next()
})
return router
}

View File

@@ -1,66 +0,0 @@
'use strict'
import Router from 'koa-router'
import db from '../db'
const router = new Router()
export default function (checkJwt) {
router
// Add a new request
.post('/', checkJwt, async (ctx, next) => {
ctx.body = await db.request.addNew(ctx.state.user.sub, ctx.request.body.requestText)
await next()
})
// Add a request history entry (prayed, updated, answered, etc.)
.post('/:id/history', checkJwt, async (ctx, next) => {
const body = ctx.request.body
ctx.response.status = await db.request.addHistory(ctx.state.user.sub, ctx.params.id, body.status, body.updateText)
await next()
})
// Add a note to a request
.post('/:id/note', checkJwt, async (ctx, next) => {
const body = ctx.request.body
ctx.response.status = await db.request.addNote(ctx.state.user.sub, ctx.params.id, body.notes)
await next()
})
// Get a journal-style request by its Id
.get('/:id', checkJwt, async (ctx, next) => {
const req = await db.request.byId(ctx.state.user.sub, ctx.params.id)
if ('Not Found' === req.text) {
ctx.response.status = 404
} else {
ctx.body = req
}
await next()
})
// Get a request, along with its full history
.get('/:id/full', checkJwt, async (ctx, next) => {
const req = await db.request.fullById(ctx.state.user.sub, ctx.params.id)
if ('Not Found' === req.text) {
ctx.response.status = 404
} else {
ctx.body = req
}
await next()
})
// Get the notes for a request
.get('/:id/notes', checkJwt, async (ctx, next) => {
const notes = await db.request.notesById(ctx.state.user.sub, ctx.params.id)
if (notes.text && 'Not Found' === notes.text) {
ctx.response.status = 404
} else {
ctx.body = notes
ctx.response.status = 200
}
await next()
})
.get('/answered', checkJwt, async (ctx, next) => {
ctx.body = await db.request.answered(ctx.state.user.sub)
ctx.response.status = 200
await next()
})
return router
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,18 +0,0 @@
{
"presets": [
["env", {
"modules": false,
"targets": {
"browsers": ["> 1%", "last 2 versions", "not ie <= 8"]
}
}],
"stage-2"
],
"plugins": ["transform-runtime"],
"env": {
"test": {
"presets": ["env", "stage-2"],
"plugins": ["istanbul"]
}
}
}

View File

@@ -1,9 +0,0 @@
root = true
[*]
charset = utf-8
indent_style = space
indent_size = 2
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true

View File

@@ -1,2 +0,0 @@
build/*.js
config/*.js

View File

@@ -1,27 +0,0 @@
// http://eslint.org/docs/user-guide/configuring
module.exports = {
root: true,
parser: 'babel-eslint',
parserOptions: {
sourceType: 'module'
},
env: {
browser: true,
},
// https://github.com/feross/standard/blob/master/RULES.md#javascript-standard-style
extends: 'standard',
// required to lint *.vue files
plugins: [
'html'
],
// add your custom rules here
'rules': {
// allow paren-less arrow functions
'arrow-parens': 0,
// allow async-await
'generator-star-spacing': 0,
// allow debugger during development
'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0
}
}

19
src/app/.gitignore vendored
View File

@@ -1,19 +0,0 @@
.DS_Store
node_modules/
dist/
npm-debug.log*
yarn-debug.log*
yarn-error.log*
test/unit/coverage
test/e2e/reports
selenium-debug.log
# Editor directories and files
.idea
*.suo
*.ntvs*
*.njsproj
*.sln
# Auth0 settings
src/auth/auth0-variables.js

View File

@@ -1,8 +0,0 @@
// https://github.com/michael-ciniawsky/postcss-load-config
module.exports = {
"plugins": {
// to edit target browsers: use "browserslist" field in package.json
"autoprefixer": {}
}
}

View File

@@ -1,21 +0,0 @@
MIT License
Copyright (c) 2017 Daniel J. Summers
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -1,6 +0,0 @@
var merge = require('webpack-merge')
var prodEnv = require('./prod.env')
module.exports = merge(prodEnv, {
NODE_ENV: '"development"'
})

View File

@@ -1,38 +0,0 @@
// see http://vuejs-templates.github.io/webpack for documentation.
var path = require('path')
module.exports = {
build: {
env: require('./prod.env'),
index: path.resolve(__dirname, '../../api/public/index.html'),
assetsRoot: path.resolve(__dirname, '../../api/public'),
assetsSubDirectory: 'static',
assetsPublicPath: '/',
productionSourceMap: true,
// Gzip off by default as many popular static hosts such as
// Surge or Netlify already gzip all static assets for you.
// Before setting to `true`, make sure to:
// npm install --save-dev compression-webpack-plugin
productionGzip: false,
productionGzipExtensions: ['js', 'css'],
// Run the build command with an extra argument to
// View the bundle analyzer report after build finishes:
// `npm run build --report`
// Set to `true` or `false` to always turn it on or off
bundleAnalyzerReport: process.env.npm_config_report
},
dev: {
env: require('./dev.env'),
port: 8080,
autoOpenBrowser: true,
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {},
// CSS Sourcemaps off by default because relative paths are "buggy"
// with this option, according to the CSS-Loader README
// (https://github.com/webpack/css-loader#sourcemaps)
// In our experience, they generally work as expected,
// just be aware of this issue when enabling this option.
cssSourceMap: false
}
}

View File

@@ -1,3 +0,0 @@
module.exports = {
NODE_ENV: '"production"'
}

View File

@@ -1,6 +0,0 @@
var merge = require('webpack-merge')
var devEnv = require('./dev.env')
module.exports = merge(devEnv, {
NODE_ENV: '"testing"'
})

View File

@@ -1,13 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>myPrayerJournal</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
</head>
<body>
<div id="app"></div>
<!-- built files will be auto injected -->
</body>
</html>

View File

@@ -1,104 +0,0 @@
{
"name": "my-prayer-journal",
"version": "0.8.4",
"description": "myPrayerJournal - Front End",
"author": "Daniel J. Summers <daniel@bitbadger.solutions>",
"private": true,
"scripts": {
"dev": "node build/dev-server.js",
"start": "node build/dev-server.js",
"build": "node build/build.js",
"unit": "cross-env BABEL_ENV=test karma start test/unit/karma.conf.js --single-run",
"e2e": "node test/e2e/runner.js",
"test": "npm run unit && npm run e2e",
"lint": "eslint --ext .js,.vue src test/unit/specs test/e2e/specs"
},
"dependencies": {
"auth0-js": "^8.10.1",
"axios": "^0.16.2",
"bootstrap-vue": "^1.0.0-beta.9",
"moment": "^2.18.1",
"pug": "^2.0.0-rc.4",
"vue": "^2.4.4",
"vue-awesome": "^2.3.3",
"vue-progressbar": "^0.7.3",
"vue-router": "^2.6.0",
"vue-toast": "^3.1.0",
"vuex": "^2.4.0"
},
"devDependencies": {
"autoprefixer": "^7.1.4",
"babel-core": "^6.26.0",
"babel-eslint": "^7.1.1",
"babel-loader": "^7.1.2",
"babel-plugin-istanbul": "^4.1.5",
"babel-plugin-transform-runtime": "^6.22.0",
"babel-preset-env": "^1.3.2",
"babel-preset-stage-2": "^6.22.0",
"babel-register": "^6.26.0",
"chai": "^3.5.0",
"chalk": "^2.1.0",
"chromedriver": "^2.32.3",
"connect-history-api-fallback": "^1.3.0",
"copy-webpack-plugin": "^4.0.1",
"cross-env": "^5.0.5",
"cross-spawn": "^5.0.1",
"css-loader": "^0.28.7",
"cssnano": "^3.10.0",
"eslint": "^3.19.0",
"eslint-config-standard": "^6.2.1",
"eslint-friendly-formatter": "^3.0.0",
"eslint-loader": "^1.7.1",
"eslint-plugin-html": "^3.2.2",
"eslint-plugin-promise": "^3.4.0",
"eslint-plugin-standard": "^2.0.1",
"eventsource-polyfill": "^0.9.6",
"express": "^4.15.4",
"extract-text-webpack-plugin": "^2.0.0",
"file-loader": "^0.11.1",
"friendly-errors-webpack-plugin": "^1.1.3",
"html-webpack-plugin": "^2.30.1",
"http-proxy-middleware": "^0.17.3",
"inject-loader": "^3.0.1",
"karma": "^1.7.1",
"karma-coverage": "^1.1.1",
"karma-mocha": "^1.3.0",
"karma-phantomjs-launcher": "^1.0.2",
"karma-phantomjs-shim": "^1.4.0",
"karma-sinon-chai": "^1.3.2",
"karma-sourcemap-loader": "^0.3.7",
"karma-spec-reporter": "0.0.31",
"karma-webpack": "^2.0.2",
"lolex": "^1.5.2",
"mocha": "^3.5.3",
"nightwatch": "^0.9.12",
"opn": "^5.1.0",
"optimize-css-assets-webpack-plugin": "^2.0.0",
"ora": "^1.2.0",
"phantomjs-prebuilt": "^2.1.15",
"rimraf": "^2.6.2",
"selenium-server": "^3.5.3",
"semver": "^5.4.1",
"shelljs": "^0.7.6",
"sinon": "^2.4.1",
"sinon-chai": "^2.13.0",
"url-loader": "^0.5.8",
"vue-loader": "^12.1.0",
"vue-style-loader": "^3.0.3",
"vue-template-compiler": "^2.4.4",
"webpack": "^2.6.1",
"webpack-bundle-analyzer": "^2.9.0",
"webpack-dev-middleware": "^1.12.0",
"webpack-hot-middleware": "^2.19.1",
"webpack-merge": "^4.1.0"
},
"engines": {
"node": ">= 4.0.0",
"npm": ">= 3.0.0"
},
"browserslist": [
"> 1%",
"last 2 versions",
"not ie <= 8"
]
}

View File

@@ -1,57 +0,0 @@
<template lang="pug">
#app
navigation
#content.container
router-view
vue-progress-bar
toast(ref='toast')
footer
p.text-right: i myPrayerJournal v0.8.4
</template>
<script>
'use strict'
import Navigation from './components/Navigation.vue'
export default {
name: 'app',
components: {
Navigation
},
mounted () {
this.$refs.toast.setOptions({ position: 'bottom right' })
},
computed: {
toast () {
return this.$refs.toast
}
}
}
</script>
<style>
html, body {
background-color: whitesmoke;
}
body {
padding-top: 60px;
}
footer {
border-top: solid 1px lightgray;
margin-top: 1rem;
padding: 0 1rem;
}
footer p {
margin: 0;
}
.mpj-request-text {
white-space: pre-line;
}
.bg-mpj {
background-image: -webkit-gradient(linear, left top, left bottom, from(#050), to(whitesmoke));
background-image: -webkit-linear-gradient(top, #050, whitesmoke);
background-image: -moz-linear-gradient(top, #050, whitesmoke);
background-image: linear-gradient(to bottom, #050, whitesmoke);
}
</style>

View File

@@ -1,73 +0,0 @@
import axios from 'axios'
const http = axios.create({
baseURL: 'http://localhost:3000/api/'
})
/**
* API access for myPrayerJournal
*/
export default {
/**
* Set the bearer token for all future requests
* @param {string} token The token to use to identify the user to the server
*/
setBearer: token => { http.defaults.headers.common['authorization'] = `Bearer ${token}` },
/**
* Remove the bearer token
*/
removeBearer: () => delete http.defaults.headers.common['authorization'],
/**
* Get all prayer requests and their most recent updates
*/
journal: () => http.get('journal/'),
/**
* Add a note for a prayer request
* @param {string} requestId The Id of the request to which the note applies
* @param {string} notes The notes to be added
*/
addNote: (requestId, notes) => http.post(`request/${requestId}/note`, { notes }),
/**
* Add a new prayer request
* @param {string} requestText The text of the request to be added
*/
addRequest: requestText => http.post('request/', { requestText }),
/**
* Update a prayer request
* @param request The request (should have requestId, status, and updateText properties)
*/
updateRequest: request => http.post(`request/${request.requestId}/history`, {
status: request.status,
updateText: request.updateText
}),
/**
* Get a prayer request (journal-style; only latest update)
* @param {string} requestId The Id of the request to retrieve
*/
getRequest: requestId => http.get(`request/${requestId}`),
/**
* Get a prayer request (full; includes all history)
* @param {string} requestId The Id of the request to retrieve
*/
getFullRequest: requestId => http.get(`request/${requestId}/full`),
/**
* Get all answered requests, along with the text they had when it was answered
*/
getAnsweredRequests: () => http.get('request/answered'),
/**
* Get past notes for a prayer request
* @param {string} requestId The Id of the request for which notes should be retrieved
*/
getNotes: requestId => http.get(`request/${requestId}/notes`)
}

View File

@@ -1,139 +0,0 @@
'use strict'
import auth0 from 'auth0-js'
import AUTH_CONFIG from './auth0-variables'
import mutations from '@/store/mutation-types'
var tokenRenewalTimeout
export default class AuthService {
constructor () {
this.login = this.login.bind(this)
this.setSession = this.setSession.bind(this)
this.logout = this.logout.bind(this)
this.isAuthenticated = this.isAuthenticated.bind(this)
}
auth0 = new auth0.WebAuth({
domain: AUTH_CONFIG.domain,
clientID: AUTH_CONFIG.clientId,
redirectUri: AUTH_CONFIG.appDomain + AUTH_CONFIG.callbackUrl,
audience: `https://${AUTH_CONFIG.domain}/userinfo`,
responseType: 'token id_token',
scope: 'openid profile email'
})
login () {
this.auth0.authorize()
}
/**
* Promisified parseHash function
*/
parseHash () {
return new Promise((resolve, reject) => {
this.auth0.parseHash((err, authResult) => {
if (err) {
reject(err)
} else {
resolve(authResult)
}
})
})
}
/**
* Promisified userInfo function
*
* @param token The auth token from the login result
*/
userInfo (token) {
return new Promise((resolve, reject) => {
this.auth0.client.userInfo(token, (err, user) => {
if (err) {
reject(err)
} else {
resolve(user)
}
})
})
}
handleAuthentication (store, router) {
this.parseHash()
.then(authResult => {
if (authResult && authResult.accessToken && authResult.idToken) {
this.setSession(authResult)
this.userInfo(authResult.accessToken)
.then(user => {
store.commit(mutations.USER_LOGGED_ON, user)
router.replace('/journal')
})
}
})
.catch(err => {
router.replace('/')
console.log(err)
alert(`Error: ${err.error}. Check the console for further details.`)
})
}
scheduleRenewal () {
let expiresAt = JSON.parse(localStorage.getItem('expires_at'))
let delay = expiresAt - Date.now()
if (delay > 0) {
tokenRenewalTimeout = setTimeout(() => {
this.renewToken()
}, delay)
}
}
setSession (authResult) {
// Set the time that the access token will expire at
let expiresAt = JSON.stringify(
authResult.expiresIn * 1000 + new Date().getTime()
)
localStorage.setItem('access_token', authResult.accessToken)
localStorage.setItem('id_token', authResult.idToken)
localStorage.setItem('expires_at', expiresAt)
this.scheduleRenewal()
}
renewToken () {
console.log('attempting renewal...')
this.auth0.renewAuth(
{
audience: `https://${AUTH_CONFIG.domain}/userinfo`,
redirectUri: `${AUTH_CONFIG.appDomain}/static/silent.html`,
usePostMessage: true
},
(err, result) => {
if (err) {
console.log(err)
} else {
this.setSession(result)
}
}
)
}
logout (store, router) {
// Clear access token and ID token from local storage
clearTimeout(tokenRenewalTimeout)
localStorage.removeItem('access_token')
localStorage.removeItem('id_token')
localStorage.removeItem('expires_at')
localStorage.setItem('user_profile', JSON.stringify({}))
// navigate to the home route
store.commit(mutations.USER_LOGGED_OFF)
router.replace('/')
}
isAuthenticated () {
// Check whether the current time is past the access token's expiry time
let expiresAt = JSON.parse(localStorage.getItem('expires_at'))
return new Date().getTime() < expiresAt
}
}

View File

@@ -1,64 +0,0 @@
<template lang="pug">
article
page-title(title='Answered Requests')
p(v-if='!loaded') Loading answered requests...
div(v-if='loaded')
p.mpj-request-text(v-for='req in requests' :key='req.requestId')
b-btn(@click='showFull(req.requestId)'
size='sm'
variant='outline-secondary')
icon(name='search')
| &nbsp;View Full Request
| &nbsp; &nbsp; {{ req.text }} &nbsp;
small.text-muted: em.
(Answered #[date-from-now(:value='req.asOf')])
full-request(:events='eventBus')
</template>
<script>
'use static'
import Vue from 'vue'
import FullRequest from './request/FullRequest'
import api from '@/api'
export default {
name: 'answered',
components: {
FullRequest
},
data () {
return {
eventBus: new Vue(),
requests: [],
loaded: false
}
},
computed: {
toast () {
return this.$parent.$refs.toast
}
},
async mounted () {
this.$Progress.start()
try {
const reqs = await api.getAnsweredRequests()
this.requests = reqs.data
this.$Progress.finish()
} catch (err) {
console.error(err)
this.toast.showToast('Error loading requests; check console for details', { theme: 'danger' })
this.$Progress.fail()
} finally {
this.loaded = true
}
},
methods: {
showFull (requestId) {
this.eventBus.$emit('full', requestId)
}
}
}
</script>

View File

@@ -1,22 +0,0 @@
<template lang="pug">
article
page-title(title='Welcome!'
hideOnPage='true')
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.&nbsp; It will also
allow individuals to review their answered prayers.
p.
This site is currently in very limited alpha, as it is being developed with a core group of test users.&nbsp; If
this is something in which you are interested, check back around mid-November 2017 for an update on the
development progress.
</template>
<script>
'use strict'
export default {
name: 'home'
}
</script>

View File

@@ -1,68 +0,0 @@
<template lang="pug">
article
page-title(:title='title')
p(v-if='isLoadingJournal') Loading your prayer journal...
template(v-if='!isLoadingJournal')
new-request
br
request-list-item(v-if='journal.length > 0'
v-for='row in journalCardRows'
:row='row'
:events='eventBus'
:toast='toast'
:key='row[0].requestId')
p.text-center(v-if='journal.length === 0'): em No requests found; click the "Add a New Request" button to add one
edit-request(:events='eventBus'
:toast='toast')
notes-edit(:events='eventBus'
:toast='toast')
full-request(:events='eventBus')
</template>
<script>
'use strict'
import Vue from 'vue'
import { mapState } from 'vuex'
import chunk from 'lodash/chunk'
import EditRequest from './request/EditRequest'
import FullRequest from './request/FullRequest'
import NewRequest from './request/NewRequest'
import NotesEdit from './request/NotesEdit'
import RequestListItem from './request/RequestListItem'
import actions from '@/store/action-types'
export default {
name: 'journal',
components: {
EditRequest,
FullRequest,
NewRequest,
NotesEdit,
RequestListItem
},
data () {
return {
eventBus: new Vue()
}
},
computed: {
title () {
return `${this.user.given_name}'s Prayer Journal`
},
journalCardRows () {
return chunk(this.journal, 3)
},
toast () {
return this.$parent.$refs.toast
},
...mapState(['user', 'journal', 'isLoadingJournal'])
},
async created () {
await this.$store.dispatch(actions.LOAD_JOURNAL, this.$Progress)
this.toast.showToast(`Loaded ${this.journal.length} prayer requests`, { theme: 'success' })
}
}
</script>

View File

@@ -1,49 +0,0 @@
<template lang="pug">
b-navbar(toggleable='sm'
type='dark'
variant='mpj'
fixed='top')
b-nav-toggle(target='nav_collapse')
b-navbar-brand(to='/')
span(style='font-weight:100;') my
span(style='font-weight:600;') Prayer
span(style='font-weight:700;') Journal
b-collapse#nav_collapse(is-nav)
b-nav(is-nav-bar)
b-nav-item(v-if='isAuthenticated'
to='/journal') Journal
b-nav-item(v-if='isAuthenticated'
to='/answered') Answered
b-nav-item(v-if='isAuthenticated'): a(@click.stop='logOff()') Log Off
b-nav-item(v-if='!isAuthenticated'): a(@click.stop='logOn()') Log On
b-nav-item(href='https://danieljsummers.github.io/myPrayerJournal/'
target='_blank'
@click.stop='') Docs
</template>
<script>
'use strict'
import { mapState } from 'vuex'
import AuthService from '@/auth/AuthService'
export default {
name: 'navigation',
data () {
return {
auth0: new AuthService()
}
},
computed: {
...mapState([ 'isAuthenticated' ])
},
methods: {
logOn () {
this.auth0.login()
},
logOff () {
this.auth0.logout(this.$store, this.$router)
}
}
}
</script>

View File

@@ -1,52 +0,0 @@
<script>
'use strict'
import moment from 'moment'
export default {
name: 'date-from-now',
props: {
tag: {
type: String,
default: 'span'
},
value: {
type: Number,
default: 0
},
interval: {
type: Number,
default: 10000
}
},
data () {
const dt = moment(this.value)
return {
fromNow: dt.fromNow(),
actual: dt.format('LLLL'),
intervalId: null
}
},
mounted () {
this.intervalId = setInterval(this.updateFromNow, this.interval)
this.$watch('value', this.updateFromNow)
},
beforeDestroy () {
clearInterval(this.intervalId)
},
methods: {
updateFromNow () {
let newFromNow = moment(this.value).fromNow()
if (newFromNow !== this.fromNow) this.fromNow = newFromNow
}
},
render (createElement) {
return createElement(this.tag, {
domProps: {
title: this.actual,
innerText: this.fromNow
}
})
}
}
</script>

View File

@@ -1,35 +0,0 @@
<template lang="pug">
h2.mpj-page-title(v-if='!hideOnPage'
v-html='title')
</template>
<script>
export default {
name: 'page-title',
props: {
title: {
type: String,
required: true
},
hideOnPage: {
type: Boolean,
default: false
}
},
watch: {
title () {
document.title = `${this.title} « myPrayerJournal`
}
},
created () {
document.title = `${this.title} « myPrayerJournal`
}
}
</script>
<style scoped>
.mpj-page-title {
border-bottom: solid 1px lightgray;
margin-bottom: 20px;
}
</style>

View File

@@ -1,89 +0,0 @@
<template lang="pug">
b-modal(v-model='editVisible'
header-bg-variant='mpj'
header-text-variant='light'
size='lg'
title='Edit Prayer Request'
@edit='openDialog()'
@shows='focusRequestText')
b-form
b-form-group(label='Prayer Request'
label-for='request_text')
b-textarea#request_text(ref='toFocus'
v-model='form.requestText'
:rows='10'
@blur='trimText()')
b-form-group(label='Also Mark As')
b-radio-group(v-model='form.status'
buttons)
b-radio(value='Updated') Updated
b-radio(value='Prayed') Prayed
b-radio(value='Answered') Answered
div.w-100.text-right(slot='modal-footer')
b-btn(variant='primary'
@click='saveRequest()') Save
| &nbsp; &nbsp;
b-btn(variant='outline-secondary'
@click='closeDialog()') Cancel
</template>
<script>
'use strict'
import actions from '@/store/action-types'
export default {
name: 'edit-request',
props: {
toast: { required: true },
events: { required: true }
},
data () {
return {
editVisible: false,
form: {
requestId: '',
requestText: '',
status: 'Updated'
}
}
},
created () {
this.events.$on('edit', this.openDialog)
},
methods: {
closeDialog () {
this.form.requestId = ''
this.form.requestText = ''
this.form.status = 'Updated'
this.editVisible = false
},
focusRequestText (e) {
this.$refs.toFocus.focus()
},
openDialog (request) {
this.form.requestId = request.requestId
this.form.requestText = request.text
this.editVisible = true
this.focusRequestText(null)
},
trimText () {
this.form.requestText = this.form.requestText.trim()
},
async saveRequest () {
await this.$store.dispatch(actions.UPDATE_REQUEST, {
progress: this.$Progress,
requestId: this.form.requestId,
updateText: this.form.requestText,
status: this.form.status
})
if (this.form.status === 'Answered') {
this.toast.showToast('Request updated and removed from active journal', { theme: 'success' })
} else {
this.toast.showToast('Request updated', { theme: 'success' })
}
this.closeDialog()
}
}
}
</script>

View File

@@ -1,57 +0,0 @@
<template lang="pug">
span
b-modal(v-model='historyVisible'
header-bg-variant='mpj'
header-text-variant='light'
size='lg'
title='Prayer Request History'
@shows='focusRequestText')
b-list-group(v-if='null !== full'
flush)
full-request-history(v-for='item in full.history'
:key='item.asOf'
:history='item')
div.w-100.text-right(slot='modal-footer')
b-btn(variant='primary'
@click='closeDialog()') Close
</template>
<script>
'use strict'
import FullRequestHistory from './FullRequestHistory'
import api from '@/api'
export default {
name: 'full-request',
components: {
FullRequestHistory
},
props: {
events: { required: true }
},
data () {
return {
historyVisible: false,
full: null
}
},
created () {
this.events.$on('full', this.openDialog)
},
methods: {
closeDialog () {
this.full = null
this.historyVisible = false
},
async openDialog (requestId) {
this.historyVisible = true
this.$Progress.start()
const req = await api.getFullRequest(requestId)
this.full = req.data
this.$Progress.finish()
}
}
}
</script>

View File

@@ -1,28 +0,0 @@
<template lang="pug">
b-list-group-item
| {{ history.status }}
|
small.text-muted {{ asOf }}
div(v-if='hasText').mpj-request-text {{ history.text }}
</template>
<script>
'use strict'
import moment from 'moment'
export default {
name: 'full-request-history',
props: {
history: { required: true }
},
computed: {
asOf () {
return moment(this.history.asOf).fromNow()
},
hasText () {
return this.history.text.length > 0
}
}
}
</script>

View File

@@ -1,71 +0,0 @@
<template lang="pug">
div
b-btn(@click='openDialog()' size='sm' variant='primary')
icon(name='plus')
| &nbsp; Add a New Request
b-modal(v-model='showNewVisible'
header-bg-variant='mpj'
header-text-variant='light'
size='lg'
title='Add a New Prayer Request'
@shown='focusRequestText')
b-form
b-form-group(label='Prayer Request'
label-for='request_text')
b-textarea#request_text(ref='toFocus'
v-model='form.requestText'
:rows='10'
@blur='trimText()')
div.w-100.text-right(slot='modal-footer')
b-btn(variant='primary'
@click='saveRequest()') Save
| &nbsp; &nbsp;
b-btn(variant='outline-secondary'
@click='closeDialog()') Cancel
toast(ref='toast')
</template>
<script>
'use strict'
import actions from '@/store/action-types'
export default {
name: 'new-request',
data () {
return {
showNewVisible: false,
form: {
requestText: ''
},
formLabelWidth: '120px'
}
},
mounted () {
this.$refs.toast.setOptions({ position: 'bottom right' })
},
methods: {
closeDialog () {
this.form.requestText = ''
this.showNewVisible = false
},
focusRequestText (e) {
this.$refs.toFocus.focus()
},
openDialog () {
this.showNewVisible = true
},
trimText () {
this.form.requestText = this.form.requestText.trim()
},
async saveRequest () {
await this.$store.dispatch(actions.ADD_REQUEST, {
progress: this.$Progress,
requestText: this.form.requestText
})
this.$refs.toast.showToast('New prayer request added', { theme: 'success' })
this.closeDialog()
}
}
}
</script>

View File

@@ -1,116 +0,0 @@
<template lang="pug">
b-modal(v-model='notesVisible'
header-bg-variant='mpj'
header-text-variant='light'
size='lg'
title='Add Notes to Prayer Request'
@edit='openDialog()'
@shows='focusNotes')
b-form
b-form-group(label='Notes'
label-for='notes')
b-textarea#notes(ref='toFocus'
v-model='form.notes'
:rows='10'
@blur='trimText()')
div(v-if='hasPriorNotes')
p.text-center: strong Prior Notes for This Request
b-list-group(flush)
b-list-group-item(v-for='note in priorNotes'
:key='note.asOf')
small.text-muted: date-from-now(:value='note.asOf')
br
div.mpj-request-text {{ note.notes }}
div(v-if='noPriorNotes').text-center.text-muted There are no prior notes for this request
div(v-if='!priorNotesLoaded').text-center
b-btn(variant='outline-secondary'
@click='loadNotes()') Load Prior Notes
div.w-100.text-right(slot='modal-footer')
b-btn(variant='primary'
@click='saveNotes()') Save
| &nbsp; &nbsp;
b-btn(variant='outline-secondary'
@click='closeDialog()') Cancel
</template>
<script>
'use strict'
import api from '@/api'
export default {
name: 'notes-edit',
props: {
toast: { required: true },
events: { required: true }
},
data () {
return {
notesVisible: false,
form: {
requestId: '',
notes: ''
},
priorNotes: [],
priorNotesLoaded: false
}
},
computed: {
hasPriorNotes () {
return this.priorNotesLoaded && this.priorNotes.length > 0
},
noPriorNotes () {
return this.priorNotesLoaded && this.priorNotes.length === 0
}
},
created () {
this.events.$on('notes', this.openDialog)
},
methods: {
closeDialog () {
this.form.requestId = ''
this.form.notes = ''
this.priorNotes = []
this.priorNotesLoaded = false
this.notesVisible = false
},
focusNotes (e) {
this.$refs.toFocus.focus()
},
async loadNotes () {
this.$Progress.start()
try {
const notes = await api.getNotes(this.form.requestId)
this.priorNotes = notes.data
console.log(this.priorNotes)
this.$Progress.finish()
} catch (e) {
console.error(e)
this.$Progress.fail()
} finally {
this.priorNotesLoaded = true
}
},
openDialog (request) {
this.form.requestId = request.requestId
this.notesVisible = true
this.focusNotes(null)
},
async saveNotes () {
this.$Progress.start()
try {
await api.addNote(this.form.requestId, this.form.notes)
this.$Progress.finish()
this.toast.showToast('Added notes', { theme: 'success' })
this.closeDialog()
} catch (e) {
console.error(e)
this.$Progress.fail()
}
},
trimText () {
this.form.notes = this.form.notes.trim()
}
}
}
</script>

View File

@@ -1,57 +0,0 @@
<template lang="pug">
div
b-card-group.w-100(deck)
b-card(v-for='(request, idx) in row'
:key='request.requestId'
border-variant='dark'
no-body)
b-card-header.text-center.py-1.
#[b-btn(@click='markPrayed(idx)' variant='outline-primary' title='Pray' size='sm'): icon(name='check')]
#[b-btn(@click.stop='showEdit(request)' variant='outline-secondary' title='Edit' size='sm'): icon(name='pencil')]
#[b-btn(@click.stop='showNotes(request)' variant='outline-secondary' title='Add Notes' size='sm'): icon(name='file-text-o')]
#[b-btn(@click.stop='showFull(idx)' variant='outline-secondary' title='View Full Request' size='sm'): icon(name='search')]
b-card-body.p-0
p.card-text.mpj-request-text.mb-1.px-3.pt-3
| {{ request.text }}
p.card-text.p-0.pr-1.text-right: small.text-muted: em
= '(last activity '
date-from-now(:value='request.asOf')
| )
b-card(v-for='it in 3 - row.length')
br
</template>
<script>
'use strict'
import actions from '@/store/action-types'
export default {
name: 'request-list-item',
props: {
row: { required: true },
toast: { required: true },
events: { required: true }
},
methods: {
async markPrayed (idx) {
await this.$store.dispatch(actions.UPDATE_REQUEST, {
progress: this.$Progress,
requestId: this.row[idx].requestId,
status: 'Prayed',
updateText: ''
})
this.toast.showToast('Request marked as prayed', { theme: 'success' })
},
showEdit (request) {
this.events.$emit('edit', request)
},
showFull (idx) {
this.events.$emit('full', this.row[idx].requestId)
},
showNotes (request) {
this.events.$emit('notes', request)
}
}
}
</script>

View File

@@ -1,20 +0,0 @@
<template lang="pug">
article
pageTitle(title='Logging On')
p Logging you on...
</template>
<script>
'use strict'
import AuthService from '@/auth/AuthService'
export default {
name: 'log-on',
created () {
this.$Progress.start()
new AuthService().handleAuthentication(this.$store, this.$router)
// Auth service redirects to dashboard, which restarts the progress bar
}
}
</script>

View File

@@ -1,52 +0,0 @@
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import BootstrapVue from 'bootstrap-vue'
import Icon from 'vue-awesome/components/Icon'
import VueProgressBar from 'vue-progressbar'
import VueToast from 'vue-toast'
import 'bootstrap-vue/dist/bootstrap-vue.css'
import 'bootstrap/dist/css/bootstrap.css'
import 'vue-toast/dist/vue-toast.min.css'
// Only import the icons we need; the whole set is ~500K!
import 'vue-awesome/icons/check'
import 'vue-awesome/icons/file-text-o'
import 'vue-awesome/icons/pencil'
import 'vue-awesome/icons/plus'
import 'vue-awesome/icons/search'
import App from './App'
import router from './router'
import store from './store'
import DateFromNow from './components/common/DateFromNow'
import PageTitle from './components/common/PageTitle'
Vue.config.productionTip = false
Vue.use(BootstrapVue)
Vue.use(VueProgressBar, {
color: 'yellow',
failedColor: 'red',
height: '5px',
transition: {
speed: '0.2s',
opacity: '0.6s',
termination: 1000
}
})
Vue.component('icon', Icon)
Vue.component('date-from-now', DateFromNow)
Vue.component('page-title', PageTitle)
Vue.component('toast', VueToast)
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store,
template: '<App/>',
components: { App }
})

View File

@@ -1,19 +0,0 @@
import Vue from 'vue'
import Router from 'vue-router'
import Answered from '@/components/Answered'
import Home from '@/components/Home'
import Journal from '@/components/Journal'
import LogOn from '@/components/user/LogOn'
Vue.use(Router)
export default new Router({
mode: 'history',
routes: [
{ path: '/', name: 'Home', component: Home },
{ path: '/answered', name: 'Answered', component: Answered },
{ path: '/journal', name: 'Journal', component: Journal },
{ path: '/user/log-on', name: 'LogOn', component: LogOn }
]
})

View File

@@ -1,10 +0,0 @@
'use strict'
export default {
/** Action to add a prayer request (pass request text) */
ADD_REQUEST: 'add-request',
/** Action to load the user's prayer journal */
LOAD_JOURNAL: 'load-journal',
/** Action to update a request */
UPDATE_REQUEST: 'update-request'
}

View File

@@ -1,116 +0,0 @@
import Vue from 'vue'
import Vuex from 'vuex'
import api from '@/api'
import AuthService from '@/auth/AuthService'
import mutations from './mutation-types'
import actions from './action-types'
Vue.use(Vuex)
this.auth0 = new AuthService()
const logError = function (error) {
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.log(error.response.data)
console.log(error.response.status)
console.log(error.response.headers)
} else if (error.request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
console.log(error.request)
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error', error.message)
}
console.log(error.config)
}
export default new Vuex.Store({
state: {
user: JSON.parse(localStorage.getItem('user_profile') || '{}'),
isAuthenticated: (() => {
this.auth0.scheduleRenewal()
if (this.auth0.isAuthenticated()) {
api.setBearer(localStorage.getItem('id_token'))
}
return this.auth0.isAuthenticated()
})(),
journal: {},
isLoadingJournal: false
},
mutations: {
[mutations.LOADING_JOURNAL] (state, flag) {
state.isLoadingJournal = flag
},
[mutations.LOADED_JOURNAL] (state, journal) {
state.journal = journal
},
[mutations.REQUEST_ADDED] (state, newRequest) {
state.journal.push(newRequest)
},
[mutations.REQUEST_UPDATED] (state, request) {
let jrnl = state.journal.filter(it => it.requestId !== request.requestId)
if (request.lastStatus !== 'Answered') jrnl.push(request)
state.journal = jrnl
},
[mutations.USER_LOGGED_OFF] (state) {
state.user = {}
api.removeBearer()
state.isAuthenticated = false
},
[mutations.USER_LOGGED_ON] (state, user) {
localStorage.setItem('user_profile', JSON.stringify(user))
state.user = user
api.setBearer(localStorage.getItem('id_token'))
state.isAuthenticated = true
}
},
actions: {
async [actions.ADD_REQUEST] ({ commit }, { progress, requestText }) {
progress.start()
try {
const newRequest = await api.addRequest(requestText)
commit(mutations.REQUEST_ADDED, newRequest.data)
progress.finish()
} catch (err) {
logError(err)
progress.fail()
}
},
async [actions.LOAD_JOURNAL] ({ commit }, progress) {
commit(mutations.LOADED_JOURNAL, {})
progress.start()
commit(mutations.LOADING_JOURNAL, true)
api.setBearer(localStorage.getItem('id_token'))
try {
const jrnl = await api.journal()
commit(mutations.LOADED_JOURNAL, jrnl.data)
progress.finish()
} catch (err) {
logError(err)
progress.fail()
} finally {
commit(mutations.LOADING_JOURNAL, false)
}
},
async [actions.UPDATE_REQUEST] ({ commit }, { progress, requestId, status, updateText }) {
progress.start()
try {
await api.updateRequest({ requestId, status, updateText })
const request = await api.getRequest(requestId)
commit(mutations.REQUEST_UPDATED, request.data)
progress.finish()
} catch (err) {
logError(err)
progress.fail()
}
}
},
getters: {},
modules: {}
})

View File

@@ -1,16 +0,0 @@
'use strict'
export default {
/** Mutation for when the user's prayer journal is being loaded */
LOADING_JOURNAL: 'loading-journal',
/** Mutation for when the user's prayer journal has been loaded */
LOADED_JOURNAL: 'journal-loaded',
/** Mutation for adding a new prayer request (pass text) */
REQUEST_ADDED: 'request-added',
/** Mutation to replace a prayer request at the top of the current journal */
REQUEST_UPDATED: 'request-updated',
/** Mutation for logging a user off */
USER_LOGGED_OFF: 'user-logged-off',
/** Mutation for logging a user on (pass user) */
USER_LOGGED_ON: 'user-logged-on'
}

View File

@@ -1,22 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://cdn.auth0.com/js/auth0/8.9/auth0.min.js"></script>
<script>
var webAuth = new auth0.WebAuth({
domain: 'djs-consulting.auth0.com',
clientID: 'Of2s0RQCQ3mt3dwIkOBY5h85J9sXbF2n',
scope: 'openid profile email',
responseType: 'token id_token',
redirectUri: 'http://localhost:3000/static/silent.html'
})
</script>
<script>
webAuth.parseHash(window.location.hash, function (err, response) {
parent.postMessage(err || response, 'http://localhost:3000');
})
</script>
</head>
<body></body>
</html>

View File

@@ -1,26 +0,0 @@
// A custom Nightwatch assertion.
// the name of the method is the filename.
// can be used in tests like this:
//
// browser.assert.elementCount(selector, count)
//
// for how to write custom assertions see
// http://nightwatchjs.org/guide#writing-custom-assertions
exports.assertion = function (selector, count) {
this.message = 'Testing if element <' + selector + '> has count: ' + count
this.expected = count
this.pass = function (val) {
return val === this.expected
}
this.value = function (res) {
return res.value
}
this.command = function (cb) {
var self = this
return this.api.execute(function (selector) {
return document.querySelectorAll(selector).length
}, [selector], function (res) {
cb.call(self, res)
})
}
}

View File

@@ -1,46 +0,0 @@
require('babel-register')
var config = require('../../config')
// http://nightwatchjs.org/gettingstarted#settings-file
module.exports = {
src_folders: ['test/e2e/specs'],
output_folder: 'test/e2e/reports',
custom_assertions_path: ['test/e2e/custom-assertions'],
selenium: {
start_process: true,
server_path: require('selenium-server').path,
host: '127.0.0.1',
port: 4444,
cli_args: {
'webdriver.chrome.driver': require('chromedriver').path
}
},
test_settings: {
default: {
selenium_port: 4444,
selenium_host: 'localhost',
silent: true,
globals: {
devServerURL: 'http://localhost:' + (process.env.PORT || config.dev.port)
}
},
chrome: {
desiredCapabilities: {
browserName: 'chrome',
javascriptEnabled: true,
acceptSslCerts: true
}
},
firefox: {
desiredCapabilities: {
browserName: 'firefox',
javascriptEnabled: true,
acceptSslCerts: true
}
}
}
}

View File

@@ -1,33 +0,0 @@
// 1. start the dev server using production config
process.env.NODE_ENV = 'testing'
var server = require('../../build/dev-server.js')
server.ready.then(() => {
// 2. run the nightwatch test suite against it
// to run in additional browsers:
// 1. add an entry in test/e2e/nightwatch.conf.json under "test_settings"
// 2. add it to the --env flag below
// or override the environment flag, for example: `npm run e2e -- --env chrome,firefox`
// For more information on Nightwatch's config file, see
// http://nightwatchjs.org/guide#settings-file
var opts = process.argv.slice(2)
if (opts.indexOf('--config') === -1) {
opts = opts.concat(['--config', 'test/e2e/nightwatch.conf.js'])
}
if (opts.indexOf('--env') === -1) {
opts = opts.concat(['--env', 'chrome'])
}
var spawn = require('cross-spawn')
var runner = spawn('./node_modules/.bin/nightwatch', opts, { stdio: 'inherit' })
runner.on('exit', function (code) {
server.close()
process.exit(code)
})
runner.on('error', function (err) {
server.close()
throw err
})
})

View File

@@ -1,19 +0,0 @@
// For authoring Nightwatch tests, see
// http://nightwatchjs.org/guide#usage
module.exports = {
'default e2e tests': function (browser) {
// automatically uses dev Server port from /config.index.js
// default: http://localhost:8080
// see nightwatch.conf.js
const devServer = browser.globals.devServerURL
browser
.url(devServer)
.waitForElementVisible('#app', 5000)
.assert.elementPresent('.hello')
.assert.containsText('h1', 'Welcome to Your Vue.js App')
.assert.elementCount('img', 1)
.end()
}
}

View File

@@ -1,9 +0,0 @@
{
"env": {
"mocha": true
},
"globals": {
"expect": true,
"sinon": true
}
}

View File

@@ -1,13 +0,0 @@
import Vue from 'vue'
Vue.config.productionTip = false
// require all test files (files that ends with .spec.js)
const testsContext = require.context('./specs', true, /\.spec$/)
testsContext.keys().forEach(testsContext)
// require all src files except main.js for coverage.
// you can also change this to match only the subset of files that
// you want coverage for.
const srcContext = require.context('../../src', true, /^\.\/(?!main(\.js)?$)/)
srcContext.keys().forEach(srcContext)

View File

@@ -1,33 +0,0 @@
// This is a karma config file. For more details see
// http://karma-runner.github.io/0.13/config/configuration-file.html
// we are also using it with karma-webpack
// https://github.com/webpack/karma-webpack
var webpackConfig = require('../../build/webpack.test.conf')
module.exports = function (config) {
config.set({
// to run in additional browsers:
// 1. install corresponding karma launcher
// http://karma-runner.github.io/0.13/config/browsers.html
// 2. add it to the `browsers` array below.
browsers: ['PhantomJS'],
frameworks: ['mocha', 'sinon-chai', 'phantomjs-shim'],
reporters: ['spec', 'coverage'],
files: ['./index.js'],
preprocessors: {
'./index.js': ['webpack', 'sourcemap']
},
webpack: webpackConfig,
webpackMiddleware: {
noInfo: true
},
coverageReporter: {
dir: './coverage',
reporters: [
{ type: 'lcov', subdir: '.' },
{ type: 'text-summary' }
]
}
})
}

File diff suppressed because it is too large Load Diff

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

104
src/public/script/mpj.js Normal file
View File

@@ -0,0 +1,104 @@
"use strict"
/** myPrayerJournal script */
this.mpj = {
/**
* Show a message via toast
* @param {string} message The message to show
*/
showToast (message) {
const [level, msg] = message.split("|||")
let header
if (level !== "success") {
const heading = typ => `<span class="me-auto"><strong>${typ.toUpperCase()}</strong></span>`
header = document.createElement("div")
header.className = "toast-header"
header.innerHTML = heading(level === "warning" ? level : "error")
const close = document.createElement("button")
close.type = "button"
close.className = "btn-close"
close.setAttribute("data-bs-dismiss", "toast")
close.setAttribute("aria-label", "Close")
header.appendChild(close)
}
const body = document.createElement("div")
body.className = "toast-body"
body.innerText = msg
const toastEl = document.createElement("div")
toastEl.className = `toast bg-${level === "error" ? "danger" : level} text-white`
toastEl.setAttribute("role", "alert")
toastEl.setAttribute("aria-live", "assertlive")
toastEl.setAttribute("aria-atomic", "true")
toastEl.addEventListener("hidden.bs.toast", e => e.target.remove())
if (header) toastEl.appendChild(header)
toastEl.appendChild(body)
document.getElementById("toasts").appendChild(toastEl)
new bootstrap.Toast(toastEl, { autohide: level === "success" }).show()
},
/**
* Load local version of Bootstrap CSS if the CDN load failed
*/
ensureCss () {
let loaded = false
for (let i = 0; !loaded && i < document.styleSheets.length; i++) {
loaded = document.styleSheets[i].href.endsWith("bootstrap.min.css")
}
if (!loaded) {
const css = document.createElement("link")
css.rel = "stylesheet"
css.href = "/style/bootstrap.min.css"
document.getElementsByTagName("head")[0].appendChild(css)
}
},
/** Script for the request edit component */
edit: {
/**
* Toggle the recurrence input fields
* @param {Event} e The click event
*/
toggleRecurrence ({ target }) {
const isDisabled = target.value === "Immediate"
;["recurCount", "recurInterval"].forEach(it => document.getElementById(it).disabled = isDisabled)
}
},
/**
* The time zone of the current browser
* @type {string}
**/
timeZone: undefined,
/**
* Derive the time zone from the current browser
*/
deriveTimeZone () {
try {
this.timeZone = (new Intl.DateTimeFormat()).resolvedOptions().timeZone
} catch (_) { }
}
}
htmx.on("htmx:afterOnLoad", function (evt) {
const hdrs = evt.detail.xhr.getAllResponseHeaders()
// Show a message if there was one in the response
if (hdrs.indexOf("x-toast") >= 0) {
mpj.showToast(evt.detail.xhr.getResponseHeader("x-toast"))
}
// Hide a modal window if requested
if (hdrs.indexOf("x-hide-modal") >= 0) {
document.getElementById(evt.detail.xhr.getResponseHeader("x-hide-modal") + "Dismiss").click()
}
})
htmx.on("htmx:configRequest", function (evt) {
// Send the user's current time zone so that we can display local time
if (mpj.timeZone) {
evt.detail.headers["X-Time-Zone"] = mpj.timeZone
}
})
mpj.deriveTimeZone()

View File

@@ -0,0 +1,57 @@
nav {
background-color: green;
}
nav .m {
font-weight: 100;
}
nav .p {
font-weight: 400;
}
nav .j {
font-weight: 700;
}
.nav-item a:link,
.nav-item a:visited {
padding: .5rem 1rem;
margin: 0 .5rem;
border-radius: .5rem;
color: white;
text-decoration: none;
}
.nav-item a:hover {
cursor: pointer;
background-color: rgba(255, 255, 255, .2);
}
.nav-item a.is-active-route {
border-top-left-radius: 0;
border-top-right-radius: 0;
border-top: solid 4px rgba(255, 255, 255, .3);
}
form {
max-width: 60rem;
margin: auto;
}
.action-cell .material-icons {
font-size: 1.1rem ;
}
.material-icons {
vertical-align: bottom;
}
#toastHost {
position: sticky;
bottom: 0;
}
.request-text {
white-space: pre-line
}
footer {
border-top: solid 1px lightgray;
margin: 1rem -1rem 0;
padding: 0 1rem;
}
footer p {
margin: 0;
}

Some files were not shown because too many files have changed in this diff Show More