49 Commits

Author SHA1 Message Date
733a730591 Add order by field via library 2025-05-26 09:58:37 -04:00
0c1285eaa7 Format Dockerfile 2025-02-03 07:55:37 -05:00
c9ccfe8b68 Fix request search (#55); WIP on full htmx (#56)
- Removed fixi library (not a good fit)
2025-02-01 15:52:31 -05:00
2e5a1426f6 Migration runs successfully 2025-01-31 22:19:35 -05:00
05394b4461 Finish first cut of doc access (#55)
- Update paths for build.fs
- Remove unused/unneeded deps
2025-01-31 21:57:39 -05:00
14b0a58d98 WIP on doc queries (#55) 2025-01-31 17:24:12 -05:00
bade89dd37 Removed PrayerTracker from Test project path 2025-01-31 07:22:58 -05:00
26f408bb54 Removed PrayerTracker from UI project path 2025-01-31 07:19:53 -05:00
9d71177352 Removed PrayerTracker from Data project path 2025-01-31 07:15:13 -05:00
2b5ec692f2 Config conns for migration (#55)
- Update deps
2025-01-31 07:02:10 -05:00
d86249c18e Being migrating application to doc lib (#55) 2025-01-30 23:01:49 -05:00
194cd2b5cc First cut of migration program 2025-01-30 21:28:04 -05:00
42e3a58131 Move module funcs to properties 2025-01-30 20:36:00 -05:00
facc294d66 Convert module funcs to ToString/Parse 2025-01-30 19:22:45 -05:00
5240b78487 WIP on fixi implementation 2025-01-30 15:51:52 -05:00
7fb1eca2a3 Convert FAKE to project (#54) 2024-12-26 15:10:39 -05:00
ae8cf9ad80 Update to .NET 9 (#54)
- Update deps
- Fake build not working
2024-12-24 13:47:16 -05:00
bb79b38738 v8.4 (#53)
- Bring help into the application (#51)
- Dependency updates

Reviewed-on: #53
2024-06-29 00:22:43 +00:00
fdb8f2ebf1 Merge pull request 'Update to .NET 8 (#50)' (#52) from 8.3 into main
Reviewed-on: #52
2024-06-07 01:03:23 +00:00
0f9837c257 Merge branch 'main' into 8.3 2024-06-07 01:02:51 +00:00
51ad71074c Merge pull request 'Bump commonmarker from 0.23.9 to 0.23.10 in /docs' (#48) from dependabot/bundler/docs/commonmarker-0.23.10 into main
Reviewed-on: #48
2024-06-07 00:54:04 +00:00
377e19ca78 Merge branch 'main' into dependabot/bundler/docs/commonmarker-0.23.10 2024-06-07 00:53:50 +00:00
259cc91a11 Merge pull request 'Bump activesupport from 7.0.4.3 to 7.0.7.2 in /docs' (#49) from dependabot/bundler/docs/activesupport-7.0.7.2 into main
Reviewed-on: #49
2024-06-07 00:53:20 +00:00
131012b320 Update to .NET 8
- Update dependencies
- Replace document library
2024-06-05 22:32:00 -04:00
dependabot[bot]
cd41aef0ba Bump activesupport from 7.0.4.3 to 7.0.7.2 in /docs
Bumps [activesupport](https://github.com/rails/rails) from 7.0.4.3 to 7.0.7.2.
- [Release notes](https://github.com/rails/rails/releases)
- [Changelog](https://github.com/rails/rails/blob/v7.0.7.2/activesupport/CHANGELOG.md)
- [Commits](https://github.com/rails/rails/compare/v7.0.4.3...v7.0.7.2)

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

Signed-off-by: dependabot[bot] <support@github.com>
2023-08-23 21:43:25 +00:00
dependabot[bot]
8aa3e41f50 Bump commonmarker from 0.23.9 to 0.23.10 in /docs
Bumps [commonmarker](https://github.com/gjtorikian/commonmarker) from 0.23.9 to 0.23.10.
- [Release notes](https://github.com/gjtorikian/commonmarker/releases)
- [Changelog](https://github.com/gjtorikian/commonmarker/blob/v0.23.10/CHANGELOG.md)
- [Commits](https://github.com/gjtorikian/commonmarker/compare/v0.23.9...v0.23.10)

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

Signed-off-by: dependabot[bot] <support@github.com>
2023-08-08 20:26:42 +00:00
39af0fb9a5 Implement e-mail changes
- Add canonical domain handling
- Bump version
2023-07-12 20:46:01 -04:00
dd5f32e320 v8.1 (#47)
- Update to .NET 7
- Update database access to use data source vs. connection
- Allow e-mail server address to be configurable
- Support Docker hosting
2023-07-04 20:03:43 -04:00
370fbb0c3e Fix time zone in tests 2023-05-25 19:45:28 -04:00
14608de5be Update doc dependencies 2023-05-23 21:37:06 -04:00
ec6eea21c8 Merge pull request #45 from bit-badger/dependabot/nuget/src/PrayerTracker.UI/Newtonsoft.Json-13.0.2
Bump Newtonsoft.Json from 13.0.1 to 13.0.2 in /src/PrayerTracker.UI
2023-05-23 21:24:16 -04:00
dependabot[bot]
3b0d304595 Bump Newtonsoft.Json from 13.0.1 to 13.0.2 in /src/PrayerTracker.UI
Bumps [Newtonsoft.Json](https://github.com/JamesNK/Newtonsoft.Json) from 13.0.1 to 13.0.2.
- [Release notes](https://github.com/JamesNK/Newtonsoft.Json/releases)
- [Commits](https://github.com/JamesNK/Newtonsoft.Json/compare/13.0.1...13.0.2)

---
updated-dependencies:
- dependency-name: Newtonsoft.Json
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-12-08 14:53:23 +00:00
50a91cd725 Remove v8 migration code
(and prior)
2022-08-19 15:37:48 -04:00
13ace6ca61 Version 8 (#43)
* Use htmx for front end (#36)
* Use short GUIDs in URLs and forms (#1)
* Refresh theme (#38)
* Use ASP.NET Core for log on/off (#39)
* Fix date/time / time zone issues (#41)
* Update help for v8 (#42)
* Add FAKE build script (#37)
2022-08-19 15:08:30 -04:00
58519f9a4d Fix announcement send problem (#40) 2022-08-06 09:06:11 -04:00
6b1a5e31b5 Merge pull request #35 from bit-badger/dependabot/bundler/docs/nokogiri-1.13.6
Bump nokogiri from 1.11.4 to 1.13.6 in /docs
2022-08-01 16:24:04 -04:00
dependabot[bot]
d332322200 Bump nokogiri from 1.11.4 to 1.13.6 in /docs
Bumps [nokogiri](https://github.com/sparklemotion/nokogiri) from 1.11.4 to 1.13.6.
- [Release notes](https://github.com/sparklemotion/nokogiri/releases)
- [Changelog](https://github.com/sparklemotion/nokogiri/blob/main/CHANGELOG.md)
- [Commits](https://github.com/sparklemotion/nokogiri/compare/v1.11.4...v1.13.6)

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

Signed-off-by: dependabot[bot] <support@github.com>
2022-05-18 22:14:29 +00:00
dependabot[bot]
1d4e66b863 Bump nokogiri from 1.10.10 to 1.11.4 in /docs (#29)
Bumps [nokogiri](https://github.com/sparklemotion/nokogiri) from 1.10.10 to 1.11.4.
- [Release notes](https://github.com/sparklemotion/nokogiri/releases)
- [Changelog](https://github.com/sparklemotion/nokogiri/blob/main/CHANGELOG.md)
- [Commits](https://github.com/sparklemotion/nokogiri/compare/v1.10.10...v1.11.4)

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2021-09-18 22:47:29 -04:00
dependabot[bot]
8c3cce2fd8 Bump rexml from 3.2.4 to 3.2.5 in /docs (#28)
Bumps [rexml](https://github.com/ruby/rexml) from 3.2.4 to 3.2.5.
- [Release notes](https://github.com/ruby/rexml/releases)
- [Changelog](https://github.com/ruby/rexml/blob/master/NEWS.md)
- [Commits](https://github.com/ruby/rexml/compare/v3.2.4...v3.2.5)

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2021-09-18 22:46:58 -04:00
dependabot[bot]
0de3eac7be Bump addressable from 2.7.0 to 2.8.0 in /docs (#30)
Bumps [addressable](https://github.com/sporkmonger/addressable) from 2.7.0 to 2.8.0.
- [Release notes](https://github.com/sporkmonger/addressable/releases)
- [Changelog](https://github.com/sporkmonger/addressable/blob/main/CHANGELOG.md)
- [Commits](https://github.com/sporkmonger/addressable/compare/addressable-2.7.0...addressable-2.8.0)

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

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2021-09-18 22:45:35 -04:00
1a07c673c7 .NET 6 (#32)
- Convert back-end to .NET 6
- Upgrade Giraffe, convert routing to endpoint style
- Refactor code to take advantage of F# advances
2021-09-18 22:42:40 -04:00
665d80261d Update deps for GitHub Pages 2020-11-16 08:21:08 -05:00
b0d3bd4e35 Update to F# 5 (#27) 2020-11-15 21:57:09 -05:00
e3583f9152 Update branch name in AppVeyor link 2020-06-19 16:36:00 -05:00
7fd15a5cff Display new user name (#26)
Also did some refactoring to pull static members into modules
2020-06-10 23:11:28 -05:00
Daniel J. Summers
cb8c2558e0 Update to .NET Core 3.1 (and deps) (#25) 2020-03-07 12:22:39 -06:00
ffc008e07a Merge pull request #24 from bit-badger/dependabot/bundler/docs/nokogiri-1.10.8
Bump nokogiri from 1.10.4 to 1.10.8 in /docs
2020-03-07 11:24:51 -06:00
dependabot[bot]
81445d48f3 Bump nokogiri from 1.10.4 to 1.10.8 in /docs
Bumps [nokogiri](https://github.com/sparklemotion/nokogiri) from 1.10.4 to 1.10.8.
- [Release notes](https://github.com/sparklemotion/nokogiri/releases)
- [Changelog](https://github.com/sparklemotion/nokogiri/blob/master/CHANGELOG.md)
- [Commits](https://github.com/sparklemotion/nokogiri/compare/v1.10.4...v1.10.8)

Signed-off-by: dependabot[bot] <support@github.com>
2020-02-25 21:22:27 +00:00
Daniel J. Summers
1c33c1368f Change from address (#23) 2019-12-02 21:37:27 -06:00
116 changed files with 9266 additions and 9081 deletions

13
.config/dotnet-tools.json Normal file
View File

@@ -0,0 +1,13 @@
{
"version": 1,
"isRoot": true,
"tools": {
"fake-cli": {
"version": "6.1.3",
"commands": [
"fake"
],
"rollForward": false
}
}
}

4
.gitignore vendored
View File

@@ -332,3 +332,7 @@ ASALocalRun/
### --- ### ### --- ###
src/PrayerTracker/appsettings.json src/PrayerTracker/appsettings.json
docs/_site docs/_site
**/*.db*
.ionide
.vscode

View File

@@ -1,6 +1,6 @@
# PrayerTracker # PrayerTracker
[![Build status](https://ci.appveyor.com/api/projects/status/j5nt9o3pu7er7hyi/branch/master?svg=true)](https://ci.appveyor.com/project/danieljsummers/prayertracker/branch/master) [![Build status](https://ci.appveyor.com/api/projects/status/j5nt9o3pu7er7hyi/branch/main?svg=true)](https://ci.appveyor.com/project/danieljsummers/prayertracker/branch/main)
### Visit the Site ### Visit the Site

50
build.fs Normal file
View File

@@ -0,0 +1,50 @@
open Fake.Core
open Fake.DotNet
open Fake.IO
open Fake.IO.Globbing.Operators
let execContext = Context.FakeExecutionContext.Create false "build.fsx" []
Context.setExecutionContext (Context.RuntimeContext.Fake execContext)
/// The root path to the projects within this solution
let projPath = "src"
Target.create "Clean" (fun _ ->
!! "src/**/bin"
++ "src/**/obj"
|> Shell.cleanDirs
)
Target.create "Test" (fun _ ->
let testPath = $"{projPath}/Tests"
DotNet.build (fun opts -> { opts with NoLogo = true }) $"{testPath}/PrayerTracker.Tests.fsproj"
Testing.Expecto.run
(fun opts -> { opts with WorkingDirectory = $"{testPath}/bin/Release/net9.0" })
[ "PrayerTracker.Tests.dll" ])
Target.create "Publish" (fun _ ->
DotNet.publish
(fun opts -> { opts with Runtime = Some "linux-x64"; SelfContained = Some false; NoLogo = true })
$"{projPath}/PrayerTracker/PrayerTracker.fsproj")
Target.create "All" ignore
open Fake.Core.TargetOperators
let dependencies = [
"Clean"
==> "Test"
==> "Publish"
==> "All"
]
[<EntryPoint>]
let main args =
try
match args with
| [| target |] -> Target.runOrDefault target
| _ -> Target.runOrDefault "All"
0
with e ->
printfn "%A" e
1

19
build.fsproj Normal file
View File

@@ -0,0 +1,19 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net9.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<Compile Include="build.fs" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Fake.Core.Target" Version="6.1.3" />
<PackageReference Include="Fake.DotNet.Cli" Version="6.1.3" />
<PackageReference Include="Fake.Dotnet.Testing.Expecto" Version="6.1.3" />
<PackageReference Include="MSBuild.StructuredLogger" Version="2.2.386" />
</ItemGroup>
</Project>

View File

@@ -1 +0,0 @@
docs.prayer.bitbadger.solutions

View File

@@ -1,24 +0,0 @@
source "https://rubygems.org"
# Hello! This is where you manage which Jekyll version is used to run.
# When you want to use a different version, change it below, save the
# file and run `bundle install`. Run Jekyll with `bundle exec`, like so:
#
# bundle exec jekyll serve
#
# This will help ensure the proper Jekyll version is running.
# Happy Jekylling!
# If you want to use GitHub Pages, remove the "gem "jekyll"" above and
# uncomment the line below. To upgrade, run `bundle update github-pages`.
gem "github-pages", group: :jekyll_plugins
# If you have any plugins, put them here!
group :jekyll_plugins do
end
# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem "tzinfo-data", platforms: [:mingw, :mswin, :x64_mingw, :jruby]
# Performance-booster for watching directories on Windows
gem "wdm", "~> 0.1.0" if Gem.win_platform?

View File

@@ -1,259 +0,0 @@
GEM
remote: https://rubygems.org/
specs:
activesupport (4.2.11.1)
i18n (~> 0.7)
minitest (~> 5.1)
thread_safe (~> 0.3, >= 0.3.4)
tzinfo (~> 1.1)
addressable (2.7.0)
public_suffix (>= 2.0.2, < 5.0)
coffee-script (2.4.1)
coffee-script-source
execjs
coffee-script-source (1.11.1)
colorator (1.1.0)
commonmarker (0.17.13)
ruby-enum (~> 0.5)
concurrent-ruby (1.1.5)
dnsruby (1.61.3)
addressable (~> 2.5)
em-websocket (0.5.1)
eventmachine (>= 0.12.9)
http_parser.rb (~> 0.6.0)
ethon (0.12.0)
ffi (>= 1.3.0)
eventmachine (1.2.7)
eventmachine (1.2.7-x64-mingw32)
execjs (2.7.0)
faraday (0.17.0)
multipart-post (>= 1.2, < 3)
ffi (1.11.1)
ffi (1.11.1-x64-mingw32)
forwardable-extended (2.6.0)
gemoji (3.0.1)
github-pages (201)
activesupport (= 4.2.11.1)
github-pages-health-check (= 1.16.1)
jekyll (= 3.8.5)
jekyll-avatar (= 0.6.0)
jekyll-coffeescript (= 1.1.1)
jekyll-commonmark-ghpages (= 0.1.6)
jekyll-default-layout (= 0.1.4)
jekyll-feed (= 0.11.0)
jekyll-gist (= 1.5.0)
jekyll-github-metadata (= 2.12.1)
jekyll-mentions (= 1.4.1)
jekyll-optional-front-matter (= 0.3.0)
jekyll-paginate (= 1.1.0)
jekyll-readme-index (= 0.2.0)
jekyll-redirect-from (= 0.14.0)
jekyll-relative-links (= 0.6.0)
jekyll-remote-theme (= 0.4.0)
jekyll-sass-converter (= 1.5.2)
jekyll-seo-tag (= 2.5.0)
jekyll-sitemap (= 1.2.0)
jekyll-swiss (= 0.4.0)
jekyll-theme-architect (= 0.1.1)
jekyll-theme-cayman (= 0.1.1)
jekyll-theme-dinky (= 0.1.1)
jekyll-theme-hacker (= 0.1.1)
jekyll-theme-leap-day (= 0.1.1)
jekyll-theme-merlot (= 0.1.1)
jekyll-theme-midnight (= 0.1.1)
jekyll-theme-minimal (= 0.1.1)
jekyll-theme-modernist (= 0.1.1)
jekyll-theme-primer (= 0.5.3)
jekyll-theme-slate (= 0.1.1)
jekyll-theme-tactile (= 0.1.1)
jekyll-theme-time-machine (= 0.1.1)
jekyll-titles-from-headings (= 0.5.1)
jemoji (= 0.10.2)
kramdown (= 1.17.0)
liquid (= 4.0.0)
listen (= 3.1.5)
mercenary (~> 0.3)
minima (= 2.5.0)
nokogiri (>= 1.10.4, < 2.0)
rouge (= 3.11.0)
terminal-table (~> 1.4)
github-pages-health-check (1.16.1)
addressable (~> 2.3)
dnsruby (~> 1.60)
octokit (~> 4.0)
public_suffix (~> 3.0)
typhoeus (~> 1.3)
html-pipeline (2.12.0)
activesupport (>= 2)
nokogiri (>= 1.4)
http_parser.rb (0.6.0)
i18n (0.9.5)
concurrent-ruby (~> 1.0)
jekyll (3.8.5)
addressable (~> 2.4)
colorator (~> 1.0)
em-websocket (~> 0.5)
i18n (~> 0.7)
jekyll-sass-converter (~> 1.0)
jekyll-watch (~> 2.0)
kramdown (~> 1.14)
liquid (~> 4.0)
mercenary (~> 0.3.3)
pathutil (~> 0.9)
rouge (>= 1.7, < 4)
safe_yaml (~> 1.0)
jekyll-avatar (0.6.0)
jekyll (~> 3.0)
jekyll-coffeescript (1.1.1)
coffee-script (~> 2.2)
coffee-script-source (~> 1.11.1)
jekyll-commonmark (1.3.1)
commonmarker (~> 0.14)
jekyll (>= 3.7, < 5.0)
jekyll-commonmark-ghpages (0.1.6)
commonmarker (~> 0.17.6)
jekyll-commonmark (~> 1.2)
rouge (>= 2.0, < 4.0)
jekyll-default-layout (0.1.4)
jekyll (~> 3.0)
jekyll-feed (0.11.0)
jekyll (~> 3.3)
jekyll-gist (1.5.0)
octokit (~> 4.2)
jekyll-github-metadata (2.12.1)
jekyll (~> 3.4)
octokit (~> 4.0, != 4.4.0)
jekyll-mentions (1.4.1)
html-pipeline (~> 2.3)
jekyll (~> 3.0)
jekyll-optional-front-matter (0.3.0)
jekyll (~> 3.0)
jekyll-paginate (1.1.0)
jekyll-readme-index (0.2.0)
jekyll (~> 3.0)
jekyll-redirect-from (0.14.0)
jekyll (~> 3.3)
jekyll-relative-links (0.6.0)
jekyll (~> 3.3)
jekyll-remote-theme (0.4.0)
addressable (~> 2.0)
jekyll (~> 3.5)
rubyzip (>= 1.2.1, < 3.0)
jekyll-sass-converter (1.5.2)
sass (~> 3.4)
jekyll-seo-tag (2.5.0)
jekyll (~> 3.3)
jekyll-sitemap (1.2.0)
jekyll (~> 3.3)
jekyll-swiss (0.4.0)
jekyll-theme-architect (0.1.1)
jekyll (~> 3.5)
jekyll-seo-tag (~> 2.0)
jekyll-theme-cayman (0.1.1)
jekyll (~> 3.5)
jekyll-seo-tag (~> 2.0)
jekyll-theme-dinky (0.1.1)
jekyll (~> 3.5)
jekyll-seo-tag (~> 2.0)
jekyll-theme-hacker (0.1.1)
jekyll (~> 3.5)
jekyll-seo-tag (~> 2.0)
jekyll-theme-leap-day (0.1.1)
jekyll (~> 3.5)
jekyll-seo-tag (~> 2.0)
jekyll-theme-merlot (0.1.1)
jekyll (~> 3.5)
jekyll-seo-tag (~> 2.0)
jekyll-theme-midnight (0.1.1)
jekyll (~> 3.5)
jekyll-seo-tag (~> 2.0)
jekyll-theme-minimal (0.1.1)
jekyll (~> 3.5)
jekyll-seo-tag (~> 2.0)
jekyll-theme-modernist (0.1.1)
jekyll (~> 3.5)
jekyll-seo-tag (~> 2.0)
jekyll-theme-primer (0.5.3)
jekyll (~> 3.5)
jekyll-github-metadata (~> 2.9)
jekyll-seo-tag (~> 2.0)
jekyll-theme-slate (0.1.1)
jekyll (~> 3.5)
jekyll-seo-tag (~> 2.0)
jekyll-theme-tactile (0.1.1)
jekyll (~> 3.5)
jekyll-seo-tag (~> 2.0)
jekyll-theme-time-machine (0.1.1)
jekyll (~> 3.5)
jekyll-seo-tag (~> 2.0)
jekyll-titles-from-headings (0.5.1)
jekyll (~> 3.3)
jekyll-watch (2.2.1)
listen (~> 3.0)
jemoji (0.10.2)
gemoji (~> 3.0)
html-pipeline (~> 2.2)
jekyll (~> 3.0)
kramdown (1.17.0)
liquid (4.0.0)
listen (3.1.5)
rb-fsevent (~> 0.9, >= 0.9.4)
rb-inotify (~> 0.9, >= 0.9.7)
ruby_dep (~> 1.2)
mercenary (0.3.6)
mini_portile2 (2.4.0)
minima (2.5.0)
jekyll (~> 3.5)
jekyll-feed (~> 0.9)
jekyll-seo-tag (~> 2.1)
minitest (5.12.2)
multipart-post (2.1.1)
nokogiri (1.10.4)
mini_portile2 (~> 2.4.0)
nokogiri (1.10.4-x64-mingw32)
mini_portile2 (~> 2.4.0)
octokit (4.14.0)
sawyer (~> 0.8.0, >= 0.5.3)
pathutil (0.16.2)
forwardable-extended (~> 2.6)
public_suffix (3.1.1)
rb-fsevent (0.10.3)
rb-inotify (0.10.0)
ffi (~> 1.0)
rouge (3.11.0)
ruby-enum (0.7.2)
i18n
ruby_dep (1.5.0)
rubyzip (2.0.0)
safe_yaml (1.0.5)
sass (3.7.4)
sass-listen (~> 4.0.0)
sass-listen (4.0.0)
rb-fsevent (~> 0.9, >= 0.9.4)
rb-inotify (~> 0.9, >= 0.9.7)
sawyer (0.8.2)
addressable (>= 2.3.5)
faraday (> 0.8, < 2.0)
terminal-table (1.8.0)
unicode-display_width (~> 1.1, >= 1.1.1)
thread_safe (0.3.6)
typhoeus (1.3.1)
ethon (>= 0.9.0)
tzinfo (1.2.5)
thread_safe (~> 0.1)
tzinfo-data (1.2019.3)
tzinfo (>= 1.0.0)
unicode-display_width (1.6.0)
wdm (0.1.1)
PLATFORMS
ruby
x64-mingw32
DEPENDENCIES
github-pages
tzinfo-data
wdm (~> 0.1.0)
BUNDLED WITH
2.0.2

View File

@@ -1,11 +0,0 @@
defaults:
-
scope:
path: "en"
values:
layout: "en"
-
scope:
path: "es"
values:
layout: "es"

View File

@@ -1,41 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{{ page.title }} &#xab; PrayerTracker Help</title>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link href="https://prayer.bitbadger.solutions/css/app.css" rel="stylesheet">
<link href="/css/help.css" rel="stylesheet">
</head>
<body>
<header class="pt-title-bar">
<section class="pt-title-bar-left"><span class="pt-title-bar-home"><a href="/" title="Home">PrayerTracker</a></span></section>
<section class="pt-title-bar-right">Help</section>
</header>
<div id="pt-body">
<header id="pt-language">
<div>
Language: English &bull;
<a href="{{ page.url | replace_first: "/en", "/es" }}">Esta pagina en español</a>
</div>
</header>
<h2 id="pt-page-title">{{ page.title }}</h2>
<div class="pt-content">
{{ content }}
<div class="pt-close-window">
<p class="pt-center-text">
<a href="#" title="Click to Close This Window" onclick="window.close();return false">
<i class="material-icons">cancel</i> Close Window
</a>
</p>
</div>
<div class="pt-help-index">
<p class="pt-center-text">
<a href="/en/" title="Help Index">&#xab; Back to Help Index</a>
</p>
</div>
</div>
</div>
</body>
</html>

View File

@@ -1,44 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{{ page.title }} &#xab; Ayuda de SeguidorOración</title>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link href="https://prayer.bitbadger.solutions/css/app.css" rel="stylesheet">
<link href="/css/help.css" rel="stylesheet">
</head>
<body>
<header class="pt-title-bar">
<section class="pt-title-bar-left"><span class="pt-title-bar-home"><a href="/" title="Home">SeguidorOración</a></span></section>
<section class="pt-title-bar-right">Ayuda</section>
</header>
<div id="pt-body">
<header id="pt-language">
<div>
Lengua: Español &bull;
<a href="{{ page.url | replace_first: "/es", "/en" }}">This page in English</a>
</div>
</header>
<h2 id="pt-page-title">{{ page.title }}</h2>
<div class="pt-content">
{{ content }}
{% if page.skip_footer %}
{% else %}
<div class="pt-close-window">
<p class="pt-center-text">
<a href="#" title="Haga Clic para Cerrar Esta Ventana" onclick="window.close();return false">
<i class="material-icons">cancel</i> Cerrar Esta Ventana
</a>
</p>
</div>
<div class="pt-help-index">
<p class="pt-center-text">
<a href="/es/" title="Índice de ayuda">&#xab; Volver al índice de ayuda</a>
</p>
</div>
{% endif %}
</div>
</div>
</body>
</html>

View File

@@ -1,26 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{{ page.title }} &#xab; PrayerTracker Help / Ayuda de SeguidorOración</title>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link href="https://prayer.bitbadger.solutions/css/app.css" rel="stylesheet">
<link href="/css/help.css" rel="stylesheet">
</head>
<body>
<header class="pt-title-bar">
<section class="pt-title-bar-left"><span class="pt-title-bar-home"><a href="/" title="Home">PrayerTracker / SeguidorOración</a></span></section>
<section class="pt-title-bar-right">Help / Ayuda</section>
</header>
<div id="pt-body">
<header id="pt-language">
<div>&nbsp;</div>
</header>
<h2 id="pt-page-title">{{ page.title }}</h2>
<div class="pt-content pt-center-text">
{{ content }}
</div>
</div>
</body>
</html>

View File

@@ -1,26 +0,0 @@
---
title: Help
skip_footer: true
---
Throughout PrayerTracker, you'll see an icon (a question mark in a circle) next to the title on each page. Clicking this will open a new, small window with directions on using that page. If you are looking for a quick overview of PrayerTracker, start with the “Add / Edit a Request” and “Change Preferences” entries.
----
<p class="pt-center-text"><strong>Help Topics</strong></p>
[Change Preferences](./small-group/preferences.html)
[Send Announcement](./small-group/announcement.html)
[Maintain Group Members](./small-group/members.html)
[Add / Edit a Request](./requests/edit.html)
[Maintain Requests](./requests/maintain.html)
[View Request List](./requests/view.html)
[Log On](./user/log-on.html)
[Change Your Password](./user/password.html)

View File

@@ -1,27 +0,0 @@
---
title: Add / Edit a Request
---
This page allows you to enter or update a new prayer request.
## Request Type
There are 5 request types in PrayerTracker. “Current Requests” are your regular requests that people may have regarding things happening over the next week or so. “Long-Term Requests” are requests that may occur repeatedly or continue indefinitely. “Praise Reports” are like “Current Requests”, but they are answers to prayer to share with your group. “Expecting” is for those who are pregnant. “Announcements” are like “Current Requests”, but instead of a request, they are simply passing information along about something coming up.
The order above is the order in which the request types appear on the list. “Long-Term Requests” and “Expecting” are not subject to the automatic expiration (set on the “Change Preferences” page) that the other requests are.
## Date
For new requests, this is a box with a calendar date picker. Click or tab into the box to display the calendar, which will be preselected to today's date. For existing requests, there will be a check box labeled “Check to not update the date”. This can be used if you are correcting spelling or punctuation, and do not have an actual update to make to the request.
## Requestor / Subject
For requests or praises, this field is for the name of the person who made the request or offered the praise report. For announcements, this should contain the subject of the announcement. For all types, it is optional; I used to have an announcement with no subject that ran every week, telling where to send requests and updates.
## Expiration
“Expire Normally” means that the request is subject to the expiration days in the group preferences. “Request Never Expires” can be used to make a request never expire (note that this is redundant for “Long-Term Requests” and “Expecting”). If you are editing an existing request, a third option appears. “Expire Immediately” will make the request expire when it is saved. Apart from the icons on the request maintenance page, this is the only way to expire “Long-Term Requests” and “Expecting” requests, but it can be used for any request type.
## Request
This is the text of the request. The editor provides many formatting capabilities, including “Spell Check as you Type” (enabled by default), “Paste from Word”, and “Paste Plain”, as well as “Source” view, if you want to edit the HTML yourself. It also supports undo and redo, and the editor supports full-screen mode. Hover over each icon to see what each button does.

View File

@@ -1,29 +0,0 @@
---
title: Maintain Requests
---
From this page, you can add, edit, and delete your current requests. You can also restore requests that may have expired, but should be made active once again.
## Add a New Request
To add a request, click the icon or text in the center of the page, below the title and above the list of requests for your group.
## Search Requests
If you are looking for a particular requests, enter some text in the search box and click “Search”. PrayerTracker will search the Requestor/Subject and Request Text fields (case-insensitively) of both active and inactive requests. The results will be displayed in the same format as the original Maintain Requests page, so the buttons described below will work the same for those requests as well. They will also be displayed in pages, if there are a lot of results; the number per page is configurable by small group.
## Edit Request
To edit a request, click the blue pencil icon; it's the first icon under the “Actions” column heading.
## Expire a Request
For active requests, the second icon is an eye with a slash through it; clicking this icon will expire the request immediately. This is equivalent to editing the request, selecting “Expire Immediately”, and saving it.
## Restore an Inactive Request
When the page is first displayed, it does not display inactive requests. However, clicking the link at the bottom of the page will refresh the page with the inactive requests shown. The middle icon will look like an eye; clicking it will restore the request as an active request. The last updated date will be current, and the request is set to expire normally.
## Delete a Request
Deleting a request is contrary to the intent of PrayerTracker, as you can retrieve requests that have expired. However, if there is a request that needs to be deleted, clicking the blue trash can icon in the “Actions” column will allow you to do it. Use this option carefully, as these deletions cannot be undone; once a request is deleted, it is gone for good.

View File

@@ -1,17 +0,0 @@
---
title: View Request List
---
From this page, you can view the request list (for today or for the next Sunday), view a printable version of the list, and e-mail the list to the members of your group. (NOTE: If you are logged in as a group member, the only option you will see is to view a printable list.)
## List for Next Sunday
This will modify the date for the list, so it will look like it is currently next Sunday. This can be used, for example, to see what requests will expire, or allow you to print a list with Sunday's date on Saturday evening. Note that this link does not appear if it is Sunday.
## View Printable
Clicking this link will display the list in a format that is suitable for printing; it does not have the normal PrayerTracker header across the top. Once you have clicked the link, you can print it using your browser's standard “Print” functionality.
## Send Via E-mail
Clicking this link will send the list you are currently viewing to your group members. The page will remind you that you are about to do that, and ask for your confirmation. If you proceed, you will see a page that shows to whom the list was sent, and what the list looked like. You may safely use your browser's “Back” button to navigate away from the page.

View File

@@ -1,11 +0,0 @@
---
title: Send Announcement
---
## Announcement Text
This is the text of the announcement you would like to send. It functions the same way as the text box on the [“Edit Request” page](../requests/edit.html#request).
## Add to Request List
Without this box checked, the text of the announcement will only be e-mailed to your group members. If you check this box, however, the text of the announcement will be added to your prayer list under the section you have selected.

View File

@@ -1,17 +0,0 @@
---
title: Maintain Group Members
---
From this page, you can add, edit, and delete the e-mail addresses for your group.
## Add a New Group Member
To add an e-mail address, click the icon or text in the center of the page, below the title and above the list of addresses for your group.
## Edit Group Member
To edit an e-mail address, click the blue pencil icon; it's the first icon under the “Actions” column heading. This will allow you to update the name and/or the e-mail address for that member.
## Delete a Group Member
To delete an e-mail address, click the blue trash can icon in the “Actions” column. Note that once an e-mail address has been deleted, it is gone. (Of course, if you delete it in error, you can enter it again using the “Add” instructions above.)

View File

@@ -1,70 +0,0 @@
---
title: Change Preferences
---
This page allows you to change how your prayer request list looks and behaves. Each section is addressed below.
## Requests Expire After
When a regular request goes this many days without being updated, it expires and no longer appears on the request list. Note that the categories “Long-Term Requests” and “Expecting” never expire automatically.
## Requests “New” For
Requests that have been updated within this many days are identified by a hollow circle for their bullet, as opposed to a filled circle for other requests. All categories respect this setting. If you do a typo correction on a request, if you do not check the box to update the date, this setting will change the bullet. (NOTE: In the plain-text e-mail, new requests are bulleted with a “+” symbol, and old are bulleted with a “-” symbol.)
## Long-Term Requests Alerted for Update
Requests that have not been updated in this many weeks are identified by an italic font on the “Maintain Requests” page, to remind you to seek updates on these requests so that your prayers can stay relevant and current.
## Request Sorting
By default, requests are sorted within each group by the last updated date, with the most recent on top. If you would prefer to have the list sorted by requestor or subject rather than by date, select “Sort by Requestor Name” instead.
## E-mail “From” Name and Address
PrayerTracker must put an name and e-mail address in the “from” position of each e-mail it sends. The default name is “PrayerTracker”, and the default e-mail address is “prayer@djs-consulting.com”. This will work, but any bounced e-mails and out-of-office replies will be sent to that address (which is not even a real address). Changing at least the e-mail address to your address will ensure that you receive these e-mails, and can prune your e-mail list accordingly.
## E-mail Format
This is the default e-mail format for your group. The PrayerTracker default is HTML, which sends the list just as you see it online. However, some e-mail clients may not display this properly, so you can choose to default the email to a plain-text format, which does not have colors, italics, or other formatting. The setting on this page is the group default; you can select a format for each recipient on the “Maintain Group Members” page.
## Colors
You can customize the colors that are used for the headings and lines in your request list. You can select one of the 16 named colors in the drop down lists, or you can “mix your own” using red, green, and blue (RGB) values between 0 and 255. There is a link on the bottom of the page to a color list with more names and their RGB values, if you're really feeling artistic. The background color cannot be changed.
## Fonts for List
This is a comma-separated list of fonts that will be used for your request list. A warning is good here; just because you have an obscure font and like the way that it looks does not mean that others have that same font. It is generally best to stick with the fonts that come with Windows - fonts like “Arial”, “Times New Roman”, “Tahoma”, and “Comic Sans MS”. You should also end the font list with either “serif” or “sans-serif”, which will use the browser's default serif (like “Times New Roman”) or sans-serif (like “Arial”) font.
## Heading / List Text Size
This is the point size to use for each. The default for the heading is 16pt, and the default for the text is 12pt.
## Making a “Large Print” List
If your group is comprised mostly of people who prefer large print, the following settings will make your list look like the typical large-print publication:
> _Fonts_<br>
> &#8212; 'Times New Roman',serif
>
> _Heading Text Size_<br>
> &#8212; 18pt
>
> _List Text Size_<br>
> &#8212; 16pt
## Time Zone
This is the time zone that you would like to use for your group. If you do not see your time zone listed, just [contact Daniel](mailto:daniel@djs-consulting.com?subject=PrayerTracker%20Time%20Zone) and tell him what time zone you need.
## Request List Visibility
The group's request list can be either public, private, or password-protected. Public lists are available without logging in, and private lists are only available online to administrators (though the list can still be sent via e-mail by an administrator). Password-protected lists allow group members to log in and view the current request list online, using the “Group Log On” link and providing this password. As this is a shared password, it is stored in plain text, so you can easily see what it is. If you select “Password Protected” but do not enter a password, the list remains private, which is also the default value. (Changing this password will force all members of the group who logged in with the “Remember Me” box checked to provide the new password.)
## Page Size
As small groups use PrayerTracker, they accumulate many expired requests. When lists of requests that include expired requests, the results will be broken up into pages. The default value is 100 requests per page, but may be set as low as 10 or as high as 255.
## "As of" Date Display
PrayerTracker can display the last date a request was updated, at the end of the request text. By default, it does not. If you select a short date, it will show "(as of 10/11/2015)" (for October 11, 2015); if you select a long date, it will show "(as of Sunday, October 11, 2015)".

View File

@@ -1,13 +0,0 @@
---
title: Log On
---
This page allows you to log on to PrayerTracker. There are two different levels of access for PrayerTracker - user and group.
## User Log On
Enter your e-mail address and password into the appropriate boxes, then select your group. If you want PrayerTracker to remember you on your computer, click the “Remember Me” box before clicking the “Log On” button.
## Group Log On
If your group has defined a password to use to allow you to view their request list online, select your group from the drop down list, then enter the group password into the appropriate box. If you want PrayerTracker to remember your group, click the “Remember Me” box before clicking the “Log On” button.

View File

@@ -1,7 +0,0 @@
---
title: Change Your Password
---
This page will let you change your password. Enter your existing password in the top box, then enter your new password in the bottom two boxes. Entering your existing password is a security measure; with the “Remember Me” box on the log in page, this will prevent someone else who may be using your computer from being able to simply go to the site and change your password.
"If you cannot remember your existing password, we cannot retrieve it, but we can set it to something known so that you can then change it to your password. [Click here to request help resetting your password](mailto:daniel@djs-consulting.com?subject=PrayerTracker%20Password%20Help).

View File

@@ -1,26 +0,0 @@
---
title: Ayuda
skip_footer: true
---
En todo el sistema, verá un icono (un signo de interrogación en un círculo) junto al título de cada página. Al hacer clic en esta opción, se abrirá una nueva y pequeña ventana con instrucciones sobre cómo usar esa página. Si está buscando una descripción rápida de SeguidorOración, comience con las entradas "Agregar / Editar una Petición" y "Cambiar las Preferencias".
----
<p class="pt-center-text"><strong>Los Temas de Ayuda</strong></p>
[Cambiar las Preferencias](./small-group/preferences.html)
[Enviar un Anuncio](./small-group/announcement.html)
[Mantener los Miembros del Grupo](./small-group/members.html)
[Agregar / Editar una Petición](./requests/edit.html)
[Mantener las Peticiones](./requests/maintain.html)
[Ver la Lista de Peticiones](./requests/view.html)
[Iniciar Sesión](./user/log-on.html)
[Cambiar Su Contraseña](./user/password.html)

View File

@@ -1,27 +0,0 @@
---
title: Agregar / Editar una Petición
---
Esta página le permite introducir o actualizar una petición de oración nueva.
## Tipo de Petición
Hay 5 tipos de peticiones en SeguidorOración. “Peticiones Actuales” son sus peticiones habituales que la gente pueda tener acerca de las cosas que suceden durante la próxima semana o así. “Peticiones a Largo Plazo” son peticiones que pueden ocurrir varias veces, o continuar indefinidamente. “Informes de Alabanza” son como “Peticiones Actuales”, pero son respuestas a la oración para compartir con su grupo. “Embarazada” es para aquellos que están embarazadas. “Anuncios” son como “Peticiones Actuales”, pero en lugar de una petición, simplemente se pasa la información a lo largo de algo por venir.
El orden anterior es el orden en que los tipos de peticiones aparecen en la lista. “Peticiones a Largo Plazo” y “Embarazada” no están sujetos a la caducidad automática (establecida en el “Cambiar las Preferencias” de la página) que las peticiones son otros.
## Fecha
Para nuevas peticiones, se trata de una caja con un selector de fechas del calendario. Haga clic en la pestaña o en la caja para mostrar el calendario, que será preseleccionada para la fecha de hoy. Para peticiones existentes, habrá una casilla de verificación “Seleccionar para no actualizar la fecha”. Esto puede ser usado si corrige la ortografía ni la puntuacion, y no tienen una actualización real de hacer la petición.
## Peticionario / Sujeto
Para las peticiones o alabanzas, este campo es el nombre de la persona que hizo la petición o que ofrece el informe de alabanza. Para los anuncios, este debe contener el objeto del anuncio. Para todos los tipos, es opcional, yo solía tener un anuncio con ningún tema que iba todas las semanas, diciendo a dónde enviar peticiones y actualizaciones.
## Expiración
“Expirará Normalmente” significa que la petición está sujeta a los días de vencimiento de las preferencias del grupo. “Petición no Expira Nunca” se puede utilizar para hacer una petición que no caduque nunca (nótese que esto es redundante para los tipos “Peticiones a Largo Plazo” y “Embarazada”). Si está editando una petición existente, aparece una tercera opción. “Expirará Inmediatamente” hará que la petición expirará cuando se guarda. Aparte de los iconos de la página de mantenimiento de las peticiones, ésta es la única otra forma de expirar peticiones del tipos “Peticiones a Largo Plazo” y “Embarazada”, pero puede ser utilizada para cualquier tipo de petición.
## Petición
Este es el texto de la petición. El editor ofrece muchas capacidades de formato, como "El Corrector Ortográfico al Escribir" (habilitado predeterminado), "Pegar desde Word" y "Pegar sin formato", así como "Código Fuente" punto de vista, si quieres editar el código HTML usted mismo. También es compatible con deshacer y rehacer, y el editor soporta modo de pantalla completa. Pase el ratón sobre cada icono para ver qué hace cada botón.

View File

@@ -1,29 +0,0 @@
---
title: Mantener las Peticiones
---
Desde esta página, usted puede agregar, editar y borrar sus peticiones actuales. También puede restaurar peticiones que han caducado, sino que debe ser activa, una vez más.
## Agregar una Nueva Petición
Para agregar una petición, haga clic en el icono o el texto en el centro de la página, debajo del título y por encima de la lista de peticiones para su grupo.
## Busca las Peticiones
Si está buscando una solicitud en particular, ingrese un texto en el cuadro de búsqueda y haga clic en “Buscar”. SeguidorOración buscará los campos de Solicitante / Asunto y Texto de solicitud (sin distinción de mayúsculas y minúsculas) de solicitudes activas e inactivas. Los resultados se mostrarán en el mismo formato que la página de solicitudes de mantenimiento original, por lo que los botones que se describen a continuación funcionarán igual para esas solicitudes. También se mostrarán en las páginas, si hay muchos resultados; el número por página es configurable por grupos pequeños.
## Editar la Petición
Para editar una petición, haga clic en el icono de lápiz azul, el primer icono bajo el título de columna “Acciones”.
## Expirar una petición
Para las peticiones activas, el segundo icono es un ojo con una barra a través de él; Si hace clic en este icono, la petición se cancelará inmediatamente. Esto equivale a editar la petición, seleccionar "Expirará Inmediatamente" y guardarla.
## Restaurar una Petición Inactivo
Cuando la página se muestra por primera vez, que no muestra peticiones inactivos. Sin embargo, al hacer clic en el vínculo en la parte inferior de la página se actualizará la página con las peticiones se muestran inactivos. El icono del centro se verá como un ojo; Haciendo clic en él, restaurará la petición como una petición activa. La última fecha actualizada será actual, y la petición se establece para caducar normalmente.
## Eliminar una Petición
Eliminación de una petición es contraria a la intención de SeguidorOración, como se puede recuperar peticiones que han expirado. Sin embargo, si hay una solicitud que debe ser eliminado, haga clic en el icono azul de la papelera en la columna “Acciones” le permitirá hacerlo. Utilice esta opción con cuidado, ya que estas supresiones no se puede deshacer, una vez a la petición se ha borrado, ha desaparecido para siempre.

View File

@@ -1,17 +0,0 @@
---
title: Ver la Lista de Peticiones
---
Desde esta página, puede ver la lista de peticiones (para hoy o para el próximo Domingo), ver una versión imprimible de la lista, y por correo electrónico la lista de los miembros de su grupo. (NOTA: Si usted está registrado como miembro de la clase, la única opción que se ve es para ver una lista para imprimir.)
## Lista para el Próximo Domingo
Esto modificará la fecha de la lista, por lo que se verá como es en la actualidad el próximo Domingo. Esto puede ser usado, por ejemplo, para ver lo que peticiones de caducidad, ni le permite imprimir una lista con la fecha del Domingo en la noche del Sábado. Tenga en cuenta que este enlace no aparece si es Domingo.
## Versión Imprimible
Hacer clic en este vínculo, se muestra la lista en un formato que sea adecuado para imprimir, sino que no tiene el encabezado normal de SeguidorOración en la parte superior. Una vez que haya hecho clic en el enlace, se puede imprimir con el navegador estándar de “Imprimir” funcionalidad.
## Enviar por correo electrónico
Al hacer clic en este enlace le enviará la lista que está viendo en ese momento a los miembros del grupo. La página te recordará que estás a punto de hacerlo, y pedir su confirmación. Si continúa, usted verá una página que muestra a la que la lista fue enviado, y lo que la lista parecía. Usted puede utilizar con seguridad de su navegador botón “Atrás” para navegar fuera de la página.

View File

@@ -1,11 +0,0 @@
---
title: Enviar un Anuncio
---
## Texto del Anuncio
Este es el texto del anuncio que desea enviar. Funciona de la misma forma que el cuadro de texto en [la página “Editar la Petición”](../requests/edit.html#peticion).
## Agregar a la Lista de Peticiones En
Sin esta caja marcada, el texto del anuncio sólo será por correo electrónico a los miembros del su grupo. Si marca esta caja, sin embargo, el texto del anuncio será añadido a su lista de oración en la sección que ha seleccionado.

View File

@@ -1,17 +0,0 @@
---
title: Mantener los Miembros del Grupo
---
Desde esta página, usted puede agregar, editar y eliminar las direcciones de correo electrónico para su grupo.
## Añadir un Nuevo Miembro del Grupo
Para agregar una dirección de correo electrónico, haga clic en el icono o el texto en el centro de la página, debajo del título y por encima de la lista de direcciones para su grupo.
## Editar el Miembro del Grupo
Para editar una dirección de correo electrónico, haga clic en el icono de lápiz azul, es el primer icono bajo el título de columna “Acciones”. Esto le permitirá actualizar el nombre y / o la dirección de correo electrónico para ese miembro.
## Eliminar un Miembro del Grupo
Para eliminar una dirección de correo electrónico, haga clic en el icono azul de la papelera en la columna “Acciones”. Tenga en cuenta que una vez que la dirección de correo electrónico se ha eliminado, se ha ido. (Por supuesto, si usted lo elimine por error, se puede entrar de nuevo utilizando la opción “Agregar” instrucciones de arriba.)

View File

@@ -1,70 +0,0 @@
---
title: Cambiar las Preferencias
---
Esta página le permite cambiar la forma en que su lista de peticiones de la oración se ve y se comporta. Cada sección se aborda más adelante.
## Peticiones Expiran Después de
Cuando una petición regular va esta cantidad de días sin actualizar, caduca y ya no aparece en la lista de peticiones. Tenga en cuenta que las categorías “Peticiones a Largo Plazo” y “Embarazada” no expirará automáticamente.
## Peticiones “Nuevas” Para
Peticiones que han sido actualizadas dentro de esta cantidad de días se identifican por un círculo hueco para su bala, en oposición a un círculo relleno para otras peticiones. Todas las categorías respetar esta opción. Si usted hace una corrección de errata en una petición, si no marque la caja para actualizar la fecha, este valor va a cambiar la bala. (NOTA: En el texto sin formato de correo electrónico, las nuevas solicitudes se identifican con un símbolo “+”, y pide a los viejos se identifican con un símbolo “-”.)
## Peticiones a Largo Plazo Alertó para la Actualización
Peticiones que no han sido actualizados en esta semana muchos se identifican con un tipo de letra cursiva en la página “Mantener las Peticiones”, para recordarle que debe buscar novedades en estas peticiones para que vuestras oraciones pueden permanecer relevante y actual.
## Orden de Peticiones
De forma predeterminada, las solicitudes se ordenan dentro de cada grupo por la última fecha de actualización, con el más reciente en la parte superior. Si prefiere tener la lista ordenada por el solicitante o el sujeto en vez de por fecha, seleccione “Ordenar por Nombre del Solicitante” en su lugar.
## Correo Electrónico “De” Nombre y Dirección
SeguidorOración debe poner el nombre y la dirección de correo electrónico en el “de” posición de cada correo electrónico que envía. El nombre predeterminado es “PrayerTracker”, y el valor predeterminado dirección de correo electrónico es “prayer@djs-consulting.com”. Esto funciona, pero los mensajes devueltos, y las respuestas de fuera de la oficina serán enviados a esa dirección (que no es ni siquiera una dirección real). Cambiar por lo menos la dirección de correo electrónico a su dirección se asegurará de que usted recibe estos correos electrónicos, y se puede podar su lista de correo electrónico en consecuencia.
## Formato de Correo Electrónico
Este es el valor predeterminado formato de correo electrónico para su grupo. El valor predeterminado de SeguidorOración es HTML, el cual envía la lista al igual que usted lo ve en el sitio. Sin embargo, algunos clientes de correo electrónico no puede mostrar esto correctamente, para que pueda elegir el correo electrónico a un formato de texto plano predeterminadas, que no tiene colores, cursiva, u otro formato. La configuración en esta página es el valor predeterminado del grupo, se puede seleccionar un formato para cada destinatario de la página “Mantener los Miembros del Grupo”.
## Colores
Usted puede personalizar los colores que se utilizan para las partidas y líneas en su lista de peticiones. Puede seleccionar uno de los 16 colores con nombre en las listas desplegables, o puede “mezclar su propia” en colores rojo, verde y azul (RGB) valores entre 0 y 255. Hay un enlace en la parte inferior de la página para una lista de colores con más nombres y sus valores RGB, si realmente estás sintiendo artística. El color de fondo no puede ser cambiado.
## Fuentes de la Lista
Esta es una lista separada por comas de fuentes que se utilizarán para su lista de peticiones. Una advertencia de que es bueno aquí, sólo porque usted tiene una fuente oscura y gusta la forma en que se vea no significa que los demás tienen de que la misma fuente. Generalmente es mejor quedarse con las fuentes que vienen con Windows - Fuentes como “Arial”, “Times New Roman”, “Tahoma”, y “Comic Sans MS”. También debe poner fin a la lista de fuentes, ya sea con “serif” o el “sans-serif”, que utilizará el fuente serif predeterminado (como “Times New Roman”) o el fuente sans-serif predeterminado (como “Arial”).
## Tamaño del Texto de Partida y Lista
Este es el tamaño de punto a utilizar para cada uno. El valor predeterminado para el título es 16 puntos, y el valor por defecto para el texto es 12 puntos.
## Realización de una Lista de “Letra Grande”
Si el grupo está compuesta en su mayoría de la gente que prefiere letras grandes, los siguientes ajustes harán que su lista de parecerse a la típica la publicación “Letra Grande”:
> _Fuentes_<br>
> &#8212; 'Times New Roman',serif
>
> _Partida el Tamaño del Texto_<br>
> &#8212; 18pt
>
> _Lista el Tamaño del Texto_<br>
> &#8212; 16pt
## Zona Horaria
Esta es la zona horaria que desea utilizar para su clase. Si no puede ver la zona horaria en la lista, ponte en [contacto con Daniel](mailto:daniel@djs-consulting.com?subject=Zona%20Horaria%20por%20SeguidorOración) y decirle lo que la zona horaria que usted necesita.
## La Visibilidad del la Lista de las Peticiones
La lista de peticiones del grupo puede ser pública, privada o protegida por contraseña. Las listas públicas están disponibles sin iniciar sesión, y listas privadas sólo están disponibles en línea a los administradores (aunque la lista todavía puede ser enviado por correo electrónico por el administrador). Protegidos con contraseña listas permiten miembros del grupo iniciar sesión y ver la lista de peticiones actual en el sito, utilizando el "Iniciar Sesión como Grupo" enlace y proporcionar la contraseña. Como se trata de una contraseña compartida, se almacena en texto plano, así que usted puede ver fácilmente lo que es. Si selecciona "Protegido por Contraseña" pero no introduce una contraseña, la lista sigue siendo privado, que también es el valor predeterminado. (Cambiar esta contraseña obligará a todos los miembros del grupo que se iniciar sesión en el "Acuérdate de Mí" caja marcada para proporcionar la nueva contraseña.)
## Tamaño de Página
A medida que los grupos pequeños utilizan SeguidorOración, acumulan muchas solicitudes caducadas. Cuando las listas de solicitudes que incluyen solicitudes caducadas, los resultados se dividirán en páginas. El valor predeterminado es de 100 solicitudes por página, pero se puede establecer tan bajo como 10 o tan alto como 255.
## Visualización de la Fecha “Como de”
SeguidorOración puede mostrar la última fecha en que se actualizó una solicitud, al final del texto de solicitud. Por defecto, no lo hace. Si selecciona una fecha corta, se mostrará "(como de 11/10/2015)" (para el 11 de octubre de 2015); si selecciona una fecha larga, se mostrará "(como de domingo, 11 de octubre de 2015)".

View File

@@ -1,13 +0,0 @@
---
title: Iniciar Sesión
---
Esta página le permite acceder a SeguidorOración. Hay dos diferentes niveles de acceso para SeguidorOración - el usuario y el grupo.
## Iniciar Sesión como Usuario
Introduzca su dirección de correo electrónico y contraseña en las cajas apropiadas y seleccione su grupo. Si desea que SeguidorOración que le recuerde en su ordenador, haga clic en “Acuérdate de Mí” caja antes de pulsar el “Iniciar Sesión” botón.
## Iniciar Sesión como Grupo
Si el grupo se ha definido una contraseña para usar que le permite ver su lista de peticiones en línea, seleccionar el grupo en la lista desplegable y introduzca la contraseña del grupo en la caja correspondiente. Si desea que SeguidorOración recuerde su grupo, haga clic en “Acuérdate de Mí” caja antes de pulsar el “Iniciar Sesión” botón.

View File

@@ -1,7 +0,0 @@
---
title: Cambiar Su Contraseña
---
Esta página le permitirá cambiar su contraseña. Ingrese su contraseña actual en la caja superior y introduzca la nueva contraseña en la parte inferior dos cajas. Al entrar su contraseña actual es una medida de seguridad, con el “Acuérdate de Mí” caja de la página inicio de sesión, esto evitará que otra persona que pueda estar usando su computadora de la posibilidad de simplemente ir a el sitio y cambiar la contraseña.
Si no recuerdas tu contraseña actual, no podemos recuperar, pero podemos ponerlo en algo que se conoce de modo que usted puede cambiarlo a su contraseña. [Haga clic aquí para solicitar ayuda para restablecer su contraseña](mailto:daniel@djs-consulting.com?subject=Ayuda%20de%20Contraseña%20de%20SeguidorOración).

View File

@@ -1,8 +0,0 @@
---
title: Help / Ayuda
layout: home
---
## [English](/en)
## [Español](/es)

3
src/.dockerignore Normal file
View File

@@ -0,0 +1,3 @@
**/bin/*
**/obj/*
**/appsettings.*

456
src/Data/Access.fs Normal file
View File

@@ -0,0 +1,456 @@
namespace PrayerTracker.Data
/// Table names
[<RequireQualifiedAccess>]
module Table =
/// The church table
[<Literal>]
let Church = "church"
/// The small group table
[<Literal>]
let Group = "small_group"
/// The small group member table
[<Literal>]
let Member = "member"
/// The prayer request table
[<Literal>]
let Request = "prayer_request"
/// The user table
[<Literal>]
let User = "pt_user"
open System
open NodaTime
open PrayerTracker.Entities
/// JSON serialization customizations
[<RequireQualifiedAccess>]
module Json =
open System.Text.Json.Serialization
/// Convert a wrapped DU to/from its string representation
type WrappedJsonConverter<'T>(wrap: string -> 'T, unwrap: 'T -> string) =
inherit JsonConverter<'T>()
override _.Read(reader, _, _) = wrap (reader.GetString())
override _.Write(writer, value, _) = writer.WriteStringValue(unwrap value)
open System.Text.Json
open NodaTime.Serialization.SystemTextJson
/// JSON serializer options to support the target domain
let options =
let opts = JsonSerializerOptions()
[ WrappedJsonConverter<AsOfDateDisplay>(AsOfDateDisplay.Parse, string) :> JsonConverter
WrappedJsonConverter<EmailFormat>(EmailFormat.Parse, string)
WrappedJsonConverter<Expiration>(Expiration.Parse, string)
WrappedJsonConverter<PrayerRequestType>(PrayerRequestType.Parse, string)
WrappedJsonConverter<RequestSort>(RequestSort.Parse, string)
WrappedJsonConverter<TimeZoneId>(TimeZoneId, string)
WrappedJsonConverter<ChurchId>(Guid.Parse >> ChurchId, string)
WrappedJsonConverter<MemberId>(Guid.Parse >> MemberId, string)
WrappedJsonConverter<PrayerRequestId>(Guid.Parse >> PrayerRequestId, string)
WrappedJsonConverter<SmallGroupId>(Guid.Parse >> SmallGroupId, string)
WrappedJsonConverter<UserId>(Guid.Parse >> UserId, string)
JsonFSharpConverter() ]
|> List.iter opts.Converters.Add
let _ = opts.ConfigureForNodaTime DateTimeZoneProviders.Tzdb
opts.PropertyNamingPolicy <- JsonNamingPolicy.CamelCase
opts.DefaultIgnoreCondition <- JsonIgnoreCondition.WhenWritingNull
opts
module private Helpers =
let instant (it: Instant) =
it.ToString()
open BitBadger.Documents
open BitBadger.Documents.Sqlite
/// Establish the required data environment
[<RequireQualifiedAccess>]
module Connection =
open System.Text.Json
/// Ensure tables and indexes are defined
let setUp () =
backgroundTask {
Configuration.useIdField "id"
Configuration.useSerializer
{ new IDocumentSerializer with
member _.Serialize<'T>(it: 'T) =
JsonSerializer.Serialize(it, Json.options)
member _.Deserialize<'T>(it: string) =
JsonSerializer.Deserialize<'T>(it, Json.options) }
let! tables = Custom.list<string> "SELECT name FROM sqlite_master WHERE type = 'table'" [] _.GetString(0)
if not (List.contains Table.Church tables) then
do! Definition.ensureTable Table.Church
if not (List.contains Table.Group tables) then
do! Definition.ensureTable Table.Group
do! Definition.ensureFieldIndex Table.Group "church" [ "churchId" ]
if not (List.contains Table.Member tables) then
do! Definition.ensureTable Table.Member
do! Definition.ensureFieldIndex Table.Member "group" [ "smallGroupId" ]
if not (List.contains Table.Request tables) then
do! Definition.ensureTable Table.Request
do! Definition.ensureFieldIndex Table.Request "group" [ "smallGroupId" ]
if not (List.contains Table.User tables) then
do! Definition.ensureTable Table.User
do! Definition.ensureFieldIndex Table.User "email" [ "email" ]
}
open Microsoft.Data.Sqlite
/// Functions to retrieve small group information
module SmallGroups =
/// Query to retrieve data for a small group info instance
let private infoQuery =
$"SELECT g.data->>'id' AS id, g.data->>'name' AS groupName, c.data->>'name' AS churchName,
g.data->'preferences'->>'timeZoneId' AS timeZoneId, g.data->'preferences'->>'isPublic' AS isPublic
FROM {Table.Group} g
INNER JOIN {Table.Church} c ON c.data->>'id' = g.data->>'churchId'"
/// Query to retrieve data for a small group select list item
let private itemQuery =
$"SELECT g.data->>'name' AS groupName, g.data->>'id' AS id, c.data->>'name' AS churchName
FROM {Table.Group} g
INNER JOIN {Table.Church} c ON c.data->>'id' = g.data->>'churchId'"
/// The ORDER BY clause for select list item queries
let private itemOrderBy =
Query.orderBy
[ { Field.Named "name" with Qualifier = Some "c" }; { Field.Named "name" with Qualifier = Some "g" } ]
SQLite
/// Map a row to a Small Group list item
let private toSmallGroupItem (rdr: SqliteDataReader) =
(rdr.GetOrdinal >> rdr.GetString >> Guid.Parse >> Giraffe.ShortGuid.fromGuid) "id",
$"""{(rdr.GetOrdinal >> rdr.GetString) "churchName"} | {(rdr.GetOrdinal >> rdr.GetString) "groupName"}"""
/// Get the group IDs for the given church
let internal groupIdsByChurch (churchId: ChurchId) =
backgroundTask {
let! groups = Find.byFields<SmallGroup> Table.Group All [ Field.Equal "churchId" (string churchId) ]
return groups |> List.map _.Id
}
/// Count the number of small groups for a church
let countByChurch (churchId: ChurchId) =
Count.byFields Table.Group All [ Field.Equal "churchId" (string churchId) ]
/// Delete a small group by its ID
let deleteById (groupId: SmallGroupId) =
backgroundTask {
use conn = Configuration.dbConn ()
use! txn = conn.BeginTransactionAsync()
let! users =
Find.byFields<User> Table.User All [ Field.InArray "smallGroups" Table.User [ (string groupId) ] ]
for user in users do
do! Patch.byId Table.User user.Id {| SmallGroups = user.SmallGroups |> List.except [ groupId ] |}
do! conn.deleteByFields Table.Request All [ Field.Equal "smallGroupId" (string groupId) ]
do! conn.deleteById Table.Group (string groupId)
do! txn.CommitAsync()
}
/// Get information for all small groups
let infoForAll () =
Custom.list $"{infoQuery} ORDER BY g.data->>'name'" [] SmallGroupInfo.FromReader
/// Get a list of small group IDs along with a description that includes the church name
let listAll () =
Custom.list $"{itemQuery} {itemOrderBy}" [] toSmallGroupItem
/// Get a list of small group IDs and descriptions for groups with a group password
let listProtected () =
Custom.list
$"{itemQuery} WHERE COALESCE(g.data->'preferences'->>'groupPassword', '') <> '' {itemOrderBy}"
[]
toSmallGroupItem
/// Get a list of small group IDs and descriptions for groups that are public or have a group password
let listPublicAndProtected () =
Custom.list
$"{infoQuery}
WHERE g.data->'preferences'->>'isPublic' = TRUE
OR COALESCE(g.data->'preferences'->>'groupPassword', '') <> ''
{itemOrderBy}"
[]
SmallGroupInfo.FromReader
/// Log on for a small group (includes list preferences)
let logOn (groupId: SmallGroupId) (password: string) =
Find.firstByFields<SmallGroup>
Table.Group
All
[ Field.Equal "id" (string groupId); Field.Equal "preferences.groupPassword" password ]
/// Save a small group
let save group = save<SmallGroup> Table.Group group
/// Save a small group's list preferences
let savePreferences (groupId: SmallGroupId) (pref: ListPreferences) =
Patch.byId Table.Group (string groupId) {| Preferences = pref |}
/// Get a small group by its ID (including list preferences)
let tryById groupId =
Find.byId<SmallGroupId, SmallGroup> Table.Group groupId
/// Functions to manipulate churches
module Churches =
/// Get a list of all churches
let all () = Find.all<Church> Table.Church
/// Delete a church by its ID
let deleteById churchId =
backgroundTask {
use conn = Configuration.dbConn ()
use! txn = conn.BeginTransactionAsync()
let! groupIds = SmallGroups.groupIdsByChurch churchId
let gIdStrings = groupIds |> List.map string
do! Delete.byFields Table.Request All [ Field.In "smallGroupId" gIdStrings ]
let! users = Find.byFields<User> Table.User All [ Field.InArray "smallGroups" Table.User gIdStrings ]
for user in users do
do! Patch.byId Table.User (string user.Id) {| SmallGroups = user.SmallGroups |> List.except groupIds |}
do! Delete.byFields Table.Group All [ Field.Equal "churchId" (string churchId) ]
do! Delete.byId Table.Church (string churchId)
do! txn.CommitAsync()
}
/// Save a church's information
let save church = save<Church> Table.Church church
/// Find a church by its ID
let tryById churchId =
Find.byId<ChurchId, Church> Table.Church churchId
/// Functions to manipulate small group members
module Members =
/// Count members for the given small group
let countByGroup (groupId: SmallGroupId) =
Count.byFields Table.Member All [ Field.Equal "smallGroupId" (string groupId) ]
/// Delete a small group member by its ID
let deleteById (memberId: MemberId) = Delete.byId Table.Member (string memberId)
/// Retrieve all members for a given small group
let forGroup (groupId: SmallGroupId) =
Find.byFieldsOrdered<Member>
Table.Member
All
[ Field.Equal "smallGroupId" (string groupId) ]
[ Field.Named "memberName" ]
/// Save a small group member
let save mbr = save<Member> Table.Member mbr
/// Retrieve a small group member by its ID
let tryById memberId =
Find.byId<MemberId, Member> Table.Member memberId
/// Options to retrieve a list of requests
type PrayerRequestOptions =
{
/// The small group for which requests should be retrieved
SmallGroup: SmallGroup
/// The clock instance to use for date/time manipulation
Clock: IClock
/// The date for which the list is being retrieved
ListDate: LocalDate option
/// Whether only active requests should be retrieved
ActiveOnly: bool
/// The page number, for paged lists
PageNumber: int
}
/// Functions to manipulate prayer requests
module PrayerRequests =
/// Central place to append sort criteria for prayer request queries
let private orderBy sort =
match sort with
| SortByDate -> [ Field.Named "updatedDate DESC"; Field.Named "enteredDate DESC"; Field.Named "requestor" ]
| SortByRequestor -> [ Field.Named "requestor"; Field.Named "updatedDate DESC"; Field.Named "enteredDate DESC" ]
|> fun fields -> Query.orderBy fields SQLite
/// Paginate a prayer request query
let private paginate (pageNbr: int) pageSize =
if pageNbr > 0 then
$"LIMIT {pageSize} OFFSET {(pageNbr - 1) * pageSize}"
else
""
/// Count the number of prayer requests for a church
let countByChurch churchId =
backgroundTask {
let! groupIds = SmallGroups.groupIdsByChurch churchId
return! Count.byFields Table.Request All [ Field.In "smallGroupId" (List.map string groupIds) ]
}
/// Count the number of prayer requests for a small group
let countByGroup (groupId: SmallGroupId) =
Count.byFields Table.Request All [ Field.Equal "smallGroupId" (string groupId) ]
/// Delete a prayer request by its ID
let deleteById (reqId: PrayerRequestId) = Delete.byId Table.Request (string reqId)
/// Get all (or active) requests for a small group as of now or the specified date
let forGroup (opts: PrayerRequestOptions) =
let theDate = defaultArg opts.ListDate (opts.SmallGroup.LocalDateNow opts.Clock)
let sql, parameters =
if opts.ActiveOnly then
let expDate =
(theDate.AtStartOfDayInZone(opts.SmallGroup.TimeZone)
- Duration.FromDays opts.SmallGroup.Preferences.DaysToExpire)
.ToInstant()
$"""AND ( date(data->>'updatedDate') > date(:updatedDate)
OR data->>'expiration' = :expManual
OR data->>'requestType' IN (:typLongTerm, :typExpecting))
AND data->>'expiration' <> :expForced""",
[ SqliteParameter(":updatedDate", string expDate)
SqliteParameter(":expManual", string Manual)
SqliteParameter(":typLongTerm", string LongTermRequest)
SqliteParameter(":typExpecting", string Expecting)
SqliteParameter(":expForced", string Forced) ]
else
"", []
Custom.list
$"SELECT data FROM {Table.Request}
WHERE data->>'smallGroupId' = :groupId
{sql}
{orderBy opts.SmallGroup.Preferences.RequestSort}
{paginate opts.PageNumber opts.SmallGroup.Preferences.PageSize}"
(SqliteParameter(":groupId", string opts.SmallGroup.Id) :: parameters)
fromData<PrayerRequest>
/// Save a prayer request
let save req = save<PrayerRequest> Table.Request req
/// Search prayer requests for the given term
let searchForGroup group searchTerm pageNbr =
let pct = "%"
Custom.list
$"WITH results AS (
SELECT data FROM {Table.Request}
WHERE data->>'smallGroupId' = :groupId
AND data->>'text' LIKE :search
UNION
SELECT data FROM {Table.Request}
WHERE data->>'smallGroupId' = :groupId
AND COALESCE(data->>'requestor', '') LIKE :search)
SELECT data FROM results
{orderBy group.Preferences.RequestSort}
{paginate pageNbr group.Preferences.PageSize}"
[ SqliteParameter(":groupId", string group.Id); SqliteParameter(":search", $"{pct}%s{searchTerm}{pct}") ]
fromData<PrayerRequest>
/// Retrieve a prayer request by its ID
let tryById reqId =
Find.byId<PrayerRequestId, PrayerRequest> Table.Request reqId
/// Update the expiration for the given prayer request
let updateExpiration (req: PrayerRequest) withTime =
if withTime then
Patch.byId
Table.Request
(string req.Id)
{| UpdatedDate = req.UpdatedDate
Expiration = req.Expiration |}
else
Patch.byId Table.Request (string req.Id) {| Expiration = req.Expiration |}
/// Functions to manipulate users
module Users =
/// Retrieve all PrayerTracker users
let all () =
Find.allOrdered<User> Table.User [ Field.Named "lastName"; Field.Named "firstName" ]
/// Count the number of users for a church
let countByChurch churchId =
backgroundTask {
let! groupIds = SmallGroups.groupIdsByChurch churchId
return! Count.byFields Table.User All [ Field.InArray "smallGroups" Table.User (List.map string groupIds) ]
}
/// Count the number of users for a small group
let countByGroup (groupId: SmallGroupId) =
Count.byFields Table.User All [ Field.InArray "smallGroups" Table.User [ (string groupId) ] ]
/// Delete a user by its database ID
let deleteById (userId: UserId) = Delete.byId Table.User (string userId)
/// Get a list of users authorized to administer the given small group
let listByGroupId (groupId: SmallGroupId) =
Find.byFieldsOrdered<User>
Table.User
All
[ Field.InArray "smallGroups" Table.User [ (string groupId) ] ]
[ Field.Named "lastName"; Field.Named "firstName" ]
/// Save a user's information
let save user = save<User> Table.User user
/// Find a user by its e-mail address and authorized small group
let tryByEmailAndGroup (email: string) (groupId: SmallGroupId) =
Find.firstByFields<User>
Table.User
All
[ Field.Equal "email" email
Field.InArray "smallGroups" Table.User [ (string groupId) ] ]
/// Find a user by their database ID
let tryById userId =
Find.byId<UserId, User> Table.User userId
/// Update a user's last seen date/time
let updateLastSeen (userId: UserId) (now: Instant) =
Patch.byId Table.User (string userId) {| LastSeen = now |}
/// Update a user's password hash
let updatePassword (user: User) =
Patch.byId Table.User (string user.Id) {| PasswordHash = user.PasswordHash |}
/// Update a user's authorized small groups
let updateSmallGroups (userId: UserId) (groupIds: SmallGroupId list) =
Patch.byId Table.User (string userId) {| SmallGroups = groupIds |}

565
src/Data/Entities.fs Normal file
View File

@@ -0,0 +1,565 @@
namespace PrayerTracker.Entities
(*-- SUPPORT TYPES --*)
/// How as-of dates should (or should not) be displayed with requests
type AsOfDateDisplay =
/// No as-of date should be displayed
| NoDisplay
/// The as-of date should be displayed in the culture's short date format
| ShortDate
/// The as-of date should be displayed in the culture's long date format
| LongDate
/// Convert this to a single-character code
override this.ToString() =
match this with
| NoDisplay -> "N"
| ShortDate -> "S"
| LongDate -> "L"
/// <summary>Create an <c>AsOfDateDisplay</c> from a single-character code</summary>
static member Parse code =
match code with
| "N" -> NoDisplay
| "S" -> ShortDate
| "L" -> LongDate
| _ -> invalidArg "code" $"Unknown code {code}"
/// Acceptable e-mail formats
type EmailFormat =
/// HTML e-mail
| HtmlFormat
/// Plain-text e-mail
| PlainTextFormat
/// Convert this to a single-character code
override this.ToString() =
match this with
| HtmlFormat -> "H"
| PlainTextFormat -> "P"
/// <summary>Create an <c>EmailFormat</c> from a single-character code</summary>
static member Parse code =
match code with
| "H" -> HtmlFormat
| "P" -> PlainTextFormat
| _ -> invalidArg "code" $"Unknown code {code}"
/// Expiration for requests
type Expiration =
/// Follow the rules for normal expiration
| Automatic
/// Do not expire via rules
| Manual
/// Force immediate expiration
| Forced
/// Convert this to a single-character code
override this.ToString() =
match this with
| Automatic -> "A"
| Manual -> "M"
| Forced -> "F"
/// <summary>Create an <c>Expiration</c> from a single-character code</summary>
static member Parse code =
match code with
| "A" -> Automatic
| "M" -> Manual
| "F" -> Forced
| _ -> invalidArg "code" $"Unknown code {code}"
/// Types of prayer requests
type PrayerRequestType =
/// Current requests
| CurrentRequest
/// Long-term/ongoing request
| LongTermRequest
/// Expectant couples
| Expecting
/// Praise reports
| PraiseReport
/// Announcements
| Announcement
/// Convert this to a single-character code
override this.ToString() =
match this with
| CurrentRequest -> "C"
| LongTermRequest -> "L"
| Expecting -> "E"
| PraiseReport -> "P"
| Announcement -> "A"
/// <summary>Create a <c>PrayerRequestType</c> from a single-character code</summary>
static member Parse code =
match code with
| "C" -> CurrentRequest
| "L" -> LongTermRequest
| "E" -> Expecting
| "P" -> PraiseReport
| "A" -> Announcement
| _ -> invalidArg "code" $"Unknown code {code}"
/// How requests should be sorted
type RequestSort =
/// Sort by date, then by requestor/subject
| SortByDate
/// Sort by requestor/subject, then by date
| SortByRequestor
/// Convert this to a single-character code
override this.ToString() =
match this with
| SortByDate -> "D"
| SortByRequestor -> "R"
/// <summary>Create a <c>RequestSort</c> from a single-character code</summary>
static member Parse code =
match code with
| "D" -> SortByDate
| "R" -> SortByRequestor
| _ -> invalidArg "code" $"Unknown code {code}"
/// Type for a time zone ID
type TimeZoneId =
| TimeZoneId of string
override this.ToString() =
match this with
| TimeZoneId it -> it
open System
/// PK type for the Church entity
type ChurchId =
| ChurchId of Guid
/// The GUID value of the church ID
member this.Value =
this
|> function
| ChurchId guid -> guid
override this.ToString() =
this.Value.ToString "N"
/// PK type for the Member entity
type MemberId =
| MemberId of Guid
/// The GUID value of the member ID
member this.Value =
this
|> function
| MemberId guid -> guid
override this.ToString() =
this.Value.ToString "N"
/// PK type for the PrayerRequest entity
type PrayerRequestId =
| PrayerRequestId of Guid
/// The GUID value of the prayer request ID
member this.Value =
this
|> function
| PrayerRequestId guid -> guid
override this.ToString() =
this.Value.ToString "N"
/// PK type for the SmallGroup entity
type SmallGroupId =
| SmallGroupId of Guid
/// The GUID value of the small group ID
member this.Value =
this
|> function
| SmallGroupId guid -> guid
override this.ToString() =
this.Value.ToString "N"
/// PK type for the User entity
type UserId =
| UserId of Guid
/// The GUID value of the user ID
member this.Value =
this
|> function
| UserId guid -> guid
override this.ToString() =
this.Value.ToString "N"
(*-- SPECIFIC VIEW TYPES --*)
open Microsoft.Data.Sqlite
/// Statistics for churches
[<NoComparison; NoEquality>]
type ChurchStats =
{
/// The number of small groups in the church
SmallGroups: int
/// The number of prayer requests in the church
PrayerRequests: int
/// The number of users who can access small groups in the church
Users: int
}
/// Information needed to display the public/protected request list and small group maintenance pages
[<CLIMutable; NoComparison; NoEquality>]
type SmallGroupInfo =
{
/// The ID of the small group
Id: string
/// The name of the small group
Name: string
/// The name of the church to which the small group belongs
ChurchName: string
/// The ID of the time zone for the small group
TimeZoneId: TimeZoneId
/// Whether the small group has a publicly-available request list
IsPublic: bool
}
/// Map a row to a Small Group information set
static member FromReader (rdr: SqliteDataReader) =
{ Id = Giraffe.ShortGuid.fromGuid ((rdr.GetOrdinal >> rdr.GetString >> Guid.Parse) "id")
Name = (rdr.GetOrdinal >> rdr.GetString) "groupName"
ChurchName = (rdr.GetOrdinal >> rdr.GetString) "churchName"
TimeZoneId = (rdr.GetOrdinal >> rdr.GetString >> TimeZoneId) "timeZoneId"
IsPublic = (rdr.GetOrdinal >> rdr.GetBoolean) "isPublic" }
(*-- ENTITIES --*)
open NodaTime
/// This represents a church
[<CLIMutable; NoComparison; NoEquality>]
type Church =
{
/// The ID of this church
Id: ChurchId
/// The name of the church
Name: string
/// The city where the church is
City: string
/// The 2-letter state or province code for the church's location
State: string
/// Does this church have an active interface with Virtual Prayer Space?
HasVpsInterface: bool
/// The address for the interface
InterfaceAddress: string option
}
/// An empty church
// aww... how sad :(
static member Empty =
{ Id = ChurchId Guid.Empty
Name = ""
City = ""
State = ""
HasVpsInterface = false
InterfaceAddress = None }
/// Preferences for the form and format of the prayer request list
[<NoComparison; NoEquality>]
type ListPreferences =
{
/// The days after which regular requests expire
DaysToExpire: int
/// The number of days a new or updated request is considered new
DaysToKeepNew: int
/// The number of weeks after which long-term requests are flagged for follow-up
LongTermUpdateWeeks: int
/// The name from which e-mails are sent
EmailFromName: string
/// The e-mail address from which e-mails are sent
EmailFromAddress: string
/// The fonts to use in generating the list of prayer requests
Fonts: string
/// The color for the prayer request list headings
HeadingColor: string
/// The color for the lines offsetting the prayer request list headings
LineColor: string
/// The font size for the headings on the prayer request list
HeadingFontSize: int
/// The font size for the text on the prayer request list
TextFontSize: int
/// The order in which the prayer requests are sorted
RequestSort: RequestSort
/// The password used for "small group login" (view-only request list)
GroupPassword: string
/// The default e-mail type for this class
DefaultEmailType: EmailFormat
/// Whether this class makes its request list public
IsPublic: bool
/// The time zone which this class uses (use tzdata names)
TimeZoneId: TimeZoneId
/// The number of requests displayed per page
PageSize: int
/// How the as-of date should be automatically displayed
AsOfDateDisplay: AsOfDateDisplay
}
/// The list of fonts to use when displaying request lists (converts "native" to native font stack)
member this.FontStack =
if this.Fonts = "native" then
"""system-ui,-apple-system,"Segoe UI",Roboto,Ubuntu,"Liberation Sans",Cantarell,"Helvetica Neue",sans-serif"""
else
this.Fonts
/// A set of preferences with their default values
static member Empty =
{ DaysToExpire = 14
DaysToKeepNew = 7
LongTermUpdateWeeks = 4
EmailFromName = "PrayerTracker"
EmailFromAddress = "prayer@bitbadger.solutions"
Fonts = "native"
HeadingColor = "maroon"
LineColor = "navy"
HeadingFontSize = 16
TextFontSize = 12
RequestSort = SortByDate
GroupPassword = ""
DefaultEmailType = HtmlFormat
IsPublic = false
TimeZoneId = TimeZoneId "America/Denver"
PageSize = 100
AsOfDateDisplay = NoDisplay }
/// A member of a small group
[<CLIMutable; NoComparison; NoEquality>]
type Member =
{
/// The ID of the small group member
Id: MemberId
/// The Id of the small group to which this member belongs
SmallGroupId: SmallGroupId
/// The name of the member
Name: string
/// The e-mail address for the member
Email: string
/// The type of e-mail preferred by this member
Format: EmailFormat option
}
/// An empty member
static member Empty =
{ Id = MemberId Guid.Empty
SmallGroupId = SmallGroupId Guid.Empty
Name = ""
Email = ""
Format = None }
/// This represents a small group (Sunday School class, Bible study group, etc.)
[<CLIMutable; NoComparison; NoEquality>]
type SmallGroup =
{
/// The ID of this small group
Id: SmallGroupId
/// The church to which this group belongs
ChurchId: ChurchId
/// The name of the group
Name: string
/// The preferences for the request list
Preferences: ListPreferences
}
/// The DateTimeZone for the time zone ID for this small group
member this.TimeZone =
let tzId = string this.Preferences.TimeZoneId
if DateTimeZoneProviders.Tzdb.Ids.Contains tzId then
DateTimeZoneProviders.Tzdb[tzId]
else
DateTimeZone.Utc
/// Get the local date/time for this group
member this.LocalTimeNow(clock: IClock) =
if isNull clock then
nullArg (nameof clock)
clock.GetCurrentInstant().InZone(this.TimeZone).LocalDateTime
/// Get the local date for this group
member this.LocalDateNow clock = this.LocalTimeNow(clock).Date
/// An empty small group
static member Empty =
{ Id = SmallGroupId Guid.Empty
ChurchId = ChurchId Guid.Empty
Name = ""
Preferences = ListPreferences.Empty }
/// This represents a single prayer request
[<CLIMutable; NoComparison; NoEquality>]
type PrayerRequest =
{
/// The ID of this request
Id: PrayerRequestId
/// The type of the request
RequestType: PrayerRequestType
/// The ID of the user who entered the request
UserId: UserId
/// The small group to which this request belongs
SmallGroupId: SmallGroupId
/// The date/time on which this request was entered
EnteredDate: Instant
/// The date/time this request was last updated
UpdatedDate: Instant
/// The name of the requestor or subject, or title of announcement
Requestor: string option
/// The text of the request
Text: string
/// Whether the chaplain should be notified for this request
NotifyChaplain: bool
/// Is this request expired?
Expiration: Expiration
}
/// Is this request expired?
member this.IsExpired (asOf: LocalDate) (group: SmallGroup) =
match this.Expiration, this.RequestType with
| Forced, _ -> true
| Manual, _
| Automatic, LongTermRequest
| Automatic, Expecting -> false
| Automatic, _ ->
// Automatic expiration
Period
.Between(this.UpdatedDate.InZone(group.TimeZone).Date, asOf, PeriodUnits.Days)
.Days
>= group.Preferences.DaysToExpire
/// Is an update required for this long-term request?
member this.UpdateRequired asOf group =
if this.IsExpired asOf group then
false
else
asOf.PlusWeeks -group.Preferences.LongTermUpdateWeeks
>= this.UpdatedDate.InZone(group.TimeZone).Date
/// An empty request
static member Empty =
{ Id = PrayerRequestId Guid.Empty
RequestType = CurrentRequest
UserId = UserId Guid.Empty
SmallGroupId = SmallGroupId Guid.Empty
EnteredDate = Instant.MinValue
UpdatedDate = Instant.MinValue
Requestor = None
Text = ""
NotifyChaplain = false
Expiration = Automatic }
/// This represents a user of PrayerTracker
[<CLIMutable; NoComparison; NoEquality>]
type User =
{
/// The ID of this user
Id: UserId
/// The first name of this user
FirstName: string
/// The last name of this user
LastName: string
/// The e-mail address of the user
Email: string
/// Whether this user is a PrayerTracker system administrator
IsAdmin: bool
/// The user's hashed password
PasswordHash: string
/// The last time the user was seen (set whenever the user is loaded into a session)
LastSeen: Instant option
/// The small groups to which this user is authorized
SmallGroups: SmallGroupId list
}
/// The full name of the user
member this.Name = $"{this.FirstName} {this.LastName}"
/// An empty user
static member Empty =
{ Id = UserId Guid.Empty
FirstName = ""
LastName = ""
Email = ""
IsAdmin = false
PasswordHash = ""
LastSeen = None
SmallGroups = [] }

View File

@@ -0,0 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk">
<ItemGroup>
<Compile Include="Entities.fs" />
<Compile Include="Access.fs" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="BitBadger.Documents.Sqlite" Version="4.0.1" />
<PackageReference Include="Giraffe" Version="7.0.2" />
<PackageReference Include="NodaTime" Version="3.2.1" />
<PackageReference Include="NodaTime.Serialization.SystemTextJson" Version="1.3.0" />
<PackageReference Update="FSharp.Core" Version="9.0.101" />
</ItemGroup>
</Project>

View File

@@ -1,9 +1,11 @@
<Project> <Project>
<PropertyGroup> <PropertyGroup>
<AssemblyVersion>7.4.0.0</AssemblyVersion> <TargetFramework>net9.0</TargetFramework>
<FileVersion>7.4.0.0</FileVersion> <AssemblyVersion>9.0.0.0</AssemblyVersion>
<FileVersion>9.0.0.0</FileVersion>
<Authors>danieljsummers</Authors> <Authors>danieljsummers</Authors>
<Company>Bit Badger Solutions</Company> <Company>Bit Badger Solutions</Company>
<Version>7.4.0</Version> <Version>9.0.0</Version>
<DebugType>Embedded</DebugType>
</PropertyGroup> </PropertyGroup>
</Project> </Project>

25
src/Dockerfile Normal file
View File

@@ -0,0 +1,25 @@
FROM mcr.microsoft.com/dotnet/sdk:8.0-alpine AS build
WORKDIR /pt
COPY ./PrayerTracker.sln ./
COPY ./Directory.Build.props ./
COPY ./Data/PrayerTracker.Data.fsproj ./Data/
COPY ./UI/PrayerTracker.UI.fsproj ./UI/
COPY ./PrayerTracker/PrayerTracker.fsproj ./PrayerTracker/
COPY ./Tests/PrayerTracker.Tests.fsproj ./Tests/
RUN dotnet restore
COPY . ./
WORKDIR /pt/Tests
RUN dotnet run
WORKDIR /pt/PrayerTracker
RUN dotnet publish -c Release -r linux-x64
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 /pt/PrayerTracker/bin/Release/net8.0/linux-x64/publish/ ./
EXPOSE 80
CMD [ "dotnet", "/app/PrayerTracker.dll" ]

View File

@@ -1,86 +0,0 @@
namespace PrayerTracker
open Microsoft.EntityFrameworkCore
open PrayerTracker.Entities
/// EF Core data context for PrayerTracker
[<AllowNullLiteral>]
type AppDbContext (options : DbContextOptions<AppDbContext>) =
inherit DbContext (options)
[<DefaultValue>]
val mutable private churches : DbSet<Church>
[<DefaultValue>]
val mutable private members : DbSet<Member>
[<DefaultValue>]
val mutable private prayerRequests : DbSet<PrayerRequest>
[<DefaultValue>]
val mutable private preferences : DbSet<ListPreferences>
[<DefaultValue>]
val mutable private smallGroups : DbSet<SmallGroup>
[<DefaultValue>]
val mutable private timeZones : DbSet<TimeZone>
[<DefaultValue>]
val mutable private users : DbSet<User>
[<DefaultValue>]
val mutable private userGroupXref : DbSet<UserSmallGroup>
/// Churches
member this.Churches
with get() = this.churches
and set v = this.churches <- v
/// Small group members
member this.Members
with get() = this.members
and set v = this.members <- v
/// Prayer requests
member this.PrayerRequests
with get() = this.prayerRequests
and set v = this.prayerRequests <- v
/// Request list preferences (by class)
member this.Preferences
with get() = this.preferences
and set v = this.preferences <- v
/// Small groups
member this.SmallGroups
with get() = this.smallGroups
and set v = this.smallGroups <- v
/// Time zones
member this.TimeZones
with get() = this.timeZones
and set v = this.timeZones <- v
/// Users
member this.Users
with get() = this.users
and set v = this.users <- v
/// User / small group cross-reference
member this.UserGroupXref
with get() = this.userGroupXref
and set v = this.userGroupXref <- v
/// F#-style async for saving changes
member this.AsyncSaveChanges () =
this.SaveChangesAsync () |> Async.AwaitTask
override __.OnModelCreating (modelBuilder : ModelBuilder) =
base.OnModelCreating modelBuilder
modelBuilder.HasDefaultSchema "pt" |> ignore
[ Church.configureEF
ListPreferences.configureEF
Member.configureEF
PrayerRequest.configureEF
SmallGroup.configureEF
TimeZone.configureEF
User.configureEF
UserSmallGroup.configureEF
]
|> List.iter (fun x -> x modelBuilder)

View File

@@ -1,381 +0,0 @@
[<AutoOpen>]
module PrayerTracker.DataAccess
open FSharp.Control.Tasks.ContextInsensitive
open Microsoft.EntityFrameworkCore
open PrayerTracker.Entities
open System.Collections.Generic
open System.Linq
[<AutoOpen>]
module private Helpers =
open Microsoft.FSharpLu
open System.Threading.Tasks
/// Central place to append sort criteria for prayer request queries
let reqSort sort (q : IQueryable<PrayerRequest>) =
match sort with
| SortByDate ->
query {
for req in q do
sortByDescending req.updatedDate
thenByDescending req.enteredDate
thenBy req.requestor
}
| SortByRequestor ->
query {
for req in q do
sortBy req.requestor
thenByDescending req.updatedDate
thenByDescending req.enteredDate
}
/// Convert a possibly-null object to an option, wrapped as a task
let toOptionTask<'T> (item : 'T) = (Option.fromObject >> Task.FromResult) item
type AppDbContext with
(*-- DISCONNECTED DATA EXTENSIONS --*)
/// Add an entity entry to the tracked data context with the status of Added
member this.AddEntry<'TEntity when 'TEntity : not struct> (e : 'TEntity) =
this.Entry<'TEntity>(e).State <- EntityState.Added
/// Add an entity entry to the tracked data context with the status of Updated
member this.UpdateEntry<'TEntity when 'TEntity : not struct> (e : 'TEntity) =
this.Entry<'TEntity>(e).State <- EntityState.Modified
/// Add an entity entry to the tracked data context with the status of Deleted
member this.RemoveEntry<'TEntity when 'TEntity : not struct> (e : 'TEntity) =
this.Entry<'TEntity>(e).State <- EntityState.Deleted
(*-- CHURCH EXTENSIONS --*)
/// Find a church by its Id
member this.TryChurchById cId =
query {
for ch in this.Churches.AsNoTracking () do
where (ch.churchId = cId)
exactlyOneOrDefault
}
|> toOptionTask
/// Find all churches
member this.AllChurches () =
task {
let q =
query {
for ch in this.Churches.AsNoTracking () do
sortBy ch.name
}
let! churches = q.ToListAsync ()
return List.ofSeq churches
}
(*-- MEMBER EXTENSIONS --*)
/// Get a small group member by its Id
member this.TryMemberById mId =
query {
for mbr in this.Members.AsNoTracking () do
where (mbr.memberId = mId)
select mbr
exactlyOneOrDefault
}
|> toOptionTask
/// Find all members for a small group
member this.AllMembersForSmallGroup gId =
task {
let q =
query {
for mbr in this.Members.AsNoTracking () do
where (mbr.smallGroupId = gId)
sortBy mbr.memberName
}
let! mbrs = q.ToListAsync ()
return List.ofSeq mbrs
}
/// Count members for a small group
member this.CountMembersForSmallGroup gId =
this.Members.CountAsync (fun m -> m.smallGroupId = gId)
(*-- PRAYER REQUEST EXTENSIONS --*)
/// Get a prayer request by its Id
member this.TryRequestById reqId =
query {
for req in this.PrayerRequests.AsNoTracking () do
where (req.prayerRequestId = reqId)
exactlyOneOrDefault
}
|> toOptionTask
/// Get all (or active) requests for a small group as of now or the specified date
// TODO: why not make this an async list like the rest of these methods?
member this.AllRequestsForSmallGroup (grp : SmallGroup) clock listDate activeOnly pageNbr : PrayerRequest seq =
let theDate = match listDate with Some dt -> dt | _ -> grp.localDateNow clock
query {
for req in this.PrayerRequests.AsNoTracking () do
where (req.smallGroupId = grp.smallGroupId)
}
|> function
| q when activeOnly ->
let asOf = theDate.AddDays(-(float grp.preferences.daysToExpire)).Date
query {
for req in q do
where ( ( req.updatedDate > asOf
|| req.expiration = Manual
|| req.requestType = LongTermRequest
|| req.requestType = Expecting)
&& req.expiration <> Forced)
}
| q -> q
|> reqSort grp.preferences.requestSort
|> function
| q ->
match activeOnly with
| true -> upcast q
| false ->
upcast query {
for req in q do
skip ((pageNbr - 1) * grp.preferences.pageSize)
take grp.preferences.pageSize
}
/// Count prayer requests for the given small group Id
member this.CountRequestsBySmallGroup gId =
this.PrayerRequests.CountAsync (fun pr -> pr.smallGroupId = gId)
/// Count prayer requests for the given church Id
member this.CountRequestsByChurch cId =
this.PrayerRequests.CountAsync (fun pr -> pr.smallGroup.churchId = cId)
/// Get all (or active) requests for a small group as of now or the specified date
// TODO: same as above...
member this.SearchRequestsForSmallGroup (grp : SmallGroup) (searchTerm : string) pageNbr : PrayerRequest seq =
let pgSz = grp.preferences.pageSize
let toSkip = (pageNbr - 1) * pgSz
let sql =
""" SELECT * FROM pt."PrayerRequest" WHERE "SmallGroupId" = {0} AND "Text" ILIKE {1}
UNION
SELECT * FROM pt."PrayerRequest" WHERE "SmallGroupId" = {0} AND COALESCE("Requestor", '') ILIKE {1}"""
let like = sprintf "%%%s%%"
this.PrayerRequests.FromSqlRaw(sql, grp.smallGroupId, like searchTerm).AsNoTracking ()
|> reqSort grp.preferences.requestSort
|> function
| q ->
upcast query {
for req in q do
skip toSkip
take pgSz
}
(*-- SMALL GROUP EXTENSIONS --*)
/// Find a small group by its Id
member this.TryGroupById gId =
query {
for grp in this.SmallGroups.AsNoTracking().Include (fun sg -> sg.preferences) do
where (grp.smallGroupId = gId)
exactlyOneOrDefault
}
|> toOptionTask
/// Get small groups that are public or password protected
member this.PublicAndProtectedGroups () =
task {
let smallGroups = this.SmallGroups.AsNoTracking().Include(fun sg -> sg.preferences).Include (fun sg -> sg.church)
let q =
query {
for grp in smallGroups do
where ( grp.preferences.isPublic
|| (grp.preferences.groupPassword <> null && grp.preferences.groupPassword <> ""))
sortBy grp.church.name
thenBy grp.name
}
let! grps = q.ToListAsync ()
return List.ofSeq grps
}
/// Get small groups that are password protected
member this.ProtectedGroups () =
task {
let q =
query {
for grp in this.SmallGroups.AsNoTracking().Include (fun sg -> sg.church) do
where (grp.preferences.groupPassword <> null && grp.preferences.groupPassword <> "")
sortBy grp.church.name
thenBy grp.name
}
let! grps = q.ToListAsync ()
return List.ofSeq grps
}
/// Get all small groups
member this.AllGroups () =
task {
let! grps =
this.SmallGroups.AsNoTracking()
.Include(fun sg -> sg.church)
.Include(fun sg -> sg.preferences)
.Include(fun sg -> sg.preferences.timeZone)
.OrderBy(fun sg -> sg.name)
.ToListAsync ()
return List.ofSeq grps
}
/// Get a small group list by their Id, with their church prepended to their name
member this.GroupList () =
task {
let q =
query {
for grp in this.SmallGroups.AsNoTracking().Include (fun sg -> sg.church) do
sortBy grp.church.name
thenBy grp.name
}
let! grps = q.ToListAsync ()
return grps
|> Seq.map (fun grp -> grp.smallGroupId.ToString "N", sprintf "%s | %s" grp.church.name grp.name)
|> List.ofSeq
}
/// Log on a small group
member this.TryGroupLogOnByPassword gId pw =
task {
match! this.TryGroupById gId with
| None -> return None
| Some grp ->
match pw = grp.preferences.groupPassword with
| true -> return Some grp
| _ -> return None
}
/// Check a cookie log on for a small group
member this.TryGroupLogOnByCookie gId pwHash (hasher : string -> string) =
task {
match! this.TryGroupById gId with
| None -> return None
| Some grp ->
match pwHash = hasher grp.preferences.groupPassword with
| true -> return Some grp
| _ -> return None
}
/// Count small groups for the given church Id
member this.CountGroupsByChurch cId =
this.SmallGroups.CountAsync (fun sg -> sg.churchId = cId)
(*-- TIME ZONE EXTENSIONS --*)
/// Get a time zone by its Id
member this.TryTimeZoneById tzId =
query {
for tz in this.TimeZones do
where (tz.timeZoneId = tzId)
exactlyOneOrDefault
}
|> toOptionTask
/// Get all time zones
member this.AllTimeZones () =
task {
let q =
query {
for tz in this.TimeZones do
sortBy tz.sortOrder
}
let! tzs = q.ToListAsync ()
return List.ofSeq tzs
}
(*-- USER EXTENSIONS --*)
/// Find a user by its Id
member this.TryUserById uId =
query {
for usr in this.Users.AsNoTracking () do
where (usr.userId = uId)
exactlyOneOrDefault
}
|> toOptionTask
/// Find a user by its e-mail address and authorized small group
member this.TryUserByEmailAndGroup email gId =
query {
for usr in this.Users.AsNoTracking () do
where (usr.emailAddress = email && usr.smallGroups.Any (fun xref -> xref.smallGroupId = gId))
exactlyOneOrDefault
}
|> toOptionTask
/// Find a user by its Id (tracked entity), eagerly loading the user's groups
member this.TryUserByIdWithGroups uId =
query {
for usr in this.Users.AsNoTracking().Include (fun u -> u.smallGroups) do
where (usr.userId = uId)
exactlyOneOrDefault
}
|> toOptionTask
/// Get a list of all users
member this.AllUsers () =
task {
let q =
query {
for usr in this.Users.AsNoTracking () do
sortBy usr.lastName
thenBy usr.firstName
}
let! usrs = q.ToListAsync ()
return List.ofSeq usrs
}
/// Get all PrayerTracker users as members (used to send e-mails)
member this.AllUsersAsMembers () =
task {
let q =
query {
for usr in this.Users.AsNoTracking () do
sortBy usr.lastName
thenBy usr.firstName
select { Member.empty with email = usr.emailAddress; memberName = usr.fullName }
}
let! usrs = q.ToListAsync ()
return List.ofSeq usrs
}
/// Find a user based on their credentials
member this.TryUserLogOnByPassword email pwHash gId =
query {
for usr in this.Users.AsNoTracking () do
where ( usr.emailAddress = email
&& usr.passwordHash = pwHash
&& usr.smallGroups.Any (fun xref -> xref.smallGroupId = gId))
exactlyOneOrDefault
}
|> toOptionTask
/// Find a user based on credentials stored in a cookie
member this.TryUserLogOnByCookie uId gId pwHash =
task {
match! this.TryUserByIdWithGroups uId with
| None -> return None
| Some usr ->
match pwHash = usr.passwordHash && usr.smallGroups |> Seq.exists (fun xref -> xref.smallGroupId = gId) with
| true ->
this.Entry<User>(usr).State <- EntityState.Detached
return Some { usr with passwordHash = ""; salt = None; smallGroups = List<UserSmallGroup>() }
| _ -> return None
}
/// Count the number of users for a small group
member this.CountUsersBySmallGroup gId =
this.Users.CountAsync (fun u -> u.smallGroups.Any (fun xref -> xref.smallGroupId = gId))
/// Count the number of users for a church
member this.CountUsersByChurch cId =
this.Users.CountAsync (fun u -> u.smallGroups.Any (fun xref -> xref.smallGroup.churchId = cId))

View File

@@ -1,756 +0,0 @@
namespace PrayerTracker.Entities
open FSharp.EFCore.OptionConverter
open Microsoft.EntityFrameworkCore
open NodaTime
open System
open System.Collections.Generic
(*-- SUPPORT TYPES --*)
/// How as-of dates should (or should not) be displayed with requests
type AsOfDateDisplay =
/// No as-of date should be displayed
| NoDisplay
/// The as-of date should be displayed in the culture's short date format
| ShortDate
/// The as-of date should be displayed in the culture's long date format
| LongDate
with
/// Convert to a DU case from a single-character string
static member fromCode code =
match code with
| "N" -> NoDisplay
| "S" -> ShortDate
| "L" -> LongDate
| _ -> invalidArg "code" (sprintf "Unknown code %s" code)
/// Convert this DU case to a single-character string
member this.code =
match this with
| NoDisplay -> "N"
| ShortDate -> "S"
| LongDate -> "L"
/// Acceptable e-mail formats
type EmailFormat =
/// HTML e-mail
| HtmlFormat
/// Plain-text e-mail
| PlainTextFormat
with
/// Convert to a DU case from a single-character string
static member fromCode code =
match code with
| "H" -> HtmlFormat
| "P" -> PlainTextFormat
| _ -> invalidArg "code" (sprintf "Unknown code %s" code)
/// Convert this DU case to a single-character string
member this.code =
match this with
| HtmlFormat -> "H"
| PlainTextFormat -> "P"
/// Expiration for requests
type Expiration =
/// Follow the rules for normal expiration
| Automatic
/// Do not expire via rules
| Manual
/// Force immediate expiration
| Forced
with
/// Convert to a DU case from a single-character string
static member fromCode code =
match code with
| "A" -> Automatic
| "M" -> Manual
| "F" -> Forced
| _ -> invalidArg "code" (sprintf "Unknown code %s" code)
/// Convert this DU case to a single-character string
member this.code =
match this with
| Automatic -> "A"
| Manual -> "M"
| Forced -> "F"
/// Types of prayer requests
type PrayerRequestType =
/// Current requests
| CurrentRequest
/// Long-term/ongoing request
| LongTermRequest
/// Expectant couples
| Expecting
/// Praise reports
| PraiseReport
/// Announcements
| Announcement
with
/// Convert to a DU case from a single-character string
static member fromCode code =
match code with
| "C" -> CurrentRequest
| "L" -> LongTermRequest
| "E" -> Expecting
| "P" -> PraiseReport
| "A" -> Announcement
| _ -> invalidArg "code" (sprintf "Unknown code %s" code)
/// Convert this DU case to a single-character string
member this.code =
match this with
| CurrentRequest -> "C"
| LongTermRequest -> "L"
| Expecting -> "E"
| PraiseReport -> "P"
| Announcement -> "A"
/// How requests should be sorted
type RequestSort =
/// Sort by date, then by requestor/subject
| SortByDate
/// Sort by requestor/subject, then by date
| SortByRequestor
with
/// Convert to a DU case from a single-character string
static member fromCode code =
match code with
| "D" -> SortByDate
| "R" -> SortByRequestor
| _ -> invalidArg "code" (sprintf "Unknown code %s" code)
/// Convert this DU case to a single-character string
member this.code =
match this with
| SortByDate -> "D"
| SortByRequestor -> "R"
module Converters =
open Microsoft.EntityFrameworkCore.Storage.ValueConversion
open Microsoft.FSharp.Linq.RuntimeHelpers
open System.Linq.Expressions
let private asOfFromDU =
<@ Func<AsOfDateDisplay, string>(fun (x : AsOfDateDisplay) -> x.code) @>
|> LeafExpressionConverter.QuotationToExpression
|> unbox<Expression<Func<AsOfDateDisplay, string>>>
let private asOfToDU =
<@ Func<string, AsOfDateDisplay>(AsOfDateDisplay.fromCode) @>
|> LeafExpressionConverter.QuotationToExpression
|> unbox<Expression<Func<string, AsOfDateDisplay>>>
let private emailFromDU =
<@ Func<EmailFormat, string>(fun (x : EmailFormat) -> x.code) @>
|> LeafExpressionConverter.QuotationToExpression
|> unbox<Expression<Func<EmailFormat, string>>>
let private emailToDU =
<@ Func<string, EmailFormat>(EmailFormat.fromCode) @>
|> LeafExpressionConverter.QuotationToExpression
|> unbox<Expression<Func<string, EmailFormat>>>
let private expFromDU =
<@ Func<Expiration, string>(fun (x : Expiration) -> x.code) @>
|> LeafExpressionConverter.QuotationToExpression
|> unbox<Expression<Func<Expiration, string>>>
let private expToDU =
<@ Func<string, Expiration>(Expiration.fromCode) @>
|> LeafExpressionConverter.QuotationToExpression
|> unbox<Expression<Func<string, Expiration>>>
let private sortFromDU =
<@ Func<RequestSort, string>(fun (x : RequestSort) -> x.code) @>
|> LeafExpressionConverter.QuotationToExpression
|> unbox<Expression<Func<RequestSort, string>>>
let private sortToDU =
<@ Func<string, RequestSort>(RequestSort.fromCode) @>
|> LeafExpressionConverter.QuotationToExpression
|> unbox<Expression<Func<string, RequestSort>>>
let private typFromDU =
<@ Func<PrayerRequestType, string>(fun (x : PrayerRequestType) -> x.code) @>
|> LeafExpressionConverter.QuotationToExpression
|> unbox<Expression<Func<PrayerRequestType, string>>>
let private typToDU =
<@ Func<string, PrayerRequestType>(PrayerRequestType.fromCode) @>
|> LeafExpressionConverter.QuotationToExpression
|> unbox<Expression<Func<string, PrayerRequestType>>>
/// Conversion between a string and an AsOfDateDisplay DU value
type AsOfDateDisplayConverter () =
inherit ValueConverter<AsOfDateDisplay, string> (asOfFromDU, asOfToDU)
/// Conversion between a string and an EmailFormat DU value
type EmailFormatConverter () =
inherit ValueConverter<EmailFormat, string> (emailFromDU, emailToDU)
/// Conversion between a string and an Expiration DU value
type ExpirationConverter () =
inherit ValueConverter<Expiration, string> (expFromDU, expToDU)
/// Conversion between a string and an AsOfDateDisplay DU value
type PrayerRequestTypeConverter () =
inherit ValueConverter<PrayerRequestType, string> (typFromDU, typToDU)
/// Conversion between a string and a RequestSort DU value
type RequestSortConverter () =
inherit ValueConverter<RequestSort, string> (sortFromDU, sortToDU)
/// Statistics for churches
[<NoComparison; NoEquality>]
type ChurchStats =
{ /// The number of small groups in the church
smallGroups : int
/// The number of prayer requests in the church
prayerRequests : int
/// The number of users who can access small groups in the church
users : int
}
/// PK type for the Church entity
type ChurchId = Guid
/// PK type for the Member entity
type MemberId = Guid
/// PK type for the PrayerRequest entity
type PrayerRequestId = Guid
/// PK type for the SmallGroup entity
type SmallGroupId = Guid
/// PK type for the TimeZone entity
type TimeZoneId = string
/// PK type for the User entity
type UserId = Guid
/// PK for User/SmallGroup cross-reference table
type UserSmallGroupKey =
{ userId : UserId
smallGroupId : SmallGroupId
}
(*-- ENTITIES --*)
/// This represents a church
type [<CLIMutable; NoComparison; NoEquality>] Church =
{ /// The Id of this church
churchId : ChurchId
/// The name of the church
name : string
/// The city where the church is
city : string
/// The state where the church is
st : string
/// Does this church have an active interface with Virtual Prayer Room?
hasInterface : bool
/// The address for the interface
interfaceAddress : string option
/// Small groups for this church
smallGroups : ICollection<SmallGroup>
}
with
/// An empty church
// aww... how sad :(
static member empty =
{ churchId = Guid.Empty
name = ""
city = ""
st = ""
hasInterface = false
interfaceAddress = None
smallGroups = List<SmallGroup> ()
}
/// Configure EF for this entity
static member internal configureEF (mb : ModelBuilder) =
mb.Entity<Church> (
fun m ->
m.ToTable "Church" |> ignore
m.Property(fun e -> e.churchId).HasColumnName "ChurchId" |> ignore
m.Property(fun e -> e.name).HasColumnName("Name").IsRequired () |> ignore
m.Property(fun e -> e.city).HasColumnName("City").IsRequired () |> ignore
m.Property(fun e -> e.st).HasColumnName("ST").IsRequired().HasMaxLength 2 |> ignore
m.Property(fun e -> e.hasInterface).HasColumnName "HasVirtualPrayerRoomInterface" |> ignore
m.Property(fun e -> e.interfaceAddress).HasColumnName "InterfaceAddress" |> ignore)
|> ignore
mb.Model.FindEntityType(typeof<Church>).FindProperty("interfaceAddress")
.SetValueConverter(OptionConverter<string> ())
/// Preferences for the form and format of the prayer request list
and [<CLIMutable; NoComparison; NoEquality>] ListPreferences =
{ /// The Id of the small group to which these preferences belong
smallGroupId : SmallGroupId
/// The days after which regular requests expire
daysToExpire : int
/// The number of days a new or updated request is considered new
daysToKeepNew : int
/// The number of weeks after which long-term requests are flagged for follow-up
longTermUpdateWeeks : int
/// The name from which e-mails are sent
emailFromName : string
/// The e-mail address from which e-mails are sent
emailFromAddress : string
/// The fonts to use in generating the list of prayer requests
listFonts : string
/// The color for the prayer request list headings
headingColor : string
/// The color for the lines offsetting the prayer request list headings
lineColor : string
/// The font size for the headings on the prayer request list
headingFontSize : int
/// The font size for the text on the prayer request list
textFontSize : int
/// The order in which the prayer requests are sorted
requestSort : RequestSort
/// The password used for "small group login" (view-only request list)
groupPassword : string
/// The default e-mail type for this class
defaultEmailType : EmailFormat
/// Whether this class makes its request list public
isPublic : bool
/// The time zone which this class uses (use tzdata names)
timeZoneId : TimeZoneId
/// The time zone information
timeZone : TimeZone
/// The number of requests displayed per page
pageSize : int
/// How the as-of date should be automatically displayed
asOfDateDisplay : AsOfDateDisplay
}
with
/// A set of preferences with their default values
static member empty =
{ smallGroupId = Guid.Empty
daysToExpire = 14
daysToKeepNew = 7
longTermUpdateWeeks = 4
emailFromName = "PrayerTracker"
emailFromAddress = "prayer@djs-consulting.com"
listFonts = "Century Gothic,Tahoma,Luxi Sans,sans-serif"
headingColor = "maroon"
lineColor = "navy"
headingFontSize = 16
textFontSize = 12
requestSort = SortByDate
groupPassword = ""
defaultEmailType = HtmlFormat
isPublic = false
timeZoneId = "America/Denver"
timeZone = TimeZone.empty
pageSize = 100
asOfDateDisplay = NoDisplay
}
/// Configure EF for this entity
static member internal configureEF (mb : ModelBuilder) =
mb.Entity<ListPreferences> (
fun m ->
m.ToTable "ListPreference" |> ignore
m.HasKey (fun e -> e.smallGroupId :> obj) |> ignore
m.Property(fun e -> e.smallGroupId).HasColumnName "SmallGroupId" |> ignore
m.Property(fun e -> e.daysToKeepNew)
.HasColumnName("DaysToKeepNew")
.IsRequired()
.HasDefaultValue 7
|> ignore
m.Property(fun e -> e.daysToExpire)
.HasColumnName("DaysToExpire")
.IsRequired()
.HasDefaultValue 14
|> ignore
m.Property(fun e -> e.longTermUpdateWeeks)
.HasColumnName("LongTermUpdateWeeks")
.IsRequired()
.HasDefaultValue 4
|> ignore
m.Property(fun e -> e.emailFromName)
.HasColumnName("EmailFromName")
.IsRequired()
.HasDefaultValue "PrayerTracker"
|> ignore
m.Property(fun e -> e.emailFromAddress)
.HasColumnName("EmailFromAddress")
.IsRequired()
.HasDefaultValue "prayer@djs-consulting.com"
|> ignore
m.Property(fun e -> e.listFonts)
.HasColumnName("ListFonts")
.IsRequired()
.HasDefaultValue "Century Gothic,Tahoma,Luxi Sans,sans-serif"
|> ignore
m.Property(fun e -> e.headingColor)
.HasColumnName("HeadingColor")
.IsRequired()
.HasDefaultValue "maroon"
|> ignore
m.Property(fun e -> e.lineColor)
.HasColumnName("LineColor")
.IsRequired()
.HasDefaultValue "navy"
|> ignore
m.Property(fun e -> e.headingFontSize)
.HasColumnName("HeadingFontSize")
.IsRequired()
.HasDefaultValue 16
|> ignore
m.Property(fun e -> e.textFontSize)
.HasColumnName("TextFontSize")
.IsRequired()
.HasDefaultValue 12
|> ignore
m.Property(fun e -> e.requestSort)
.HasColumnName("RequestSort")
.IsRequired()
.HasMaxLength(1)
.HasDefaultValue SortByDate
|> ignore
m.Property(fun e -> e.groupPassword)
.HasColumnName("GroupPassword")
.IsRequired()
.HasDefaultValue ""
|> ignore
m.Property(fun e -> e.defaultEmailType)
.HasColumnName("DefaultEmailType")
.IsRequired()
.HasDefaultValue HtmlFormat
|> ignore
m.Property(fun e -> e.isPublic)
.HasColumnName("IsPublic")
.IsRequired()
.HasDefaultValue false
|> ignore
m.Property(fun e -> e.timeZoneId)
.HasColumnName("TimeZoneId")
.IsRequired()
.HasDefaultValue "America/Denver"
|> ignore
m.Property(fun e -> e.pageSize)
.HasColumnName("PageSize")
.IsRequired()
.HasDefaultValue 100
|> ignore
m.Property(fun e -> e.asOfDateDisplay)
.HasColumnName("AsOfDateDisplay")
.IsRequired()
.HasMaxLength(1)
.HasDefaultValue NoDisplay
|> ignore)
|> ignore
mb.Model.FindEntityType(typeof<ListPreferences>).FindProperty("requestSort")
.SetValueConverter(Converters.RequestSortConverter ())
mb.Model.FindEntityType(typeof<ListPreferences>).FindProperty("defaultEmailType")
.SetValueConverter(Converters.EmailFormatConverter ())
mb.Model.FindEntityType(typeof<ListPreferences>).FindProperty("asOfDateDisplay")
.SetValueConverter(Converters.AsOfDateDisplayConverter ())
/// A member of a small group
and [<CLIMutable; NoComparison; NoEquality>] Member =
{ /// The Id of the member
memberId : MemberId
/// The Id of the small group to which this member belongs
smallGroupId : SmallGroupId
/// The name of the member
memberName : string
/// The e-mail address for the member
email : string
/// The type of e-mail preferred by this member (see <see cref="EmailTypes"/> constants)
format : string option // TODO - do I need a custom formatter for this?
/// The small group to which this member belongs
smallGroup : SmallGroup
}
with
/// An empty member
static member empty =
{ memberId = Guid.Empty
smallGroupId = Guid.Empty
memberName = ""
email = ""
format = None
smallGroup = SmallGroup.empty
}
/// Configure EF for this entity
static member internal configureEF (mb : ModelBuilder) =
mb.Entity<Member> (
fun m ->
m.ToTable "Member" |> ignore
m.Property(fun e -> e.memberId).HasColumnName "MemberId" |> ignore
m.Property(fun e -> e.smallGroupId).HasColumnName "SmallGroupId" |> ignore
m.Property(fun e -> e.memberName).HasColumnName("MemberName").IsRequired() |> ignore
m.Property(fun e -> e.email).HasColumnName("Email").IsRequired() |> ignore
m.Property(fun e -> e.format).HasColumnName "Format" |> ignore)
|> ignore
mb.Model.FindEntityType(typeof<Member>).FindProperty("format").SetValueConverter(OptionConverter<string> ())
/// This represents a single prayer request
and [<CLIMutable; NoComparison; NoEquality>] PrayerRequest =
{ /// The Id of this request
prayerRequestId : PrayerRequestId
/// The type of the request
requestType : PrayerRequestType
/// The user who entered the request
userId : UserId
/// The small group to which this request belongs
smallGroupId : SmallGroupId
/// The date/time on which this request was entered
enteredDate : DateTime
/// The date/time this request was last updated
updatedDate : DateTime
/// The name of the requestor or subject, or title of announcement
requestor : string option
/// The text of the request
text : string
/// Whether the chaplain should be notified for this request
notifyChaplain : bool
/// The user who entered this request
user : User
/// The small group to which this request belongs
smallGroup : SmallGroup
/// Is this request expired?
expiration : Expiration
}
with
/// An empty request
static member empty =
{ prayerRequestId = Guid.Empty
requestType = CurrentRequest
userId = Guid.Empty
smallGroupId = Guid.Empty
enteredDate = DateTime.MinValue
updatedDate = DateTime.MinValue
requestor = None
text = ""
notifyChaplain = false
user = User.empty
smallGroup = SmallGroup.empty
expiration = Automatic
}
/// Is this request expired?
member this.isExpired (curr : DateTime) expDays =
match this.expiration with
| Forced -> true
| Manual -> false
| Automatic ->
match this.requestType with
| LongTermRequest
| Expecting -> false
| _ -> curr.AddDays(-(float expDays)).Date > this.updatedDate.Date // Automatic expiration
/// Is an update required for this long-term request?
member this.updateRequired curr expDays updWeeks =
match this.isExpired curr expDays with
| true -> false
| false -> curr.AddDays(-(float (updWeeks * 7))).Date > this.updatedDate.Date
/// Configure EF for this entity
static member internal configureEF (mb : ModelBuilder) =
mb.Entity<PrayerRequest> (
fun m ->
m.ToTable "PrayerRequest" |> ignore
m.Property(fun e -> e.prayerRequestId).HasColumnName "PrayerRequestId" |> ignore
m.Property(fun e -> e.requestType).HasColumnName("RequestType").IsRequired() |> ignore
m.Property(fun e -> e.userId).HasColumnName "UserId" |> ignore
m.Property(fun e -> e.smallGroupId).HasColumnName "SmallGroupId" |> ignore
m.Property(fun e -> e.enteredDate).HasColumnName "EnteredDate" |> ignore
m.Property(fun e -> e.updatedDate).HasColumnName "UpdatedDate" |> ignore
m.Property(fun e -> e.requestor).HasColumnName "Requestor" |> ignore
m.Property(fun e -> e.text).HasColumnName("Text").IsRequired() |> ignore
m.Property(fun e -> e.notifyChaplain).HasColumnName "NotifyChaplain" |> ignore
m.Property(fun e -> e.expiration).HasColumnName "Expiration" |> ignore)
|> ignore
mb.Model.FindEntityType(typeof<PrayerRequest>).FindProperty("requestType")
.SetValueConverter(Converters.PrayerRequestTypeConverter ())
mb.Model.FindEntityType(typeof<PrayerRequest>).FindProperty("requestor")
.SetValueConverter(OptionConverter<string> ())
mb.Model.FindEntityType(typeof<PrayerRequest>).FindProperty("expiration")
.SetValueConverter(Converters.ExpirationConverter ())
/// This represents a small group (Sunday School class, Bible study group, etc.)
and [<CLIMutable; NoComparison; NoEquality>] SmallGroup =
{ /// The Id of this small group
smallGroupId : SmallGroupId
/// The church to which this group belongs
churchId : ChurchId
/// The name of the group
name : string
/// The church to which this small group belongs
church : Church
/// The preferences for the request list
preferences : ListPreferences
/// The members of the group
members : ICollection<Member>
/// Prayer requests for this small group
prayerRequests : ICollection<PrayerRequest>
/// The users authorized to manage this group
users : ICollection<UserSmallGroup>
}
with
/// An empty small group
static member empty =
{ smallGroupId = Guid.Empty
churchId = Guid.Empty
name = ""
church = Church.empty
preferences = ListPreferences.empty
members = List<Member> ()
prayerRequests = List<PrayerRequest> ()
users = List<UserSmallGroup> ()
}
/// Get the local date for this group
member this.localTimeNow (clock : IClock) =
match clock with null -> nullArg "clock" | _ -> ()
let tz =
match DateTimeZoneProviders.Tzdb.Ids.Contains this.preferences.timeZoneId with
| true -> DateTimeZoneProviders.Tzdb.[this.preferences.timeZoneId]
| false -> DateTimeZone.Utc
clock.GetCurrentInstant().InZone(tz).ToDateTimeUnspecified()
/// Get the local date for this group
member this.localDateNow clock =
(this.localTimeNow clock).Date
/// Configure EF for this entity
static member internal configureEF (mb : ModelBuilder) =
mb.Entity<SmallGroup> (
fun m ->
m.ToTable "SmallGroup" |> ignore
m.Property(fun e -> e.smallGroupId).HasColumnName "SmallGroupId" |> ignore
m.Property(fun e -> e.churchId).HasColumnName "ChurchId" |> ignore
m.Property(fun e -> e.name).HasColumnName("Name").IsRequired() |> ignore
m.HasOne(fun e -> e.preferences) |> ignore)
|> ignore
/// This represents a time zone in which a class may reside
and [<CLIMutable; NoComparison; NoEquality>] TimeZone =
{ /// The Id for this time zone (uses tzdata names)
timeZoneId : TimeZoneId
/// The description of this time zone
description : string
/// The order in which this timezone should be displayed
sortOrder : int
/// Whether this timezone is active
isActive : bool
}
with
/// An empty time zone
static member empty =
{ timeZoneId = ""
description = ""
sortOrder = 0
isActive = false
}
/// Configure EF for this entity
static member internal configureEF (mb : ModelBuilder) =
mb.Entity<TimeZone> (
fun m ->
m.ToTable "TimeZone" |> ignore
m.Property(fun e -> e.timeZoneId).HasColumnName "TimeZoneId" |> ignore
m.Property(fun e -> e.description).HasColumnName("Description").IsRequired() |> ignore
m.Property(fun e -> e.sortOrder).HasColumnName "SortOrder" |> ignore
m.Property(fun e -> e.isActive).HasColumnName "IsActive" |> ignore)
|> ignore
/// This represents a user of PrayerTracker
and [<CLIMutable; NoComparison; NoEquality>] User =
{ /// The Id of this user
userId : UserId
/// The first name of this user
firstName : string
/// The last name of this user
lastName : string
/// The e-mail address of the user
emailAddress : string
/// Whether this user is a PrayerTracker system administrator
isAdmin : bool
/// The user's hashed password
passwordHash : string
/// The salt for the user's hashed password
salt : Guid option
/// The small groups which this user is authorized
smallGroups : ICollection<UserSmallGroup>
}
with
/// An empty user
static member empty =
{ userId = Guid.Empty
firstName = ""
lastName = ""
emailAddress = ""
isAdmin = false
passwordHash = ""
salt = None
smallGroups = List<UserSmallGroup> ()
}
/// The full name of the user
member this.fullName =
sprintf "%s %s" this.firstName this.lastName
/// Configure EF for this entity
static member internal configureEF (mb : ModelBuilder) =
mb.Entity<User> (
fun m ->
m.ToTable "User" |> ignore
m.Ignore(fun e -> e.fullName :> obj) |> ignore
m.Property(fun e -> e.userId).HasColumnName "UserId" |> ignore
m.Property(fun e -> e.firstName).HasColumnName("FirstName").IsRequired() |> ignore
m.Property(fun e -> e.lastName).HasColumnName("LastName").IsRequired() |> ignore
m.Property(fun e -> e.emailAddress).HasColumnName("EmailAddress").IsRequired() |> ignore
m.Property(fun e -> e.isAdmin).HasColumnName "IsSystemAdmin" |> ignore
m.Property(fun e -> e.passwordHash).HasColumnName("PasswordHash").IsRequired() |> ignore
m.Property(fun e -> e.salt).HasColumnName "Salt" |> ignore)
|> ignore
mb.Model.FindEntityType(typeof<User>).FindProperty("salt")
.SetValueConverter(OptionConverter<Guid> ())
/// Cross-reference between user and small group
and [<CLIMutable; NoComparison; NoEquality>] UserSmallGroup =
{ /// The Id of the user who has access to the small group
userId : UserId
/// The Id of the small group to which the user has access
smallGroupId : SmallGroupId
/// The user who has access to the small group
user : User
/// The small group to which the user has access
smallGroup : SmallGroup
}
with
/// An empty user/small group xref
static member empty =
{ userId = Guid.Empty
smallGroupId = Guid.Empty
user = User.empty
smallGroup = SmallGroup.empty
}
/// Configure EF for this entity
static member internal configureEF (mb : ModelBuilder) =
mb.Entity<UserSmallGroup> (
fun m ->
m.ToTable "User_SmallGroup" |> ignore
m.HasKey(fun e -> { userId = e.userId; smallGroupId = e.smallGroupId } :> obj) |> ignore
m.Property(fun e -> e.userId).HasColumnName "UserId" |> ignore
m.Property(fun e -> e.smallGroupId).HasColumnName "SmallGroupId" |> ignore
m.HasOne(fun e -> e.user)
.WithMany(fun e -> e.smallGroups :> IEnumerable<UserSmallGroup>)
.HasForeignKey(fun e -> e.userId :> obj)
|> ignore
m.HasOne(fun e -> e.smallGroup)
.WithMany(fun e -> e.users :> IEnumerable<UserSmallGroup>)
.HasForeignKey(fun e -> e.smallGroupId :> obj)
|> ignore)
|> ignore

View File

@@ -1,513 +0,0 @@
namespace PrayerTracker.Migrations
open Microsoft.EntityFrameworkCore
open Microsoft.EntityFrameworkCore.Infrastructure
open Microsoft.EntityFrameworkCore.Migrations
open Microsoft.EntityFrameworkCore.Migrations.Operations
open Microsoft.EntityFrameworkCore.Migrations.Operations.Builders
open Npgsql.EntityFrameworkCore.PostgreSQL.Metadata
open PrayerTracker
open PrayerTracker.Entities
open System
type ChurchTable =
{ churchId : OperationBuilder<AddColumnOperation>
city : OperationBuilder<AddColumnOperation>
hasInterface : OperationBuilder<AddColumnOperation>
interfaceAddress : OperationBuilder<AddColumnOperation>
name : OperationBuilder<AddColumnOperation>
st : OperationBuilder<AddColumnOperation>
}
type ListPreferencesTable =
{ smallGroupId : OperationBuilder<AddColumnOperation>
daysToExpire : OperationBuilder<AddColumnOperation>
daysToKeepNew : OperationBuilder<AddColumnOperation>
defaultEmailType : OperationBuilder<AddColumnOperation>
emailFromAddress : OperationBuilder<AddColumnOperation>
emailFromName : OperationBuilder<AddColumnOperation>
groupPassword : OperationBuilder<AddColumnOperation>
headingColor : OperationBuilder<AddColumnOperation>
headingFontSize : OperationBuilder<AddColumnOperation>
isPublic : OperationBuilder<AddColumnOperation>
lineColor : OperationBuilder<AddColumnOperation>
listFonts : OperationBuilder<AddColumnOperation>
longTermUpdateWeeks : OperationBuilder<AddColumnOperation>
requestSort : OperationBuilder<AddColumnOperation>
textFontSize : OperationBuilder<AddColumnOperation>
timeZoneId : OperationBuilder<AddColumnOperation>
pageSize : OperationBuilder<AddColumnOperation>
asOfDateDisplay : OperationBuilder<AddColumnOperation>
}
type MemberTable =
{ memberId : OperationBuilder<AddColumnOperation>
email : OperationBuilder<AddColumnOperation>
format : OperationBuilder<AddColumnOperation>
memberName : OperationBuilder<AddColumnOperation>
smallGroupId : OperationBuilder<AddColumnOperation>
}
type PrayerRequestTable =
{ prayerRequestId : OperationBuilder<AddColumnOperation>
enteredDate : OperationBuilder<AddColumnOperation>
expiration : OperationBuilder<AddColumnOperation>
notifyChaplain : OperationBuilder<AddColumnOperation>
requestType : OperationBuilder<AddColumnOperation>
requestor : OperationBuilder<AddColumnOperation>
smallGroupId : OperationBuilder<AddColumnOperation>
text : OperationBuilder<AddColumnOperation>
updatedDate : OperationBuilder<AddColumnOperation>
userId : OperationBuilder<AddColumnOperation>
}
type SmallGroupTable =
{ smallGroupId : OperationBuilder<AddColumnOperation>
churchId : OperationBuilder<AddColumnOperation>
name : OperationBuilder<AddColumnOperation>
}
type TimeZoneTable =
{ timeZoneId : OperationBuilder<AddColumnOperation>
description : OperationBuilder<AddColumnOperation>
isActive : OperationBuilder<AddColumnOperation>
sortOrder : OperationBuilder<AddColumnOperation>
}
type UserSmallGroupTable =
{ userId : OperationBuilder<AddColumnOperation>
smallGroupId : OperationBuilder<AddColumnOperation>
}
type UserTable =
{ userId : OperationBuilder<AddColumnOperation>
emailAddress : OperationBuilder<AddColumnOperation>
firstName : OperationBuilder<AddColumnOperation>
isAdmin : OperationBuilder<AddColumnOperation>
lastName : OperationBuilder<AddColumnOperation>
passwordHash : OperationBuilder<AddColumnOperation>
salt : OperationBuilder<AddColumnOperation>
}
[<DbContext (typeof<AppDbContext>)>]
[<Migration "20161217153124_InitialDatabase">]
type InitialDatabase () =
inherit Migration ()
override __.Up (migrationBuilder : MigrationBuilder) =
migrationBuilder.EnsureSchema (name = "pt")
|> ignore
migrationBuilder.CreateTable (
name = "Church",
schema = "pt",
columns =
(fun table ->
{ churchId = table.Column<Guid> (name = "ChurchId", nullable = false)
city = table.Column<string> (name = "City", nullable = false)
hasInterface = table.Column<bool> (name = "HasVirtualPrayerRoomInterface", nullable = false)
interfaceAddress = table.Column<string> (name = "InterfaceAddress", nullable = true)
name = table.Column<string> (name = "Name", nullable = false)
st = table.Column<string> (name = "ST", nullable = false, maxLength = Nullable<int> 2)
}),
constraints =
fun table ->
table.PrimaryKey ("PK_Church", fun x -> upcast x.churchId) |> ignore)
|> ignore
migrationBuilder.CreateTable (
name = "TimeZone",
schema = "pt",
columns =
(fun table ->
{ timeZoneId = table.Column<string> (name = "TimeZoneId", nullable = false)
description = table.Column<string> (name = "Description", nullable = false)
isActive = table.Column<bool> (name = "IsActive", nullable = false)
sortOrder = table.Column<int> (name = "SortOrder", nullable = false)
}),
constraints =
fun table ->
table.PrimaryKey ("PK_TimeZone", fun x -> upcast x.timeZoneId) |> ignore)
|> ignore
migrationBuilder.CreateTable (
name = "User",
schema = "pt",
columns =
(fun table ->
{ userId = table.Column<Guid> (name = "UserId", nullable = false)
emailAddress = table.Column<string> (name = "EmailAddress", nullable = false)
firstName = table.Column<string> (name = "FirstName", nullable = false)
isAdmin = table.Column<bool> (name = "IsSystemAdmin", nullable = false)
lastName = table.Column<string> (name = "LastName", nullable = false)
passwordHash = table.Column<string> (name = "PasswordHash", nullable = false)
salt = table.Column<Guid> (name = "Salt", nullable = true)
}),
constraints =
fun table ->
table.PrimaryKey("PK_User", fun x -> upcast x.userId) |> ignore)
|> ignore
migrationBuilder.CreateTable (
name = "SmallGroup",
schema = "pt",
columns =
(fun table ->
{ smallGroupId = table.Column<Guid> (name = "SmallGroupId", nullable = false)
churchId = table.Column<Guid> (name = "ChurchId", nullable = false)
name = table.Column<string> (name = "Name", nullable = false)
}),
constraints =
fun table ->
table.PrimaryKey ("PK_SmallGroup", fun x -> upcast x.smallGroupId) |> ignore
table.ForeignKey (
name = "FK_SmallGroup_Church_ChurchId",
column = (fun x -> upcast x.churchId),
principalSchema = "pt",
principalTable = "Church",
principalColumn = "ChurchId",
onDelete = ReferentialAction.Cascade)
|> ignore)
|> ignore
migrationBuilder.CreateTable (
name = "ListPreference",
schema = "pt",
columns =
(fun table ->
{ smallGroupId = table.Column<Guid> (name = "SmallGroupId", nullable = false)
daysToExpire = table.Column<int> (name = "DaysToExpire", nullable = false, defaultValue = 14)
daysToKeepNew = table.Column<int> (name = "DaysToKeepNew", nullable = false, defaultValue = 7)
defaultEmailType = table.Column<string> (name = "DefaultEmailType", nullable = false, defaultValue = "Html")
emailFromAddress = table.Column<string> (name = "EmailFromAddress", nullable = false, defaultValue = "prayer@djs-consulting.com")
emailFromName = table.Column<string> (name = "EmailFromName", nullable = false, defaultValue = "PrayerTracker")
groupPassword = table.Column<string> (name = "GroupPassword", nullable = false, defaultValue = "")
headingColor = table.Column<string> (name = "HeadingColor", nullable = false, defaultValue = "maroon")
headingFontSize = table.Column<int> (name = "HeadingFontSize", nullable = false, defaultValue = 16)
isPublic = table.Column<bool> (name = "IsPublic", nullable = false, defaultValue = false)
lineColor = table.Column<string> (name = "LineColor", nullable = false, defaultValue = "navy")
listFonts = table.Column<string> (name = "ListFonts", nullable = false, defaultValue = "Century Gothic,Tahoma,Luxi Sans,sans-serif")
longTermUpdateWeeks = table.Column<int> (name = "LongTermUpdateWeeks", nullable = false, defaultValue = 4)
requestSort = table.Column<string> (name = "RequestSort", nullable = false, defaultValue = "D", maxLength = Nullable<int> 1)
textFontSize = table.Column<int> (name = "TextFontSize", nullable = false, defaultValue = 12)
timeZoneId = table.Column<string> (name = "TimeZoneId", nullable = false, defaultValue = "America/Denver")
pageSize = table.Column<int> (name = "PageSize", nullable = false, defaultValue = 100)
asOfDateDisplay = table.Column<string> (name = "AsOfDateDisplay", nullable = false, defaultValue = "N", maxLength = Nullable<int> 1)
}),
constraints =
fun table ->
table.PrimaryKey ("PK_ListPreference", fun x -> upcast x.smallGroupId) |> ignore
table.ForeignKey (
name = "FK_ListPreference_SmallGroup_SmallGroupId",
column = (fun x -> upcast x.smallGroupId),
principalSchema = "pt",
principalTable = "SmallGroup",
principalColumn = "SmallGroupId",
onDelete = ReferentialAction.Cascade)
|> ignore
table.ForeignKey (
name = "FK_ListPreference_TimeZone_TimeZoneId",
column = (fun x -> upcast x.timeZoneId),
principalSchema = "pt",
principalTable = "TimeZone",
principalColumn = "TimeZoneId",
onDelete = ReferentialAction.Cascade)
|> ignore)
|> ignore
migrationBuilder.CreateTable (
name = "Member",
schema = "pt",
columns =
(fun table ->
{ memberId = table.Column<Guid> (name = "MemberId", nullable = false)
email = table.Column<string> (name = "Email", nullable = false)
format = table.Column<string> (name = "Format", nullable = true)
memberName = table.Column<string> (name = "MemberName", nullable = false)
smallGroupId = table.Column<Guid> (name = "SmallGroupId", nullable = false)
}),
constraints =
fun table ->
table.PrimaryKey ("PK_Member", fun x -> upcast x.memberId) |> ignore
table.ForeignKey (
name = "FK_Member_SmallGroup_SmallGroupId",
column = (fun x -> upcast x.smallGroupId),
principalSchema = "pt",
principalTable = "SmallGroup",
principalColumn = "SmallGroupId",
onDelete = ReferentialAction.Cascade)
|> ignore)
|> ignore
migrationBuilder.CreateTable (
name = "PrayerRequest",
schema = "pt",
columns =
(fun table ->
{ prayerRequestId = table.Column<Guid> (name = "PrayerRequestId", nullable = false)
expiration = table.Column<bool> (name = "Expiration", nullable = false)
enteredDate = table.Column<DateTime> (name = "EnteredDate", nullable = false)
notifyChaplain = table.Column<bool> (name = "NotifyChaplain", nullable = false)
requestType = table.Column<string> (name = "RequestType", nullable = false)
requestor = table.Column<string> (name = "Requestor", nullable = true)
smallGroupId = table.Column<Guid> (name = "SmallGroupId", nullable = false)
text = table.Column<string> (name = "Text", nullable = false)
updatedDate = table.Column<DateTime> (name = "UpdatedDate", nullable = false)
userId = table.Column<Guid> (name = "UserId", nullable = false)
}),
constraints =
fun table ->
table.PrimaryKey ("PK_PrayerRequest", fun x -> upcast x.prayerRequestId) |> ignore
table.ForeignKey (
name = "FK_PrayerRequest_SmallGroup_SmallGroupId",
column = (fun x -> upcast x.smallGroupId),
principalSchema = "pt",
principalTable = "SmallGroup",
principalColumn = "SmallGroupId",
onDelete = ReferentialAction.Cascade)
|> ignore
table.ForeignKey (
name = "FK_PrayerRequest_User_UserId",
column = (fun x -> upcast x.userId),
principalSchema = "pt",
principalTable = "User",
principalColumn = "UserId",
onDelete = ReferentialAction.Cascade)
|> ignore)
|> ignore
migrationBuilder.CreateTable(
name = "User_SmallGroup",
schema = "pt",
columns =
(fun table ->
{ userId = table.Column<Guid> (name = "UserId", nullable = false)
smallGroupId = table.Column<Guid> (name = "SmallGroupId", nullable = false)
}),
constraints =
fun table ->
table.PrimaryKey ("PK_User_SmallGroup", fun x -> upcast x) |> ignore
table.ForeignKey (
name = "FK_User_SmallGroup_SmallGroup_SmallGroupId",
column = (fun x -> upcast x.smallGroupId),
principalSchema = "pt",
principalTable = "SmallGroup",
principalColumn = "SmallGroupId",
onDelete = ReferentialAction.Cascade)
|> ignore
table.ForeignKey (
name = "FK_User_SmallGroup_User_UserId",
column = (fun x -> upcast x.userId),
principalSchema = "pt",
principalTable = "User",
principalColumn = "UserId",
onDelete = ReferentialAction.Cascade)
|> ignore)
|> ignore
migrationBuilder.CreateIndex (name = "IX_ListPreference_TimeZoneId", schema = "pt", table = "ListPreference", column = "TimeZoneId") |> ignore
migrationBuilder.CreateIndex (name = "IX_Member_SmallGroupId", schema = "pt", table = "Member", column = "SmallGroupId") |> ignore
migrationBuilder.CreateIndex (name = "IX_PrayerRequest_SmallGroupId", schema = "pt", table = "PrayerRequest", column = "SmallGroupId") |> ignore
migrationBuilder.CreateIndex (name = "IX_PrayerRequest_UserId", schema = "pt", table = "PrayerRequest", column = "UserId") |> ignore
migrationBuilder.CreateIndex (name = "IX_SmallGroup_ChurchId", schema = "pt", table = "SmallGroup", column = "ChurchId") |> ignore
migrationBuilder.CreateIndex (name = "IX_User_SmallGroup_SmallGroupId", schema = "pt", table = "User_SmallGroup", column = "SmallGroupId") |> ignore
override __.Down (migrationBuilder : MigrationBuilder) =
migrationBuilder.DropTable (name = "ListPreference", schema = "pt") |> ignore
migrationBuilder.DropTable (name = "Member", schema = "pt") |> ignore
migrationBuilder.DropTable (name = "PrayerRequest", schema = "pt") |> ignore
migrationBuilder.DropTable (name = "User_SmallGroup", schema = "pt") |> ignore
migrationBuilder.DropTable (name = "TimeZone", schema = "pt") |> ignore
migrationBuilder.DropTable (name = "SmallGroup", schema = "pt") |> ignore
migrationBuilder.DropTable (name = "User", schema = "pt") |> ignore
migrationBuilder.DropTable (name = "Church", schema = "pt") |> ignore
override __.BuildTargetModel (modelBuilder : ModelBuilder) =
modelBuilder
.HasDefaultSchema("pt")
.HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.SerialColumn)
.HasAnnotation("ProductVersion", "1.1.0-rtm-22752")
|> ignore
modelBuilder.Entity (
typeof<Church>,
fun b ->
b.Property<Guid>("churchId").ValueGeneratedOnAdd() |> ignore
b.Property<string>("city").IsRequired() |> ignore
b.Property<bool>("hasInterface") |> ignore
b.Property<string>("interfaceAddress") |> ignore
b.Property<string>("name").IsRequired() |> ignore
b.Property<string>("st").IsRequired().HasMaxLength(2) |> ignore
b.HasKey("churchId") |> ignore
b.ToTable("Church") |> ignore)
|> ignore
modelBuilder.Entity (
typeof<ListPreferences>,
fun b ->
b.Property<Guid>("smallGroupId") |> ignore
b.Property<int>("daysToExpire").ValueGeneratedOnAdd().HasDefaultValue(14) |> ignore
b.Property<int>("daysToKeepNew").ValueGeneratedOnAdd().HasDefaultValue(7) |> ignore
b.Property<string>("defaultEmailType").IsRequired().ValueGeneratedOnAdd().HasDefaultValue("H") |> ignore
b.Property<string>("emailFromAddress").IsRequired().ValueGeneratedOnAdd().HasDefaultValue("prayer@djs-consulting.com") |> ignore
b.Property<string>("emailFromName").IsRequired().ValueGeneratedOnAdd().HasDefaultValue("PrayerTracker") |> ignore
b.Property<string>("groupPassword").IsRequired().ValueGeneratedOnAdd().HasDefaultValue("") |> ignore
b.Property<string>("headingColor").IsRequired().ValueGeneratedOnAdd().HasDefaultValue("maroon") |> ignore
b.Property<int>("headingFontSize").ValueGeneratedOnAdd().HasDefaultValue(16) |> ignore
b.Property<bool>("isPublic").ValueGeneratedOnAdd().HasDefaultValue(false) |> ignore
b.Property<string>("lineColor").IsRequired().ValueGeneratedOnAdd().HasDefaultValue("navy") |> ignore
b.Property<string>("listFonts").IsRequired().ValueGeneratedOnAdd().HasDefaultValue("Century Gothic,Tahoma,Luxi Sans,sans-serif") |> ignore
b.Property<int>("longTermUpdateWeeks").ValueGeneratedOnAdd().HasDefaultValue(4) |> ignore
b.Property<string>("requestSort").IsRequired().ValueGeneratedOnAdd().HasDefaultValue("D").HasMaxLength(1) |> ignore
b.Property<int>("textFontSize").ValueGeneratedOnAdd().HasDefaultValue(12) |> ignore
b.Property<string>("timeZoneId").IsRequired().ValueGeneratedOnAdd().HasDefaultValue("America/Denver") |> ignore
b.Property<int>("pageSize").IsRequired().ValueGeneratedOnAdd().HasDefaultValue(100) |> ignore
b.Property<string>("asOfDateDisplay").IsRequired().ValueGeneratedOnAdd().HasDefaultValue("N").HasMaxLength(1) |> ignore
b.HasKey("smallGroupId") |> ignore
b.HasIndex("timeZoneId") |> ignore
b.ToTable("ListPreference") |> ignore)
|> ignore
modelBuilder.Entity (
typeof<Member>,
fun b ->
b.Property<Guid>("memberId").ValueGeneratedOnAdd() |> ignore
b.Property<string>("email").IsRequired() |> ignore
b.Property<string>("format") |> ignore
b.Property<string>("memberName").IsRequired() |> ignore
b.Property<Guid>("smallGroupId") |> ignore
b.HasKey("memberId") |> ignore
b.HasIndex("smallGroupId") |> ignore
b.ToTable("Member") |> ignore)
|> ignore
modelBuilder.Entity (
typeof<PrayerRequest>,
fun b ->
b.Property<Guid>("prayerRequestId").ValueGeneratedOnAdd() |> ignore
b.Property<DateTime>("enteredDate").IsRequired() |> ignore
b.Property<string>("expiration").IsRequired().HasMaxLength 1 |> ignore
b.Property<bool>("notifyChaplain") |> ignore
b.Property<string>("requestType").IsRequired().HasMaxLength 1 |> ignore
b.Property<string>("requestor") |> ignore
b.Property<Guid>("smallGroupId") |> ignore
b.Property<string>("text").IsRequired() |> ignore
b.Property<DateTime>("updatedDate") |> ignore
b.Property<Guid>("userId") |> ignore
b.HasKey("prayerRequestId") |> ignore
b.HasIndex("smallGroupId") |> ignore
b.HasIndex("userId") |> ignore
b.ToTable("PrayerRequest") |> ignore)
|> ignore
modelBuilder.Entity (
typeof<SmallGroup>,
fun b ->
b.Property<Guid>("smallGroupId").ValueGeneratedOnAdd() |> ignore
b.Property<Guid>("churchId") |> ignore
b.Property<string>("name").IsRequired() |> ignore
b.HasKey("smallGroupId") |> ignore
b.HasIndex("churchId") |> ignore
b.ToTable("SmallGroup") |> ignore)
|> ignore
modelBuilder.Entity (
typeof<PrayerTracker.Entities.TimeZone>,
fun b ->
b.Property<string>("timeZoneId").ValueGeneratedOnAdd() |> ignore
b.Property<string>("description").IsRequired() |> ignore
b.Property<bool>("isActive") |> ignore
b.Property<int>("sortOrder") |> ignore
b.HasKey("timeZoneId") |> ignore
b.ToTable("TimeZone") |> ignore)
|> ignore
modelBuilder.Entity (
typeof<User>,
fun b ->
b.Property<Guid>("userId").ValueGeneratedOnAdd() |> ignore
b.Property<string>("emailAddress").IsRequired() |> ignore
b.Property<string>("firstName").IsRequired() |> ignore
b.Property<bool>("isAdmin") |> ignore
b.Property<string>("lastName").IsRequired() |> ignore
b.Property<string>("passwordHash").IsRequired() |> ignore
b.Property<Guid>("salt") |> ignore
b.HasKey("userId") |> ignore
b.ToTable("User") |> ignore)
|> ignore
modelBuilder.Entity (
typeof<UserSmallGroup>,
fun b ->
b.Property<Guid>("userId") |> ignore
b.Property<Guid>("smallGroupId") |> ignore
b.HasKey("userId", "smallGroupId") |> ignore
b.HasIndex("smallGroupId") |> ignore
b.ToTable("User_SmallGroup") |> ignore)
|> ignore
modelBuilder.Entity (
typeof<ListPreferences>,
fun b ->
b.HasOne("PrayerTracker.Entities.SmallGroup")
.WithOne("preferences")
.HasForeignKey("PrayerTracker.Entities.ListPreferences", "smallGroupId")
.OnDelete(DeleteBehavior.Cascade)
|> ignore
b.HasOne("PrayerTracker.Entities.TimeZone", "timeZone")
.WithMany()
.HasForeignKey("timeZoneId")
.OnDelete(DeleteBehavior.Cascade)
|> ignore)
|> ignore
modelBuilder.Entity (
typeof<Member>,
fun b ->
b.HasOne("PrayerTracker.Entities.SmallGroup", "smallGroup")
.WithMany("members")
.HasForeignKey("smallGroupId")
.OnDelete(DeleteBehavior.Cascade)
|> ignore)
|> ignore
modelBuilder.Entity (
typeof<PrayerRequest>,
fun b ->
b.HasOne("PrayerTracker.Entities.SmallGroup", "smallGroup")
.WithMany("prayerRequests")
.HasForeignKey("smallGroupId")
.OnDelete(DeleteBehavior.Cascade)
|> ignore
b.HasOne("PrayerTracker.Entities.User", "user")
.WithMany()
.HasForeignKey("userId")
.OnDelete(DeleteBehavior.Cascade)
|> ignore)
|> ignore
modelBuilder.Entity (
typeof<SmallGroup>,
fun b ->
b.HasOne("PrayerTracker.Entities.Church", "Church")
.WithMany("SmallGroups")
.HasForeignKey("ChurchId")
.OnDelete(DeleteBehavior.Cascade)
|> ignore)
|> ignore
modelBuilder.Entity (
typeof<UserSmallGroup>,
fun b ->
b.HasOne("PrayerTracker.Entities.SmallGroup", "smallGroup")
.WithMany("users")
.HasForeignKey("smallGroupId")
.OnDelete(DeleteBehavior.Cascade)
|> ignore
b.HasOne("PrayerTracker.Entities.User", "user")
.WithMany("smallGroups")
.HasForeignKey("userId")
.OnDelete(DeleteBehavior.Cascade)
|> ignore)
|> ignore

View File

@@ -1,200 +0,0 @@
namespace PrayerTracker.Migrations
open Microsoft.EntityFrameworkCore
open Microsoft.EntityFrameworkCore.Infrastructure
open Npgsql.EntityFrameworkCore.PostgreSQL.Metadata
open PrayerTracker
open PrayerTracker.Entities
open System
[<DbContext (typeof<AppDbContext>)>]
type AppDbContextModelSnapshot () =
inherit ModelSnapshot ()
override __.BuildModel (modelBuilder : ModelBuilder) =
modelBuilder
.HasDefaultSchema("pt")
.HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.SerialColumn)
.HasAnnotation("ProductVersion", "1.1.0-rtm-22752")
|> ignore
modelBuilder.Entity (
typeof<Church>,
fun b ->
b.Property<Guid>("churchId").ValueGeneratedOnAdd() |> ignore
b.Property<string>("city").IsRequired() |> ignore
b.Property<bool>("hasInterface") |> ignore
b.Property<string>("interfaceAddress") |> ignore
b.Property<string>("name").IsRequired() |> ignore
b.Property<string>("st").IsRequired().HasMaxLength(2) |> ignore
b.HasKey("churchId") |> ignore
b.ToTable("Church") |> ignore)
|> ignore
modelBuilder.Entity (
typeof<ListPreferences>,
fun b ->
b.Property<Guid>("smallGroupId") |> ignore
b.Property<int>("daysToExpire").ValueGeneratedOnAdd().HasDefaultValue(14) |> ignore
b.Property<int>("daysToKeepNew").ValueGeneratedOnAdd().HasDefaultValue(7) |> ignore
b.Property<string>("defaultEmailType").IsRequired().ValueGeneratedOnAdd().HasDefaultValue("H").HasMaxLength(1) |> ignore
b.Property<string>("emailFromAddress").IsRequired().ValueGeneratedOnAdd().HasDefaultValue("prayer@djs-consulting.com") |> ignore
b.Property<string>("emailFromName").IsRequired().ValueGeneratedOnAdd().HasDefaultValue("PrayerTracker") |> ignore
b.Property<string>("groupPassword").IsRequired().ValueGeneratedOnAdd().HasDefaultValue("") |> ignore
b.Property<string>("headingColor").IsRequired().ValueGeneratedOnAdd().HasDefaultValue("maroon") |> ignore
b.Property<int>("headingFontSize").ValueGeneratedOnAdd().HasDefaultValue(16) |> ignore
b.Property<bool>("isPublic").ValueGeneratedOnAdd().HasDefaultValue(false) |> ignore
b.Property<string>("lineColor").IsRequired().ValueGeneratedOnAdd().HasDefaultValue("navy") |> ignore
b.Property<string>("listFonts").IsRequired().ValueGeneratedOnAdd().HasDefaultValue("Century Gothic,Tahoma,Luxi Sans,sans-serif") |> ignore
b.Property<int>("longTermUpdateWeeks").ValueGeneratedOnAdd().HasDefaultValue(4) |> ignore
b.Property<string>("requestSort").IsRequired().ValueGeneratedOnAdd().HasDefaultValue("D").HasMaxLength(1) |> ignore
b.Property<int>("textFontSize").ValueGeneratedOnAdd().HasDefaultValue(12) |> ignore
b.Property<string>("timeZoneId").IsRequired().ValueGeneratedOnAdd().HasDefaultValue("America/Denver") |> ignore
b.Property<int>("pageSize").IsRequired().ValueGeneratedOnAdd().HasDefaultValue(100) |> ignore
b.Property<string>("asOfDateDisplay").IsRequired().ValueGeneratedOnAdd().HasDefaultValue("N").HasMaxLength(1) |> ignore
b.HasKey("smallGroupId") |> ignore
b.HasIndex("timeZoneId") |> ignore
b.ToTable("ListPreference") |> ignore)
|> ignore
modelBuilder.Entity (
typeof<Member>,
fun b ->
b.Property<Guid>("memberId").ValueGeneratedOnAdd() |> ignore
b.Property<string>("email").IsRequired() |> ignore
b.Property<string>("format") |> ignore
b.Property<string>("memberName").IsRequired() |> ignore
b.Property<Guid>("smallGroupId") |> ignore
b.HasKey("memberId") |> ignore
b.HasIndex("smallGroupId") |> ignore
b.ToTable("Member") |> ignore)
|> ignore
modelBuilder.Entity (
typeof<PrayerRequest>,
fun b ->
b.Property<Guid>("prayerRequestId").ValueGeneratedOnAdd() |> ignore
b.Property<DateTime>("enteredDate") |> ignore
b.Property<string>("expiration").IsRequired().HasMaxLength(1) |> ignore
b.Property<bool>("notifyChaplain") |> ignore
b.Property<string>("requestType").IsRequired().HasMaxLength(1) |> ignore
b.Property<string>("requestor") |> ignore
b.Property<Guid>("smallGroupId") |> ignore
b.Property<string>("text").IsRequired() |> ignore
b.Property<DateTime>("updatedDate") |> ignore
b.Property<Guid>("userId") |> ignore
b.HasKey("prayerRequestId") |> ignore
b.HasIndex("smallGroupId") |> ignore
b.HasIndex("userId") |> ignore
b.ToTable("PrayerRequest") |> ignore)
|> ignore
modelBuilder.Entity (
typeof<SmallGroup>,
fun b ->
b.Property<Guid>("smallGroupId").ValueGeneratedOnAdd() |> ignore
b.Property<Guid>("churchId") |> ignore
b.Property<string>("name").IsRequired() |> ignore
b.HasKey("smallGroupId") |> ignore
b.HasIndex("churchId") |> ignore
b.ToTable("SmallGroup") |> ignore)
|> ignore
modelBuilder.Entity (
typeof<PrayerTracker.Entities.TimeZone>,
fun b ->
b.Property<string>("timeZoneId").ValueGeneratedOnAdd() |> ignore
b.Property<string>("description").IsRequired() |> ignore
b.Property<bool>("isActive") |> ignore
b.Property<int>("sortOrder") |> ignore
b.HasKey("timeZoneId") |> ignore
b.ToTable("TimeZone") |> ignore)
|> ignore
modelBuilder.Entity (
typeof<User>,
fun b ->
b.Property<Guid>("userId").ValueGeneratedOnAdd() |> ignore
b.Property<string>("emailAddress").IsRequired() |> ignore
b.Property<string>("firstName").IsRequired() |> ignore
b.Property<bool>("isAdmin") |> ignore
b.Property<string>("lastName").IsRequired() |> ignore
b.Property<string>("passwordHash").IsRequired() |> ignore
b.Property<Guid>("salt") |> ignore
b.HasKey("userId") |> ignore
b.ToTable("User") |> ignore)
|> ignore
modelBuilder.Entity (
typeof<UserSmallGroup>,
fun b ->
b.Property<Guid>("userId") |> ignore
b.Property<Guid>("smallGroupId") |> ignore
b.HasKey("userId", "smallGroupId") |> ignore
b.HasIndex("smallGroupId") |> ignore
b.ToTable("User_SmallGroup") |> ignore)
|> ignore
modelBuilder.Entity (
typeof<ListPreferences>,
fun b ->
b.HasOne("PrayerTracker.Entities.SmallGroup")
.WithOne("preferences")
.HasForeignKey("PrayerTracker.Entities.ListPreferences", "smallGroupId")
.OnDelete(DeleteBehavior.Cascade)
|> ignore
b.HasOne("PrayerTracker.Entities.TimeZone", "timeZone")
.WithMany()
.HasForeignKey("timeZoneId")
.OnDelete(DeleteBehavior.Cascade)
|> ignore)
|> ignore
modelBuilder.Entity (
typeof<Member>,
fun b ->
b.HasOne("PrayerTracker.Entities.SmallGroup", "smallGroup")
.WithMany("members")
.HasForeignKey("smallGroupId")
.OnDelete(DeleteBehavior.Cascade)
|> ignore)
|> ignore
modelBuilder.Entity (
typeof<PrayerRequest>,
fun b ->
b.HasOne("PrayerTracker.Entities.SmallGroup", "smallGroup")
.WithMany("prayerRequests")
.HasForeignKey("smallGroupId")
.OnDelete(DeleteBehavior.Cascade)
|> ignore
b.HasOne("PrayerTracker.Entities.User", "user")
.WithMany()
.HasForeignKey("userId")
.OnDelete(DeleteBehavior.Cascade)
|> ignore)
|> ignore
modelBuilder.Entity (
typeof<SmallGroup>,
fun b ->
b.HasOne("PrayerTracker.Entities.Church", "Church")
.WithMany("SmallGroups")
.HasForeignKey("ChurchId")
.OnDelete(DeleteBehavior.Cascade)
|> ignore)
|> ignore
modelBuilder.Entity (
typeof<UserSmallGroup>,
fun b ->
b.HasOne("PrayerTracker.Entities.SmallGroup", "smallGroup")
.WithMany("users")
.HasForeignKey("smallGroupId")
.OnDelete(DeleteBehavior.Cascade)
|> ignore
b.HasOne("PrayerTracker.Entities.User", "user")
.WithMany("smallGroups")
.HasForeignKey("userId")
.OnDelete(DeleteBehavior.Cascade)
|> ignore)
|> ignore

View File

@@ -1,27 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<Compile Include="Entities.fs" />
<Compile Include="AppDbContext.fs" />
<Compile Include="DataAccess.fs" />
<Compile Include="Migrations\20161217153124_InitialDatabase.fs" />
<Compile Include="Migrations\AppDbContextModelSnapshot.fs" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="FSharp.EFCore.OptionConverter" Version="1.0.0" />
<PackageReference Include="Microsoft.FSharpLu" Version="0.11.5" />
<PackageReference Include="NodaTime" Version="2.4.7" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="3.0.1" />
<PackageReference Include="TaskBuilder.fs" Version="2.1.0" />
</ItemGroup>
<ItemGroup>
<PackageReference Update="FSharp.Core" Version="4.7.0" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net9.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<Compile Include="Program.fs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Data\PrayerTracker.Data.fsproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="BitBadger.Documents.Postgres" Version="4.0.1" />
<PackageReference Include="Npgsql.NodaTime" Version="9.0.2" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,133 @@

open NodaTime
open PrayerTracker.Entities
module PgMappings =
/// Map a row to a Church instance
let mapToChurch (row: RowReader) =
{ Id = ChurchId (row.uuid "id")
Name = row.string "church_name"
City = row.string "city"
State = row.string "state"
HasVpsInterface = row.bool "has_vps_interface"
InterfaceAddress = row.stringOrNone "interface_address" }
/// Map a row to a Member instance
let mapToMember (row: RowReader) =
{ Id = MemberId (row.uuid "id")
SmallGroupId = SmallGroupId (row.uuid "small_group_id")
Name = row.string "member_name"
Email = row.string "email"
Format = row.stringOrNone "email_format" |> Option.map EmailFormat.Parse }
/// Map a row to a Prayer Request instance
let mapToPrayerRequest (row: RowReader) =
{ Id = PrayerRequestId (row.uuid "id")
UserId = UserId (row.uuid "user_id")
SmallGroupId = SmallGroupId (row.uuid "small_group_id")
EnteredDate = row.fieldValue<Instant> "entered_date"
UpdatedDate = row.fieldValue<Instant> "updated_date"
Requestor = row.stringOrNone "requestor"
Text = row.string "request_text"
NotifyChaplain = row.bool "notify_chaplain"
RequestType = PrayerRequestType.Parse (row.string "request_type")
Expiration = Expiration.Parse (row.string "expiration") }
/// Map a row to a Small Group instance
let mapToSmallGroup (row: RowReader) =
{ Id = SmallGroupId (row.uuid "id")
ChurchId = ChurchId (row.uuid "church_id")
Name = row.string "group_name"
Preferences =
{ DaysToKeepNew = row.int "days_to_keep_new"
DaysToExpire = row.int "days_to_expire"
LongTermUpdateWeeks = row.int "long_term_update_weeks"
EmailFromName = row.string "email_from_name"
EmailFromAddress = row.string "email_from_address"
Fonts = row.string "fonts"
HeadingColor = row.string "heading_color"
LineColor = row.string "line_color"
HeadingFontSize = row.int "heading_font_size"
TextFontSize = row.int "text_font_size"
GroupPassword = row.string "group_password"
IsPublic = row.bool "is_public"
PageSize = row.int "page_size"
TimeZoneId = TimeZoneId (row.string "time_zone_id")
RequestSort = RequestSort.Parse (row.string "request_sort")
DefaultEmailType = EmailFormat.Parse (row.string "default_email_type")
AsOfDateDisplay = AsOfDateDisplay.Parse (row.string "as_of_date_display") } }
/// Map a row to a User instance
let mapToUser (row: RowReader) =
{ Id = UserId (row.uuid "id")
FirstName = row.string "first_name"
LastName = row.string "last_name"
Email = row.string "email"
IsAdmin = row.bool "is_admin"
PasswordHash = row.string "password_hash"
LastSeen = row.fieldValueOrNone<Instant> "last_seen"
SmallGroups = [] }
open System
open BitBadger.Documents.Sqlite
open Npgsql
open Npgsql.FSharp
open PrayerTracker.Data
task {
Configuration.useConnectionString (Environment.GetEnvironmentVariable "PT_SQLITE_CONN")
do! Connection.setUp ()
let builder = NpgsqlDataSourceBuilder(Environment.GetEnvironmentVariable "PT_PG_CONN")
let _ = builder.UseNodaTime()
use source = builder.Build()
let! churches =
Sql.fromDataSource source
|> Sql.query "SELECT * FROM pt.church"
|> Sql.executeAsync PgMappings.mapToChurch
for church in churches do
do! Churches.save church
printfn "Migrated %d churches" churches.Length
let! groups =
Sql.fromDataSource source
|> Sql.query "SELECT sg.*, lp.* FROM pt.small_group sg
INNER JOIN pt.list_preference lp ON lp.small_group_id = sg.id"
|> Sql.executeAsync PgMappings.mapToSmallGroup
for group in groups do
do! SmallGroups.save group
printfn "Migrated %d groups" groups.Length
let! members =
Sql.fromDataSource source
|> Sql.query "SELECT * from pt.member"
|> Sql.executeAsync PgMappings.mapToMember
for mbr in members do
do! Members.save mbr
printfn "Migrated %d members" members.Length
let! requests =
Sql.fromDataSource source
|> Sql.query "SELECT * from pt.prayer_request"
|> Sql.executeAsync PgMappings.mapToPrayerRequest
for request in requests do
do! PrayerRequests.save request
printfn "Migrated %d requests" requests.Length
let! users =
Sql.fromDataSource source
|> Sql.query "SELECT * FROM pt.pt_user"
|> Sql.executeAsync PgMappings.mapToUser
for user in users do
let! groups =
Sql.fromDataSource source
|> Sql.query "SELECT small_group_id FROM pt.user_small_group WHERE user_id = @user_id"
|> Sql.parameters [ "@user_id", Sql.uuid user.Id.Value ]
|> Sql.executeAsync (fun row -> (row.uuid >> SmallGroupId) "small_group_id")
do! Users.save { user with SmallGroups = groups }
printfn "Migrated %d users" users.Length
} |> Async.AwaitTask |> Async.RunSynchronously

View File

@@ -1,362 +0,0 @@
module PrayerTracker.Entities.EntitiesTests
open Expecto
open NodaTime.Testing
open NodaTime
open System
[<Tests>]
let asOfDateDisplayTests =
testList "AsOfDateDisplay" [
test "NoDisplay code is correct" {
Expect.equal NoDisplay.code "N" "The code for NoDisplay should have been \"N\""
}
test "ShortDate code is correct" {
Expect.equal ShortDate.code "S" "The code for ShortDate should have been \"S\""
}
test "LongDate code is correct" {
Expect.equal LongDate.code "L" "The code for LongDate should have been \"N\""
}
test "fromCode N should return NoDisplay" {
Expect.equal (AsOfDateDisplay.fromCode "N") NoDisplay "\"N\" should have been converted to NoDisplay"
}
test "fromCode S should return ShortDate" {
Expect.equal (AsOfDateDisplay.fromCode "S") ShortDate "\"S\" should have been converted to ShortDate"
}
test "fromCode L should return LongDate" {
Expect.equal (AsOfDateDisplay.fromCode "L") LongDate "\"L\" should have been converted to LongDate"
}
test "fromCode X should raise" {
Expect.throws (fun () -> AsOfDateDisplay.fromCode "X" |> ignore)
"An unknown code should have raised an exception"
}
]
[<Tests>]
let churchTests =
testList "Church" [
test "empty is as expected" {
let mt = Church.empty
Expect.equal mt.churchId Guid.Empty "The church ID should have been an empty GUID"
Expect.equal mt.name "" "The name should have been blank"
Expect.equal mt.city "" "The city should have been blank"
Expect.equal mt.st "" "The state should have been blank"
Expect.isFalse mt.hasInterface "The church should not show that it has an interface"
Expect.isNone mt.interfaceAddress "The interface address should not exist"
Expect.isNotNull mt.smallGroups "The small groups navigation property should not be null"
Expect.isEmpty mt.smallGroups "There should be no small groups for an empty church"
}
]
[<Tests>]
let emailFormatTests =
testList "EmailFormat" [
test "HtmlFormat code is correct" {
Expect.equal HtmlFormat.code "H" "The code for HtmlFormat should have been \"H\""
}
test "PlainTextFormat code is correct" {
Expect.equal PlainTextFormat.code "P" "The code for PlainTextFormat should have been \"P\""
}
test "fromCode H should return HtmlFormat" {
Expect.equal (EmailFormat.fromCode "H") HtmlFormat "\"H\" should have been converted to HtmlFormat"
}
test "fromCode P should return ShortDate" {
Expect.equal (EmailFormat.fromCode "P") PlainTextFormat "\"P\" should have been converted to PlainTextFormat"
}
test "fromCode Z should raise" {
Expect.throws (fun () -> EmailFormat.fromCode "Z" |> ignore) "An unknown code should have raised an exception"
}
]
[<Tests>]
let expirationTests =
testList "Expiration" [
test "Automatic code is correct" {
Expect.equal Automatic.code "A" "The code for Automatic should have been \"A\""
}
test "Manual code is correct" {
Expect.equal Manual.code "M" "The code for Manual should have been \"M\""
}
test "Forced code is correct" {
Expect.equal Forced.code "F" "The code for Forced should have been \"F\""
}
test "fromCode A should return Automatic" {
Expect.equal (Expiration.fromCode "A") Automatic "\"A\" should have been converted to Automatic"
}
test "fromCode M should return Manual" {
Expect.equal (Expiration.fromCode "M") Manual "\"M\" should have been converted to Manual"
}
test "fromCode F should return Forced" {
Expect.equal (Expiration.fromCode "F") Forced "\"F\" should have been converted to Forced"
}
test "fromCode V should raise" {
Expect.throws (fun () -> Expiration.fromCode "V" |> ignore) "An unknown code should have raised an exception"
}
]
[<Tests>]
let listPreferencesTests =
testList "ListPreferences" [
test "empty is as expected" {
let mt = ListPreferences.empty
Expect.equal mt.smallGroupId Guid.Empty "The small group ID should have been an empty GUID"
Expect.equal mt.daysToExpire 14 "The default days to expire should have been 14"
Expect.equal mt.daysToKeepNew 7 "The default days to keep new should have been 7"
Expect.equal mt.longTermUpdateWeeks 4 "The default long term update weeks should have been 4"
Expect.equal mt.emailFromName "PrayerTracker" "The default e-mail from name should have been PrayerTracker"
Expect.equal mt.emailFromAddress "prayer@djs-consulting.com"
"The default e-mail from address should have been prayer@djs-consulting.com"
Expect.equal mt.listFonts "Century Gothic,Tahoma,Luxi Sans,sans-serif" "The default list fonts were incorrect"
Expect.equal mt.headingColor "maroon" "The default heading text color should have been maroon"
Expect.equal mt.lineColor "navy" "The default heding line color should have been navy"
Expect.equal mt.headingFontSize 16 "The default heading font size should have been 16"
Expect.equal mt.textFontSize 12 "The default text font size should have been 12"
Expect.equal mt.requestSort SortByDate "The default request sort should have been by date"
Expect.equal mt.groupPassword "" "The default group password should have been blank"
Expect.equal mt.defaultEmailType HtmlFormat "The default e-mail type should have been HTML"
Expect.isFalse mt.isPublic "The isPublic flag should not have been set"
Expect.equal mt.timeZoneId "America/Denver" "The default time zone should have been America/Denver"
Expect.equal mt.timeZone.timeZoneId "" "The default preferences should have included an empty time zone"
Expect.equal mt.pageSize 100 "The default page size should have been 100"
Expect.equal mt.asOfDateDisplay NoDisplay "The as-of date display should have been No Display"
}
]
[<Tests>]
let memberTests =
testList "Member" [
test "empty is as expected" {
let mt = Member.empty
Expect.equal mt.memberId Guid.Empty "The member ID should have been an empty GUID"
Expect.equal mt.smallGroupId Guid.Empty "The small group ID should have been an empty GUID"
Expect.equal mt.memberName "" "The member name should have been blank"
Expect.equal mt.email "" "The member e-mail address should have been blank"
Expect.isNone mt.format "The preferred e-mail format should not exist"
Expect.equal mt.smallGroup.smallGroupId Guid.Empty "The small group should have been an empty one"
}
]
[<Tests>]
let prayerRequestTests =
testList "PrayerRequest" [
test "empty is as expected" {
let mt = PrayerRequest.empty
Expect.equal mt.prayerRequestId Guid.Empty "The request ID should have been an empty GUID"
Expect.equal mt.requestType CurrentRequest "The request type should have been Current"
Expect.equal mt.userId Guid.Empty "The user ID should have been an empty GUID"
Expect.equal mt.smallGroupId Guid.Empty "The small group ID should have been an empty GUID"
Expect.equal mt.enteredDate DateTime.MinValue "The entered date should have been the minimum"
Expect.equal mt.updatedDate DateTime.MinValue "The updated date should have been the minimum"
Expect.isNone mt.requestor "The requestor should not exist"
Expect.equal mt.text "" "The request text should have been blank"
Expect.isFalse mt.notifyChaplain "The notify chaplain flag should not have been set"
Expect.equal mt.expiration Automatic "The expiration should have been Automatic"
Expect.equal mt.user.userId Guid.Empty "The user should have been an empty one"
Expect.equal mt.smallGroup.smallGroupId Guid.Empty "The small group should have been an empty one"
}
test "isExpired always returns false for expecting requests" {
let req = { PrayerRequest.empty with requestType = Expecting }
Expect.isFalse (req.isExpired DateTime.Now 0) "An expecting request should never be considered expired"
}
test "isExpired always returns false for manually-expired requests" {
let req = { PrayerRequest.empty with updatedDate = DateTime.Now.AddMonths -1; expiration = Manual }
Expect.isFalse (req.isExpired DateTime.Now 4) "A never-expired request should never be considered expired"
}
test "isExpired always returns false for long term/recurring requests" {
let req = { PrayerRequest.empty with requestType = LongTermRequest }
Expect.isFalse (req.isExpired DateTime.Now 0) "A recurring/long-term request should never be considered expired"
}
test "isExpired always returns true for force-expired requests" {
let req = { PrayerRequest.empty with updatedDate = DateTime.Now; expiration = Forced }
Expect.isTrue (req.isExpired DateTime.Now 5) "A force-expired request should always be considered expired"
}
test "isExpired returns false for non-expired requests" {
let now = DateTime.Now
let req = { PrayerRequest.empty with updatedDate = now.AddDays -5. }
Expect.isFalse (req.isExpired now 7) "A request updated 5 days ago should not be considered expired"
}
test "isExpired returns true for expired requests" {
let now = DateTime.Now
let req = { PrayerRequest.empty with updatedDate = now.AddDays -8. }
Expect.isTrue (req.isExpired now 7) "A request updated 8 days ago should be considered expired"
}
test "isExpired returns true for same-day expired requests" {
let now = DateTime.Now
let req = { PrayerRequest.empty with updatedDate = now.Date.AddDays(-7.).AddSeconds -1. }
Expect.isTrue (req.isExpired now 7) "A request entered a second before midnight should be considered expired"
}
test "updateRequired returns false for expired requests" {
let req = { PrayerRequest.empty with expiration = Forced }
Expect.isFalse (req.updateRequired DateTime.Now 7 4) "An expired request should not require an update"
}
test "updateRequired returns false when an update is not required for an active request" {
let now = DateTime.Now
let req =
{ PrayerRequest.empty with
requestType = LongTermRequest
updatedDate = now.AddDays -14.
}
Expect.isFalse (req.updateRequired now 7 4)
"An active request updated 14 days ago should not require an update until 28 days"
}
test "updateRequired returns true when an update is required for an active request" {
let now = DateTime.Now
let req =
{ PrayerRequest.empty with
requestType = LongTermRequest
updatedDate = now.AddDays -34.
}
Expect.isTrue (req.updateRequired now 7 4)
"An active request updated 34 days ago should require an update (past 28 days)"
}
]
[<Tests>]
let prayerRequestTypeTests =
testList "PrayerRequestType" [
test "CurrentRequest code is correct" {
Expect.equal CurrentRequest.code "C" "The code for CurrentRequest should have been \"C\""
}
test "LongTermRequest code is correct" {
Expect.equal LongTermRequest.code "L" "The code for LongTermRequest should have been \"L\""
}
test "PraiseReport code is correct" {
Expect.equal PraiseReport.code "P" "The code for PraiseReport should have been \"P\""
}
test "Expecting code is correct" {
Expect.equal Expecting.code "E" "The code for Expecting should have been \"E\""
}
test "Announcement code is correct" {
Expect.equal Announcement.code "A" "The code for Announcement should have been \"A\""
}
test "fromCode C should return CurrentRequest" {
Expect.equal (PrayerRequestType.fromCode "C") CurrentRequest
"\"C\" should have been converted to CurrentRequest"
}
test "fromCode L should return LongTermRequest" {
Expect.equal (PrayerRequestType.fromCode "L") LongTermRequest
"\"L\" should have been converted to LongTermRequest"
}
test "fromCode P should return PraiseReport" {
Expect.equal (PrayerRequestType.fromCode "P") PraiseReport "\"P\" should have been converted to PraiseReport"
}
test "fromCode E should return Expecting" {
Expect.equal (PrayerRequestType.fromCode "E") Expecting "\"E\" should have been converted to Expecting"
}
test "fromCode A should return Announcement" {
Expect.equal (PrayerRequestType.fromCode "A") Announcement "\"A\" should have been converted to Announcement"
}
test "fromCode R should raise" {
Expect.throws (fun () -> PrayerRequestType.fromCode "R" |> ignore)
"An unknown code should have raised an exception"
}
]
[<Tests>]
let requestSortTests =
testList "RequestSort" [
test "SortByDate code is correct" {
Expect.equal SortByDate.code "D" "The code for SortByDate should have been \"D\""
}
test "SortByRequestor code is correct" {
Expect.equal SortByRequestor.code "R" "The code for SortByRequestor should have been \"R\""
}
test "fromCode D should return SortByDate" {
Expect.equal (RequestSort.fromCode "D") SortByDate "\"D\" should have been converted to SortByDate"
}
test "fromCode R should return SortByRequestor" {
Expect.equal (RequestSort.fromCode "R") SortByRequestor "\"R\" should have been converted to SortByRequestor"
}
test "fromCode Q should raise" {
Expect.throws (fun () -> RequestSort.fromCode "Q" |> ignore) "An unknown code should have raised an exception"
}
]
[<Tests>]
let smallGroupTests =
testList "SmallGroup" [
let now = DateTime (2017, 5, 12, 12, 15, 0, DateTimeKind.Utc)
let withFakeClock f () =
FakeClock (Instant.FromDateTimeUtc now) |> f
yield test "empty is as expected" {
let mt = SmallGroup.empty
Expect.equal mt.smallGroupId Guid.Empty "The small group ID should have been an empty GUID"
Expect.equal mt.churchId Guid.Empty "The church ID should have been an empty GUID"
Expect.equal mt.name "" "The name should have been blank"
Expect.equal mt.church.churchId Guid.Empty "The church should have been an empty one"
Expect.isNotNull mt.members "The members navigation property should not be null"
Expect.isEmpty mt.members "There should be no members for an empty small group"
Expect.isNotNull mt.prayerRequests "The prayer requests navigation property should not be null"
Expect.isEmpty mt.prayerRequests "There should be no prayer requests for an empty small group"
Expect.isNotNull mt.users "The users navigation property should not be null"
Expect.isEmpty mt.users "There should be no users for an empty small group"
}
yield! testFixture withFakeClock [
"localTimeNow adjusts the time ahead of UTC",
fun clock ->
let grp = { SmallGroup.empty with preferences = { ListPreferences.empty with timeZoneId = "Europe/Berlin" } }
Expect.isGreaterThan (grp.localTimeNow clock) now "UTC to Europe/Berlin should have added hours"
"localTimeNow adjusts the time behind UTC",
fun clock ->
Expect.isLessThan (SmallGroup.empty.localTimeNow clock) now
"UTC to America/Denver should have subtracted hours"
"localTimeNow returns UTC when the time zone is invalid",
fun clock ->
let grp = { SmallGroup.empty with preferences = { ListPreferences.empty with timeZoneId = "garbage" } }
Expect.equal (grp.localTimeNow clock) now "UTC should have been returned for an invalid time zone"
]
yield test "localTimeNow fails when clock is not passed" {
Expect.throws (fun () -> (SmallGroup.empty.localTimeNow >> ignore) null)
"Should have raised an exception for null clock"
}
yield test "localDateNow returns the date portion" {
let now' = DateTime (2017, 5, 12, 1, 15, 0, DateTimeKind.Utc)
let clock = FakeClock (Instant.FromDateTimeUtc now')
Expect.isLessThan (SmallGroup.empty.localDateNow clock) now.Date "The date should have been a day earlier"
}
]
[<Tests>]
let timeZoneTests =
testList "TimeZone" [
test "empty is as expected" {
let mt = TimeZone.empty
Expect.equal mt.timeZoneId "" "The time zone ID should have been blank"
Expect.equal mt.description "" "The description should have been blank"
Expect.equal mt.sortOrder 0 "The sort order should have been zero"
Expect.isFalse mt.isActive "The is-active flag should not have been set"
}
]
[<Tests>]
let userTests =
testList "User" [
test "empty is as expected" {
let mt = User.empty
Expect.equal mt.userId Guid.Empty "The user ID should have been an empty GUID"
Expect.equal mt.firstName "" "The first name should have been blank"
Expect.equal mt.lastName "" "The last name should have been blank"
Expect.equal mt.emailAddress "" "The e-mail address should have been blank"
Expect.isFalse mt.isAdmin "The is admin flag should not have been set"
Expect.equal mt.passwordHash "" "The password hash should have been blank"
Expect.isNone mt.salt "The password salt should not exist"
Expect.isNotNull mt.smallGroups "The small groups navigation property should not have been null"
Expect.isEmpty mt.smallGroups "There should be no small groups for an empty user"
}
test "fullName concatenates first and last names" {
let user = { User.empty with firstName = "Unit"; lastName = "Test" }
Expect.equal user.fullName "Unit Test" "The full name should be the first and last, separated by a space"
}
]
[<Tests>]
let userSmallGroupTests =
testList "UserSmallGroup" [
test "empty is as expected" {
let mt = UserSmallGroup.empty
Expect.equal mt.userId Guid.Empty "The user ID should have been an empty GUID"
Expect.equal mt.smallGroupId Guid.Empty "The small group ID should have been an empty GUID"
Expect.equal mt.user.userId Guid.Empty "The user should have been an empty one"
Expect.equal mt.smallGroup.smallGroupId Guid.Empty "The small group should have been an empty one"
}
]

View File

@@ -1,208 +0,0 @@
module PrayerTracker.UI.CommonFunctionsTests
open Expecto
open Giraffe.GiraffeViewEngine
open Microsoft.AspNetCore.Mvc.Localization
open Microsoft.Extensions.Localization
open PrayerTracker.Tests.TestLocalization
open PrayerTracker.Views
open System.IO
[<Tests>]
let iconSizedTests =
testList "iconSized" [
test "succeeds" {
let ico = iconSized 18 "tom-&-jerry" |> renderHtmlNode
Expect.equal ico "<i class=\"material-icons md-18\">tom-&-jerry</i>" "icon HTML not correct"
}
]
[<Tests>]
let iconTests =
testList "icon" [
test "succeeds" {
let ico = icon "bob-&-tom" |> renderHtmlNode
Expect.equal ico "<i class=\"material-icons\">bob-&-tom</i>" "icon HTML not correct"
}
]
[<Tests>]
let locStrTests =
testList "locStr" [
test "succeeds" {
let enc = locStr (LocalizedString ("test", "test&")) |> renderHtmlNode
Expect.equal enc "test&amp;" "string not encoded correctly"
}
]
[<Tests>]
let namedColorListTests =
testList "namedColorList" [
test "succeeds with default values" {
let expected =
[ "<select name=\"the-name\">"
"<option value=\"aqua\" style=\"background-color:aqua;color:black;\">aqua</option>"
"<option value=\"black\" style=\"background-color:black;color:white;\">black</option>"
"<option value=\"blue\" style=\"background-color:blue;color:white;\">blue</option>"
"<option value=\"fuchsia\" style=\"background-color:fuchsia;color:black;\">fuchsia</option>"
"<option value=\"gray\" style=\"background-color:gray;color:white;\">gray</option>"
"<option value=\"green\" style=\"background-color:green;color:white;\">green</option>"
"<option value=\"lime\" style=\"background-color:lime;color:black;\">lime</option>"
"<option value=\"maroon\" style=\"background-color:maroon;color:white;\">maroon</option>"
"<option value=\"navy\" style=\"background-color:navy;color:white;\">navy</option>"
"<option value=\"olive\" style=\"background-color:olive;color:white;\">olive</option>"
"<option value=\"purple\" style=\"background-color:purple;color:white;\">purple</option>"
"<option value=\"red\" style=\"background-color:red;color:black;\">red</option>"
"<option value=\"silver\" style=\"background-color:silver;color:black;\">silver</option>"
"<option value=\"teal\" style=\"background-color:teal;color:white;\">teal</option>"
"<option value=\"white\" style=\"background-color:white;color:black;\">white</option>"
"<option value=\"yellow\" style=\"background-color:yellow;color:black;\">yellow</option>"
"</select>"
]
|> String.concat ""
let selectList = namedColorList "the-name" "" [] _s |> renderHtmlNode
Expect.equal expected selectList "The default select list was not generated correctly"
}
test "succeeds with a selected value" {
let selectList = namedColorList "the-name" "white" [] _s |> renderHtmlNode
Expect.stringContains selectList " selected>white</option>" "Selected option not generated correctly"
}
test "succeeds with extra attributes" {
let selectList = namedColorList "the-name" "" [ _id "myId" ] _s |> renderHtmlNode
Expect.stringStarts selectList "<select name=\"the-name\" id=\"myId\">" "Attributes not included correctly"
}
]
[<Tests>]
let radioTests =
testList "radio" [
test "succeeds when not selected" {
let rad = radio "a-name" "anId" "test" "unit" |> renderHtmlNode
Expect.equal rad "<input type=\"radio\" name=\"a-name\" id=\"anId\" value=\"test\">"
"Unselected radio button not generated correctly"
}
test "succeeds when selected" {
let rad = radio "a-name" "anId" "unit" "unit" |> renderHtmlNode
Expect.equal rad "<input type=\"radio\" name=\"a-name\" id=\"anId\" value=\"unit\" checked>"
"Selected radio button not generated correctly"
}
]
[<Tests>]
let rawLocTextTests =
testList "rawLocText" [
test "succeeds" {
use sw = new StringWriter ()
let raw = rawLocText sw (LocalizedHtmlString ("test", "test&")) |> renderHtmlNode
Expect.equal raw "test&" "string not written correctly"
}
]
[<Tests>]
let selectDefaultTests =
testList "selectDefault" [
test "succeeds" {
Expect.equal (selectDefault "a&b") "— a&b —" "Default selection not generated correctly"
}
]
[<Tests>]
let selectListTests =
testList "selectList" [
test "succeeds with minimum options" {
let theList = selectList "a-list" "" [] [] |> renderHtmlNode
Expect.equal theList "<select name=\"a-list\" id=\"a-list\"></select>" "Empty select list not generated correctly"
}
test "succeeds with all options" {
let theList =
[ "tom", "Tom&"
"bob", "Bob"
"jan", "Jan"
]
|> selectList "the-list" "bob" [ _style "ugly" ]
|> renderHtmlNode
let expected =
[ "<select name=\"the-list\" id=\"the-list\" style=\"ugly\">"
"<option value=\"tom\">Tom&amp;</option>"
"<option value=\"bob\" selected>Bob</option>"
"<option value=\"jan\">Jan</option>"
"</select>"
]
|> String.concat ""
Expect.equal theList expected "Filled select list not generated correctly"
}
]
[<Tests>]
let spaceTests =
testList "space" [
test "succeeds" {
Expect.equal (renderHtmlNode space) " " "space literal not correct"
}
]
[<Tests>]
let submitTests =
testList "submit" [
test "succeeds" {
let btn = submit [ _class "slick" ] "file-ico" _s.["a&b"] |> renderHtmlNode
Expect.equal
btn
"<button type=\"submit\" class=\"slick\"><i class=\"material-icons\">file-ico</i> &nbsp;a&amp;b</button>"
"Submit button not generated correctly"
}
]
[<Tests>]
let tableSummaryTests =
testList "tableSummary" [
test "succeeds for no entries" {
let sum = tableSummary 0 _s |> renderHtmlNode
Expect.equal sum "<div class=\"pt-center-text\"><small>No Entries to Display</small></div>"
"Summary for no items is incorrect"
}
test "succeeds for one entry" {
let sum = tableSummary 1 _s |> renderHtmlNode
Expect.equal sum "<div class=\"pt-center-text\"><small>Displaying 1 Entry</small></div>"
"Summary for one item is incorrect"
}
test "succeeds for many entries" {
let sum = tableSummary 5 _s |> renderHtmlNode
Expect.equal sum "<div class=\"pt-center-text\"><small>Displaying 5 Entries</small></div>"
"Summary for many items is incorrect"
}
]
module TimeZones =
open PrayerTracker.Views.CommonFunctions.TimeZones
[<Tests>]
let nameTests =
testList "TimeZones.name" [
test "succeeds for US Eastern time" {
Expect.equal (name "America/New_York" _s |> string) "Eastern" "US Eastern time zone not returned correctly"
}
test "succeeds for US Central time" {
Expect.equal (name "America/Chicago" _s |> string) "Central" "US Central time zone not returned correctly"
}
test "succeeds for US Mountain time" {
Expect.equal (name "America/Denver" _s |> string) "Mountain" "US Mountain time zone not returned correctly"
}
test "succeeds for US Mountain (AZ) time" {
Expect.equal (name "America/Phoenix" _s |> string) "Mountain (Arizona)"
"US Mountain (AZ) time zone not returned correctly"
}
test "succeeds for US Pacific time" {
Expect.equal (name "America/Los_Angeles" _s |> string) "Pacific" "US Pacific time zone not returned correctly"
}
test "succeeds for Central European time" {
Expect.equal (name "Europe/Berlin" _s |> string) "Central European"
"Central European time zone not returned correctly"
}
test "fails for unexpected time zone" {
Expect.equal (name "Wakanda" _s |> string) "Wakanda" "Unexpected time zone should have returned the original ID"
}
]

View File

@@ -1,193 +0,0 @@
module PrayerTracker.UI.UtilsTests
open Expecto
open PrayerTracker
[<Tests>]
let ckEditorToTextTests =
testList "ckEditorToText" [
test "replaces newline/tab sequence with nothing" {
Expect.equal (ckEditorToText "Here is some \n\ttext") "Here is some text"
"Newline/tab sequence should have been removed"
}
test "replaces &nbsp; with a space" {
Expect.equal (ckEditorToText "Test&nbsp;text") "Test text" "&nbsp; should have been replaced with a space"
}
test "replaces double space with one non-breaking space and one regular space" {
Expect.equal (ckEditorToText "Test text") "Test&#xa0; text"
"double space should have been replaced with one non-breaking space and one regular space"
}
test "replaces paragraph break with two line breaks" {
Expect.equal (ckEditorToText "some</p><p>text") "some<br><br>text"
"paragraph break should have been replaced with two line breaks"
}
test "removes start and end paragraph tags" {
Expect.equal (ckEditorToText "<p>something something</p>") "something something"
"start/end paragraph tags should have been removed"
}
test "trims the result" {
Expect.equal (ckEditorToText " abc ") "abc" "Should have trimmed the resulting text"
}
test "does all the replacements and removals at one time" {
Expect.equal (ckEditorToText " <p>Paragraph&nbsp;1\n\t line two</p><p>Paragraph 2 x</p>")
"Paragraph 1 line two<br><br>Paragraph 2&#xa0; x"
"all replacements and removals were not made correctly"
}
]
[<Tests>]
let htmlToPlainTextTests =
testList "htmlToPlainText" [
test "decodes HTML-encoded entities" {
Expect.equal (htmlToPlainText "1 &gt; 0") "1 > 0" "HTML-encoded entities should have been decoded"
}
test "trims the input HTML" {
Expect.equal (htmlToPlainText " howdy ") "howdy" "HTML input string should have been trimmed"
}
test "replaces line breaks with new lines" {
Expect.equal (htmlToPlainText "Lots<br>of<br />new<br>lines") "Lots\nof\nnew\nlines"
"Break tags should have been converted to newline characters"
}
test "replaces non-breaking spaces with spaces" {
Expect.equal (htmlToPlainText "Here&nbsp;is&#xa0;some&nbsp;more&#xa0;text") "Here is some more text"
"Non-breaking spaces should have been replaced with spaces"
}
test "does all replacements at one time" {
Expect.equal (htmlToPlainText " &lt;&nbsp;&lt;<br>test") "< <\ntest" "All replacements were not made correctly"
}
test "does not fail when passed null" {
Expect.equal (htmlToPlainText null) "" "Should return an empty string for null input"
}
test "does not fail when passed an empty string" {
Expect.equal (htmlToPlainText "") "" "Should return an empty string when given an empty string"
}
test "preserves blank lines for two consecutive line breaks" {
let expected = "Paragraph 1\n\nParagraph 2\n\n...and paragraph 3"
Expect.equal (htmlToPlainText "Paragraph 1<br><br>Paragraph 2<br><br>...and <strong>paragraph</strong> <i>3</i>")
expected "Blank lines not preserved for consecutive line breaks"
}
]
[<Tests>]
let makeUrlTests =
testList "makeUrl" [
test "returns the URL when there are no parameters" {
Expect.equal (makeUrl "/test" []) "/test" "The URL should not have had any query string parameters added"
}
test "returns the URL with one query string parameter" {
Expect.equal (makeUrl "/test" [ "unit", "true" ]) "/test?unit=true" "The URL was not constructed properly"
}
test "returns the URL with multiple encoded query string parameters" {
let url = makeUrl "/test" [ "space", "a space"; "turkey", "=" ]
Expect.equal url "/test?space=a+space&turkey=%3D" "The URL was not constructed properly"
}
]
[<Tests>]
let sndAsStringTests =
testList "sndAsString" [
test "converts the second item to a string" {
Expect.equal (sndAsString ("a", 5)) "5" "The second part of the tuple should have been converted to a string"
}
]
module StringTests =
open PrayerTracker.Utils.String
[<Tests>]
let replaceFirstTests =
testList "String.replaceFirst" [
test "replaces the first occurrence when it is found at the beginning of the string" {
let testString = "unit unit unit"
Expect.equal (replaceFirst "unit" "test" testString) "test unit unit"
"First occurrence of a substring was not replaced properly at the beginning of the string"
}
test "replaces the first occurrence when it is found in the center of the string" {
let testString = "test unit test"
Expect.equal (replaceFirst "unit" "test" testString) "test test test"
"First occurrence of a substring was not replaced properly when it is in the center of the string"
}
test "returns the original string if the replacement isn't found" {
let testString = "unit tests"
Expect.equal (replaceFirst "tested" "testing" testString) "unit tests"
"String which did not have the target substring was not returned properly"
}
]
[<Tests>]
let replaceTests =
testList "String.replace" [
test "succeeds" {
Expect.equal (replace "a" "b" "abacab") "bbbcbb" "String did not replace properly"
}
]
[<Tests>]
let trimTests =
testList "String.trim" [
test "succeeds" {
Expect.equal (trim " abc ") "abc" "Space not trimmed from string properly"
}
]
[<Tests>]
let stripTagsTests =
let testString = "<p class=\"testing\">Here is some text<br> <br />and some more</p>"
testList "stripTags" [
test "does nothing if all tags are allowed" {
Expect.equal (stripTags [ "p"; "br" ] testString) testString
"There should have been no replacements in the target string"
}
test "strips the start/end tag for non allowed tag" {
Expect.equal (stripTags [ "br" ] testString) "Here is some text<br> <br />and some more"
"There should have been no \"p\" tag, but all \"br\" tags, in the returned string"
}
test "strips void/self-closing tags" {
Expect.equal (stripTags [] testString) "Here is some text and some more"
"There should have been no tags; all void and self-closing tags should have been stripped"
}
]
[<Tests>]
let wordWrapTests =
testList "wordWrap" [
test "breaks where it is supposed to" {
let testString = "The quick brown fox jumps over the lazy dog\nIt does!"
Expect.equal (wordWrap 20 testString) "The quick brown fox\njumps over the lazy\ndog\nIt does!\n"
"Line not broken correctly"
}
test "wraps long line without a space" {
let testString = "Asamatteroffact, the dog does too"
Expect.equal (wordWrap 10 testString) "Asamattero\nffact, the\ndog does\ntoo\n"
"Longer line not broken correctly"
}
test "preserves blank lines" {
let testString = "Here is\n\na string with blank lines"
Expect.equal (wordWrap 80 testString) testString "Blank lines were not preserved"
}
]
[<Tests>]
let wordWrapBTests =
testList "wordWrapB" [
test "breaks where it is supposed to" {
let testString = "The quick brown fox jumps over the lazy dog\nIt does!"
Expect.equal (wordWrap 20 testString) "The quick brown fox\njumps over the lazy\ndog\nIt does!\n"
"Line not broken correctly"
}
test "wraps long line without a space and a line with exact length" {
let testString = "Asamatteroffact, the dog does too"
Expect.equal (wordWrap 10 testString) "Asamattero\nffact, the\ndog does\ntoo\n"
"Longer line not broken correctly"
}
test "wraps long line without a space and a line with non-exact length" {
let testString = "Asamatteroffact, that dog does too"
Expect.equal (wordWrap 10 testString) "Asamattero\nffact,\nthat dog\ndoes too\n"
"Longer line not broken correctly"
}
test "preserves blank lines" {
let testString = "Here is\n\na string with blank lines"
Expect.equal (wordWrap 80 testString) testString "Blank lines were not preserved"
}
]

View File

@@ -1,680 +0,0 @@
module PrayerTracker.UI.ViewModelsTests
open Expecto
open Microsoft.AspNetCore.Html
open PrayerTracker.Entities
open PrayerTracker.Tests.TestLocalization
open PrayerTracker.Utils
open PrayerTracker.ViewModels
open System
/// Filter function that filters nothing
let countAll _ = true
module ReferenceListTests =
[<Tests>]
let asOfDateListTests =
testList "ReferenceList.asOfDateList" [
test "has all three options listed" {
let asOf = ReferenceList.asOfDateList _s
Expect.hasCountOf asOf 3u countAll "There should have been 3 as-of choices returned"
Expect.exists asOf (fun (x, _) -> x = NoDisplay.code) "The option for no display was not found"
Expect.exists asOf (fun (x, _) -> x = ShortDate.code) "The option for a short date was not found"
Expect.exists asOf (fun (x, _) -> x = LongDate.code) "The option for a full date was not found"
}
]
[<Tests>]
let emailTypeListTests =
testList "ReferenceList.emailTypeList" [
test "includes default type" {
let typs = ReferenceList.emailTypeList HtmlFormat _s
Expect.hasCountOf typs 3u countAll "There should have been 3 e-mail type options returned"
let top = Seq.head typs
Expect.equal (fst top) "" "The default option should have been blank"
Expect.equal (snd top).Value "Group Default (HTML Format)" "The default option label was incorrect"
let nxt = typs |> Seq.skip 1 |> Seq.head
Expect.equal (fst nxt) HtmlFormat.code "The 2nd option should have been HTML"
let lst = typs |> Seq.last
Expect.equal (fst lst) PlainTextFormat.code "The 3rd option should have been plain text"
}
]
[<Tests>]
let expirationListTests =
testList "ReferenceList.expirationList" [
test "excludes immediate expiration if not required" {
let exps = ReferenceList.expirationList _s false
Expect.hasCountOf exps 2u countAll "There should have been 2 expiration types returned"
Expect.exists exps (fun (exp, _) -> exp = Automatic.code) "The option for automatic expiration was not found"
Expect.exists exps (fun (exp, _) -> exp = Manual.code) "The option for manual expiration was not found"
}
test "includes immediate expiration if required" {
let exps = ReferenceList.expirationList _s true
Expect.hasCountOf exps 3u countAll "There should have been 3 expiration types returned"
Expect.exists exps (fun (exp, _) -> exp = Automatic.code) "The option for automatic expiration was not found"
Expect.exists exps (fun (exp, _) -> exp = Manual.code) "The option for manual expiration was not found"
Expect.exists exps (fun (exp, _) -> exp = Forced.code) "The option for immediate expiration was not found"
}
]
[<Tests>]
let requestTypeListTests =
testList "ReferenceList.requestTypeList" [
let withList f () =
(ReferenceList.requestTypeList >> f) _s
yield! testFixture withList [
yield "returns 5 types",
fun typs -> Expect.hasCountOf typs 5u countAll "There should have been 5 request types returned"
yield! [ CurrentRequest; LongTermRequest; PraiseReport; Expecting; Announcement ]
|> List.map (fun typ ->
sprintf "contains \"%O\"" typ,
fun typs ->
Expect.isSome (typs |> List.tryFind (fun x -> fst x = typ))
(sprintf "The \"%O\" option was not found" typ))
]
]
[<Tests>]
let announcementTests =
let empty = { sendToClass = "N"; text = "<p>unit testing</p>"; addToRequestList = None; requestType = None }
testList "Announcement" [
test "plainText strips HTML" {
let ann = { empty with text = "<p>unit testing</p>" }
Expect.equal (ann.plainText ()) "unit testing" "Plain text should have stripped HTML"
}
test "plainText wraps at 74 characters" {
let ann = { empty with text = String.replicate 80 "x" }
let txt = (ann.plainText ()).Split "\n"
Expect.hasCountOf txt 3u countAll "There should have been two lines of plain text returned"
Expect.stringHasLength txt.[0] 74 "The first line should have been wrapped at 74 characters"
Expect.stringHasLength txt.[1] 6 "The second line should have had the remaining 6 characters"
Expect.stringHasLength txt.[2] 0 "The third line should have been blank"
}
test "plainText wraps at 74 characters and strips HTML" {
let ann = { empty with text = sprintf "<strong>%s</strong>" (String.replicate 80 "z") }
let txt = ann.plainText ()
Expect.stringStarts txt "zzz" "HTML should have been stripped from the front of the plain text"
Expect.equal (txt.ToCharArray ()).[74] '\n' "The text should have been broken at 74 characters"
}
]
[<Tests>]
let appViewInfoTests =
testList "AppViewInfo" [
test "fresh is constructed properly" {
let vi = AppViewInfo.fresh
Expect.isEmpty vi.style "There should have been no styles set"
Expect.isEmpty vi.script "There should have been no scripts set"
Expect.isNone vi.helpLink "The help link should have been set to none"
Expect.isEmpty vi.messages "There should have been no messages set"
Expect.equal vi.version "" "The version should have been blank"
Expect.isGreaterThan vi.requestStart DateTime.MinValue.Ticks "The request start time should have been set"
Expect.isNone vi.user "There should not have been a user"
Expect.isNone vi.group "There should not have been a small group"
}
]
[<Tests>]
let assignGroupsTests =
testList "AssignGroups" [
test "fromUser populates correctly" {
let usr = { User.empty with userId = Guid.NewGuid (); firstName = "Alice"; lastName = "Bob" }
let asg = AssignGroups.fromUser usr
Expect.equal asg.userId usr.userId "The user ID was not filled correctly"
Expect.equal asg.userName usr.fullName "The user name was not filled correctly"
Expect.equal asg.smallGroups "" "The small group string was not filled correctly"
}
]
[<Tests>]
let editChurchTests =
testList "EditChurch" [
test "fromChurch populates correctly when interface exists" {
let church =
{ Church.empty with
churchId = Guid.NewGuid ()
name = "Unit Test"
city = "Testlandia"
st = "UT"
hasInterface = true
interfaceAddress = Some "https://test-dem-units.test"
}
let edit = EditChurch.fromChurch church
Expect.equal edit.churchId church.churchId "The church ID was not filled correctly"
Expect.equal edit.name church.name "The church name was not filled correctly"
Expect.equal edit.city church.city "The church's city was not filled correctly"
Expect.equal edit.st church.st "The church's state was not filled correctly"
Expect.isSome edit.hasInterface "The church should show that it has an interface"
Expect.equal edit.hasInterface (Some true) "The hasInterface flag should be true"
Expect.isSome edit.interfaceAddress "The interface address should exist"
Expect.equal edit.interfaceAddress church.interfaceAddress "The interface address was not filled correctly"
}
test "fromChurch populates correctly when interface does not exist" {
let edit =
EditChurch.fromChurch
{ Church.empty with
churchId = Guid.NewGuid ()
name = "Unit Test"
city = "Testlandia"
st = "UT"
}
Expect.isNone edit.hasInterface "The church should not show that it has an interface"
Expect.isNone edit.interfaceAddress "The interface address should not exist"
}
test "empty is as expected" {
let edit = EditChurch.empty
Expect.equal edit.churchId Guid.Empty "The church ID should be the empty GUID"
Expect.equal edit.name "" "The church name should be blank"
Expect.equal edit.city "" "The church's city should be blank"
Expect.equal edit.st "" "The church's state should be blank"
Expect.isNone edit.hasInterface "The church should not show that it has an interface"
Expect.isNone edit.interfaceAddress "The interface address should not exist"
}
test "isNew works on a new church" {
Expect.isTrue (EditChurch.empty.isNew ()) "An empty GUID should be flagged as a new church"
}
test "isNew works on an existing church" {
Expect.isFalse ({ EditChurch.empty with churchId = Guid.NewGuid () }.isNew ())
"A non-empty GUID should not be flagged as a new church"
}
test "populateChurch works correctly when an interface exists" {
let edit =
{ EditChurch.empty with
churchId = Guid.NewGuid ()
name = "Test Baptist Church"
city = "Testerville"
st = "TE"
hasInterface = Some true
interfaceAddress = Some "https://test.units"
}
let church = edit.populateChurch Church.empty
Expect.notEqual church.churchId edit.churchId "The church ID should not have been modified"
Expect.equal church.name edit.name "The church name was not updated correctly"
Expect.equal church.city edit.city "The church's city was not updated correctly"
Expect.equal church.st edit.st "The church's state was not updated correctly"
Expect.isTrue church.hasInterface "The church should show that it has an interface"
Expect.isSome church.interfaceAddress "The interface address should exist"
Expect.equal church.interfaceAddress edit.interfaceAddress "The interface address was not updated correctly"
}
test "populateChurch works correctly when an interface does not exist" {
let church =
{ EditChurch.empty with
name = "Test Baptist Church"
city = "Testerville"
st = "TE"
}.populateChurch Church.empty
Expect.isFalse church.hasInterface "The church should show that it has an interface"
Expect.isNone church.interfaceAddress "The interface address should exist"
}
]
[<Tests>]
let editMemberTests =
testList "EditMember" [
test "fromMember populates with group default format" {
let mbr =
{ Member.empty with
memberId = Guid.NewGuid ()
memberName = "Test Name"
email = "test_units@example.com"
}
let edit = EditMember.fromMember mbr
Expect.equal edit.memberId mbr.memberId "The member ID was not filled correctly"
Expect.equal edit.memberName mbr.memberName "The member name was not filled correctly"
Expect.equal edit.emailAddress mbr.email "The e-mail address was not filled correctly"
Expect.equal edit.emailType "" "The e-mail type should have been blank for group default"
}
test "fromMember populates with specific format" {
let edit = EditMember.fromMember { Member.empty with format = Some HtmlFormat.code }
Expect.equal edit.emailType HtmlFormat.code "The e-mail type was not filled correctly"
}
test "empty is as expected" {
let edit = EditMember.empty
Expect.equal edit.memberId Guid.Empty "The member ID should have been an empty GUID"
Expect.equal edit.memberName "" "The member name should have been blank"
Expect.equal edit.emailAddress "" "The e-mail address should have been blank"
Expect.equal edit.emailType "" "The e-mail type should have been blank"
}
test "isNew works for a new member" {
Expect.isTrue (EditMember.empty.isNew ()) "An empty GUID should be flagged as a new member"
}
test "isNew works for an existing member" {
Expect.isFalse ({ EditMember.empty with memberId = Guid.NewGuid () }.isNew ())
"A non-empty GUID should not be flagged as a new member"
}
]
[<Tests>]
let editPreferencesTests =
testList "EditPreferences" [
test "fromPreferences succeeds for named colors and private list" {
let prefs = ListPreferences.empty
let edit = EditPreferences.fromPreferences prefs
Expect.equal edit.expireDays prefs.daysToExpire "The expiration days were not filled correctly"
Expect.equal edit.daysToKeepNew prefs.daysToKeepNew "The days to keep new were not filled correctly"
Expect.equal edit.longTermUpdateWeeks prefs.longTermUpdateWeeks "The weeks for update were not filled correctly"
Expect.equal edit.requestSort prefs.requestSort.code "The request sort was not filled correctly"
Expect.equal edit.emailFromName prefs.emailFromName "The e-mail from name was not filled correctly"
Expect.equal edit.emailFromAddress prefs.emailFromAddress "The e-mail from address was not filled correctly"
Expect.equal edit.defaultEmailType prefs.defaultEmailType.code "The default e-mail type was not filled correctly"
Expect.equal edit.headingLineType "Name" "The heading line color type was not derived correctly"
Expect.equal edit.headingLineColor prefs.lineColor "The heading line color was not filled correctly"
Expect.equal edit.headingTextType "Name" "The heading text color type was not derived correctly"
Expect.equal edit.headingTextColor prefs.headingColor "The heading text color was not filled correctly"
Expect.equal edit.listFonts prefs.listFonts "The list fonts were not filled correctly"
Expect.equal edit.headingFontSize prefs.headingFontSize "The heading font size was not filled correctly"
Expect.equal edit.listFontSize prefs.textFontSize "The list text font size was not filled correctly"
Expect.equal edit.timeZone prefs.timeZoneId "The time zone was not filled correctly"
Expect.isSome edit.groupPassword "The group password should have been set"
Expect.equal edit.groupPassword (Some prefs.groupPassword) "The group password was not filled correctly"
Expect.equal edit.listVisibility RequestVisibility.``private`` "The list visibility was not derived correctly"
}
test "fromPreferences succeeds for RGB line color and password-protected list" {
let prefs = { ListPreferences.empty with lineColor = "#ff0000"; groupPassword = "pw" }
let edit = EditPreferences.fromPreferences prefs
Expect.equal edit.headingLineType "RGB" "The heading line color type was not derived correctly"
Expect.equal edit.headingLineColor prefs.lineColor "The heading line color was not filled correctly"
Expect.isSome edit.groupPassword "The group password should have been set"
Expect.equal edit.groupPassword (Some prefs.groupPassword) "The group password was not filled correctly"
Expect.equal edit.listVisibility RequestVisibility.passwordProtected
"The list visibility was not derived correctly"
}
test "fromPreferences succeeds for RGB text color and public list" {
let prefs = { ListPreferences.empty with headingColor = "#0000ff"; isPublic = true }
let edit = EditPreferences.fromPreferences prefs
Expect.equal edit.headingTextType "RGB" "The heading text color type was not derived correctly"
Expect.equal edit.headingTextColor prefs.headingColor "The heading text color was not filled correctly"
Expect.isSome edit.groupPassword "The group password should have been set"
Expect.equal edit.groupPassword (Some "") "The group password was not filled correctly"
Expect.equal edit.listVisibility RequestVisibility.``public`` "The list visibility was not derived correctly"
}
]
[<Tests>]
let editRequestTests =
testList "EditRequest" [
test "empty is as expected" {
let mt = EditRequest.empty
Expect.equal mt.requestId Guid.Empty "The request ID should be an empty GUID"
Expect.equal mt.requestType CurrentRequest.code "The request type should have been \"Current\""
Expect.isNone mt.enteredDate "The entered date should have been None"
Expect.isNone mt.skipDateUpdate "The \"skip date update\" flag should have been None"
Expect.isNone mt.requestor "The requestor should have been None"
Expect.equal mt.expiration Automatic.code "The expiration should have been \"A\" (Automatic)"
Expect.equal mt.text "" "The text should have been blank"
}
test "fromRequest succeeds" {
let req =
{ PrayerRequest.empty with
prayerRequestId = Guid.NewGuid ()
requestType = CurrentRequest
requestor = Some "Me"
expiration = Manual
text = "the text"
}
let edit = EditRequest.fromRequest req
Expect.equal edit.requestId req.prayerRequestId "The request ID was not filled correctly"
Expect.equal edit.requestType req.requestType.code "The request type was not filled correctly"
Expect.equal edit.requestor req.requestor "The requestor was not filled correctly"
Expect.equal edit.expiration Manual.code "The expiration was not filled correctly"
Expect.equal edit.text req.text "The text was not filled correctly"
}
test "isNew works for a new request" {
Expect.isTrue (EditRequest.empty.isNew ()) "An empty GUID should be flagged as a new request"
}
test "isNew works for an existing request" {
Expect.isFalse ({ EditRequest.empty with requestId = Guid.NewGuid () }.isNew ())
"A non-empty GUID should not be flagged as a new request"
}
]
[<Tests>]
let editSmallGroupTests =
testList "EditSmallGroup" [
test "fromGroup succeeds" {
let grp =
{ SmallGroup.empty with
smallGroupId = Guid.NewGuid ()
name = "test group"
churchId = Guid.NewGuid ()
}
let edit = EditSmallGroup.fromGroup grp
Expect.equal edit.smallGroupId grp.smallGroupId "The small group ID was not filled correctly"
Expect.equal edit.name grp.name "The name was not filled correctly"
Expect.equal edit.churchId grp.churchId "The church ID was not filled correctly"
}
test "empty is as expected" {
let mt = EditSmallGroup.empty
Expect.equal mt.smallGroupId Guid.Empty "The small group ID should be an empty GUID"
Expect.equal mt.name "" "The name should be blank"
Expect.equal mt.churchId Guid.Empty "The church ID should be an empty GUID"
}
test "isNew works for a new small group" {
Expect.isTrue (EditSmallGroup.empty.isNew ()) "An empty GUID should be flagged as a new small group"
}
test "isNew works for an existing small group" {
Expect.isFalse ({ EditSmallGroup.empty with smallGroupId = Guid.NewGuid () }.isNew ())
"A non-empty GUID should not be flagged as a new small group"
}
test "populateGroup succeeds" {
let edit =
{ EditSmallGroup.empty with
name = "test name"
churchId = Guid.NewGuid ()
}
let grp = edit.populateGroup SmallGroup.empty
Expect.equal grp.name edit.name "The name was not populated correctly"
Expect.equal grp.churchId edit.churchId "The church ID was not populated correctly"
}
]
[<Tests>]
let editUserTests =
testList "EditUser" [
test "empty is as expected" {
let mt = EditUser.empty
Expect.equal mt.userId Guid.Empty "The user ID should be an empty GUID"
Expect.equal mt.firstName "" "The first name should be blank"
Expect.equal mt.lastName "" "The last name should be blank"
Expect.equal mt.emailAddress "" "The e-mail address should be blank"
Expect.equal mt.password "" "The password should be blank"
Expect.equal mt.passwordConfirm "" "The confirmed password should be blank"
Expect.isNone mt.isAdmin "The isAdmin flag should be None"
}
test "fromUser succeeds" {
let usr =
{ User.empty with
userId = Guid.NewGuid ()
firstName = "user"
lastName = "test"
emailAddress = "a@b.c"
}
let edit = EditUser.fromUser usr
Expect.equal edit.userId usr.userId "The user ID was not filled correctly"
Expect.equal edit.firstName usr.firstName "The first name was not filled correctly"
Expect.equal edit.lastName usr.lastName "The last name was not filled correctly"
Expect.equal edit.emailAddress usr.emailAddress "The e-mail address was not filled correctly"
Expect.isNone edit.isAdmin "The isAdmin flag was not filled correctly"
}
test "isNew works for a new user" {
Expect.isTrue (EditUser.empty.isNew ()) "An empty GUID should be flagged as a new user"
}
test "isNew works for an existing user" {
Expect.isFalse ({ EditUser.empty with userId = Guid.NewGuid () }.isNew ())
"A non-empty GUID should not be flagged as a new user"
}
test "populateUser succeeds" {
let edit =
{ EditUser.empty with
firstName = "name"
lastName = "eman"
emailAddress = "n@m.e"
isAdmin = Some true
password = "testpw"
}
let hasher = fun x -> x + "+"
let usr = edit.populateUser User.empty hasher
Expect.equal usr.firstName edit.firstName "The first name was not populated correctly"
Expect.equal usr.lastName edit.lastName "The last name was not populated correctly"
Expect.equal usr.emailAddress edit.emailAddress "The e-mail address was not populated correctly"
Expect.isTrue usr.isAdmin "The isAdmin flag was not populated correctly"
Expect.equal usr.passwordHash (hasher edit.password) "The password hash was not populated correctly"
}
]
[<Tests>]
let groupLogOnTests =
testList "GroupLogOn" [
test "empty is as expected" {
let mt = GroupLogOn.empty
Expect.equal mt.smallGroupId Guid.Empty "The small group ID should be an empty GUID"
Expect.equal mt.password "" "The password should be blank"
Expect.isNone mt.rememberMe "Remember Me should be None"
}
]
[<Tests>]
let maintainRequestsTests =
testList "MaintainRequests" [
test "empty is as expected" {
let mt = MaintainRequests.empty
Expect.isEmpty mt.requests "The requests for the model should have been empty"
Expect.equal mt.smallGroup.smallGroupId Guid.Empty "The small group should have been an empty one"
Expect.isNone mt.onlyActive "The only active flag should have been None"
Expect.isNone mt.searchTerm "The search term should have been None"
Expect.isNone mt.pageNbr "The page number should have been None"
}
]
[<Tests>]
let requestListTests =
testList "RequestList" [
let withRequestList f () =
{ requests = [
{ PrayerRequest.empty with
requestType = CurrentRequest
requestor = Some "Zeb"
text = "zyx"
updatedDate = DateTime.Today
}
{ PrayerRequest.empty with
requestType = CurrentRequest
requestor = Some "Aaron"
text = "abc"
updatedDate = DateTime.Today - TimeSpan.FromDays 9.
}
{ PrayerRequest.empty with
requestType = PraiseReport
text = "nmo"
updatedDate = DateTime.Today
}
]
date = DateTime.Today
listGroup = SmallGroup.empty
showHeader = false
recipients = []
canEmail = false
}
|> f
yield! testFixture withRequestList [
"asHtml succeeds without header or as-of date",
fun reqList ->
let htmlList = { reqList with listGroup = { reqList.listGroup with name = "Test HTML Group" } }
let html = htmlList.asHtml _s
Expect.equal -1 (html.IndexOf "Test HTML Group") "The small group name should not have existed (no header)"
let curReqHeading =
[ "<table style=\"font-family:Century Gothic,Tahoma,Luxi Sans,sans-serif;page-break-inside:avoid;\">"
"<tr>"
"<td style=\"font-size:16pt;color:maroon;padding:3px 0;border-top:solid 3px navy;border-bottom:solid 3px navy;font-weight:bold;\">"
"&nbsp; &nbsp; Current Requests&nbsp; &nbsp; </td></tr></table>"
]
|> String.concat ""
Expect.stringContains html curReqHeading "Heading for category \"Current Requests\" not found"
let curReqHtml =
[ "<ul>"
"<li style=\"list-style-type:circle;font-family:Century Gothic,Tahoma,Luxi Sans,sans-serif;font-size:12pt;padding-bottom:.25em;\">"
"<strong>Zeb</strong> &mdash; zyx</li>"
"<li style=\"list-style-type:disc;font-family:Century Gothic,Tahoma,Luxi Sans,sans-serif;font-size:12pt;padding-bottom:.25em;\">"
"<strong>Aaron</strong> &mdash; abc</li></ul>"
]
|> String.concat ""
Expect.stringContains html curReqHtml "Expected HTML for \"Current Requests\" requests not found"
let praiseHeading =
[ "<table style=\"font-family:Century Gothic,Tahoma,Luxi Sans,sans-serif;page-break-inside:avoid;\">"
"<tr>"
"<td style=\"font-size:16pt;color:maroon;padding:3px 0;border-top:solid 3px navy;border-bottom:solid 3px navy;font-weight:bold;\">"
"&nbsp; &nbsp; Praise Reports&nbsp; &nbsp; </td></tr></table>"
]
|> String.concat ""
Expect.stringContains html praiseHeading "Heading for category \"Praise Reports\" not found"
let praiseHtml =
[ "<ul>"
"<li style=\"list-style-type:circle;font-family:Century Gothic,Tahoma,Luxi Sans,sans-serif;font-size:12pt;padding-bottom:.25em;\">"
"nmo</li></ul>"
]
|> String.concat ""
Expect.stringContains html praiseHtml "Expected HTML for \"Praise Reports\" requests not found"
"asHtml succeeds with header",
fun reqList ->
let htmlList =
{ reqList with
listGroup = { reqList.listGroup with name = "Test HTML Group" }
showHeader = true
}
let html = htmlList.asHtml _s
let lstHeading =
[ "<div style=\"text-align:center;font-family:Century Gothic,Tahoma,Luxi Sans,sans-serif\">"
"<span style=\"font-size:16pt;\"><strong>Prayer Requests</strong></span><br>"
"<span style=\"font-size:12pt;\"><strong>Test HTML Group</strong><br>"
htmlList.date.ToString "MMMM d, yyyy"
"</span></div><br>"
]
|> String.concat ""
Expect.stringContains html lstHeading "Expected HTML for the list heading not found"
// spot check; without header test tests this exhaustively
Expect.stringContains html "<strong>Zeb</strong> &mdash; zyx</li>" "Expected requests not found"
"asHtml succeeds with short as-of date",
fun reqList ->
let htmlList =
{ reqList with
listGroup =
{ reqList.listGroup with
preferences = { reqList.listGroup.preferences with asOfDateDisplay = ShortDate }
}
}
let html = htmlList.asHtml _s
let expected =
htmlList.requests.[0].updatedDate.ToShortDateString ()
|> sprintf "<strong>Zeb</strong> &mdash; zyx<i style=\"font-size:9.60pt\">&nbsp; (as of %s)</i>"
// spot check; if one request has it, they all should
Expect.stringContains html expected "Expected short as-of date not found"
"asHtml succeeds with long as-of date",
fun reqList ->
let htmlList =
{ reqList with
listGroup =
{ reqList.listGroup with
preferences = { reqList.listGroup.preferences with asOfDateDisplay = LongDate }
}
}
let html = htmlList.asHtml _s
let expected =
htmlList.requests.[0].updatedDate.ToLongDateString ()
|> sprintf "<strong>Zeb</strong> &mdash; zyx<i style=\"font-size:9.60pt\">&nbsp; (as of %s)</i>"
// spot check; if one request has it, they all should
Expect.stringContains html expected "Expected long as-of date not found"
"asText succeeds with no as-of date",
fun reqList ->
let textList = { reqList with listGroup = { reqList.listGroup with name = "Test Group" } }
let text = textList.asText _s
Expect.stringContains text (textList.listGroup.name + "\n") "Small group name not found"
Expect.stringContains text "Prayer Requests\n" "List heading not found"
Expect.stringContains text ((textList.date.ToString "MMMM d, yyyy") + "\n \n") "List date not found"
Expect.stringContains text "--------------------\n CURRENT REQUESTS\n--------------------\n"
"Heading for category \"Current Requests\" not found"
Expect.stringContains text " + Zeb - zyx\n" "First request not found"
Expect.stringContains text " - Aaron - abc\n \n" "Second request not found; should have been end of category"
Expect.stringContains text "------------------\n PRAISE REPORTS\n------------------\n"
"Heading for category \"Praise Reports\" not found"
Expect.stringContains text " + nmo\n \n" "Last request not found"
"asText succeeds with short as-of date",
fun reqList ->
let textList =
{ reqList with
listGroup =
{ reqList.listGroup with
preferences = { reqList.listGroup.preferences with asOfDateDisplay = ShortDate }
}
}
let text = textList.asText _s
let expected =
textList.requests.[0].updatedDate.ToShortDateString ()
|> sprintf " + Zeb - zyx (as of %s)"
// spot check; if one request has it, they all should
Expect.stringContains text expected "Expected short as-of date not found"
"asText succeeds with long as-of date",
fun reqList ->
let textList =
{ reqList with
listGroup =
{ reqList.listGroup with
preferences = { reqList.listGroup.preferences with asOfDateDisplay = LongDate }
}
}
let text = textList.asText _s
let expected =
textList.requests.[0].updatedDate.ToLongDateString ()
|> sprintf " + Zeb - zyx (as of %s)"
// spot check; if one request has it, they all should
Expect.stringContains text expected "Expected long as-of date not found"
"isNew succeeds for both old and new requests",
fun reqList ->
let reqs = reqList.requestsInCategory CurrentRequest
Expect.hasCountOf reqs 2u countAll "There should have been two requests"
Expect.isTrue (reqList.isNew (List.head reqs)) "The first request should have been new"
Expect.isFalse (reqList.isNew (List.last reqs)) "The second request should not have been new"
"requestsInCategory succeeds when requests exist",
fun reqList ->
let reqs = reqList.requestsInCategory CurrentRequest
Expect.hasCountOf reqs 2u countAll "There should have been two requests"
let first = List.head reqs
Expect.equal first.text "zyx" "The requests should be sorted by updated date descending"
"requestsInCategory succeeds when requests do not exist",
fun reqList ->
Expect.isEmpty (reqList.requestsInCategory Announcement) "There should have been no \"Announcement\" requests"
"requestsInCategory succeeds and sorts by requestor",
fun reqList ->
let newList =
{ reqList with
listGroup =
{ reqList.listGroup with
preferences = { reqList.listGroup.preferences with requestSort = SortByRequestor }
}
}
let reqs = newList.requestsInCategory CurrentRequest
Expect.hasCountOf reqs 2u countAll "There should have been two requests"
let first = List.head reqs
Expect.equal first.text "abc" "The requests should be sorted by requestor"
]
]
[<Tests>]
let userLogOnTests =
testList "UserLogOn" [
test "empty is as expected" {
let mt = UserLogOn.empty
Expect.equal mt.emailAddress "" "The e-mail address should be blank"
Expect.equal mt.password "" "The password should be blank"
Expect.equal mt.smallGroupId Guid.Empty "The small group ID should be an empty GUID"
Expect.isNone mt.rememberMe "Remember Me should be None"
Expect.isNone mt.redirectUrl "Redirect URL should be None"
}
]
[<Tests>]
let userMessageTests =
testList "UserMessage" [
test "Error is constructed properly" {
let msg = UserMessage.Error
Expect.equal msg.level "ERROR" "Incorrect message level"
Expect.equal msg.text HtmlString.Empty "Text should have been blank"
Expect.isNone msg.description "Description should have been None"
}
test "Warning is constructed properly" {
let msg = UserMessage.Warning
Expect.equal msg.level "WARNING" "Incorrect message level"
Expect.equal msg.text HtmlString.Empty "Text should have been blank"
Expect.isNone msg.description "Description should have been None"
}
test "Info is constructed properly" {
let msg = UserMessage.Info
Expect.equal msg.level "Info" "Incorrect message level"
Expect.equal msg.text HtmlString.Empty "Text should have been blank"
Expect.isNone msg.description "Description should have been None"
}
]

View File

@@ -1,109 +0,0 @@
module PrayerTracker.Views.Church
open Giraffe.GiraffeViewEngine
open PrayerTracker.Entities
open PrayerTracker.ViewModels
/// View for the church edit page
let edit (m : EditChurch) ctx vi =
let pageTitle = match m.isNew () with true -> "Add a New Church" | false -> "Edit Church"
let s = I18N.localizer.Force ()
[ form [ _action "/web/church/save"; _method "post"; _class "pt-center-columns" ] [
style [ _scoped ]
[ rawText "#name { width: 20rem; } #city { width: 10rem; } #st { width: 3rem; } #interfaceAddress { width: 30rem; }" ]
csrfToken ctx
input [ _type "hidden"; _name "churchId"; _value (flatGuid m.churchId) ]
div [ _class "pt-field-row" ] [
div [ _class "pt-field" ] [
label [ _for "name" ] [ locStr s.["Church Name"] ]
input [ _type "text"; _name "name"; _id "name"; _required; _autofocus; _value m.name ]
]
div [ _class "pt-field" ] [
label [ _for "City"] [ locStr s.["City"] ]
input [ _type "text"; _name "city"; _id "city"; _required; _value m.city ]
]
div [ _class "pt-field" ] [
label [ _for "ST" ] [ locStr s.["State"] ]
input [ _type "text"; _name "st"; _id "st"; _required; _minlength "2"; _maxlength "2"; _value m.st ]
]
]
div [ _class "pt-field-row" ] [
div [ _class "pt-checkbox-field" ] [
input [ _type "checkbox"
_name "hasInterface"
_id "hasInterface"
_value "True"
match m.hasInterface with Some x when x -> _checked | _ -> () ]
label [ _for "hasInterface" ] [ locStr s.["Has an interface with Virtual Prayer Room"] ]
]
]
div [ _class "pt-field-row pt-fadeable"; _id "divInterfaceAddress" ] [
div [ _class "pt-field" ] [
label [ _for "interfaceAddress" ] [ locStr s.["VPR Interface URL"] ]
input [ _type "url"; _name "interfaceAddress"; _id "interfaceAddress";
_value (match m.interfaceAddress with Some ia -> ia | None -> "") ]
]
]
div [ _class "pt-field-row" ] [ submit [] "save" s.["Save Church"] ]
]
script [] [ rawText "PT.onLoad(PT.church.edit.onPageLoad)" ]
]
|> Layout.Content.standard
|> Layout.standard vi pageTitle
/// View for church maintenance page
let maintain (churches : Church list) (stats : Map<string, ChurchStats>) ctx vi =
let s = I18N.localizer.Force ()
let chTbl =
match churches with
| [] -> space
| _ ->
table [ _class "pt-table pt-action-table" ] [
thead [] [
tr [] [
th [] [ locStr s.["Actions"] ]
th [] [ locStr s.["Name"] ]
th [] [ locStr s.["Location"] ]
th [] [ locStr s.["Groups"] ]
th [] [ locStr s.["Requests"] ]
th [] [ locStr s.["Users"] ]
th [] [ locStr s.["Interface?"] ]
]
]
churches
|> List.map (fun ch ->
let chId = flatGuid ch.churchId
let delAction = sprintf "/web/church/%s/delete" chId
let delPrompt = s.["Are you sure you want to delete this {0}? This action cannot be undone.",
sprintf "%s (%s)" (s.["Church"].Value.ToLower ()) ch.name]
tr [] [
td [] [
a [ _href (sprintf "/web/church/%s/edit" chId); _title s.["Edit This Church"].Value ] [ icon "edit" ]
a [ _href delAction
_title s.["Delete This Church"].Value
_onclick (sprintf "return PT.confirmDelete('%s','%A')" delAction delPrompt) ]
[ icon "delete_forever" ]
]
td [] [ str ch.name ]
td [] [ str ch.city; rawText ", "; str ch.st ]
td [ _class "pt-right-text" ] [ rawText (stats.[chId].smallGroups.ToString "N0") ]
td [ _class "pt-right-text" ] [ rawText (stats.[chId].prayerRequests.ToString "N0") ]
td [ _class "pt-right-text" ] [ rawText (stats.[chId].users.ToString "N0") ]
td [ _class "pt-center-text" ] [ locStr s.[match ch.hasInterface with true -> "Yes" | false -> "No"] ]
])
|> tbody []
]
[ div [ _class "pt-center-text" ] [
br []
a [ _href (sprintf "/web/church/%s/edit" emptyGuid); _title s.["Add a New Church"].Value ]
[ icon "add_circle"; rawText " &nbsp;"; locStr s.["Add a New Church"] ]
br []
br []
]
tableSummary churches.Length s
chTbl
form [ _id "DeleteForm"; _action ""; _method "post" ] [ csrfToken ctx ]
]
|> Layout.Content.wide
|> Layout.standard vi "Maintain Churches"

View File

@@ -1,147 +0,0 @@
[<AutoOpen>]
module PrayerTracker.Views.CommonFunctions
open Giraffe
open Giraffe.GiraffeViewEngine
open Microsoft.AspNetCore.Antiforgery
open Microsoft.AspNetCore.Http
open Microsoft.AspNetCore.Mvc.Localization
open Microsoft.Extensions.Localization
open System
open System.IO
open System.Text.Encodings.Web
/// Encoded text for a localized string
let locStr (text : LocalizedString) = str text.Value
/// Raw text for a localized HTML string
let rawLocText (writer : StringWriter) (text : LocalizedHtmlString) =
text.WriteTo (writer, HtmlEncoder.Default)
let txt = string writer
writer.GetStringBuilder().Clear () |> ignore
rawText txt
/// A space (used for back-to-back localization string breaks)
let space = rawText " "
/// Generate a Material Design icon
let icon name = i [ _class "material-icons" ] [ rawText name ]
/// Generate a Material Design icon, specifying the point size (must be defined in CSS)
let iconSized size name = i [ _class (sprintf "material-icons md-%i" size) ] [ rawText name ]
/// Generate a CSRF prevention token
let csrfToken (ctx : HttpContext) =
let antiForgery = ctx.GetService<IAntiforgery> ()
let tokenSet = antiForgery.GetAndStoreTokens ctx
input [ _type "hidden"; _name tokenSet.FormFieldName; _value tokenSet.RequestToken ]
/// Create a summary for a table of items
let tableSummary itemCount (s : IStringLocalizer) =
div [ _class "pt-center-text" ] [
small [] [
match itemCount with
| 0 -> s.["No Entries to Display"]
| 1 -> s.["Displaying {0} Entry", itemCount]
| _ -> s.["Displaying {0} Entries", itemCount]
|> locStr
]
]
/// Generate a list of named HTML colors
let namedColorList name selected attrs (s : IStringLocalizer) =
/// The list of HTML named colors (name, display, text color)
seq {
("aqua", s.["Aqua"], "black")
("black", s.["Black"], "white")
("blue", s.["Blue"], "white")
("fuchsia", s.["Fuchsia"], "black")
("gray", s.["Gray"], "white")
("green", s.["Green"], "white")
("lime", s.["Lime"], "black")
("maroon", s.["Maroon"], "white")
("navy", s.["Navy"], "white")
("olive", s.["Olive"], "white")
("purple", s.["Purple"], "white")
("red", s.["Red"], "black")
("silver", s.["Silver"], "black")
("teal", s.["Teal"], "white")
("white", s.["White"], "black")
("yellow", s.["Yellow"], "black")
}
|> Seq.map (fun color ->
let (colorName, dispText, txtColor) = color
option [ yield _value colorName
yield _style (sprintf "background-color:%s;color:%s;" colorName txtColor)
match colorName = selected with true -> yield _selected | false -> () ] [
encodedText (dispText.Value.ToLower ())
])
|> List.ofSeq
|> select (_name name :: attrs)
/// Generate an input[type=radio] that is selected if its value is the current value
let radio name domId value current =
input [ _type "radio"
_name name
_id domId
_value value
match value = current with true -> _checked | false -> () ]
/// Generate a select list with the current value selected
let selectList name selected attrs items =
items
|> Seq.map (fun (value, text) ->
option [ _value value
match value = selected with true -> _selected | false -> () ] [ encodedText text ])
|> List.ofSeq
|> select (List.concat [ [ _name name; _id name ]; attrs ])
/// Generate the text for a default entry at the top of a select list
let selectDefault text = sprintf "— %s —" text
/// Generate a standard submit button with icon and text
let submit attrs ico text = button (_type "submit" :: attrs) [ icon ico; rawText " &nbsp;"; locStr text ]
/// Format a GUID with no dashes (used for URLs and forms)
let flatGuid (x : Guid) = x.ToString "N"
/// An empty GUID string (used for "add" actions)
let emptyGuid = flatGuid Guid.Empty
/// blockquote tag
let blockquote = tag "blockquote"
/// role attribute
let _role = attr "role"
/// aria-* attribute
let _aria typ = attr (sprintf "aria-%s" typ)
/// onclick attribute
let _onclick = attr "onclick"
/// onsubmit attribute
let _onsubmit = attr "onsubmit"
/// scoped flag (used for <style> tag)
let _scoped = flag "scoped"
/// Utility methods to help with time zones (and localization of their names)
module TimeZones =
open System.Collections.Generic
/// Cross-reference between time zone Ids and their English names
let private xref =
[ "America/Chicago", "Central"
"America/Denver", "Mountain"
"America/Los_Angeles", "Pacific"
"America/New_York", "Eastern"
"America/Phoenix", "Mountain (Arizona)"
"Europe/Berlin", "Central European"
]
|> Map.ofList
/// Get the name of a time zone, given its Id
let name tzId (s : IStringLocalizer) =
try s.[xref.[tzId]]
with :? KeyNotFoundException -> LocalizedString (tzId, tzId)

View File

@@ -1,262 +0,0 @@
/// Views associated with the home page, or those that don't fit anywhere else
module PrayerTracker.Views.Home
open Giraffe.GiraffeViewEngine
open Microsoft.AspNetCore.Html
open PrayerTracker.ViewModels
open System.IO
/// The error page
let error code vi =
let s = I18N.localizer.Force ()
let l = I18N.forView "Home/Error"
use sw = new StringWriter ()
let raw = rawLocText sw
let is404 = "404" = code
let pageTitle = match is404 with true -> "Page Not Found" | false -> "Server Error"
[ yield!
match is404 with
| true ->
[ p [] [
raw l.["The page you requested cannot be found."]
raw l.["Please use your &ldquo;Back&rdquo; button to return to {0}.", s.["PrayerTracker"]]
]
p [] [
raw l.["If you reached this page from a link within {0}, please copy the link from the browser's address bar, and send it to support, along with the group for which you were currently authenticated (if any).",
s.["PrayerTracker"]]
]
]
| false ->
[ p [] [
raw l.["An error ({0}) has occurred.", code]
raw l.["Please use your &ldquo;Back&rdquo; button to return to {0}.", s.["PrayerTracker"]]
]
]
br []
hr []
div [ _style "font-size:70%;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Oxygen-Sans,Ubuntu,Cantarell,'Helvetica Neue',sans-serif" ] [
img [ _src (sprintf "/img/%A.png" s.["footer_en"])
_alt (sprintf "%A %A" s.["PrayerTracker"] s.["from Bit Badger Solutions"])
_title (sprintf "%A %A" s.["PrayerTracker"] s.["from Bit Badger Solutions"])
_style "vertical-align:text-bottom;" ]
str vi.version
]
]
|> div []
|> Layout.bare pageTitle
/// The home page
let index vi =
let s = I18N.localizer.Force ()
let l = I18N.forView "Home/Index"
use sw = new StringWriter ()
let raw = rawLocText sw
[ p [] [
raw l.["Welcome to <strong>{0}</strong>!", s.["PrayerTracker"]]
space
raw l.["{0} is an interactive website that provides churches, Sunday School classes, and other organizations an easy way to keep up with their prayer requests.",
s.["PrayerTracker"]]
space
raw l.["It is provided at no charge, as a ministry and a community service."]
]
h4 [] [ raw l.["What Does It Do?"] ]
p [] [
raw l.["{0} has what you need to make maintaining a prayer request list a breeze.", s.["PrayerTracker"]]
space
raw l.["Some of the things it can do..."]
]
ul [] [
li [] [
raw l.["It drops old requests off the list automatically."]
space
raw l.["Requests other than “{0}” requests will expire at 14 days, though this can be changed by the organization.",
s.["Long-Term Requests"]]
space
raw l.["This expiration is based on the last update, not the initial request."]
space
raw l.["(And, once requests do “drop off”, they are not gone - they may be recovered if needed.)"]
]
li [] [
raw l.["Requests can be viewed any time."]
space
raw l.["Lists can be made public, or they can be secured with a password, if desired."]
]
li [] [
raw l.["Lists can be e-mailed to a pre-defined list of members."]
space
raw l.["This can be useful for folks who may not be able to write down all the requests during class, but want a list so that they can pray for them the rest of week."]
space
raw l.["E-mails are sent individually to each person, which keeps the e-mail list private and keeps the messages from being flagged as spam."]
]
li [] [
raw l.["The look and feel of the list can be configured for each group."]
space
raw l.["All fonts, colors, and sizes can be customized."]
space
raw l.["This allows for configuration of large-print lists, among other things."]
]
]
h4 [] [ raw l.["How Can Your Organization Use {0}?", s.["PrayerTracker"]] ]
p [] [
raw l.["Like Gods gift of salvation, {0} is free for the asking for any church, Sunday School class, or other organization who wishes to use it.",
s.["PrayerTracker"]]
space
raw l.["If your organization would like to get set up, just <a href=\"mailto:daniel@djs-consulting.com?subject=New%20{0}%20Class\">e-mail</a> Daniel and let him know.",
s.["PrayerTracker"]]
]
h4 [] [ raw l.["Do I Have to Register to See the Requests?"] ]
p [] [
raw l.["This depends on the group."]
space
raw l.["Lists can be configured to be password-protected, but they do not have to be."]
space
raw l.["If you click on the “{0}” link above, you will see a list of groups - those that do not indicate that they require logging in are publicly viewable.",
s.["View Request List"]]
]
h4 [] [ raw l.["How Does It Work?"] ]
p [] [
raw l.["Check out the “{0}” link above - it details each of the processes and how they work.", s.["Help"]]
]
]
|> Layout.Content.standard
|> Layout.standard vi "Welcome!"
/// Privacy Policy page
let privacyPolicy vi =
let s = I18N.localizer.Force ()
let l = I18N.forView "Home/PrivacyPolicy"
use sw = new StringWriter ()
let raw = rawLocText sw
[ p [ _class "pt-right-text" ] [ small[] [ em [] [ raw l.["(as of July 31, 2018)"] ] ] ]
p [] [
raw l.["The nature of the service is one where privacy is a must."]
space
raw l.["The items below will help you understand the data we collect, access, and store on your behalf as you use this service."]
]
h3 [] [ raw l.["What We Collect"] ]
ul [] [
li [] [
strong [] [ raw l.["Identifying Data"] ]
rawText " &ndash; "
raw l.["{0} stores the first and last names, e-mail addresses, and hashed passwords of all authorized users.", s.["PrayerTracker"]]
space
raw l.["Users are also associated with one or more small groups."]
]
li [] [
strong [] [ raw l.["User Provided Data"] ]
rawText " &ndash; "
raw l.["{0} stores the text of prayer requests.", s.["PrayerTracker"]]
space
raw l.["It also stores names and e-mail addreses of small group members, and plain-text passwords for small groups with password-protected lists."]
]
]
h3 [] [ raw l.["How Your Data Is Accessed / Secured"] ]
ul [] [
li [] [
raw l.["While you are signed in, {0} utilizes a session cookie, and transmits that cookie to the server to establish your identity.",
s.["PrayerTracker"]]
space
raw l.["If you utilize the “{0}” box on sign in, a second cookie is stored, and transmitted to establish a session; this cookie is removed by clicking the “{1}” link.",
s.["Remember Me"], s.["Log Off"]]
space
raw l.["Both of these cookies are encrypted, both in your browser and in transit."]
space
raw l.["Finally, a third cookie is used to maintain your currently selected language, so that this selection is maintained across browser sessions."]
]
li [] [
raw l.["Data for your small group is returned to you, as required, to display and edit."]
space
raw l.["{0} also sends e-mails on behalf of the configured owner of a small group; these e-mails are sent from prayer@djs-consulting.com, with the “Reply To” header set to the configured owner of the small group.",
s.["PrayerTracker"]]
space
raw l.["Distinct e-mails are sent to each user, as to not disclose the other recipients."]
space
raw l.["On the server, all data is stored in a controlled-access database."]
]
li [] [
raw l.["Your data is backed up, along with other Bit Badger Solutions hosted systems, in a rolling manner; backups are preserved for the prior 7 days, and backups from the 1st and 15th are preserved for 3 months."]
space
raw l.["These backups are stored in a private cloud data repository."]
]
li [] [
raw l.["Access to servers and backups is strictly controlled and monitored for unauthorized access attempts."]
]
]
h3 [] [ raw l.["Removing Your Data"] ]
p [] [
raw l.["At any time, you may choose to discontinue using {0}; just e-mail Daniel, as you did to register, and request deletion of your small group.",
s.["PrayerTracker"]]
]
]
|> Layout.Content.standard
|> Layout.standard vi "Privacy Policy"
/// Terms of Service page
let termsOfService vi =
let s = I18N.localizer.Force ()
let l = I18N.forView "Home/TermsOfService"
use sw = new StringWriter ()
let raw = rawLocText sw
let ppLink =
a [ _href "/web/legal/privacy-policy" ] [ str (s.["Privacy Policy"].Value.ToLower ()) ]
|> (renderHtmlNode >> HtmlString)
[ p [ _class "pt-right-text" ] [ small [] [ em [] [ raw l.["(as of May 24, 2018)"] ] ] ]
h3 [] [ str "1. "; raw l.["Acceptance of Terms"] ]
p [] [
raw l.["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."]
space
raw l.["Your continued use of this site implies your acceptance of these terms."]
]
h3 [] [ str "2. "; raw l.["Description of Service and Registration"] ]
p [] [
raw l.["{0} is a service that allows individuals to enter and amend prayer requests on behalf of organizations.",
s.["PrayerTracker"]]
space
raw l.["Registration is accomplished via e-mail to Daniel Summers (daniel at bitbadger dot solutions, substituting punctuation)."]
space
raw l.["See our {0} for details on the personal (user) information we maintain.", ppLink]
]
h3 [] [ str "3. "; raw l.["Liability"] ]
p [] [
raw l.["This service is provided “as is”, and no warranty (express or implied) exists."]
space
raw l.["The service and its developers may not be held liable for any damages that may arise through the use of this service."]
]
h3 [] [ str "4. "; raw l.["Updates to Terms"] ]
p [] [
raw l.["These terms and conditions may be updated at any time."]
space
raw l.["When these terms are updated, users will be notified by a system-generated announcement."]
space
raw l.["Additionally, the date at the top of this page will be updated."]
]
hr []
p [] [ raw l.["You may also wish to review our {0} to learn how we handle your data.", ppLink] ]
]
|> Layout.Content.standard
|> Layout.standard vi "Terms of Service"
/// View for unauthorized page
let unauthorized vi =
let s = I18N.localizer.Force ()
let l = I18N.forView "Home/Unauthorized"
use sw = new StringWriter ()
let raw = rawLocText sw
[ p [] [
raw l.["If you feel you have reached this page in error, please <a href=\"mailto:daniel@djs-consulting.com?Subject={0}%20Unauthorized%20Access\">contact Daniel</a> and provide the details as to what you were doing (i.e., what link did you click, where had you been, etc.).",
s.["PrayerTracker"]]
]
p [] [
raw l.["Otherwise, you may select one of the links above to get back into an authorized portion of {0}.",
s.["PrayerTracker"]]
]
]
|> Layout.Content.standard
|> Layout.standard vi "Unauthorized Access"

View File

@@ -1,290 +0,0 @@
/// Layout items for PrayerTracker
module PrayerTracker.Views.Layout
open Giraffe.GiraffeViewEngine
open PrayerTracker
open PrayerTracker.ViewModels
open System
open System.Globalization
/// Get the two-character language code for the current request
let langCode () = match CultureInfo.CurrentCulture.Name.StartsWith "es" with true -> "es" | _ -> "en"
/// Navigation items
module Navigation =
/// Top navigation bar
let top m =
let s = PrayerTracker.Views.I18N.localizer.Force ()
let menuSpacer = rawText "&nbsp; "
let leftLinks = [
match m.user with
| Some u ->
li [ _class "dropdown" ] [
a [ _class "dropbtn"; _role "button"; _aria "label" s.["Requests"].Value; _title s.["Requests"].Value ]
[ icon "question_answer"; space; locStr s.["Requests"]; space; icon "keyboard_arrow_down" ]
div [ _class "dropdown-content"; _role "menu" ] [
a [ _href "/web/prayer-requests" ] [ icon "compare_arrows"; menuSpacer; locStr s.["Maintain"] ]
a [ _href "/web/prayer-requests/view" ] [ icon "list"; menuSpacer; locStr s.["View List"] ]
]
]
li [ _class "dropdown" ] [
a [ _class "dropbtn"; _role "button"; _aria "label" s.["Group"].Value; _title s.["Group"].Value ]
[ icon "group"; space; locStr s.["Group"]; space; icon "keyboard_arrow_down" ]
div [ _class "dropdown-content"; _role "menu" ] [
a [ _href "/web/small-group/members" ] [ icon "email"; menuSpacer; locStr s.["Maintain Group Members"] ]
a [ _href "/web/small-group/announcement" ] [ icon "send"; menuSpacer; locStr s.["Send Announcement"] ]
a [ _href "/web/small-group/preferences" ] [ icon "build"; menuSpacer; locStr s.["Change Preferences"] ]
]
]
match u.isAdmin with
| true ->
li [ _class "dropdown" ] [
a [ _class "dropbtn"; _role "button"; _aria "label" s.["Administration"].Value; _title s.["Administration"].Value ]
[ icon "settings"; space; locStr s.["Administration"]; space; icon "keyboard_arrow_down" ]
div [ _class "dropdown-content"; _role "menu" ] [
a [ _href "/web/churches" ] [ icon "home"; menuSpacer; locStr s.["Churches"] ]
a [ _href "/web/small-groups" ] [ icon "send"; menuSpacer; locStr s.["Groups"] ]
a [ _href "/web/users" ] [ icon "build"; menuSpacer; locStr s.["Users"] ]
]
]
| false -> ()
| None ->
match m.group with
| Some _ ->
li [] [
a [ _href "/web/prayer-requests/view"
_aria "label" s.["View Request List"].Value
_title s.["View Request List"].Value ]
[ icon "list"; space; locStr s.["View Request List"] ]
]
| None ->
li [ _class "dropdown" ] [
a [ _class "dropbtn"; _role "button"; _aria "label" s.["Log On"].Value; _title s.["Log On"].Value ]
[ icon "security"; space; locStr s.["Log On"]; space; icon "keyboard_arrow_down" ]
div [ _class "dropdown-content"; _role "menu" ] [
a [ _href "/web/user/log-on" ] [ icon "person"; menuSpacer; locStr s.["User"] ]
a [ _href "/web/small-group/log-on" ] [ icon "group"; menuSpacer; locStr s.["Group"] ]
]
]
li [] [
a [ _href "/web/prayer-requests/lists"
_aria "label" s.["View Request List"].Value
_title s.["View Request List"].Value ]
[ icon "list"; space; locStr s.["View Request List"] ]
]
li [] [
a [ _href (sprintf "https://docs.prayer.bitbadger.solutions/%s" <| langCode ())
_aria "label" s.["Help"].Value;
_title s.["View Help"].Value
_target "_blank"
]
[ icon "help"; space; locStr s.["Help"] ]
]
]
let rightLinks =
match m.group with
| Some _ ->
[ match m.user with
| Some _ ->
li [] [
a [ _href "/web/user/password"
_aria "label" s.["Change Your Password"].Value
_title s.["Change Your Password"].Value ]
[ icon "lock"; space; locStr s.["Change Your Password"] ]
]
| None -> ()
li [] [
a [ _href "/web/log-off"; _aria "label" s.["Log Off"].Value; _title s.["Log Off"].Value ]
[ icon "power_settings_new"; space; locStr s.["Log Off"] ]
]
]
| None -> List.empty
header [ _class "pt-title-bar" ] [
section [ _class "pt-title-bar-left" ] [
span [ _class "pt-title-bar-home" ] [
a [ _href "/web/"; _title s.["Home"].Value ] [ locStr s.["PrayerTracker"] ]
]
ul [] leftLinks
]
section [ _class "pt-title-bar-center" ] []
section [ _class "pt-title-bar-right"; _role "toolbar" ] [
ul [] rightLinks
]
]
/// Identity bar (below top nav)
let identity m =
let s = I18N.localizer.Force ()
header [ _id "pt-language" ] [
div [] [
span [ _class "u" ] [ locStr s.["Language"]; rawText ": " ]
match langCode () with
| "es" ->
locStr s.["Spanish"]
rawText " &nbsp; &bull; &nbsp; "
a [ _href "/web/language/en" ] [ locStr s.["Change to English"] ]
| _ ->
locStr s.["English"]
rawText " &nbsp; &bull; &nbsp; "
a [ _href "/web/language/es" ] [ locStr s.["Cambie a Español"] ]
]
match m.group with
| Some g ->
[ match m.user with
| Some u ->
span [ _class "u" ] [ locStr s.["Currently Logged On"] ]
rawText "&nbsp; &nbsp;"
icon "person"
strong [] [ str u.fullName ]
rawText "&nbsp; &nbsp; "
| None ->
locStr s.["Logged On as a Member of"]
rawText "&nbsp; "
icon "group"
space
match m.user with
| Some _ -> a [ _href "/web/small-group" ] [ strong [] [ str g.name ] ]
| None -> strong [] [ str g.name ]
rawText " &nbsp;"
]
| None -> []
|> div []
]
/// Content layouts
module Content =
/// Content layout that tops at 60rem
let standard = div [ _class "pt-content" ]
/// Content layout that uses the full width of the browser window
let wide = div [ _class "pt-content pt-full-width" ]
/// Separator for parts of the title
let private titleSep = rawText " &#xab; "
let private commonHead =
[ meta [ _name "viewport"; _content "width=device-width, initial-scale=1" ]
meta [ _name "generator"; _content "Giraffe" ]
link [ _rel "stylesheet"; _href "https://fonts.googleapis.com/icon?family=Material+Icons" ]
link [ _rel "stylesheet"; _href "/css/app.css" ]
script [ _src "/js/app.js" ] []
]
/// Render the <head> portion of the page
let private htmlHead m pageTitle =
let s = I18N.localizer.Force ()
head [] [
meta [ _charset "UTF-8" ]
title [] [ locStr pageTitle; titleSep; locStr s.["PrayerTracker"] ]
yield! commonHead
for cssFile in m.style do
link [ _rel "stylesheet"; _href (sprintf "/css/%s.css" cssFile); _type "text/css" ]
for jsFile in m.script do
script [ _src (sprintf "/js/%s.js" jsFile) ] []
]
/// Render a link to the help page for the current page
let private helpLink link =
let s = I18N.localizer.Force ()
sup [] [
a [ _href link
_title s.["Click for Help on This Page"].Value
_onclick (sprintf "return PT.showHelp('%s')" link) ] [
icon "help_outline"
]
]
/// Render the page title, and optionally a help link
let private renderPageTitle m pageTitle =
h2 [ _id "pt-page-title" ] [
match m.helpLink with Some link -> Help.fullLink (langCode ()) link |> helpLink | None -> ()
locStr pageTitle
]
/// Render the messages that may need to be displayed to the user
let private messages m =
let s = I18N.localizer.Force ()
m.messages
|> List.map (fun msg ->
table [ _class (sprintf "pt-msg %s" (msg.level.ToLower ())) ] [
tr [] [
td [] [
match msg.level with
| "Info" -> ()
| lvl ->
strong [] [ locStr s.[lvl] ]
rawText " &#xbb; "
rawText msg.text.Value
match msg.description with
| Some desc ->
br []
div [ _class "description" ] [ rawText desc.Value ]
| None -> ()
]
]
])
/// Render the <footer> at the bottom of the page
let private htmlFooter m =
let s = I18N.localizer.Force ()
let imgText = sprintf "%O %O" s.["PrayerTracker"] s.["from Bit Badger Solutions"]
let resultTime = TimeSpan(DateTime.Now.Ticks - m.requestStart).TotalSeconds
footer [] [
div [ _id "pt-legal" ] [
a [ _href "/web/legal/privacy-policy" ] [ locStr s.["Privacy Policy"] ]
rawText " &bull; "
a [ _href "/web/legal/terms-of-service" ] [ locStr s.["Terms of Service"] ]
rawText " &bull; "
a [ _href "https://github.com/bit-badger/PrayerTracker"
_title s.["View source code and get technical support"].Value
_target "_blank"
_rel "noopener" ] [
locStr s.["Source & Support"]
]
]
div [ _id "pt-footer" ] [
a [ _href "/web/"; _style "line-height:28px;" ] [
img [ _src (sprintf "/img/%O.png" s.["footer_en"]); _alt imgText; _title imgText ]
]
str m.version
space
i [ _title s.["This page loaded in {0:N3} seconds", resultTime].Value; _class "material-icons md-18" ] [
str "schedule"
]
]
]
/// The standard layout for PrayerTracker
let standard m pageTitle (content : XmlNode) =
let s = I18N.localizer.Force ()
let ttl = s.[pageTitle]
html [ _lang "" ] [
htmlHead m ttl
body [] [
Navigation.top m
div [ _id "pt-body" ] [
Navigation.identity m
renderPageTitle m ttl
yield! messages m
content
htmlFooter m
]
]
]
/// A layout with nothing but a title and content
let bare pageTitle content =
let s = I18N.localizer.Force ()
let ttl = s.[pageTitle]
html [ _lang "" ] [
head [] [
meta [ _charset "UTF-8" ]
title [] [ locStr ttl; titleSep; locStr s.["PrayerTracker"] ]
]
body [] [ content ]
]

View File

@@ -1,370 +0,0 @@
module PrayerTracker.Views.PrayerRequest
open Giraffe
open Giraffe.GiraffeViewEngine
open Microsoft.AspNetCore.Http
open NodaTime
open PrayerTracker
open PrayerTracker.Entities
open PrayerTracker.ViewModels
open System
open System.IO
open System.Text
/// View for the prayer request edit page
let edit (m : EditRequest) today ctx vi =
let s = I18N.localizer.Force ()
let pageTitle = match m.isNew () with true -> "Add a New Request" | false -> "Edit Request"
[ form [ _action "/web/prayer-request/save"; _method "post"; _class "pt-center-columns" ] [
csrfToken ctx
input [ _type "hidden"; _name "requestId"; _value (flatGuid m.requestId) ]
div [ _class "pt-field-row" ] [
div [ _class "pt-field" ] [
label [ _for "requestType" ] [ locStr s.["Request Type"] ]
ReferenceList.requestTypeList s
|> Seq.ofList
|> Seq.map (fun (typ, desc) -> typ.code, desc.Value)
|> selectList "requestType" m.requestType [ _required; _autofocus ]
]
div [ _class "pt-field" ] [
label [ _for "requestor" ] [ locStr s.["Requestor / Subject"] ]
input [ _type "text"
_name "requestor"
_id "requestor"
_value (match m.requestor with Some x -> x | None -> "") ]
]
match m.isNew () with
| true ->
div [ _class "pt-field" ] [
label [ _for "enteredDate" ] [ locStr s.["Date"] ]
input [ _type "date"; _name "enteredDate"; _id "enteredDate"; _placeholder today ]
]
| false ->
div [ _class "pt-field" ] [
div [ _class "pt-checkbox-field" ] [
br []
input [ _type "checkbox"; _name "skipDateUpdate"; _id "skipDateUpdate"; _value "True" ]
label [ _for "skipDateUpdate" ] [ locStr s.["Check to not update the date"] ]
br []
small [] [ em [] [ str (s.["Typo Corrections"].Value.ToLower ()); rawText ", etc." ] ]
]
]
]
div [ _class "pt-field-row" ] [
div [ _class "pt-field" ] [
label [] [ locStr s.["Expiration"] ]
ReferenceList.expirationList s ((m.isNew >> not) ())
|> List.map (fun exp ->
let radioId = sprintf "expiration_%s" (fst exp)
span [ _class "text-nowrap" ] [
radio "expiration" radioId (fst exp) m.expiration
label [ _for radioId ] [ locStr (snd exp) ]
rawText " &nbsp; &nbsp; "
])
|> div [ _class "pt-center-text" ]
]
]
div [ _class "pt-field-row" ] [
div [ _class "pt-field pt-editor" ] [
label [ _for "text" ] [ locStr s.["Request"] ]
textarea [ _name "text"; _id "text" ] [ str m.text ]
]
]
div [ _class "pt-field-row" ] [ submit [] "save" s.["Save Request"] ]
]
script [] [ rawText "PT.onLoad(PT.initCKEditor)" ]
]
|> Layout.Content.standard
|> Layout.standard vi pageTitle
/// View for the request e-mail results page
let email m vi =
let s = I18N.localizer.Force ()
let pageTitle = sprintf "%s %s" s.["Prayer Requests"].Value m.listGroup.name
let prefs = m.listGroup.preferences
let addresses =
m.recipients
|> List.fold (fun (acc : StringBuilder) mbr -> acc.AppendFormat(", {0} <{1}>", mbr.memberName, mbr.email))
(StringBuilder ())
[ p [ _style (sprintf "font-family:%s;font-size:%ipt;" prefs.listFonts prefs.textFontSize) ] [
locStr s.["The request list was sent to the following people, via individual e-mails"]
rawText ":"
br []
small [] [ str (addresses.Remove(0, 2).ToString ()) ]
]
span [ _class "pt-email-heading" ] [ locStr s.["HTML Format"]; rawText ":" ]
div [ _class "pt-email-canvas" ] [ rawText (m.asHtml s) ]
br []
br []
span [ _class "pt-email-heading" ] [ locStr s.["Plain-Text Format"]; rawText ":" ]
div[ _class "pt-email-canvas" ] [ pre [] [ str (m.asText s) ] ]
]
|> Layout.Content.standard
|> Layout.standard vi pageTitle
/// View for a small group's public prayer request list
let list (m : RequestList) vi =
[ br []
I18N.localizer.Force () |> (m.asHtml >> rawText)
]
|> Layout.Content.standard
|> Layout.standard vi "View Request List"
/// View for the prayer request lists page
let lists (grps : SmallGroup list) vi =
let s = I18N.localizer.Force ()
let l = I18N.forView "Requests/Lists"
use sw = new StringWriter ()
let raw = rawLocText sw
[ p [] [
raw l.["The groups listed below have either public or password-protected request lists."]
space
raw l.["Those with list icons are public, and those with log on icons are password-protected."]
space
raw l.["Click the appropriate icon to log on or view the request list."]
]
match grps.Length with
| 0 -> p [] [ raw l.["There are no groups with public or password-protected request lists."] ]
| count ->
tableSummary count s
table [ _class "pt-table pt-action-table" ] [
thead [] [
tr [] [
th [] [ locStr s.["Actions"] ]
th [] [ locStr s.["Church"] ]
th [] [ locStr s.["Group"] ]
]
]
grps
|> List.map (fun grp ->
let grpId = flatGuid grp.smallGroupId
tr [] [
match grp.preferences.isPublic with
| true ->
a [ _href (sprintf "/web/prayer-requests/%s/list" grpId); _title s.["View"].Value ] [ icon "list" ]
| false ->
a [ _href (sprintf "/web/small-group/log-on/%s" grpId); _title s.["Log On"].Value ]
[ icon "verified_user" ]
|> List.singleton
|> td []
td [] [ str grp.church.name ]
td [] [ str grp.name ]
])
|> tbody []
]
]
|> Layout.Content.standard
|> Layout.standard vi "Request Lists"
/// View for the prayer request maintenance page
let maintain m (ctx : HttpContext) vi =
let s = I18N.localizer.Force ()
let l = I18N.forView "Requests/Maintain"
use sw = new StringWriter ()
let raw = rawLocText sw
let now = m.smallGroup.localDateNow (ctx.GetService<IClock> ())
let typs = ReferenceList.requestTypeList s |> Map.ofList
let updReq (req : PrayerRequest) =
match req.updateRequired now m.smallGroup.preferences.daysToExpire m.smallGroup.preferences.longTermUpdateWeeks with
| true -> "pt-request-update"
| false -> ""
|> _class
let reqExp (req : PrayerRequest) =
_class (match req.isExpired now m.smallGroup.preferences.daysToExpire with true -> "pt-request-expired" | false -> "")
/// Iterate the sequence once, before we render, so we can get the count of it at the top of the table
let requests =
m.requests
|> Seq.map (fun req ->
let reqId = flatGuid req.prayerRequestId
let reqText = Utils.htmlToPlainText req.text
let delAction = sprintf "/web/prayer-request/%s/delete" reqId
let delPrompt =
[ s.["Are you sure you want to delete this {0}? This action cannot be undone.",
s.["Prayer Request"].Value.ToLower() ]
.Value
"\\n"
l.["(If the prayer request has been answered, or an event has passed, consider inactivating it instead.)"]
.Value
]
|> String.concat ""
tr [] [
td [] [
a [ _href (sprintf "/web/prayer-request/%s/edit" reqId); _title l.["Edit This Prayer Request"].Value ]
[ icon "edit" ]
match req.isExpired now m.smallGroup.preferences.daysToExpire with
| true ->
a [ _href (sprintf "/web/prayer-request/%s/restore" reqId)
_title l.["Restore This Inactive Request"].Value ]
[ icon "visibility" ]
| false ->
a [ _href (sprintf "/web/prayer-request/%s/expire" reqId)
_title l.["Expire This Request Immediately"].Value ]
[ icon "visibility_off" ]
a [ _href delAction; _title l.["Delete This Request"].Value;
_onclick (sprintf "return PT.confirmDelete('%s','%s')" delAction delPrompt) ]
[ icon "delete_forever" ]
]
td [ updReq req ] [
str (req.updatedDate.ToString(s.["MMMM d, yyyy"].Value, System.Globalization.CultureInfo.CurrentUICulture))
]
td [] [ locStr typs.[req.requestType] ]
td [ reqExp req ] [ str (match req.requestor with Some r -> r | None -> " ") ]
td [] [
match reqText.Length with
| len when len < 60 -> rawText reqText
| _ -> rawText (sprintf "%s&hellip;" reqText.[0..59])
]
])
|> List.ofSeq
[ div [ _class "pt-center-text" ] [
br []
a [ _href (sprintf "/web/prayer-request/%s/edit" emptyGuid); _title s.["Add a New Request"].Value ]
[ icon "add_circle"; rawText " &nbsp;"; locStr s.["Add a New Request"] ]
rawText " &nbsp; &nbsp; &nbsp; "
a [ _href "/web/prayer-requests/view"; _title s.["View Prayer Request List"].Value ]
[ icon "list"; rawText " &nbsp;"; locStr s.["View Prayer Request List"] ]
match m.searchTerm with
| Some _ ->
rawText " &nbsp; &nbsp; &nbsp; "
a [ _href "/web/prayer-requests"; _title l.["Clear Search Criteria"].Value ]
[ icon "highlight_off"; rawText " &nbsp;"; raw l.["Clear Search Criteria"] ]
| None -> ()
]
form [ _action "/web/prayer-requests"; _method "get"; _class "pt-center-text pt-search-form" ] [
input [ _type "text"
_name "search"
_placeholder l.["Search requests..."].Value
_value (defaultArg m.searchTerm "")
]
space
submit [] "search" s.["Search"]
]
br []
tableSummary requests.Length s
match requests.Length with
| 0 -> ()
| _ ->
table [ _class "pt-table pt-action-table" ] [
thead [] [
tr [] [
th [] [ locStr s.["Actions"] ]
th [] [ locStr s.["Updated Date"] ]
th [] [ locStr s.["Type"] ]
th [] [ locStr s.["Requestor"] ]
th [] [ locStr s.["Request"] ]
]
]
tbody [] requests
]
div [ _class "pt-center-text" ] [
br []
match m.onlyActive with
| Some true ->
raw l.["Inactive requests are currently not shown"]
br []
a [ _href "/web/prayer-requests/inactive" ] [ raw l.["Show Inactive Requests"] ]
| _ ->
match Option.isSome m.onlyActive with
| true ->
raw l.["Inactive requests are currently shown"]
br []
a [ _href "/web/prayer-requests" ] [ raw l.["Do Not Show Inactive Requests"] ]
br []
br []
| false -> ()
let srch = [ match m.searchTerm with Some s -> "search", s | None -> () ]
let pg = defaultArg m.pageNbr 1
let url =
match m.onlyActive with Some true | None -> "" | _ -> "/inactive" |> sprintf "/web/prayer-requests%s"
match pg with
| 1 -> ()
| _ ->
// button (_type "submit" :: attrs) [ icon ico; rawText " &nbsp;"; locStr text ]
let withPage = match pg with 2 -> srch | _ -> ("page", string (pg - 1)) :: srch
a [ _href (makeUrl url withPage) ]
[ icon "keyboard_arrow_left"; space; raw l.["Previous Page"] ]
rawText " &nbsp; &nbsp; "
match requests.Length = m.smallGroup.preferences.pageSize with
| true ->
a [ _href (makeUrl url (("page", string (pg + 1)) :: srch)) ]
[ raw l.["Next Page"]; space; icon "keyboard_arrow_right" ]
| false -> ()
]
form [ _id "DeleteForm"; _action ""; _method "post" ] [ csrfToken ctx ]
]
|> Layout.Content.wide
|> Layout.standard vi (match m.searchTerm with Some _ -> "Search Results" | None -> "Maintain Requests")
/// View for the printable prayer request list
let print m version =
let s = I18N.localizer.Force ()
let pageTitle = sprintf "%s %s" s.["Prayer Requests"].Value m.listGroup.name
let imgAlt = sprintf "%s %s" s.["PrayerTracker"].Value s.["from Bit Badger Solutions"].Value
article [] [
rawText (m.asHtml s)
br []
hr []
div [ _style "font-size:70%;font-family:@Model.ListGroup.preferences.listFonts;" ] [
img [ _src (sprintf "/img/%s.png" s.["footer_en"].Value)
_style "vertical-align:text-bottom;"
_alt imgAlt
_title imgAlt ]
space
str version
]
]
|> Layout.bare pageTitle
/// View for the prayer request list
let view m vi =
let s = I18N.localizer.Force ()
let pageTitle = sprintf "%s %s" s.["Prayer Requests"].Value m.listGroup.name
let spacer = rawText " &nbsp; &nbsp; &nbsp; "
let dtString = m.date.ToString "yyyy-MM-dd"
[ div [ _class "pt-center-text" ] [
br []
a [ _class "pt-icon-link"
_href (sprintf "/web/prayer-requests/print/%s" dtString)
_title s.["View Printable"].Value ] [
icon "print"; rawText " &nbsp;"; locStr s.["View Printable"]
]
match m.canEmail with
| true ->
spacer
match m.date.DayOfWeek = DayOfWeek.Sunday with
| true -> ()
| false ->
let rec findSunday (date : DateTime) =
match date.DayOfWeek = DayOfWeek.Sunday with
| true -> date
| false -> findSunday (date.AddDays 1.)
let sunday = findSunday m.date
a [ _class "pt-icon-link"
_href (sprintf "/web/prayer-requests/view/%s" (sunday.ToString "yyyy-MM-dd"))
_title s.["List for Next Sunday"].Value ] [
icon "update"; rawText " &nbsp;"; locStr s.["List for Next Sunday"]
]
spacer
let emailPrompt = s.["This will e-mail the current list to every member of your group, without further prompting. Are you sure this is what you are ready to do?"].Value
a [ _class "pt-icon-link"
_href (sprintf "/web/prayer-requests/email/%s" dtString)
_title s.["Send via E-mail"].Value
_onclick (sprintf "return PT.requests.view.promptBeforeEmail('%s')" emailPrompt) ] [
icon "mail_outline"; rawText " &nbsp;"; locStr s.["Send via E-mail"]
]
spacer
a [ _class "pt-icon-link"; _href "/web/prayer-requests"; _title s.["Maintain Prayer Requests"].Value ] [
icon "compare_arrows"; rawText " &nbsp;"; locStr s.["Maintain Prayer Requests"]
]
| false -> ()
]
br []
rawText (m.asHtml s)
]
|> Layout.Content.standard
|> Layout.standard vi pageTitle

View File

@@ -1,546 +0,0 @@
module PrayerTracker.Views.SmallGroup
open Giraffe.GiraffeViewEngine
open Microsoft.Extensions.Localization
open PrayerTracker
open PrayerTracker.Entities
open PrayerTracker.ViewModels
open System.IO
/// View for the announcement page
let announcement isAdmin ctx vi =
let s = I18N.localizer.Force ()
let reqTypes = ReferenceList.requestTypeList s
[ form [ _action "/web/small-group/announcement/send"; _method "post"; _class "pt-center-columns" ] [
csrfToken ctx
div [ _class "pt-field-row" ] [
div [ _class "pt-field pt-editor" ] [
label [ _for "text" ] [ locStr s.["Announcement Text"] ]
textarea [ _name "text"; _id "text"; _autofocus ] []
]
]
match isAdmin with
| true ->
div [ _class "pt-field-row" ] [
div [ _class "pt-field" ] [
label [] [ locStr s.["Send Announcement to"]; rawText ":" ]
div [ _class "pt-center-text" ] [
radio "sendToClass" "sendY" "Y" "Y"
label [ _for "sendY" ] [ locStr s.["This Group"]; rawText " &nbsp; &nbsp; " ]
radio "sendToClass" "sendN" "N" "Y"
label [ _for "sendN" ] [ locStr s.["All {0} Users", s.["PrayerTracker"]] ]
]
]
]
| false -> input [ _type "hidden"; _name "sendToClass"; _value "Y" ]
div [ _class "pt-field-row pt-fadeable pt-shown"; _id "divAddToList" ] [
div [ _class "pt-checkbox-field" ] [
input [ _type "checkbox"; _name "addToRequestList"; _id "addToRequestList"; _value "True" ]
label [ _for "addToRequestList" ] [ locStr s.["Add to Request List"] ]
]
]
div [ _class "pt-field-row pt-fadeable"; _id "divCategory" ] [
div [ _class "pt-field" ] [
label [ _for "requestType" ] [ locStr s.["Request Type"] ]
reqTypes
|> Seq.ofList
|> Seq.map (fun (typ, desc) -> typ.code, desc.Value)
|> selectList "requestType" "Announcement" []
]
]
div [ _class "pt-field-row" ] [ submit [] "send" s.["Send Announcement"] ]
]
script [] [ rawText "PT.onLoad(PT.smallGroup.announcement.onPageLoad)" ]
]
|> Layout.Content.standard
|> Layout.standard vi "Send Announcement"
/// View for once an announcement has been sent
let announcementSent (m : Announcement) vi =
let s = I18N.localizer.Force ()
[ span [ _class "pt-email-heading" ] [ locStr s.["HTML Format"]; rawText ":" ]
div [ _class "pt-email-canvas" ] [ rawText m.text ]
br []
br []
span [ _class "pt-email-heading" ] [ locStr s.["Plain-Text Format"]; rawText ":" ]
div [ _class "pt-email-canvas" ] [ pre [] [ str (m.plainText ()) ] ]
]
|> Layout.Content.standard
|> Layout.standard vi "Announcement Sent"
/// View for the small group add/edit page
let edit (m : EditSmallGroup) (churches : Church list) ctx vi =
let s = I18N.localizer.Force ()
let pageTitle = match m.isNew () with true -> "Add a New Group" | false -> "Edit Group"
form [ _action "/web/small-group/save"; _method "post"; _class "pt-center-columns" ] [
csrfToken ctx
input [ _type "hidden"; _name "smallGroupId"; _value (flatGuid m.smallGroupId) ]
div [ _class "pt-field-row" ] [
div [ _class "pt-field" ] [
label [ _for "name" ] [ locStr s.["Group Name"] ]
input [ _type "text"; _name "name"; _id "name"; _value m.name; _required; _autofocus ]
]
]
div [ _class "pt-field-row" ] [
div [ _class "pt-field" ] [
label [ _for "churchId" ] [ locStr s.["Church"] ]
seq {
"", selectDefault s.["Select Church"].Value
yield! churches |> List.map (fun c -> flatGuid c.churchId, c.name)
}
|> selectList "churchId" (flatGuid m.churchId) [ _required ]
]
]
div [ _class "pt-field-row" ] [ submit [] "save" s.["Save Group"] ]
]
|> List.singleton
|> Layout.Content.standard
|> Layout.standard vi pageTitle
/// View for the member edit page
let editMember (m : EditMember) (typs : (string * LocalizedString) seq) ctx vi =
let s = I18N.localizer.Force ()
let pageTitle = match m.isNew () with true -> "Add a New Group Member" | false -> "Edit Group Member"
form [ _action "/web/small-group/member/save"; _method "post"; _class "pt-center-columns" ] [
style [ _scoped ] [ rawText "#memberName { width: 15rem; } #emailAddress { width: 20rem; }" ]
csrfToken ctx
input [ _type "hidden"; _name "memberId"; _value (flatGuid m.memberId) ]
div [ _class "pt-field-row" ] [
div [ _class "pt-field" ] [
label [ _for "memberName" ] [ locStr s.["Member Name"] ]
input [ _type "text"; _name "memberName"; _id "memberName"; _required; _autofocus; _value m.memberName ]
]
div [ _class "pt-field" ] [
label [ _for "emailAddress" ] [ locStr s.["E-mail Address"] ]
input [ _type "email"; _name "emailAddress"; _id "emailAddress"; _required; _value m.emailAddress ]
]
]
div [ _class "pt-field-row" ] [
div [ _class "pt-field" ] [
label [ _for "emailType" ] [ locStr s.["E-mail Format"] ]
typs
|> Seq.map (fun typ -> fst typ, (snd typ).Value)
|> selectList "emailType" m.emailType []
]
]
div [ _class "pt-field-row" ] [ submit [] "save" s.["Save"] ]
]
|> List.singleton
|> Layout.Content.standard
|> Layout.standard vi pageTitle
/// View for the small group log on page
let logOn (grps : SmallGroup list) grpId ctx vi =
let s = I18N.localizer.Force ()
[ form [ _action "/web/small-group/log-on/submit"; _method "post"; _class "pt-center-columns" ] [
csrfToken ctx
div [ _class "pt-field-row" ] [
div [ _class "pt-field" ] [
label [ _for "smallGroupId" ] [ locStr s.["Group"] ]
seq {
match grps.Length with
| 0 -> "", s.["There are no classes with passwords defined"].Value
| _ ->
"", selectDefault s.["Select Group"].Value
yield! grps
|> List.map (fun grp -> flatGuid grp.smallGroupId, sprintf "%s | %s" grp.church.name grp.name)
}
|> selectList "smallGroupId" grpId [ _required ]
]
div [ _class "pt-field" ] [
label [ _for "password" ] [ locStr s.["Password"] ]
input [ _type "password"; _name "password"; _id "password"; _required;
_placeholder (s.["Case-Sensitive"].Value.ToLower ()) ]
]
]
div [ _class "pt-checkbox-field" ] [
input [ _type "checkbox"; _name "rememberMe"; _id "rememberMe"; _value "True" ]
label [ _for "rememberMe" ] [ locStr s.["Remember Me"] ]
br []
small [] [ em [] [ str (s.["Requires Cookies"].Value.ToLower ()) ] ]
]
div [ _class "pt-field-row" ] [ submit [] "account_circle" s.["Log On"] ]
]
script [] [ rawText "PT.onLoad(PT.smallGroup.logOn.onPageLoad)" ]
]
|> Layout.Content.standard
|> Layout.standard vi "Group Log On"
/// View for the small group maintenance page
let maintain (grps : SmallGroup list) ctx vi =
let s = I18N.localizer.Force ()
let grpTbl =
match grps with
| [] -> space
| _ ->
table [ _class "pt-table pt-action-table" ] [
thead [] [
tr [] [
th [] [ locStr s.["Actions"] ]
th [] [ locStr s.["Name"] ]
th [] [ locStr s.["Church"] ]
th [] [ locStr s.["Time Zone"] ]
]
]
grps
|> List.map (fun g ->
let grpId = flatGuid g.smallGroupId
let delAction = sprintf "/web/small-group/%s/delete" grpId
let delPrompt = s.["Are you sure you want to delete this {0}? This action cannot be undone.",
sprintf "%s (%s)" (s.["Small Group"].Value.ToLower ()) g.name].Value
tr [] [
td [] [
a [ _href (sprintf "/web/small-group/%s/edit" grpId); _title s.["Edit This Group"].Value ] [ icon "edit" ]
a [ _href delAction
_title s.["Delete This Group"].Value
_onclick (sprintf "return PT.confirmDelete('%s','%s')" delAction delPrompt) ]
[ icon "delete_forever" ]
]
td [] [ str g.name ]
td [] [ str g.church.name ]
td [] [ locStr (TimeZones.name g.preferences.timeZoneId s) ]
])
|> tbody []
]
[ div [ _class "pt-center-text" ] [
br []
a [ _href (sprintf "/web/small-group/%s/edit" emptyGuid); _title s.["Add a New Group"].Value ] [
icon "add_circle"
rawText " &nbsp;"
locStr s.["Add a New Group"]
]
br []
br []
]
tableSummary grps.Length s
grpTbl
form [ _id "DeleteForm"; _action ""; _method "post" ] [ csrfToken ctx ]
]
|> Layout.Content.standard
|> Layout.standard vi "Maintain Groups"
/// View for the member maintenance page
let members (mbrs : Member list) (emailTyps : Map<string, LocalizedString>) ctx vi =
let s = I18N.localizer.Force ()
let mbrTbl =
match mbrs with
| [] -> space
| _ ->
table [ _class "pt-table pt-action-table" ] [
thead [] [
tr [] [
th [] [ locStr s.["Actions"] ]
th [] [ locStr s.["Name"] ]
th [] [ locStr s.["E-mail Address"] ]
th [] [ locStr s.["Format"] ]
]
]
mbrs
|> List.map (fun mbr ->
let mbrId = flatGuid mbr.memberId
let delAction = sprintf "/web/small-group/member/%s/delete" mbrId
let delPrompt =
s.["Are you sure you want to delete this {0}? This action cannot be undone.", s.["group member"]]
.Value
.Replace("?", sprintf " (%s)?" mbr.memberName)
tr [] [
td [] [
a [ _href (sprintf "/web/small-group/member/%s/edit" mbrId); _title s.["Edit This Group Member"].Value ]
[ icon "edit" ]
a [ _href delAction
_title s.["Delete This Group Member"].Value
_onclick (sprintf "return PT.confirmDelete('%s','%s')" delAction delPrompt) ]
[ icon "delete_forever" ]
]
td [] [ str mbr.memberName ]
td [] [ str mbr.email ]
td [] [ locStr emailTyps.[defaultArg mbr.format ""] ]
])
|> tbody []
]
[ div [ _class"pt-center-text" ] [
br []
a [ _href (sprintf "/web/small-group/member/%s/edit" emptyGuid); _title s.["Add a New Group Member"].Value ]
[ icon "add_circle"; rawText " &nbsp;"; locStr s.["Add a New Group Member"] ]
br []
br []
]
tableSummary mbrs.Length s
mbrTbl
form [ _id "DeleteForm"; _action ""; _method "post" ] [ csrfToken ctx ]
]
|> Layout.Content.standard
|> Layout.standard vi "Maintain Group Members"
/// View for the small group overview page
let overview m vi =
let s = I18N.localizer.Force ()
let linkSpacer = rawText "&nbsp; "
let typs = ReferenceList.requestTypeList s |> dict
article [ _class "pt-overview" ] [
section [] [
header [ _role "heading" ] [
iconSized 72 "bookmark_border"
locStr s.["Quick Actions"]
]
div [] [
a [ _href "/web/prayer-requests/view" ] [ icon "list"; linkSpacer; locStr s.["View Prayer Request List"] ]
hr []
a [ _href "/web/small-group/announcement" ] [ icon "send"; linkSpacer; locStr s.["Send Announcement"] ]
hr []
a [ _href "/web/small-group/preferences" ] [ icon "build"; linkSpacer; locStr s.["Change Preferences"] ]
]
]
section [] [
header [ _role "heading" ] [
iconSized 72 "question_answer"
locStr s.["Prayer Requests"]
]
div [] [
p [ _class "pt-center-text" ] [
strong [] [ str (m.totalActiveReqs.ToString "N0"); space; locStr s.["Active Requests"] ]
]
hr []
for cat in m.activeReqsByCat do
str (cat.Value.ToString "N0")
space
locStr typs.[cat.Key]
br []
br []
str (m.allReqs.ToString "N0")
space
locStr s.["Total Requests"]
hr []
a [ _href "/web/prayer-requests/maintain" ] [
icon "compare_arrows"
linkSpacer
locStr s.["Maintain Prayer Requests"]
]
]
]
section [] [
header [ _role "heading" ] [
iconSized 72 "people_outline"
locStr s.["Group Members"]
]
div [ _class "pt-center-text" ] [
strong [] [ str (m.totalMbrs.ToString "N0"); space; locStr s.["Members"] ]
hr []
a [ _href "/web/small-group/members" ] [ icon "email"; linkSpacer; locStr s.["Maintain Group Members"] ]
]
]
]
|> List.singleton
|> Layout.Content.wide
|> Layout.standard vi "Small Group Overview"
/// View for the small group preferences page
let preferences (m : EditPreferences) (tzs : TimeZone list) ctx vi =
let s = I18N.localizer.Force ()
let l = I18N.forView "SmallGroup/Preferences"
use sw = new StringWriter ()
let raw = rawLocText sw
[ form [ _action "/web/small-group/preferences/save"; _method "post"; _class "pt-center-columns" ] [
style [ _scoped ] [ rawText "#expireDays, #daysToKeepNew, #longTermUpdateWeeks, #headingFontSize, #listFontSize, #pageSize { width: 3rem; } #emailFromAddress { width: 20rem; } #listFonts { width: 40rem; } @media screen and (max-width: 40rem) { #listFonts { width: 100%; } }" ]
csrfToken ctx
fieldset [] [
legend [] [ strong [] [ icon "date_range"; rawText " &nbsp;"; locStr s.["Dates"] ] ]
div [ _class "pt-field-row" ] [
div [ _class "pt-field" ] [
label [ _for "expireDays" ] [ locStr s.["Requests Expire After"] ]
span [] [
input [ _type "number"; _name "expireDays"; _id "expireDays"; _min "1"; _max "30"; _required; _autofocus
_value (string m.expireDays) ]
space; str (s.["Days"].Value.ToLower ())
]
]
div [ _class "pt-field" ] [
label [ _for "daysToKeepNew" ] [ locStr s.["Requests “New” For"] ]
span [] [
input [ _type "number"; _name "daysToKeepNew"; _id "daysToKeepNew"; _min "1"; _max "30"; _required
_value (string m.daysToKeepNew) ]
space; str (s.["Days"].Value.ToLower ())
]
]
div [ _class "pt-field" ] [
label [ _for "longTermUpdateWeeks" ] [ locStr s.["Long-Term Requests Alerted for Update"] ]
span [] [
input [ _type "number"; _name "longTermUpdateWeeks"; _id "longTermUpdateWeeks"; _min "1"; _max "30"
_required; _value (string m.longTermUpdateWeeks) ]
space; str (s.["Weeks"].Value.ToLower ())
]
]
]
]
fieldset [] [
legend [] [ strong [] [ icon "sort"; rawText " &nbsp;"; locStr s.["Request Sorting"] ] ]
radio "requestSort" "requestSort_D" "D" m.requestSort
label [ _for "requestSort_D" ] [ locStr s.["Sort by Last Updated Date"] ]
rawText " &nbsp; "
radio "requestSort" "requestSort_R" "R" m.requestSort
label [ _for "requestSort_R" ] [ locStr s.["Sort by Requestor Name"] ]
]
fieldset [] [
legend [] [ strong [] [ icon "mail_outline"; rawText " &nbsp;"; locStr s.["E-mail"] ] ]
div [ _class "pt-field-row" ] [
div [ _class "pt-field" ] [
label [ _for "emailFromName" ] [ locStr s.["From Name"] ]
input [ _type "text"; _name "emailFromName"; _id "emailFromName"; _required; _value m.emailFromName ]
]
div [ _class "pt-field" ] [
label [ _for "emailFromAddress" ] [ locStr s.["From Address"] ]
input [ _type "email"; _name "emailFromAddress"; _id "emailFromAddress"; _required
_value m.emailFromAddress ]
]
]
div [ _class "pt-field-row" ] [
div [ _class "pt-field" ] [
label [ _for "defaultEmailType" ] [ locStr s.["E-mail Format"] ]
seq {
"", selectDefault s.["Select"].Value
yield! ReferenceList.emailTypeList HtmlFormat s
|> Seq.skip 1
|> Seq.map (fun typ -> fst typ, (snd typ).Value)
}
|> selectList "defaultEmailType" m.defaultEmailType [ _required ]
]
]
]
fieldset [] [
legend [] [ strong [] [ icon "color_lens"; rawText " &nbsp;"; locStr s.["Colors"] ]; rawText " ***" ]
div [ _class "pt-field-row" ] [
div [ _class "pt-field" ] [
label [ _class "pt-center-text" ] [ locStr s.["Color of Heading Lines"] ]
span [] [
radio "headingLineType" "headingLineType_Name" "Name" m.headingLineType
label [ _for "headingLineType_Name" ] [ locStr s.["Named Color"] ]
namedColorList "headingLineColor" m.headingLineColor
[ _id "headingLineColor_Select"
match m.headingLineColor.StartsWith "#" with true -> _disabled | false -> () ] s
rawText "&nbsp; &nbsp; "; str (s.["or"].Value.ToUpper ())
radio "headingLineType" "headingLineType_RGB" "RGB" m.headingLineType
label [ _for "headingLineType_RGB" ] [ locStr s.["Custom Color"] ]
input [ _type "color"
_name "headingLineColor"
_id "headingLineColor_Color"
_value m.headingLineColor
match m.headingLineColor.StartsWith "#" with true -> () | false -> _disabled ]
]
]
]
div [ _class "pt-field-row" ] [
div [ _class "pt-field" ] [
label [ _class "pt-center-text" ] [ locStr s.["Color of Heading Text"] ]
span [] [
radio "headingTextType" "headingTextType_Name" "Name" m.headingTextType
label [ _for "headingTextType_Name" ] [ locStr s.["Named Color"] ]
namedColorList "headingTextColor" m.headingTextColor
[ _id "headingTextColor_Select"
match m.headingTextColor.StartsWith "#" with true -> _disabled | false -> () ] s
rawText "&nbsp; &nbsp; "; str (s.["or"].Value.ToUpper ())
radio "headingTextType" "headingTextType_RGB" "RGB" m.headingTextType
label [ _for "headingTextType_RGB" ] [ locStr s.["Custom Color"] ]
input [ _type "color"
_name "headingTextColor"
_id "headingTextColor_Color"
_value m.headingTextColor
match m.headingTextColor.StartsWith "#" with true -> () | false -> _disabled ]
]
]
]
]
fieldset [] [
legend [] [ strong [] [ icon "font_download"; rawText " &nbsp;"; locStr s.["Fonts"] ] ]
div [ _class "pt-field" ] [
label [ _for "listFonts" ] [ locStr s.["Fonts** for List"] ]
input [ _type "text"; _name "listFonts"; _id "listFonts"; _required; _value m.listFonts ]
]
div [ _class "pt-field-row" ] [
div [ _class "pt-field" ] [
label [ _for "headingFontSize" ] [ locStr s.["Heading Text Size"] ]
input [ _type "number"; _name "headingFontSize"; _id "headingFontSize"; _min "8"; _max "24"; _required
_value (string m.headingFontSize) ]
]
div [ _class "pt-field" ] [
label [ _for "listFontSize" ] [ locStr s.["List Text Size"] ]
input [ _type "number"; _name "listFontSize"; _id "listFontSize"; _min "8"; _max "24"; _required
_value (string m.listFontSize) ]
]
]
]
fieldset [] [
legend [] [ strong [] [ icon "settings"; rawText " &nbsp;"; locStr s.["Other Settings"] ] ]
div [ _class "pt-field-row" ] [
div [ _class "pt-field" ] [
label [ _for "timeZone" ] [ locStr s.["Time Zone"] ]
seq {
"", selectDefault s.["Select"].Value
yield! tzs |> List.map (fun tz -> tz.timeZoneId, (TimeZones.name tz.timeZoneId s).Value)
}
|> selectList "timeZone" m.timeZone [ _required ]
]
]
div [ _class "pt-field" ] [
label [] [ locStr s.["Request List Visibility"] ]
span [] [
radio "listVisibility" "viz_Public" (string RequestVisibility.``public``) (string m.listVisibility)
label [ _for "viz_Public" ] [ locStr s.["Public"] ]
rawText " &nbsp;"
radio "listVisibility" "viz_Private" (string RequestVisibility.``private``) (string m.listVisibility)
label [ _for "viz_Private" ] [ locStr s.["Private"] ]
rawText " &nbsp;"
radio "listVisibility" "viz_Password" (string RequestVisibility.passwordProtected) (string m.listVisibility)
label [ _for "viz_Password" ] [ locStr s.["Password Protected"] ]
]
]
div [ _id "divClassPassword"
match m.listVisibility = RequestVisibility.passwordProtected with
| true -> _class "pt-field-row pt-fadeable pt-show"
| false -> _class "pt-field-row pt-fadeable"
] [
div [ _class "pt-field" ] [
label [ _for "groupPassword" ] [ locStr s.["Group Password (Used to Read Online)"] ]
input [ _type "text"; _name "groupPassword"; _id "groupPassword";
_value (match m.groupPassword with Some x -> x | None -> "") ]
]
]
div [ _class "pt-field-row" ] [
div [ _class "pt-field" ] [
label [ _for "pageSize" ] [ locStr s.["Page Size"] ]
input [ _type "number"; _name "pageSize"; _id "pageSize"; _min "10"; _max "255"; _required
_value (string m.pageSize) ]
]
div [ _class "pt-field" ] [
label [ _for "asOfDate" ] [ locStr s.["“As of” Date Display"] ]
ReferenceList.asOfDateList s
|> List.map (fun (code, desc) -> code, desc.Value)
|> selectList "asOfDate" m.asOfDate [ _required ]
]
]
]
div [ _class "pt-field-row" ] [ submit [] "save" s.["Save Preferences"] ]
]
p [] [
rawText "** "
raw l.["List font names, separated by commas."]
space
raw l.["The first font that is matched is the one that is used."]
space
raw l.["Ending with either “serif” or “sans-serif” will cause the user's browser to use the default “serif” font (“Times New Roman” on Windows) or “sans-serif” font (“Arial” on Windows) if no other fonts in the list are found."]
]
p [] [
rawText "*** "
raw l.["If you want a custom color, you may be able to get some ideas (and a list of RGB values for those colors) from the W3 School's <a href=\"http://www.w3schools.com/html/html_colornames.asp\" title=\"HTML Color List - W3 School\">HTML color name list</a>."]
]
script [] [ rawText "PT.onLoad(PT.smallGroup.preferences.onPageLoad)" ]
]
|> Layout.Content.standard
|> Layout.standard vi "Group Preferences"

View File

@@ -1,226 +0,0 @@
module PrayerTracker.Views.User
open Giraffe.GiraffeViewEngine
open PrayerTracker.Entities
open PrayerTracker.ViewModels
/// View for the group assignment page
let assignGroups m groups curGroups ctx vi =
let s = I18N.localizer.Force ()
let pageTitle = sprintf "%s %A" m.userName s.["Assign Groups"]
form [ _action "/web/user/small-groups/save"; _method "post"; _class "pt-center-columns" ] [
csrfToken ctx
input [ _type "hidden"; _name "userId"; _value (flatGuid m.userId) ]
input [ _type "hidden"; _name "userName"; _value m.userName ]
table [ _class "pt-table" ] [
thead [] [
tr [] [
th [] [ rawText "&nbsp;" ]
th [] [ locStr s.["Group"] ]
]
]
groups
|> List.map (fun (grpId, grpName) ->
let inputId = sprintf "id-%s" grpId
tr [] [
td [] [
input [ _type "checkbox"
_name "smallGroups"
_id inputId
_value grpId
match curGroups |> List.contains grpId with true -> _checked | false -> () ]
]
td [] [ label [ _for inputId ] [ str grpName ] ]
])
|> tbody []
]
div [ _class "pt-field-row" ] [ submit [] "save" s.["Save Group Assignments"] ]
]
|> List.singleton
|> Layout.Content.standard
|> Layout.standard vi pageTitle
/// View for the password change page
let changePassword ctx vi =
let s = I18N.localizer.Force ()
[ p [ _class "pt-center-text" ] [
locStr s.["To change your password, enter your current password in the specified box below, then enter your new password twice."]
]
form [ _action "/web/user/password/change"
_method "post"
_onsubmit (sprintf "return PT.compareValidation('newPassword','newPasswordConfirm','%A')" s.["The passwords do not match"]) ] [
style [ _scoped ] [ rawText "#oldPassword, #newPassword, #newPasswordConfirm { width: 10rem; } "]
csrfToken ctx
div [ _class "pt-field-row" ] [
div [ _class "pt-field" ] [
label [ _for "oldPassword" ] [ locStr s.["Current Password"] ]
input [ _type "password"; _name "oldPassword"; _id "oldPassword"; _required; _autofocus ]
]
]
div [ _class "pt-field-row" ] [
div [ _class "pt-field" ] [
label [ _for "newPassword" ] [ locStr s.["New Password Twice"] ]
input [ _type "password"; _name "newPassword"; _id "newPassword"; _required ]
]
div [ _class "pt-field" ] [
label [] [ rawText "&nbsp;" ]
input [ _type "password"; _name "newPasswordConfirm"; _id "newPasswordConfirm"; _required ]
]
]
div [ _class "pt-field-row" ] [
submit [ _onclick "document.getElementById('newPasswordConfirm').setCustomValidity('')" ] "done"
s.["Change Your Password"]
]
]
]
|> Layout.Content.standard
|> Layout.standard vi "Change Your Password"
/// View for the edit user page
let edit (m : EditUser) ctx vi =
let s = I18N.localizer.Force ()
let pageTitle = match m.isNew () with true -> "Add a New User" | false -> "Edit User"
let pwPlaceholder = s.[match m.isNew () with true -> "" | false -> "No change"].Value
[ form [ _action "/web/user/edit/save"; _method "post"; _class "pt-center-columns"
_onsubmit (sprintf "return PT.compareValidation('password','passwordConfirm','%A')" s.["The passwords do not match"]) ] [
style [ _scoped ]
[ rawText "#firstName, #lastName, #password, #passwordConfirm { width: 10rem; } #emailAddress { width: 20rem; } " ]
csrfToken ctx
input [ _type "hidden"; _name "userId"; _value (flatGuid m.userId) ]
div [ _class "pt-field-row" ] [
div [ _class "pt-field" ] [
label [ _for "firstName" ] [ locStr s.["First Name"] ]
input [ _type "text"; _name "firstName"; _id "firstName"; _value m.firstName; _required; _autofocus ]
]
div [ _class "pt-field" ] [
label [ _for "lastName" ] [ locStr s.["Last Name"] ]
input [ _type "text"; _name "lastName"; _id "lastName"; _value m.lastName; _required ]
]
div [ _class "pt-field" ] [
label [ _for "emailAddress" ] [ locStr s.["E-mail Address"] ]
input [ _type "email"; _name "emailAddress"; _id "emailAddress"; _value m.emailAddress; _required ]
]
]
div [ _class "pt-field-row" ] [
div [ _class "pt-field" ] [
label [ _for "password" ] [ locStr s.["Password"] ]
input [ _type "password"; _name "password"; _id "password"; _placeholder pwPlaceholder ]
]
div [ _class "pt-field" ] [
label [ _for "passwordConfirm" ] [ locStr s.["Password Again"] ]
input [ _type "password"; _name "passwordConfirm"; _id "passwordConfirm"; _placeholder pwPlaceholder ]
]
]
div [ _class "pt-checkbox-field" ] [
input [ _type "checkbox"
_name "isAdmin"
_id "isAdmin"
_value "True"
match m.isAdmin with Some x when x -> _checked | _ -> () ]
label [ _for "isAdmin" ] [ locStr s.["This user is a PrayerTracker administrator"] ]
]
div [ _class "pt-field-row" ] [ submit [] "save" s.["Save User"] ]
]
script [] [ rawText (sprintf "PT.onLoad(PT.user.edit.onPageLoad(%s))" ((string (m.isNew ())).ToLower ())) ]
]
|> Layout.Content.standard
|> Layout.standard vi pageTitle
/// View for the user log on page
let logOn (m : UserLogOn) groups ctx vi =
let s = I18N.localizer.Force ()
form [ _action "/web/user/log-on"; _method "post"; _class "pt-center-columns" ] [
style [ _scoped ] [ rawText "#emailAddress { width: 20rem; }" ]
csrfToken ctx
input [ _type "hidden"; _name "redirectUrl"; _value (defaultArg m.redirectUrl "") ]
div [ _class "pt-field-row" ] [
div [ _class "pt-field" ] [
label [ _for "emailAddress"] [ locStr s.["E-mail Address"] ]
input [ _type "email"; _name "emailAddress"; _id "emailAddress"; _value m.emailAddress; _required; _autofocus ]
]
div [ _class "pt-field" ] [
label [ _for "password" ] [ locStr s.["Password"] ]
input [ _type "password"; _name "password"; _id "password"; _required;
_placeholder (sprintf "(%s)" (s.["Case-Sensitive"].Value.ToLower ())) ]
]
]
div [ _class "pt-field-row" ] [
div [ _class "pt-field" ] [
label [ _for "smallGroupId" ] [ locStr s.["Group"] ]
seq {
"", selectDefault s.["Select Group"].Value
yield! groups
}
|> selectList "smallGroupId" "" [ _required ]
]
]
div [ _class "pt-checkbox-field" ] [
input [ _type "checkbox"; _name "rememberMe"; _id "rememberMe"; _value "True" ]
label [ _for "rememberMe" ] [ locStr s.["Remember Me"] ]
br []
small [] [ em [] [ rawText "("; str (s.["Requires Cookies"].Value.ToLower ()); rawText ")" ] ]
]
div [ _class "pt-field-row" ] [ submit [] "account_circle" s.["Log On"] ]
]
|> List.singleton
|> Layout.Content.standard
|> Layout.standard vi "User Log On"
/// View for the user maintenance page
let maintain (users : User list) ctx vi =
let s = I18N.localizer.Force ()
let usrTbl =
match users with
| [] -> space
| _ ->
table [ _class "pt-table pt-action-table" ] [
thead [] [
tr [] [
th [] [ locStr s.["Actions"] ]
th [] [ locStr s.["Name"] ]
th [] [ locStr s.["Admin?"] ]
]
]
users
|> List.map (fun user ->
let userId = flatGuid user.userId
let delAction = sprintf "/web/user/%s/delete" userId
let delPrompt = s.["Are you sure you want to delete this {0}? This action cannot be undone.",
(sprintf "%s (%s)" (s.["User"].Value.ToLower()) user.fullName)].Value
tr [] [
td [] [
a [ _href (sprintf "/web/user/%s/edit" userId); _title s.["Edit This User"].Value ] [ icon "edit" ]
a [ _href (sprintf "/web/user/%s/small-groups" userId); _title s.["Assign Groups to This User"].Value ]
[ icon "group" ]
a [ _href delAction
_title s.["Delete This User"].Value
_onclick (sprintf "return PT.confirmDelete('%s','%s')" delAction delPrompt) ]
[ icon "delete_forever" ]
]
td [] [ str user.fullName ]
td [ _class "pt-center-text" ] [
match user.isAdmin with
| true -> strong [] [ locStr s.["Yes"] ]
| false -> locStr s.["No"]
]
])
|> tbody []
]
[ div [ _class "pt-center-text" ] [
br []
a [ _href (sprintf "/web/user/%s/edit" emptyGuid); _title s.["Add a New User"].Value ]
[ icon "add_circle"; rawText " &nbsp;"; locStr s.["Add a New User"] ]
br []
br []
]
tableSummary users.Length s
usrTbl
form [ _id "DeleteForm"; _action ""; _method "post" ] [ csrfToken ctx ]
]
|> Layout.Content.standard
|> Layout.standard vi "Maintain Users"

View File

@@ -1,207 +0,0 @@
[<AutoOpen>]
module PrayerTracker.Utils
open System.Net
open System.Security.Cryptography
open System.Text
open System.Text.RegularExpressions
open System
/// Hash a string with a SHA1 hash
let sha1Hash (x : string) =
use alg = SHA1.Create ()
alg.ComputeHash (Encoding.ASCII.GetBytes x)
|> Seq.map (fun chr -> chr.ToString "x2")
|> String.concat ""
/// Hash a string using 1,024 rounds of PBKDF2 and a salt
let pbkdf2Hash (salt : Guid) (x : string) =
use alg = new Rfc2898DeriveBytes (x, Encoding.UTF8.GetBytes (salt.ToString "N"), 1024)
(alg.GetBytes >> Convert.ToBase64String) 64
/// String helper functions
module String =
/// string.Trim()
let trim (str: string) = str.Trim ()
/// string.Replace()
let replace (find : string) repl (str : string) = str.Replace (find, repl)
/// Replace the first occurrence of a string with a second string within a given string
let replaceFirst (needle : string) replacement (haystack : string) =
match haystack.IndexOf needle with
| -1 -> haystack
| idx ->
[ haystack.[0..idx - 1]
replacement
haystack.[idx + needle.Length..]
]
|> String.concat ""
/// Strip HTML tags from the given string
// Adapted from http://www.dijksterhuis.org/safely-cleaning-html-with-strip_tags-in-csharp/
let stripTags allowedTags input =
let stripHtmlExp = Regex @"(<\/?[^>]+>)"
let mutable output = input
for tag in stripHtmlExp.Matches input do
let htmlTag = tag.Value.ToLower ()
let isAllowed =
allowedTags
|> List.fold
(fun acc t ->
acc
|| htmlTag.IndexOf (sprintf "<%s>" t) = 0
|| htmlTag.IndexOf (sprintf "<%s " t) = 0
|| htmlTag.IndexOf (sprintf "</%s" t) = 0) false
match isAllowed with
| true -> ()
| false -> output <- String.replaceFirst tag.Value "" output
output
/// Wrap a string at the specified number of characters
let wordWrap charPerLine (input : string) =
match input.Length with
| len when len <= charPerLine -> input
| _ ->
seq {
for line in input.Replace("\r", "").Split '\n' do
let mutable remaining = line
match remaining.Length with
| 0 -> ()
| _ ->
while charPerLine < remaining.Length do
match charPerLine + 1 < remaining.Length && remaining.[charPerLine] = ' ' with
| true ->
// Line length is followed by a space; return [charPerLine] as a line
yield remaining.[0..charPerLine - 1]
remaining <- remaining.[charPerLine + 1..]
| false ->
match remaining.[0..charPerLine - 1].LastIndexOf ' ' with
| -1 ->
// No whitespace; just break it at [characters]
yield remaining.[0..charPerLine - 1]
remaining <- remaining.[charPerLine..]
| spaceIdx ->
// Break on the last space in the line
yield remaining.[0..spaceIdx - 1]
remaining <- remaining.[spaceIdx + 1..]
// Leftovers - yum!
match remaining.Length with 0 -> () | _ -> yield remaining
}
|> Seq.fold (fun (acc : StringBuilder) line -> acc.AppendFormat ("{0}\n", line)) (StringBuilder ())
|> string
/// Modify the text returned by CKEditor into the format we need for request and announcement text
let ckEditorToText (text : string) =
let trim (str : string) = str.Trim ()
[ "\n\t", ""
"&nbsp;", " "
" ", "&#xa0; "
"</p><p>", "<br><br>"
"</p>", ""
"<p>", ""
]
|> List.fold (fun (txt : string) (x, y) -> String.replace x y txt) text
|> trim
/// Convert an HTML piece of text to plain text
let htmlToPlainText html =
match html with
| null | "" -> ""
| _ ->
html.Trim ()
|> stripTags [ "br" ]
|> String.replace "<br />" "\n"
|> String.replace "<br>" "\n"
|> WebUtility.HtmlDecode
|> String.replace "\u00a0" " "
/// Get the second portion of a tuple as a string
let sndAsString x = (snd >> string) x
/// Make a URL with query string parameters
let makeUrl (url : string) (qs : (string * string) list) =
let queryString =
qs
|> List.fold
(fun (acc : StringBuilder) (key, value) ->
acc.Append(key).Append("=").Append(WebUtility.UrlEncode value).Append "&")
(StringBuilder ())
match queryString.Length with
| 0 -> url
| _ -> queryString.Insert(0, "?").Insert(0, url).Remove(queryString.Length - 1, 1).ToString ()
/// "Magic string" repository
[<RequireQualifiedAccess>]
module Key =
/// This contains constants for session-stored objects within PrayerTracker
module Session =
/// The currently logged-on small group
let currentGroup = "CurrentGroup"
/// The currently logged-on user
let currentUser = "CurrentUser"
/// User messages to be displayed the next time a page is sent
let userMessages = "UserMessages"
/// The URL to which the user should be redirected once they have logged in
let redirectUrl = "RedirectUrl"
/// Names and value names for use with cookies
module Cookie =
/// The name of the user cookie
let user = "LoggedInUser"
/// The name of the class cookie
let group = "LoggedInClass"
/// The name of the culture cookie
let culture = "CurrentCulture"
/// The name of the idle timeout cookie
let timeout = "TimeoutCookie"
/// The cookies that should be cleared when a user or group logs off
let logOffCookies = [ user; group; timeout ]
/// Enumerated values for small group request list visibility (derived from preferences, used in UI)
module RequestVisibility =
/// Requests are publicly accessible
[<Literal>]
let ``public`` = 1
/// The small group members can enter a password to view the request list
[<Literal>]
let passwordProtected = 2
/// No one can see the requests for a small group except its administrators ("User" access level)
[<Literal>]
let ``private`` = 3
/// Links for help locations
module Help =
/// Help link for small group preference edit page
let groupPreferences = "small-group/preferences"
/// Help link for send announcement page
let sendAnnouncement = "small-group/announcement"
/// Help link for maintain group members page
let maintainGroupMembers = "small-group/members"
/// Help link for request edit page
let editRequest = "requests/edit"
/// Help link for maintain requests page
let maintainRequests = "requests/maintain"
/// Help link for view request list page
let viewRequestList = "requests/view"
/// Help link for user and class login pages
let logOn = "user/log-on"
/// Help link for user password change page
let changePassword = "user/password"
/// Create a full link for a help page
let fullLink lang url = sprintf "https://docs.prayer.bitbadger.solutions/%s/%s.html" lang url
/// This class serves as a common anchor for resources
type Common () =
do ()

View File

@@ -1,682 +0,0 @@
namespace PrayerTracker.ViewModels
open Microsoft.AspNetCore.Html
open Microsoft.Extensions.Localization
open PrayerTracker
open PrayerTracker.Entities
open System
/// Helper module to return localized reference lists
module ReferenceList =
/// A localized list of the AsOfDateDisplay DU cases
let asOfDateList (s : IStringLocalizer) =
[ NoDisplay.code, s.["Do not display the “as of” date"]
ShortDate.code, s.["Display a short “as of” date"]
LongDate.code, s.["Display a full “as of” date"]
]
/// A list of e-mail type options
let emailTypeList def (s : IStringLocalizer) =
// Localize the default type
let defaultType =
match def with
| HtmlFormat -> s.["HTML Format"].Value
| PlainTextFormat -> s.["Plain-Text Format"].Value
seq {
"", LocalizedString ("", sprintf "%s (%s)" s.["Group Default"].Value defaultType)
HtmlFormat.code, s.["HTML Format"]
PlainTextFormat.code, s.["Plain-Text Format"]
}
/// A list of expiration options
let expirationList (s : IStringLocalizer) includeExpireNow =
[ Automatic.code, s.["Expire Normally"]
Manual.code, s.["Request Never Expires"]
match includeExpireNow with true -> Forced.code, s.["Expire Immediately"] | false -> ()
]
/// A list of request types
let requestTypeList (s : IStringLocalizer) =
[ CurrentRequest, s.["Current Requests"]
LongTermRequest, s.["Long-Term Requests"]
PraiseReport, s.["Praise Reports"]
Expecting, s.["Expecting"]
Announcement, s.["Announcements"]
]
/// This is used to create a message that is displayed to the user
[<NoComparison; NoEquality>]
type UserMessage =
{ /// The type
level : string
/// The actual message
text : HtmlString
/// The description (further information)
description : HtmlString option
}
with
/// Error message template
static member Error =
{ level = "ERROR"
text = HtmlString.Empty
description = None
}
/// Warning message template
static member Warning =
{ level = "WARNING"
text = HtmlString.Empty
description = None
}
/// Info message template
static member Info =
{ level = "Info"
text = HtmlString.Empty
description = None
}
/// View model required by the layout template, given as first parameter for all pages in PrayerTracker
[<NoComparison; NoEquality>]
type AppViewInfo =
{ /// CSS files for the page
style : string list
/// JavaScript files for the page
script : string list
/// The link for help on this page
helpLink : string option
/// Messages to be displayed to the user
messages : UserMessage list
/// The current version of PrayerTracker
version : string
/// The ticks when the request started
requestStart : int64
/// The currently logged on user, if there is one
user : User option
/// The currently logged on small group, if there is one
group : SmallGroup option
}
with
/// A fresh version that can be populated to process the current request
static member fresh =
{ style = []
script = []
helpLink = None
messages = []
version = ""
requestStart = DateTime.Now.Ticks
user = None
group = None
}
/// Form for sending a small group or system-wide announcement
[<CLIMutable; NoComparison; NoEquality>]
type Announcement =
{ /// Whether the announcement should be sent to the class or to PrayerTracker users
sendToClass : string
/// The text of the announcement
text : string
/// Whether this announcement should be added to the "Announcements" of the prayer list
addToRequestList : bool option
/// The ID of the request type to which this announcement should be added
requestType : string option
}
with
/// The text of the announcement, in plain text
member this.plainText () = (htmlToPlainText >> wordWrap 74) this.text
/// Form for assigning small groups to a user
[<CLIMutable; NoComparison; NoEquality>]
type AssignGroups =
{ /// The Id of the user being assigned
userId : UserId
/// The full name of the user being assigned
userName : string
/// The Ids of the small groups to which the user is authorized
smallGroups : string
}
with
/// Create an instance of this form from an existing user
static member fromUser (u : User) =
{ userId = u.userId
userName = u.fullName
smallGroups = ""
}
/// Form to allow users to change their password
[<CLIMutable; NoComparison; NoEquality>]
type ChangePassword =
{ /// The user's current password
oldPassword : string
/// The user's new password
newPassword : string
/// The user's new password, confirmed
newPasswordConfirm : string
}
/// Form for adding or editing a church
[<CLIMutable; NoComparison; NoEquality>]
type EditChurch =
{ /// The Id of the church
churchId : ChurchId
/// The name of the church
name : string
/// The city for the church
city : string
/// The state for the church
st : string
/// Whether the church has an active VPR interface
hasInterface : bool option
/// The address for the interface
interfaceAddress : string option
}
with
/// Create an instance from an existing church
static member fromChurch (ch : Church) =
{ churchId = ch.churchId
name = ch.name
city = ch.city
st = ch.st
hasInterface = match ch.hasInterface with true -> Some true | false -> None
interfaceAddress = ch.interfaceAddress
}
/// An instance to use for adding churches
static member empty =
{ churchId = Guid.Empty
name = ""
city = ""
st = ""
hasInterface = None
interfaceAddress = None
}
/// Is this a new church?
member this.isNew () = Guid.Empty = this.churchId
/// Populate a church from this form
member this.populateChurch (church : Church) =
{ church with
name = this.name
city = this.city
st = this.st
hasInterface = match this.hasInterface with Some x -> x | None -> false
interfaceAddress = match this.hasInterface with Some x when x -> this.interfaceAddress | _ -> None
}
/// Form for adding/editing small group members
[<CLIMutable; NoComparison; NoEquality>]
type EditMember =
{ /// The Id for this small group member (not user-entered)
memberId : MemberId
/// The name of the member
memberName : string
/// The e-mail address
emailAddress : string
/// The e-mail format
emailType : string
}
with
/// Create an instance from an existing member
static member fromMember (m : Member) =
{ memberId = m.memberId
memberName = m.memberName
emailAddress = m.email
emailType = match m.format with Some f -> f | None -> ""
}
/// An empty instance
static member empty =
{ memberId = Guid.Empty
memberName = ""
emailAddress = ""
emailType = ""
}
/// Is this a new member?
member this.isNew () = Guid.Empty = this.memberId
/// This form allows the user to set class preferences
[<CLIMutable; NoComparison; NoEquality>]
type EditPreferences =
{ /// The number of days after which requests are automatically expired
expireDays : int
/// The number of days requests are considered "new"
daysToKeepNew : int
/// The number of weeks after which a long-term requests is flagged as requiring an update
longTermUpdateWeeks : int
/// Whether to sort by updated date or requestor/subject
requestSort : string
/// The name from which e-mail will be sent
emailFromName : string
/// The e-mail address from which e-mail will be sent
emailFromAddress : string
/// The default e-mail type for this group
defaultEmailType : string
/// Whether the heading line color uses named colors or R/G/B
headingLineType : string
/// The named color for the heading lines
headingLineColor : string
/// Whether the heading text color uses named colors or R/G/B
headingTextType : string
/// The named color for the heading text
headingTextColor : string
/// The fonts to use for the list
listFonts : string
/// The font size for the heading text
headingFontSize : int
/// The font size for the list text
listFontSize : int
/// The time zone for the class
timeZone : string
/// The list visibility
listVisibility : int
/// The small group password
groupPassword : string option
/// The page size for search / inactive requests
pageSize : int
/// How the as-of date should be displayed
asOfDate : string
}
with
static member fromPreferences (prefs : ListPreferences) =
let setType (x : string) = match x.StartsWith "#" with true -> "RGB" | false -> "Name"
{ expireDays = prefs.daysToExpire
daysToKeepNew = prefs.daysToKeepNew
longTermUpdateWeeks = prefs.longTermUpdateWeeks
requestSort = prefs.requestSort.code
emailFromName = prefs.emailFromName
emailFromAddress = prefs.emailFromAddress
defaultEmailType = prefs.defaultEmailType.code
headingLineType = setType prefs.lineColor
headingLineColor = prefs.lineColor
headingTextType = setType prefs.headingColor
headingTextColor = prefs.headingColor
listFonts = prefs.listFonts
headingFontSize = prefs.headingFontSize
listFontSize = prefs.textFontSize
timeZone = prefs.timeZoneId
groupPassword = Some prefs.groupPassword
pageSize = prefs.pageSize
asOfDate = prefs.asOfDateDisplay.code
listVisibility =
match true with
| _ when prefs.isPublic -> RequestVisibility.``public``
| _ when prefs.groupPassword = "" -> RequestVisibility.``private``
| _ -> RequestVisibility.passwordProtected
}
/// Set the properties of a small group based on the form's properties
member this.populatePreferences (prefs : ListPreferences) =
let isPublic, grpPw =
match this.listVisibility with
| RequestVisibility.``public`` -> true, ""
| RequestVisibility.passwordProtected -> false, (defaultArg this.groupPassword "")
| RequestVisibility.``private``
| _ -> false, ""
{ prefs with
daysToExpire = this.expireDays
daysToKeepNew = this.daysToKeepNew
longTermUpdateWeeks = this.longTermUpdateWeeks
requestSort = RequestSort.fromCode this.requestSort
emailFromName = this.emailFromName
emailFromAddress = this.emailFromAddress
defaultEmailType = EmailFormat.fromCode this.defaultEmailType
lineColor = this.headingLineColor
headingColor = this.headingTextColor
listFonts = this.listFonts
headingFontSize = this.headingFontSize
textFontSize = this.listFontSize
timeZoneId = this.timeZone
isPublic = isPublic
groupPassword = grpPw
pageSize = this.pageSize
asOfDateDisplay = AsOfDateDisplay.fromCode this.asOfDate
}
/// Form for adding or editing prayer requests
[<CLIMutable; NoComparison; NoEquality>]
type EditRequest =
{ /// The Id of the request
requestId : PrayerRequestId
/// The type of the request
requestType : string
/// The date of the request
//[<Display (Name = "Date")>]
enteredDate : DateTime option
/// Whether to update the date or not
skipDateUpdate : bool option
/// The requestor or subject
requestor : string option
/// How this request is expired
expiration : string
/// The text of the request
text : string
}
with
/// An empty instance to use for new requests
static member empty =
{ requestId = Guid.Empty
requestType = CurrentRequest.code
enteredDate = None
skipDateUpdate = None
requestor = None
expiration = Automatic.code
text = ""
}
/// Create an instance from an existing request
static member fromRequest req =
{ EditRequest.empty with
requestId = req.prayerRequestId
requestType = req.requestType.code
requestor = req.requestor
expiration = req.expiration.code
text = req.text
}
/// Is this a new request?
member this.isNew () = Guid.Empty = this.requestId
/// Form for the admin-level editing of small groups
[<CLIMutable; NoComparison; NoEquality>]
type EditSmallGroup =
{ /// The Id of the small group
smallGroupId : SmallGroupId
/// The name of the small group
name : string
/// The Id of the church to which this small group belongs
churchId : ChurchId
}
with
/// Create an instance from an existing small group
static member fromGroup (g : SmallGroup) =
{ smallGroupId = g.smallGroupId
name = g.name
churchId = g.churchId
}
/// An empty instance (used when adding a new group)
static member empty =
{ smallGroupId = Guid.Empty
name = ""
churchId = Guid.Empty
}
/// Is this a new small group?
member this.isNew () = Guid.Empty = this.smallGroupId
/// Populate a small group from this form
member this.populateGroup (grp : SmallGroup) =
{ grp with
name = this.name
churchId = this.churchId
}
/// Form for the user edit page
[<CLIMutable; NoComparison; NoEquality>]
type EditUser =
{ /// The Id of the user
userId : UserId
/// The first name of the user
firstName : string
/// The last name of the user
lastName : string
/// The e-mail address for the user
emailAddress : string
/// The password for the user
password : string
/// The password hash for the user a second time
passwordConfirm : string
/// Is this user a PrayerTracker administrator?
isAdmin : bool option
}
with
/// An empty instance
static member empty =
{ userId = Guid.Empty
firstName = ""
lastName = ""
emailAddress = ""
password = ""
passwordConfirm = ""
isAdmin = None
}
/// Create an instance from an existing user
static member fromUser (user : User) =
{ EditUser.empty with
userId = user.userId
firstName = user.firstName
lastName = user.lastName
emailAddress = user.emailAddress
isAdmin = match user.isAdmin with true -> Some true | false -> None
}
/// Is this a new user?
member this.isNew () = Guid.Empty = this.userId
/// Populate a user from the form
member this.populateUser (user : User) hasher =
{ user with
firstName = this.firstName
lastName = this.lastName
emailAddress = this.emailAddress
isAdmin = match this.isAdmin with Some x -> x | None -> false
}
|> function
| u when this.password = null || this.password = "" -> u
| u -> { u with passwordHash = hasher this.password }
/// Form for the small group log on page
[<CLIMutable; NoComparison; NoEquality>]
type GroupLogOn =
{ /// The ID of the small group to which the user is logging on
smallGroupId : SmallGroupId
/// The password entered
password : string
/// Whether to remember the login
rememberMe : bool option
}
with
static member empty =
{ smallGroupId = Guid.Empty
password = ""
rememberMe = None
}
/// Items needed to display the request maintenance page
[<NoComparison; NoEquality>]
type MaintainRequests =
{ /// The requests to be displayed
requests : PrayerRequest seq
/// The small group to which the requests belong
smallGroup : SmallGroup
/// Whether only active requests are included
onlyActive : bool option
/// The search term for the requests
searchTerm : string option
/// The page number of the results
pageNbr : int option
}
with
static member empty =
{ requests = Seq.empty
smallGroup = SmallGroup.empty
onlyActive = None
searchTerm = None
pageNbr = None
}
/// Items needed to display the small group overview page
[<NoComparison; NoEquality>]
type Overview =
{ /// The total number of active requests
totalActiveReqs : int
/// The numbers of active requests by category
activeReqsByCat : Map<PrayerRequestType, int>
/// A count of all requests
allReqs : int
/// A count of all members
totalMbrs : int
}
/// Form for the user log on page
[<CLIMutable; NoComparison; NoEquality>]
type UserLogOn =
{ /// The e-mail address of the user
emailAddress : string
/// The password entered
password : string
/// The ID of the small group to which the user is logging on
smallGroupId : SmallGroupId
/// Whether to remember the login
rememberMe : bool option
/// The URL to which the user should be redirected once login is successful
redirectUrl : string option
}
with
static member empty =
{ emailAddress = ""
password = ""
smallGroupId = Guid.Empty
rememberMe = None
redirectUrl = None
}
open Giraffe.GiraffeViewEngine
/// This represents a list of requests
type RequestList =
{ /// The prayer request list
requests : PrayerRequest list
/// The date for which this list is being generated
date : DateTime
/// The small group to which this list belongs
listGroup : SmallGroup
/// Whether to show the class header
showHeader : bool
/// The list of recipients (populated if requests are e-mailed)
recipients : Member list
/// Whether the user can e-mail this list
canEmail : bool
}
with
/// Get the requests for a specified type
member this.requestsInCategory cat =
let reqs =
this.requests
|> Seq.ofList
|> Seq.filter (fun req -> req.requestType = cat)
match this.listGroup.preferences.requestSort with
| SortByDate -> reqs |> Seq.sortByDescending (fun req -> req.updatedDate)
| SortByRequestor -> reqs |> Seq.sortBy (fun req -> req.requestor)
|> List.ofSeq
/// Is this request new?
member this.isNew (req : PrayerRequest) =
(this.date - req.updatedDate).Days <= this.listGroup.preferences.daysToKeepNew
/// Generate this list as HTML
member this.asHtml (s : IStringLocalizer) =
let prefs = this.listGroup.preferences
let asOfSize = Math.Round (float prefs.textFontSize * 0.8, 2)
[ match this.showHeader with
| true ->
div [ _style (sprintf "text-align:center;font-family:%s" prefs.listFonts) ] [
span [ _style (sprintf "font-size:%ipt;" prefs.headingFontSize) ] [
strong [] [ str s.["Prayer Requests"].Value ]
]
br []
span [ _style (sprintf "font-size:%ipt;" prefs.textFontSize) ] [
strong [] [ str this.listGroup.name ]
br []
str (this.date.ToString s.["MMMM d, yyyy"].Value)
]
]
br []
| false -> ()
let typs = ReferenceList.requestTypeList s
for cat in
typs
|> Seq.ofList
|> Seq.map fst
|> Seq.filter (fun c -> 0 < (this.requests |> List.filter (fun req -> req.requestType = c) |> List.length)) do
let reqs = this.requestsInCategory cat
let catName = typs |> List.filter (fun t -> fst t = cat) |> List.head |> snd
div [ _style "padding-left:10px;padding-bottom:.5em;" ] [
table [ _style (sprintf "font-family:%s;page-break-inside:avoid;" prefs.listFonts) ] [
tr [] [
td [ _style (sprintf "font-size:%ipt;color:%s;padding:3px 0;border-top:solid 3px %s;border-bottom:solid 3px %s;font-weight:bold;"
prefs.headingFontSize prefs.headingColor prefs.lineColor prefs.lineColor) ] [
rawText "&nbsp; &nbsp; "; str catName.Value; rawText "&nbsp; &nbsp; "
]
]
]
]
reqs
|> List.map (fun req ->
let bullet = match this.isNew req with true -> "circle" | false -> "disc"
li [ _style (sprintf "list-style-type:%s;font-family:%s;font-size:%ipt;padding-bottom:.25em;"
bullet prefs.listFonts prefs.textFontSize) ] [
match req.requestor with
| Some rqstr when rqstr <> "" ->
strong [] [ str rqstr ]
rawText " &mdash; "
| Some _ -> ()
| None -> ()
rawText req.text
match prefs.asOfDateDisplay with
| NoDisplay -> ()
| ShortDate
| LongDate ->
let dt =
match prefs.asOfDateDisplay with
| ShortDate -> req.updatedDate.ToShortDateString ()
| LongDate -> req.updatedDate.ToLongDateString ()
| _ -> ""
i [ _style (sprintf "font-size:%.2fpt" asOfSize) ] [
rawText "&nbsp; ("; str s.["as of"].Value; str " "; str dt; rawText ")"
]
])
|> ul []
br []
]
|> renderHtmlNodes
/// Generate this list as plain text
member this.asText (s : IStringLocalizer) =
seq {
this.listGroup.name
s.["Prayer Requests"].Value
this.date.ToString s.["MMMM d, yyyy"].Value
" "
let typs = ReferenceList.requestTypeList s
for cat in
typs
|> Seq.ofList
|> Seq.map fst
|> Seq.filter (fun c -> 0 < (this.requests |> List.filter (fun req -> req.requestType = c) |> List.length)) do
let reqs = this.requestsInCategory cat
let typ = (typs |> List.filter (fun t -> fst t = cat) |> List.head |> snd).Value
let dashes = String.replicate (typ.Length + 4) "-"
dashes
sprintf @" %s" (typ.ToUpper ())
dashes
for req in reqs do
let bullet = match this.isNew req with true -> "+" | false -> "-"
let requestor = match req.requestor with Some r -> sprintf "%s - " r | None -> ""
match this.listGroup.preferences.asOfDateDisplay with
| NoDisplay -> ""
| _ ->
let dt =
match this.listGroup.preferences.asOfDateDisplay with
| ShortDate -> req.updatedDate.ToShortDateString ()
| LongDate -> req.updatedDate.ToLongDateString ()
| _ -> ""
sprintf " (%s %s)" s.["as of"].Value dt
|> sprintf " %s %s%s%s" bullet requestor (htmlToPlainText req.text)
" "
}
|> String.concat "\n"
|> wordWrap 74

View File

@@ -1,21 +1,23 @@
 
Microsoft Visual Studio Solution File, Format Version 12.00 Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16 # Visual Studio Version 17
VisualStudioVersion = 16.0.29411.108 VisualStudioVersion = 17.2.32630.192
MinimumVisualStudioVersion = 10.0.40219.1 MinimumVisualStudioVersion = 10.0.40219.1
Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "PrayerTracker", "PrayerTracker\PrayerTracker.fsproj", "{63780D3F-D811-4BFB-9FB0-C28A83CCE28F}" Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "PrayerTracker", "PrayerTracker\PrayerTracker.fsproj", "{63780D3F-D811-4BFB-9FB0-C28A83CCE28F}"
EndProject EndProject
Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "PrayerTracker.UI", "PrayerTracker.UI\PrayerTracker.UI.fsproj", "{EEE04A2B-818C-4241-90C5-69097CB0BF71}" Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "PrayerTracker.UI", "UI\PrayerTracker.UI.fsproj", "{EEE04A2B-818C-4241-90C5-69097CB0BF71}"
EndProject EndProject
Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "PrayerTracker.Tests", "PrayerTracker.Tests\PrayerTracker.Tests.fsproj", "{786E7BE9-9370-4117-B194-02CC2F71AA09}" Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "PrayerTracker.Tests", "Tests\PrayerTracker.Tests.fsproj", "{786E7BE9-9370-4117-B194-02CC2F71AA09}"
EndProject EndProject
Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "PrayerTracker.Data", "PrayerTracker.Data\PrayerTracker.Data.fsproj", "{2B5BA107-9BDA-4A1D-A9AF-AFEE6BF12270}" Project("{6EC3EE1D-3C4E-46DD-8F32-0CC8E7565705}") = "PrayerTracker.Data", "Data\PrayerTracker.Data.fsproj", "{2B5BA107-9BDA-4A1D-A9AF-AFEE6BF12270}"
EndProject EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{B290BA27-C8B8-44F3-BF01-D103302D815F}" Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{B290BA27-C8B8-44F3-BF01-D103302D815F}"
ProjectSection(SolutionItems) = preProject ProjectSection(SolutionItems) = preProject
Directory.Build.props = Directory.Build.props Directory.Build.props = Directory.Build.props
EndProjectSection EndProjectSection
EndProject EndProject
Project("{F2A71F9B-5D33-465A-A702-920D77279786}") = "PrayerTracker.MigrateV9", "PrayerTracker.MigrateV9\PrayerTracker.MigrateV9.fsproj", "{CE7C5972-AC9A-44A8-8265-771483FD87DB}"
EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU Debug|Any CPU = Debug|Any CPU
@@ -38,6 +40,10 @@ Global
{2B5BA107-9BDA-4A1D-A9AF-AFEE6BF12270}.Debug|Any CPU.Build.0 = Debug|Any CPU {2B5BA107-9BDA-4A1D-A9AF-AFEE6BF12270}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2B5BA107-9BDA-4A1D-A9AF-AFEE6BF12270}.Release|Any CPU.ActiveCfg = Release|Any CPU {2B5BA107-9BDA-4A1D-A9AF-AFEE6BF12270}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2B5BA107-9BDA-4A1D-A9AF-AFEE6BF12270}.Release|Any CPU.Build.0 = Release|Any CPU {2B5BA107-9BDA-4A1D-A9AF-AFEE6BF12270}.Release|Any CPU.Build.0 = Release|Any CPU
{CE7C5972-AC9A-44A8-8265-771483FD87DB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{CE7C5972-AC9A-44A8-8265-771483FD87DB}.Debug|Any CPU.Build.0 = Debug|Any CPU
{CE7C5972-AC9A-44A8-8265-771483FD87DB}.Release|Any CPU.ActiveCfg = Release|Any CPU
{CE7C5972-AC9A-44A8-8265-771483FD87DB}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE

View File

@@ -0,0 +1,12 @@
{
"version": 1,
"isRoot": true,
"tools": {
"dotnet-ef": {
"version": "3.1.2",
"commands": [
"dotnet-ef"
]
}
}
}

View File

@@ -1,199 +1,286 @@
namespace PrayerTracker namespace PrayerTracker
open Microsoft.AspNetCore.Http
/// Middleware to add the starting ticks for the request
type RequestStartMiddleware(next: RequestDelegate) =
member this.InvokeAsync(ctx: HttpContext) =
task {
ctx.Items[Key.startTime] <- ctx.Now
return! next.Invoke ctx
}
open System
open Microsoft.AspNetCore.Builder open Microsoft.AspNetCore.Builder
open Microsoft.AspNetCore.Hosting open Microsoft.AspNetCore.Hosting
open Microsoft.Extensions.Configuration
/// Module to hold configuration for the web app /// Module to hold configuration for the web app
[<RequireQualifiedAccess>] [<RequireQualifiedAccess>]
module Configure = module Configure =
open Cookies
open Giraffe
open Giraffe.TokenRouter
open Microsoft.AspNetCore.Localization
open Microsoft.AspNetCore.Server.Kestrel.Core
open Microsoft.EntityFrameworkCore
open Microsoft.Extensions.Configuration
open Microsoft.Extensions.DependencyInjection
open Microsoft.Extensions.Hosting
open Microsoft.Extensions.Localization
open Microsoft.Extensions.Logging
open Microsoft.Extensions.Options
open NodaTime
open System.Globalization
/// Set up the configuration for the app /// Set up the configuration for the app
let configuration (ctx : WebHostBuilderContext) (cfg : IConfigurationBuilder) = let configuration (ctx: WebHostBuilderContext) (cfg: IConfigurationBuilder) =
cfg.SetBasePath(ctx.HostingEnvironment.ContentRootPath) cfg
.AddJsonFile("appsettings.json", optional = true, reloadOnChange = true) .SetBasePath(ctx.HostingEnvironment.ContentRootPath)
.AddJsonFile(sprintf "appsettings.%s.json" ctx.HostingEnvironment.EnvironmentName, optional = true) .AddJsonFile("appsettings.json", optional = true, reloadOnChange = true)
.AddEnvironmentVariables() .AddJsonFile($"appsettings.{ctx.HostingEnvironment.EnvironmentName}.json", optional = true)
|> ignore .AddEnvironmentVariables()
|> ignore
/// Configure Kestrel from appsettings.json open Microsoft.AspNetCore.Server.Kestrel.Core
let kestrel (ctx : WebHostBuilderContext) (opts : KestrelServerOptions) =
(ctx.Configuration.GetSection >> opts.Configure >> ignore) "Kestrel"
let services (svc : IServiceCollection) = /// Configure Kestrel from appsettings.json
svc.AddOptions() let kestrel (ctx: WebHostBuilderContext) (opts: KestrelServerOptions) =
.AddLocalization(fun options -> options.ResourcesPath <- "Resources") (ctx.Configuration.GetSection >> opts.Configure >> ignore) "Kestrel"
.Configure<RequestLocalizationOptions>(
fun (opts : RequestLocalizationOptions) ->
let supportedCultures =
[| CultureInfo "en-US"; CultureInfo "en-GB"; CultureInfo "en-AU"; CultureInfo "en"
CultureInfo "es-MX"; CultureInfo "es-ES"; CultureInfo "es"
|]
opts.DefaultRequestCulture <- RequestCulture ("en-US", "en-US")
opts.SupportedCultures <- supportedCultures
opts.SupportedUICultures <- supportedCultures)
.AddDistributedMemoryCache()
.AddSession()
.AddAntiforgery()
.AddSingleton<IClock>(SystemClock.Instance)
|> ignore
let config = svc.BuildServiceProvider().GetRequiredService<IConfiguration>()
let crypto = config.GetSection "CookieCrypto"
CookieCrypto (crypto.["Key"], crypto.["IV"]) |> setCrypto
svc.AddDbContext<AppDbContext>(
fun options ->
options.UseNpgsql (config.GetConnectionString "PrayerTracker") |> ignore)
|> ignore
/// Routes for PrayerTracker open System.Globalization
let webApp = open BitBadger.Documents.Sqlite
router Handlers.CommonFunctions.fourOhFour [ open Microsoft.AspNetCore.Authentication.Cookies
// Traditional web app routes open Microsoft.AspNetCore.Localization
subRoute"/web" [ open Microsoft.Extensions.DependencyInjection
GET [ open NeoSmart.Caching.Sqlite
subRoute "/church" [ open NodaTime
route "es" Handlers.Church.maintain open PrayerTracker.Data
routef "/%O/edit" Handlers.Church.edit
]
route "/class/logon" (redirectTo true "/web/small-group/log-on")
routef "/error/%s" Handlers.Home.error
routef "/language/%s" Handlers.Home.language
subRoute "/legal" [
route "/privacy-policy" Handlers.Home.privacyPolicy
route "/terms-of-service" Handlers.Home.tos
]
route "/log-off" Handlers.Home.logOff
subRoute "/prayer-request" [
route "s" (Handlers.PrayerRequest.maintain true)
routef "s/email/%s" Handlers.PrayerRequest.email
route "s/inactive" (Handlers.PrayerRequest.maintain false)
route "s/lists" Handlers.PrayerRequest.lists
routef "s/%O/list" Handlers.PrayerRequest.list
route "s/maintain" (redirectTo true "/web/prayer-requests")
routef "s/print/%s" Handlers.PrayerRequest.print
route "s/view" (Handlers.PrayerRequest.view None)
routef "s/view/%s" (Some >> Handlers.PrayerRequest.view)
routef "/%O/edit" Handlers.PrayerRequest.edit
routef "/%O/expire" Handlers.PrayerRequest.expire
routef "/%O/restore" Handlers.PrayerRequest.restore
]
subRoute "/small-group" [
route "" Handlers.SmallGroup.overview
route "s" Handlers.SmallGroup.maintain
route "/announcement" Handlers.SmallGroup.announcement
routef "/%O/edit" Handlers.SmallGroup.edit
route "/log-on" (Handlers.SmallGroup.logOn None)
routef "/log-on/%O" (Some >> Handlers.SmallGroup.logOn)
route "/logon" (redirectTo true "/web/small-group/log-on")
routef "/member/%O/edit" Handlers.SmallGroup.editMember
route "/members" Handlers.SmallGroup.members
route "/preferences" Handlers.SmallGroup.preferences
]
route "/unauthorized" Handlers.Home.unauthorized
subRoute "/user" [
route "s" Handlers.User.maintain
routef "/%O/edit" Handlers.User.edit
routef "/%O/small-groups" Handlers.User.smallGroups
route "/log-on" Handlers.User.logOn
route "/logon" (redirectTo true "/web/user/log-on")
route "/password" Handlers.User.password
]
route "/" Handlers.Home.homePage
]
POST [
subRoute "/church" [
routef "/%O/delete" Handlers.Church.delete
route "/save" Handlers.Church.save
]
subRoute "/prayer-request" [
routef "/%O/delete" Handlers.PrayerRequest.delete
route "/save" Handlers.PrayerRequest.save
]
subRoute "/small-group" [
route "/announcement/send" Handlers.SmallGroup.sendAnnouncement
routef "/%O/delete" Handlers.SmallGroup.delete
route "/log-on/submit" Handlers.SmallGroup.logOnSubmit
routef "/member/%O/delete" Handlers.SmallGroup.deleteMember
route "/member/save" Handlers.SmallGroup.saveMember
route "/preferences/save" Handlers.SmallGroup.savePreferences
route "/save" Handlers.SmallGroup.save
]
subRoute "/user" [
routef "/%O/delete" Handlers.User.delete
route "/edit/save" Handlers.User.save
route "/log-on" Handlers.User.doLogOn
route "/password/change" Handlers.User.changePassword
route "/small-groups/save" Handlers.User.saveGroups
]
]
]
// Temp redirect to new URLs
route "/" (redirectTo false "/web/")
]
let errorHandler (ex : exn) (logger : ILogger) =
logger.LogError(EventId(), ex, "An unhandled exception has occurred while executing the request.")
clearResponse >=> setStatusCode 500 >=> text ex.Message
/// Configure logging
let logging (log : ILoggingBuilder) =
let env = log.Services.BuildServiceProvider().GetService<IWebHostEnvironment> ()
match env.IsDevelopment () with
| true -> log
| false -> log.AddFilter (fun l -> l > LogLevel.Information)
|> function l -> l.AddConsole().AddDebug()
|> ignore
let app (app : IApplicationBuilder) =
let env = app.ApplicationServices.GetRequiredService<IWebHostEnvironment>()
(match env.IsDevelopment () with
| true ->
app.UseDeveloperExceptionPage ()
| false ->
try
use scope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope ()
scope.ServiceProvider.GetService<AppDbContext>().Database.Migrate ()
with _ -> () // om nom nom
app.UseGiraffeErrorHandler errorHandler)
.UseStatusCodePagesWithReExecute("/error/{0}")
.UseStaticFiles()
.UseSession()
.UseRequestLocalization(app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>().Value)
.UseGiraffe(webApp)
|> ignore
Views.I18N.setUpFactories <| app.ApplicationServices.GetRequiredService<IStringLocalizerFactory> ()
/// Configure ASP.NET Core's service collection (dependency injection container)
let services (svc: IServiceCollection) =
let _ = svc.AddOptions()
let _ = svc.AddLocalization(fun options -> options.ResourcesPath <- "Resources")
let _ =
svc.Configure<RequestLocalizationOptions>(fun (opts: RequestLocalizationOptions) ->
let supportedCultures =
[| CultureInfo "en-US"
CultureInfo "en-GB"
CultureInfo "en-AU"
CultureInfo "en"
CultureInfo "es-MX"
CultureInfo "es-ES"
CultureInfo "es" |]
opts.DefaultRequestCulture <- RequestCulture("en-US", "en-US")
opts.SupportedCultures <- supportedCultures
opts.SupportedUICultures <- supportedCultures)
let _ =
svc
.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(fun opts ->
opts.ExpireTimeSpan <- TimeSpan.FromMinutes 120.
opts.SlidingExpiration <- true
opts.AccessDeniedPath <- "/error/403")
let _ = svc.AddAuthorization()
let cfg = svc.BuildServiceProvider().GetService<IConfiguration>()
Configuration.useConnectionString (cfg.GetConnectionString "PrayerTracker")
Connection.setUp () |> Async.AwaitTask |> Async.RunSynchronously
let emailCfg = cfg.GetSection "Email"
if (emailCfg.GetChildren >> Seq.isEmpty >> not) () then
ConfigurationBinder.Bind(emailCfg, Email.smtpOptions)
let cachePath = defaultArg (Option.ofObj (cfg.GetConnectionString "SessionDB")) "./data/session.db"
let _ = svc.AddSqliteCache(fun o -> o.CachePath <- cachePath)
let _ = svc.AddSession()
let _ = svc.AddLogging()
let _ = svc.AddAntiforgery()
let _ = svc.AddRouting()
let _ = svc.AddSingleton<IClock> SystemClock.Instance
()
open Giraffe
/// <summary>Endpoint to redirect URLs starting with <c>/web</c> to their non-web equivalent</summary>
let noWeb: HttpHandler =
fun next ctx -> redirectTo true $"""/{string ctx.Request.RouteValues["path"]}""" next ctx
open Giraffe.EndpointRouting
/// Routes for PrayerTracker
let routes =
[ route "/web/{**path}" noWeb
GET_HEAD
[ subRoute "/church" [ route "es" Handlers.Church.maintain; routef "/%O/edit" Handlers.Church.edit ]
route "/class/logon" (redirectTo true "/small-group/log-on")
routef "/error/%s" Handlers.Home.error
subRoute
"/help"
[ route "" Handlers.Help.index
subRoute
"/requests"
[ route "/edit" Handlers.Help.Requests.edit
route "/maintain" Handlers.Help.Requests.maintain
route "/view" Handlers.Help.Requests.view ]
subRoute
"/small-group"
[ route "/announcement" Handlers.Help.SmallGroup.announcement
route "/members" Handlers.Help.SmallGroup.members
route "/preferences" Handlers.Help.SmallGroup.preferences ]
subRoute
"/user"
[ route "/log-on" Handlers.Help.User.logOn
route "/password" Handlers.Help.User.password ] ]
routef "/language/%s" Handlers.Home.language
subRoute
"/legal"
[ route "/privacy-policy" Handlers.Home.privacyPolicy
route "/terms-of-service" Handlers.Home.tos ]
route "/log-off" Handlers.Home.logOff
subRoute
"/prayer-request"
[ route "s" (Handlers.PrayerRequest.maintain true)
routef "s/email/%s" Handlers.PrayerRequest.email
route "s/inactive" (Handlers.PrayerRequest.maintain false)
route "s/lists" Handlers.PrayerRequest.lists
routef "s/%O/list" Handlers.PrayerRequest.list
route "s/maintain" (redirectTo true "/prayer-requests")
routef "s/print/%s" Handlers.PrayerRequest.print
route "s/view" (Handlers.PrayerRequest.view None)
routef "s/view/%s" (Some >> Handlers.PrayerRequest.view)
routef "/%O/edit" Handlers.PrayerRequest.edit
routef "/%O/expire" Handlers.PrayerRequest.expire
routef "/%O/restore" Handlers.PrayerRequest.restore ]
subRoute
"/small-group"
[ route "" Handlers.SmallGroup.overview
route "s" Handlers.SmallGroup.maintain
route "/announcement" Handlers.SmallGroup.announcement
routef "/%O/edit" Handlers.SmallGroup.edit
route "/log-on" (Handlers.SmallGroup.logOn None)
routef "/log-on/%O" (Some >> Handlers.SmallGroup.logOn)
route "/logon" (redirectTo true "/small-group/log-on")
routef "/member/%O/edit" Handlers.SmallGroup.editMember
route "/members" Handlers.SmallGroup.members
route "/preferences" Handlers.SmallGroup.preferences ]
route "/unauthorized" Handlers.Home.unauthorized
subRoute
"/user"
[ route "s" Handlers.User.maintain
routef "/%O/edit" Handlers.User.edit
routef "/%O/small-groups" Handlers.User.smallGroups
route "/log-on" Handlers.User.logOn
route "/logon" (redirectTo true "/user/log-on")
route "/password" Handlers.User.password ]
route "/" Handlers.Home.homePage ]
POST
[ subRoute
"/church"
[ routef "/%O/delete" Handlers.Church.delete
route "/save" Handlers.Church.save ]
subRoute
"/prayer-request"
[ routef "/%O/delete" Handlers.PrayerRequest.delete
route "/save" Handlers.PrayerRequest.save ]
subRoute
"/small-group"
[ route "/announcement/send" Handlers.SmallGroup.sendAnnouncement
routef "/%O/delete" Handlers.SmallGroup.delete
route "/log-on/submit" Handlers.SmallGroup.logOnSubmit
routef "/member/%O/delete" Handlers.SmallGroup.deleteMember
route "/member/save" Handlers.SmallGroup.saveMember
route "/preferences/save" Handlers.SmallGroup.savePreferences
route "/save" Handlers.SmallGroup.save ]
subRoute
"/user"
[ routef "/%O/delete" Handlers.User.delete
route "/edit/save" Handlers.User.save
route "/log-on" Handlers.User.doLogOn
route "/password/change" Handlers.User.changePassword
route "/small-groups/save" Handlers.User.saveGroups ] ] ]
open Microsoft.Extensions.Logging
/// Giraffe error handler
let errorHandler (ex: exn) (logger: ILogger) =
logger.LogError(EventId(), ex, "An unhandled exception has occurred while executing the request.")
clearResponse >=> setStatusCode 500 >=> text ex.Message
open Microsoft.Extensions.Hosting
/// Configure logging
let logging (log: ILoggingBuilder) =
let env = log.Services.BuildServiceProvider().GetService<IWebHostEnvironment>()
if env.IsDevelopment() then
log
else
log.AddFilter(fun l -> l > LogLevel.Information)
|> function
| l -> l.AddConsole().AddDebug()
|> ignore
open BitBadger.AspNetCore.CanonicalDomains
open Microsoft.Extensions.Localization
open Microsoft.Extensions.Options
/// Configure the application
let app (app: WebApplication) =
let env = app.Services.GetRequiredService<IWebHostEnvironment>()
if env.IsDevelopment() then
app.UseDeveloperExceptionPage()
else
app.UseGiraffeErrorHandler errorHandler
|> ignore
let _ = app.UseForwardedHeaders()
let _ = app.UseCanonicalDomains()
let _ = app.UseStatusCodePagesWithReExecute "/error/{0}"
let _ = app.UseStaticFiles()
let _ = app.UseCookiePolicy(CookiePolicyOptions(MinimumSameSitePolicy = SameSiteMode.Strict))
let _ = app.UseMiddleware<RequestStartMiddleware>()
let _ = app.UseRouting()
let _ = app.UseSession()
let _ = app.UseRequestLocalization(app.Services.GetService<IOptions<RequestLocalizationOptions>>().Value)
let _ = app.UseAuthentication()
let _ = app.UseAuthorization()
let _ = app.UseEndpoints(fun e -> e.MapGiraffeEndpoints routes)
app.Services.GetRequiredService<IStringLocalizerFactory>()
|> Views.I18N.setUpFactories
open Microsoft.Extensions.DependencyInjection
open Microsoft.Extensions.Logging
/// The web application /// The web application
module App = module App =
open System.IO
[<EntryPoint>] open System.IO
let main _ =
let contentRoot = Directory.GetCurrentDirectory () [<EntryPoint>]
WebHostBuilder() let main args =
.UseContentRoot(contentRoot)
.ConfigureAppConfiguration(Configure.configuration) let contentRoot = Directory.GetCurrentDirectory()
.UseKestrel(Configure.kestrel) let builder =
.UseWebRoot(Path.Combine (contentRoot, "wwwroot")) WebApplication.CreateBuilder(
.ConfigureServices(Configure.services) WebApplicationOptions(
.ConfigureLogging(Configure.logging) Args = args,
.Configure(System.Action<IApplicationBuilder> Configure.app) ApplicationName = "PrayerTracker",
.Build() ContentRootPath = contentRoot,
.Run () WebRootPath = Path.Combine(contentRoot, "wwwroot")))
0 let _ =
builder.WebHost
.ConfigureAppConfiguration(Configure.configuration)
.ConfigureKestrel(Configure.kestrel)
.ConfigureServices(Configure.services)
.ConfigureLogging(Configure.logging)
use app = builder.Build()
Configure.app app
let fac = app.Services.GetRequiredService<ILoggerFactory>()
let log = fac.CreateLogger "PrayerTracker"
log.LogInformation "Application Started"
app.Run()
log.LogInformation "Application Shutting Down"
0

View File

@@ -1,111 +1,76 @@
module PrayerTracker.Handlers.Church module PrayerTracker.Handlers.Church
open FSharp.Control.Tasks.V2.ContextInsensitive open System.Threading.Tasks
open Giraffe open Giraffe
open PrayerTracker open PrayerTracker
open PrayerTracker.Data
open PrayerTracker.Entities open PrayerTracker.Entities
open PrayerTracker.ViewModels open PrayerTracker.ViewModels
open PrayerTracker.Views.CommonFunctions
open System
open System.Threading.Tasks
/// Find statistics for the given church /// Find statistics for the given church
let private findStats (db : AppDbContext) churchId = let private findStats churchId = task {
task { let! groups = SmallGroups.countByChurch churchId
let! grps = db.CountGroupsByChurch churchId let! requests = PrayerRequests.countByChurch churchId
let! reqs = db.CountRequestsByChurch churchId let! users = Users.countByChurch churchId
let! usrs = db.CountUsersByChurch churchId return shortGuid churchId.Value, { SmallGroups = int groups; PrayerRequests = int requests; Users = int users }
return flatGuid churchId, { smallGroups = grps; prayerRequests = reqs; users = usrs } }
}
// POST /church/[church-id]/delete
let delete chId : HttpHandler = requireAccess [ Admin ] >=> validateCsrf >=> fun next ctx -> task {
let churchId = ChurchId chId
match! Churches.tryById churchId with
| Some church ->
let! _, stats = findStats churchId
do! Churches.deleteById churchId
addInfo ctx
ctx.Strings["The church “{0}” and its {1} small group(s) (with {2} prayer request(s)) were deleted successfully; revoked access from {3} user(s)",
church.Name, stats.SmallGroups, stats.PrayerRequests, stats.Users]
return! redirectTo false "/churches" next ctx
| None -> return! fourOhFour ctx
}
/// POST /church/[church-id]/delete open System
let delete churchId : HttpHandler =
requireAccess [ Admin ]
>=> validateCSRF
>=> fun next ctx ->
let db = ctx.dbContext ()
task {
let! church = db.TryChurchById churchId
match church with
| Some ch ->
let! _, stats = findStats db churchId
db.RemoveEntry ch
let! _ = db.SaveChangesAsync ()
let s = Views.I18N.localizer.Force ()
addInfo ctx
s.["The church {0} and its {1} small groups (with {2} prayer request(s)) were deleted successfully; revoked access from {3} user(s)",
ch.name, stats.smallGroups, stats.prayerRequests, stats.users]
return! redirectTo false "/web/churches" next ctx
| None -> return! fourOhFour next ctx
}
// GET /church/[church-id]/edit
/// GET /church/[church-id]/edit let edit churchId : HttpHandler = requireAccess [ Admin ] >=> fun next ctx -> task {
let edit churchId : HttpHandler = if churchId = Guid.Empty then
requireAccess [ Admin ] return!
>=> fun next ctx -> viewInfo ctx
let startTicks = DateTime.Now.Ticks
task {
match churchId with
| x when x = Guid.Empty ->
return!
viewInfo ctx startTicks
|> Views.Church.edit EditChurch.empty ctx |> Views.Church.edit EditChurch.empty ctx
|> renderHtml next ctx |> renderHtml next ctx
| _ -> else
let db = ctx.dbContext () match! Churches.tryById (ChurchId churchId) with
let! church = db.TryChurchById churchId | Some church ->
match church with return!
| Some ch -> viewInfo ctx
return! |> Views.Church.edit (EditChurch.fromChurch church) ctx
viewInfo ctx startTicks
|> Views.Church.edit (EditChurch.fromChurch ch) ctx
|> renderHtml next ctx |> renderHtml next ctx
| None -> return! fourOhFour next ctx | None -> return! fourOhFour ctx
} }
// GET /churches
/// GET /churches let maintain : HttpHandler = requireAccess [ Admin ] >=> fun next ctx -> task {
let maintain : HttpHandler = let! churches = Churches.all ()
requireAccess [ Admin ] let stats = churches |> List.map (fun c -> findStats c.Id |> Async.AwaitTask |> Async.RunSynchronously)
>=> fun next ctx -> return!
let startTicks = DateTime.Now.Ticks viewInfo ctx
let await = Async.AwaitTask >> Async.RunSynchronously
let db = ctx.dbContext ()
task {
let! churches = db.AllChurches ()
let stats = churches |> List.map (fun c -> await (findStats db c.churchId))
return!
viewInfo ctx startTicks
|> Views.Church.maintain churches (stats |> Map.ofList) ctx |> Views.Church.maintain churches (stats |> Map.ofList) ctx
|> renderHtml next ctx |> renderHtml next ctx
} }
// POST /church/save
/// POST /church/save let save : HttpHandler = requireAccess [ Admin ] >=> validateCsrf >=> fun next ctx -> task {
let save : HttpHandler = match! ctx.TryBindFormAsync<EditChurch> () with
requireAccess [ Admin ] | Ok model ->
>=> validateCSRF let! church =
>=> fun next ctx -> if model.IsNew then Task.FromResult(Some { Church.Empty with Id = (Guid.NewGuid >> ChurchId) () })
task { else Churches.tryById (idFromShort ChurchId model.ChurchId)
let! result = ctx.TryBindFormAsync<EditChurch> () match church with
match result with | Some ch ->
| Ok m -> do! Churches.save (model.PopulateChurch ch)
let db = ctx.dbContext () let act = ctx.Strings[if model.IsNew then "Added" else "Updated"].Value.ToLower()
let! church = addInfo ctx ctx.Strings["Successfully {0} church “{1}”", act, model.Name]
match m.isNew () with return! redirectTo false "/churches" next ctx
| true -> Task.FromResult<Church option>(Some { Church.empty with churchId = Guid.NewGuid () }) | None -> return! fourOhFour ctx
| false -> db.TryChurchById m.churchId | Result.Error e -> return! bindError e next ctx
match church with }
| Some ch ->
m.populateChurch ch
|> (match m.isNew () with true -> db.AddEntry | false -> db.UpdateEntry)
let! _ = db.SaveChangesAsync ()
let s = Views.I18N.localizer.Force ()
let act = s.[match m.isNew () with true -> "Added" | _ -> "Updated"].Value.ToLower ()
addInfo ctx s.["Successfully {0} church “{1}”", act, m.name]
return! redirectTo false "/web/churches" next ctx
| None -> return! fourOhFour next ctx
| Error e -> return! bindError e next ctx
}

View File

@@ -2,271 +2,163 @@
[<AutoOpen>] [<AutoOpen>]
module PrayerTracker.Handlers.CommonFunctions module PrayerTracker.Handlers.CommonFunctions
open FSharp.Control.Tasks.V2.ContextInsensitive
open Giraffe
open Microsoft.AspNetCore.Antiforgery
open Microsoft.AspNetCore.Html
open Microsoft.AspNetCore.Http
open Microsoft.AspNetCore.Http.Extensions
open Microsoft.AspNetCore.Mvc.Rendering open Microsoft.AspNetCore.Mvc.Rendering
open Microsoft.Extensions.Localization
open PrayerTracker
open PrayerTracker.Cookies
open PrayerTracker.ViewModels
open System
open System.Net
open System.Reflection
open System.Threading.Tasks
/// Create a select list from an enumeration /// Create a select list from an enumeration
let toSelectList<'T> valFunc textFunc withDefault emptyText (items : 'T seq) = let toSelectList<'T> valFunc textFunc withDefault emptyText (items: 'T seq) =
match items with null -> nullArg "items" | _ -> () if isNull items then nullArg (nameof items)
[ match withDefault with [ match withDefault with
| true -> | true ->
let s = PrayerTracker.Views.I18N.localizer.Force () let s = PrayerTracker.Views.I18N.localizer.Force()
yield SelectListItem (sprintf "&mdash; %A &mdash;" s.[emptyText], "") SelectListItem($"""&mdash; %A{s[emptyText]} &mdash;""", "")
| _ -> () | _ -> ()
yield! items |> Seq.map (fun x -> SelectListItem (textFunc x, valFunc x)) yield! items |> Seq.map (fun x -> SelectListItem(textFunc x, valFunc x)) ]
]
/// Create a select list from an enumeration /// Create a select list from an enumeration
let toSelectListWithEmpty<'T> valFunc textFunc emptyText (items : 'T seq) = let toSelectListWithEmpty<'T> valFunc textFunc emptyText (items: 'T seq) =
toSelectList valFunc textFunc true emptyText items toSelectList valFunc textFunc true emptyText items
/// Create a select list from an enumeration /// Create a select list from an enumeration
let toSelectListWithDefault<'T> valFunc textFunc (items : 'T seq) = let toSelectListWithDefault<'T> valFunc textFunc (items: 'T seq) =
toSelectList valFunc textFunc true "Select" items toSelectList valFunc textFunc true "Select" items
/// The version of PrayerTracker /// The version of PrayerTracker
let appVersion = let appVersion =
let v = Assembly.GetExecutingAssembly().GetName().Version let v = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version
#if (DEBUG) #if (DEBUG)
sprintf "v%A" v $"v{v}"
#else #else
seq { seq {
sprintf "v%d" v.Major $"v%d{v.Major}"
match v.Minor with match v.Minor with
| 0 -> match v.Build with 0 -> () | _ -> sprintf ".0.%d" v.Build | 0 -> match v.Build with 0 -> () | _ -> $".0.%d{v.Build}"
| _ -> | _ ->
sprintf ".%d" v.Minor $".%d{v.Minor}"
match v.Build with 0 -> () | _ -> sprintf ".%d" v.Build match v.Build with 0 -> () | _ -> $".%d{v.Build}"
} }
|> String.concat "" |> String.concat ""
#endif #endif
/// An option of the currently signed-in user
let tryCurrentUser (ctx : HttpContext) =
ctx.Session.GetUser ()
/// The currently signed-in user (will raise if none exists) open Giraffe
let currentUser ctx = open Giraffe.Htmx
match tryCurrentUser ctx with Some u -> u | None -> nullArg "User" open Microsoft.AspNetCore.Http
open NodaTime
/// An option of the currently signed-in small group open PrayerTracker
let tryCurrentGroup (ctx : HttpContext) = open PrayerTracker.ViewModels
ctx.Session.GetSmallGroup ()
/// The currently signed-in small group (will raise if none exists)
let currentGroup ctx =
match tryCurrentGroup ctx with Some g -> g | None -> nullArg "SmallGroup"
/// Create the common view information heading /// Create the common view information heading
let viewInfo (ctx : HttpContext) startTicks = let viewInfo (ctx: HttpContext) =
let msg = let msg =
match ctx.Session.GetMessages () with match ctx.Session.Messages with
| [] -> [] | [] -> []
| x -> | x ->
ctx.Session.SetMessages [] ctx.Session.Messages <- []
x x
match tryCurrentUser ctx with let layout =
| Some u -> match ctx.Request.Headers.HxTarget with
// The idle timeout is 2 hours; if the app pool is recycled or the actual session goes away, we will log the | Some hdr when hdr = "pt-body" -> ContentOnly
// user back in transparently using this cookie. Every request resets the timer. | Some _ -> PartialPage
let timeout = | None -> FullPage
{ Id = u.userId { AppViewInfo.fresh with
GroupId = (currentGroup ctx).smallGroupId Version = appVersion
Until = DateTime.UtcNow.AddHours(2.).Ticks Messages = msg
Password = "" RequestStart = ctx.Items[Key.startTime] :?> Instant
} User = ctx.Session.CurrentUser
ctx.Response.Cookies.Append Group = ctx.Session.CurrentGroup
(Key.Cookie.timeout, { timeout with Password = saltedTimeoutHash timeout }.toPayload (), Layout = layout }
CookieOptions (Expires = Nullable<DateTimeOffset> (DateTimeOffset (DateTime timeout.Until)), HttpOnly = true))
| None -> ()
{ AppViewInfo.fresh with
version = appVersion
messages = msg
requestStart = startTicks
user = ctx.Session.GetUser ()
group = ctx.Session.GetSmallGroup ()
}
/// The view is the last parameter, so it can be composed /// The view is the last parameter, so it can be composed
let renderHtml next ctx view = let renderHtml next ctx view =
htmlView view next ctx htmlView view next ctx
open Microsoft.Extensions.Logging
/// Display an error regarding form submission /// Display an error regarding form submission
let bindError (msg : string) next (ctx : HttpContext) = let bindError (msg: string) =
System.Console.WriteLine msg handleContext (fun ctx ->
ctx.SetStatusCode 400 ctx.GetService<ILoggerFactory>().CreateLogger("PrayerTracker.Handlers").LogError msg
text msg next ctx (setStatusCode 400 >=> text msg) earlyReturn ctx)
/// Handler that will return a status code 404 and the text "Not Found" /// Handler that will return a status code 404 and the text "Not Found"
let fourOhFour next (ctx : HttpContext) = let fourOhFour (ctx: HttpContext) =
ctx.SetStatusCode 404 (setStatusCode 404 >=> text "Not Found") earlyReturn ctx
text "Not Found" next ctx
/// Handler to validate CSRF prevention token /// Handler to validate CSRF prevention token
let validateCSRF : HttpHandler = let validateCsrf : HttpHandler = fun next ctx -> task {
fun next ctx -> match! ctx.GetService<Microsoft.AspNetCore.Antiforgery.IAntiforgery>().IsRequestValidAsync ctx with
let antiForgery = ctx.GetService<IAntiforgery> () | true -> return! next ctx
task { | false -> return! (clearResponse >=> setStatusCode 400 >=> text "Quit hacking...") earlyReturn ctx
let! isValid = antiForgery.IsRequestValidAsync ctx }
match isValid with
| true -> return! next ctx
| false ->
return! (clearResponse >=> setStatusCode 400 >=> text "Quit hacking...") (fun _ -> Task.FromResult None) ctx
}
/// Add a message to the session /// Add a message to the session
let addUserMessage (ctx : HttpContext) msg = let addUserMessage (ctx: HttpContext) msg =
msg :: ctx.Session.GetMessages () |> ctx.Session.SetMessages ctx.Session.Messages <- msg :: ctx.Session.Messages
open Microsoft.AspNetCore.Html
open Microsoft.Extensions.Localization
/// Convert a localized string to an HTML string /// Convert a localized string to an HTML string
let htmlLocString (x : LocalizedString) = let htmlLocString (x: LocalizedString) =
(WebUtility.HtmlEncode >> HtmlString) x.Value (System.Net.WebUtility.HtmlEncode >> HtmlString) x.Value
let htmlString (x : LocalizedString) = let htmlString (x: LocalizedString) =
HtmlString x.Value HtmlString x.Value
/// Add an error message to the session /// Add an error message to the session
let addError ctx msg = let addError ctx msg =
addUserMessage ctx { UserMessage.Error with text = htmlLocString msg } addUserMessage ctx { UserMessage.error with Text = htmlLocString msg }
/// Add an informational message to the session /// Add an informational message to the session
let addInfo ctx msg = let addInfo ctx msg =
addUserMessage ctx { UserMessage.Info with text = htmlLocString msg } addUserMessage ctx { UserMessage.info with Text = htmlLocString msg }
/// Add an informational HTML message to the session /// Add an informational HTML message to the session
let addHtmlInfo ctx msg = let addHtmlInfo ctx msg =
addUserMessage ctx { UserMessage.Info with text = htmlString msg } addUserMessage ctx { UserMessage.info with Text = htmlString msg }
/// Add a warning message to the session /// Add a warning message to the session
let addWarning ctx msg = let addWarning ctx msg =
addUserMessage ctx { UserMessage.Warning with text = htmlLocString msg } addUserMessage ctx { UserMessage.warning with Text = htmlLocString msg }
/// A level of required access /// A level of required access
type AccessLevel = type AccessLevel =
/// Administrative access /// Administrative access
| Admin | Admin
/// Small group administrative access /// Small group administrative access
| User | User
/// Small group member access /// Small group member access
| Group | Group
/// Errbody /// Errbody
| Public | Public
/// Require the given access role (also refreshes "Remember Me" user and group logons) open Microsoft.AspNetCore.Http.Extensions
let requireAccess level : HttpHandler = open PrayerTracker.Entities
/// Is there currently a user logged on?
let isUserLoggedOn (ctx : HttpContext) =
ctx.Session.GetUser () |> Option.isSome
/// Log a user on from the timeout cookie /// Require one of the given access roles
let logOnUserFromTimeoutCookie (ctx : HttpContext) = let requireAccess levels : HttpHandler = fun next ctx -> task {
task { // These calls fill the user and group in the session, making .Value safe to use for the rest of the request
// Make sure the cookie hasn't been tampered with let! user = ctx.CurrentUser()
try let! group = ctx.CurrentGroup()
match TimeoutCookie.fromPayload ctx.Request.Cookies.[Key.Cookie.timeout] with match user, group with
| Some c when c.Password = saltedTimeoutHash c -> | _, _ when List.contains Public levels -> return! next ctx
let db = ctx.dbContext () | Some _, _ when List.contains User levels -> return! next ctx
let! user = db.TryUserById c.Id | _, Some _ when List.contains Group levels -> return! next ctx
match user with | Some u, _ when List.contains Admin levels && u.IsAdmin -> return! next ctx
| Some _ -> | _, _ when List.contains Admin levels ->
ctx.Session.SetUser user addError ctx ctx.Strings["You are not authorized to view the requested page."]
let! grp = db.TryGroupById c.GroupId return! redirectTo false "/unauthorized" next ctx
ctx.Session.SetSmallGroup grp | _, _ when List.contains User levels ->
| _ -> () // Redirect to the user log on page
| _ -> () ctx.Session.SetString(Key.Session.redirectUrl, ctx.Request.GetEncodedPathAndQuery())
// If something above doesn't work, the user doesn't get logged in return! redirectTo false "/user/log-on" next ctx
with _ -> () | _, _ when List.contains Group levels ->
} // Redirect to the small group log on page
return! redirectTo false "/small-group/log-on" next ctx
/// Attempt to log the user on from their stored cookie | _, _ ->
let logOnUserFromCookie (ctx : HttpContext) = addError ctx ctx.Strings["You are not authorized to view the requested page."]
task { return! redirectTo false "/unauthorized" next ctx
match UserCookie.fromPayload ctx.Request.Cookies.[Key.Cookie.user] with }
| Some c ->
let db = ctx.dbContext ()
let! user = db.TryUserLogOnByCookie c.Id c.GroupId c.PasswordHash
match user with
| Some _ ->
ctx.Session.SetUser user
let! grp = db.TryGroupById c.GroupId
ctx.Session.SetSmallGroup grp
// Rewrite the cookie to extend the expiration
ctx.Response.Cookies.Append (Key.Cookie.user, c.toPayload (), autoRefresh)
| _ -> ()
| _ -> ()
}
/// Is there currently a small group (or member thereof) logged on?
let isGroupLoggedOn (ctx : HttpContext) =
ctx.Session.GetSmallGroup () |> Option.isSome
/// Attempt to log the small group on from their stored cookie
let logOnGroupFromCookie (ctx : HttpContext) =
task {
match GroupCookie.fromPayload ctx.Request.Cookies.[Key.Cookie.group] with
| Some c ->
let! grp = (ctx.dbContext ()).TryGroupLogOnByCookie c.GroupId c.PasswordHash sha1Hash
match grp with
| Some _ ->
ctx.Session.SetSmallGroup grp
// Rewrite the cookie to extend the expiration
ctx.Response.Cookies.Append (Key.Cookie.group, c.toPayload (), autoRefresh)
| None -> ()
| None -> ()
}
fun next ctx ->
task {
// Auto-logon user or class, if required
match isUserLoggedOn ctx with
| true -> ()
| false ->
do! logOnUserFromTimeoutCookie ctx
match isUserLoggedOn ctx with
| true -> ()
| false ->
do! logOnUserFromCookie ctx
match isGroupLoggedOn ctx with true -> () | false -> do! logOnGroupFromCookie ctx
match true with
| _ when level |> List.contains Public -> return! next ctx
| _ when level |> List.contains User && isUserLoggedOn ctx -> return! next ctx
| _ when level |> List.contains Group && isGroupLoggedOn ctx -> return! next ctx
| _ when level |> List.contains Admin && isUserLoggedOn ctx ->
match (currentUser ctx).isAdmin with
| true -> return! next ctx
| false ->
let s = Views.I18N.localizer.Force ()
addError ctx s.["You are not authorized to view the requested page."]
return! redirectTo false "/web/unauthorized" next ctx
| _ when level |> List.contains User ->
// Redirect to the user log on page
ctx.Session.SetString (Key.Session.redirectUrl, ctx.Request.GetEncodedUrl ())
return! redirectTo false "/web/user/log-on" next ctx
| _ when level |> List.contains Group ->
// Redirect to the small group log on page
ctx.Session.SetString (Key.Session.redirectUrl, ctx.Request.GetEncodedUrl ())
return! redirectTo false "/web/small-group/log-on" next ctx
| _ ->
let s = Views.I18N.localizer.Force ()
addError ctx s.["You are not authorized to view the requested page."]
return! redirectTo false "/web/unauthorized" next ctx
}

View File

@@ -1,128 +0,0 @@
module PrayerTracker.Cookies
open Microsoft.AspNetCore.Http
open Newtonsoft.Json
open System
open System.Security.Cryptography
open System.IO
/// Cryptography settings to use for encrypting cookies
type CookieCrypto (key : string, iv : string) =
/// The key for the AES encryptor/decryptor
member __.Key = Convert.FromBase64String key
/// The initialization vector for the AES encryptor/decryptor
member __.IV = Convert.FromBase64String iv
/// Helpers for encrypting/decrypting cookies
[<AutoOpen>]
module private Crypto =
/// An instance of the cookie cryptography settings
let mutable crypto = CookieCrypto ("", "")
/// Encrypt a cookie payload
let encrypt (payload : string) =
use aes = new AesManaged ()
use enc = aes.CreateEncryptor (crypto.Key, crypto.IV)
use ms = new MemoryStream ()
use cs = new CryptoStream (ms, enc, CryptoStreamMode.Write)
use sw = new StreamWriter (cs)
sw.Write payload
sw.Close ()
(ms.ToArray >> Convert.ToBase64String) ()
/// Decrypt a cookie payload
let decrypt payload =
use aes = new AesManaged ()
use dec = aes.CreateDecryptor (crypto.Key, crypto.IV)
use ms = new MemoryStream (Convert.FromBase64String payload)
use cs = new CryptoStream (ms, dec, CryptoStreamMode.Read)
use sr = new StreamReader (cs)
sr.ReadToEnd ()
/// Encrypt a cookie
let encryptCookie cookie =
(JsonConvert.SerializeObject >> encrypt) cookie
/// Decrypt a cookie
let decryptCookie<'T> payload =
(decrypt >> JsonConvert.DeserializeObject<'T> >> box) payload
|> function null -> None | x -> Some (unbox<'T> x)
/// Accessor so that the crypto settings instance can be set during startup
let setCrypto c = Crypto.crypto <- c
/// Properties stored in the Small Group cookie
type GroupCookie =
{ /// The Id of the small group
[<JsonProperty "g">]
GroupId : Guid
/// The password hash of the small group
[<JsonProperty "p">]
PasswordHash : string
}
with
/// Convert these properties to a cookie payload
member this.toPayload () =
encryptCookie this
/// Create a set of strongly-typed properties from the cookie payload
static member fromPayload x =
try decryptCookie<GroupCookie> x with _ -> None
/// The payload for the timeout cookie
type TimeoutCookie =
{ /// The Id of the small group to which the user is currently logged in
[<JsonProperty "g">]
GroupId : Guid
/// The Id of the user who is currently logged in
[<JsonProperty "i">]
Id : Guid
/// The salted timeout hash to ensure that there has been no tampering with the cookie
[<JsonProperty "p">]
Password : string
/// How long this cookie is valid
[<JsonProperty "u">]
Until : int64
}
with
/// Convert this set of properties to the cookie payload
member this.toPayload () =
encryptCookie this
/// Create a strongly-typed timeout cookie from the cookie payload
static member fromPayload x =
try decryptCookie<TimeoutCookie> x with _ -> None
/// The payload for the user's "Remember Me" cookie
type UserCookie =
{ /// The Id of the group into to which the user is logged
[< JsonProperty "g">]
GroupId : Guid
/// The Id of the user
[<JsonProperty "i">]
Id : Guid
/// The user's password hash
[<JsonProperty "p">]
PasswordHash : string
}
with
/// Convert this set of properties to a cookie payload
member this.toPayload () =
encryptCookie this
/// Create the strongly-typed cookie properties from a cookie payload
static member fromPayload x =
try decryptCookie<UserCookie> x with _ -> None
/// Create a salted hash to use to validate the idle timeout key
let saltedTimeoutHash (c : TimeoutCookie) =
sha1Hash (sprintf "Prayer%ATracker%AIdle%dTimeout" c.Id c.GroupId c.Until)
/// Cookie options to push an expiration out by 100 days
let autoRefresh =
CookieOptions (Expires = Nullable<DateTimeOffset> (DateTimeOffset (DateTime.UtcNow.AddDays 100.)), HttpOnly = true)

View File

@@ -1,81 +1,115 @@
/// Methods for sending e-mails /// Methods for sending e-mails
module PrayerTracker.Email module PrayerTracker.Email
open FSharp.Control.Tasks.ContextInsensitive
open MailKit.Net.Smtp open MailKit.Net.Smtp
open MailKit.Security
open Microsoft.Extensions.Localization open Microsoft.Extensions.Localization
open MimeKit open MimeKit
open MimeKit.Text
open PrayerTracker.Entities open PrayerTracker.Entities
open System
/// The e-mail address from which e-mail is sent (must match Google account) /// Parameters required to send an e-mail
let private fromAddress = "prayer@djs-consulting.com" type EmailOptions =
{ /// The SMTP client
Client: SmtpClient
/// The people who should receive the e-mail
Recipients: Member list
/// The small group for which this e-mail is being sent
Group: SmallGroup
/// The subject of the e-mail
Subject: string
/// The body of the e-mail in HTML
HtmlBody: string
/// The body of the e-mail in plain text
PlainTextBody: string
/// Use the current user's preferred language
Strings: IStringLocalizer }
/// Options to use when sending e-mail
type SmtpServerOptions() =
/// The hostname of the SMTP server
member val SmtpHost: string = "localhost" with get, set
/// The port over which SMTP communication should occur
member val Port: int = 25 with get, set
/// Whether to use SSL when communicating with the SMTP server
member val UseSsl: bool = false with get, set
/// The authentication to use with the SMTP server
member val Authentication: string = "" with get, set
/// The e-mail address from which messages should be sent
member val FromAddress: string = "prayer@bitbadger.solutions" with get, set
/// The options for the SMTP server
let smtpOptions = SmtpServerOptions()
/// Get an SMTP client connection /// Get an SMTP client connection
// FIXME: make host configurable let getConnection () = task {
let getConnection () = let client = new SmtpClient()
task { do! client.ConnectAsync(smtpOptions.SmtpHost, smtpOptions.Port, smtpOptions.UseSsl)
let client = new SmtpClient () do! client.AuthenticateAsync(smtpOptions.FromAddress, smtpOptions.Authentication)
do! client.ConnectAsync ("127.0.0.1", 25, SecureSocketOptions.None)
return client return client
} }
/// Create a mail message object, filled with everything but the body content /// Create a mail message object, filled with everything but the body content
let createMessage (grp : SmallGroup) subj = let createMessage opts =
let msg = MimeMessage () let msg = new MimeMessage()
msg.From.Add (MailboxAddress (grp.preferences.emailFromName, fromAddress)) msg.From.Add(MailboxAddress(opts.Group.Preferences.EmailFromName, smtpOptions.FromAddress))
msg.Subject <- subj msg.Subject <- opts.Subject
msg.ReplyTo.Add (MailboxAddress (grp.preferences.emailFromName, grp.preferences.emailFromAddress)) msg.ReplyTo.Add(MailboxAddress(opts.Group.Preferences.EmailFromName, opts.Group.Preferences.EmailFromAddress))
msg msg
open MimeKit.Text
/// Create an HTML-format e-mail message /// Create an HTML-format e-mail message
let createHtmlMessage grp subj body (s : IStringLocalizer) = let createHtmlMessage opts =
let bodyText = let bodyText =
[ @"<!DOCTYPE html><html xmlns=""http://www.w3.org/1999/xhtml""><head><title></title></head><body>" [ """<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head><title></title></head><body>"""
body opts.HtmlBody
@"<hr><div style=""text-align:right;font-family:Arial,Helvetica,sans-serif;font-size:8pt;padding-right:10px;"">" """<hr><div style="text-align:right;font-family:Arial,Helvetica,sans-serif;font-size:8pt;padding-right:10px;">"""
s.["Generated by P R A Y E R T R A C K E R"].Value opts.Strings["Generated by P R A Y E R T R A C K E R"].Value
"<br><small>" "<br><small>"
s.["from Bit Badger Solutions"].Value opts.Strings["from Bit Badger Solutions"].Value
"</small></div></body></html>" "</small></div></body></html>" ]
] |> String.concat ""
|> String.concat "" let msg = createMessage opts
let msg = createMessage grp subj msg.Body <- new TextPart(TextFormat.Html, Text = bodyText)
msg.Body <- TextPart (TextFormat.Html, Text = bodyText) msg
msg
/// Create a plain-text-format e-mail message /// Create a plain-text-format e-mail message
let createTextMessage grp subj body (s : IStringLocalizer) = let createTextMessage opts =
let bodyText = let bodyText =
[ body [ opts.PlainTextBody
"\n\n--\n" "\n\n--\n"
s.["Generated by P R A Y E R T R A C K E R"].Value opts.Strings["Generated by P R A Y E R T R A C K E R"].Value
"\n" "\n"
s.["from Bit Badger Solutions"].Value opts.Strings["from Bit Badger Solutions"].Value ]
] |> String.concat ""
|> String.concat "" let msg = createMessage opts
let msg = createMessage grp subj msg.Body <- new TextPart(TextFormat.Plain, Text = bodyText)
msg.Body <- TextPart (TextFormat.Plain, Text = bodyText) msg
msg
/// Send e-mails to a class /// Send e-mails to a class
let sendEmails (client : SmtpClient) (recipients : Member list) grp subj html text s = let sendEmails opts = task {
task { use htmlMsg = createHtmlMessage opts
let htmlMsg = createHtmlMessage grp subj html s use plainTextMsg = createTextMessage opts
let plainTextMsg = createTextMessage grp subj text s
for mbr in recipients do for mbr in opts.Recipients do
let emailType = match mbr.format with Some f -> EmailFormat.fromCode f | None -> grp.preferences.defaultEmailType let emailTo = MailboxAddress(mbr.Name, mbr.Email)
let emailTo = MailboxAddress (mbr.memberName, mbr.email) match defaultArg mbr.Format opts.Group.Preferences.DefaultEmailType with
match emailType with | HtmlFormat ->
| HtmlFormat -> htmlMsg.To.Add emailTo
htmlMsg.To.Add emailTo let! _ = opts.Client.SendAsync htmlMsg
do! client.SendAsync htmlMsg htmlMsg.To.Clear()
htmlMsg.To.Clear () | PlainTextFormat ->
| PlainTextFormat -> plainTextMsg.To.Add emailTo
plainTextMsg.To.Add emailTo let! _ = opts.Client.SendAsync plainTextMsg
do! client.SendAsync plainTextMsg plainTextMsg.To.Clear()
plainTextMsg.To.Clear () }
}

View File

@@ -1,46 +1,110 @@
[<AutoOpen>] [<AutoOpen>]
module PrayerTracker.Extensions module PrayerTracker.Extensions
open BitBadger.Documents
open Microsoft.AspNetCore.Http open Microsoft.AspNetCore.Http
open Microsoft.FSharpLu open NodaTime
open Newtonsoft.Json open PrayerTracker.Data
open PrayerTracker.Entities open PrayerTracker.Entities
open PrayerTracker.ViewModels open PrayerTracker.ViewModels
/// Extensions on the .NET session object
type ISession with type ISession with
/// Set an object in the session
member this.SetObject key value =
this.SetString (key, JsonConvert.SerializeObject value)
/// Get an object from the session
member this.GetObject<'T> key =
match this.GetString key with
| null -> Unchecked.defaultof<'T>
| v -> JsonConvert.DeserializeObject<'T> v
member this.GetSmallGroup () = /// Set an object in the session
this.GetObject<SmallGroup> Key.Session.currentGroup |> Option.fromObject member this.SetObject<'T> key (value: 'T) =
member this.SetSmallGroup (group : SmallGroup option) = this.SetString(key, (Configuration.serializer ()).Serialize value)
match group with
| Some g -> this.SetObject Key.Session.currentGroup g
| None -> this.Remove Key.Session.currentGroup
member this.GetUser () = /// Get an object from the session
this.GetObject<User> Key.Session.currentUser |> Option.fromObject member this.TryGetObject<'T> key =
member this.SetUser (user: User option) = match this.GetString key with
match user with | null -> None
| Some u -> this.SetObject Key.Session.currentUser u | v -> Some ((Configuration.serializer ()).Deserialize<'T> v)
| None -> this.Remove Key.Session.currentUser
member this.GetMessages () = /// The currently logged on small group
match box (this.GetObject<UserMessage list> Key.Session.userMessages) with member this.CurrentGroup
| null -> List.empty<UserMessage> with get () = this.TryGetObject<SmallGroup> Key.Session.currentGroup
| msgs -> unbox msgs and set (v: SmallGroup option) =
member this.SetMessages (messages : UserMessage list) = match v with
this.SetObject Key.Session.userMessages messages | Some group -> this.SetObject Key.Session.currentGroup group
| None -> this.Remove Key.Session.currentGroup
/// The currently logged on user
member this.CurrentUser
with get () = this.TryGetObject<User> Key.Session.currentUser
and set (v: User option) =
match v with
| Some user -> this.SetObject Key.Session.currentUser { user with PasswordHash = "" }
| None -> this.Remove Key.Session.currentUser
/// Current messages for the session
member this.Messages
with get () =
this.TryGetObject<UserMessage list> Key.Session.userMessages
|> Option.defaultValue List.empty<UserMessage>
and set (v: UserMessage list) = this.SetObject Key.Session.userMessages v
open System.Security.Claims
/// Extensions on the claims principal
type ClaimsPrincipal with
/// The ID of the currently logged on small group
member this.SmallGroupId =
this.FindFirstValue ClaimTypes.GroupSid
|> Option.ofObj
|> Option.map (idFromShort SmallGroupId)
/// The ID of the currently signed-in user
member this.UserId =
this.FindFirstValue ClaimTypes.NameIdentifier
|> Option.ofObj
|> Option.map (idFromShort UserId)
open Giraffe
/// Extensions on the ASP.NET Core HTTP context
type HttpContext with type HttpContext with
/// Get the EF database context from DI
member this.dbContext () : AppDbContext = downcast this.RequestServices.GetService typeof<AppDbContext> /// The system clock (via DI)
member this.Clock = this.GetService<IClock>()
/// The current instant
member this.Now = this.Clock.GetCurrentInstant()
/// The common string localizer
member _.Strings = Views.I18N.localizer.Force()
/// The currently logged on small group (sets the value in the session if it is missing)
member this.CurrentGroup() = task {
match this.Session.CurrentGroup with
| Some group -> return Some group
| None ->
match this.User.SmallGroupId with
| Some groupId ->
match! SmallGroups.tryById groupId with
| Some group ->
this.Session.CurrentGroup <- Some group
return Some group
| None -> return None
| None -> return None
}
/// The currently logged on user (sets the value in the session if it is missing)
member this.CurrentUser() = task {
match this.Session.CurrentUser with
| Some user -> return Some user
| None ->
match this.User.UserId with
| Some userId ->
match! Users.tryById userId with
| Some user ->
// Set last seen for user
do! Users.updateLastSeen userId this.Now
this.Session.CurrentUser <- Some user
return Some user
| None -> return None
| None -> return None
}

86
src/PrayerTracker/Help.fs Normal file
View File

@@ -0,0 +1,86 @@
/// Handlers for /help routes
module PrayerTracker.Handlers.Help
open Giraffe
open PrayerTracker
// GET: /help
let index : HttpHandler = fun next ctx -> task {
return!
Views.Help.index ()
|> Views.Layout.help ctx.Strings["Help Index"].Value true
|> renderHtml next ctx
}
/// Handlers for /help/requests routes
module Requests =
// GET: /help/requests/edit
let edit : HttpHandler = fun next ctx -> task {
return!
Views.Help.Requests.edit ()
|> Views.Layout.help ctx.Strings["Add / Edit a Request"].Value false
|> renderHtml next ctx
}
// GET: /help/requests/maintain
let maintain : HttpHandler = fun next ctx -> task {
return!
Views.Help.Requests.maintain ()
|> Views.Layout.help ctx.Strings["Maintain Requests"].Value false
|> renderHtml next ctx
}
// GET: /help/requests/view
let view : HttpHandler = fun next ctx -> task {
return!
Views.Help.Requests.view ()
|> Views.Layout.help ctx.Strings["View Request List"].Value false
|> renderHtml next ctx
}
/// Handlers for /help/small-group routes
module SmallGroup =
// GET: /help/small-group/announcement
let announcement : HttpHandler = fun next ctx -> task {
return!
Views.Help.SmallGroup.announcement ()
|> Views.Layout.help ctx.Strings["Send Announcement"].Value false
|> renderHtml next ctx
}
// GET: /help/small-group/members
let members : HttpHandler = fun next ctx -> task {
return!
Views.Help.SmallGroup.members ()
|> Views.Layout.help ctx.Strings["Maintain Group Members"].Value false
|> renderHtml next ctx
}
// GET: /help/small-group/members
let preferences : HttpHandler = fun next ctx -> task {
return!
Views.Help.SmallGroup.preferences ()
|> Views.Layout.help ctx.Strings["Change Preferences"].Value false
|> renderHtml next ctx
}
/// Handlers for /help/user routes
module User =
// GET: /help/user/log-on
let logOn : HttpHandler = fun next ctx -> task {
return!
Views.Help.User.logOn ()
|> Views.Layout.help ctx.Strings["Log On"].Value false
|> renderHtml next ctx
}
// GET: /help/user/password
let password : HttpHandler = fun next ctx -> task {
return!
Views.Help.User.password ()
|> Views.Layout.help ctx.Strings["Change Your Password"].Value false
|> renderHtml next ctx
}

View File

@@ -1,90 +1,72 @@
module PrayerTracker.Handlers.Home module PrayerTracker.Handlers.Home
open System
open System.Globalization
open Giraffe open Giraffe
open Microsoft.AspNetCore.Http open Microsoft.AspNetCore.Http
open Microsoft.AspNetCore.Localization open Microsoft.AspNetCore.Localization
open PrayerTracker open PrayerTracker
open System
open System.Globalization
/// GET /error/[error-code] // GET /error/[error-code]
let error code : HttpHandler = let error code : HttpHandler = requireAccess [ AccessLevel.Public ] >=> fun next ctx ->
requireAccess [ AccessLevel.Public ] viewInfo ctx
>=> fun next ctx ->
viewInfo ctx DateTime.Now.Ticks
|> Views.Home.error code |> Views.Home.error code
|> renderHtml next ctx |> renderHtml next ctx
// GET /
/// GET / let homePage : HttpHandler = requireAccess [ AccessLevel.Public ] >=> fun next ctx ->
let homePage : HttpHandler = viewInfo ctx
requireAccess [ AccessLevel.Public ]
>=> fun next ctx ->
viewInfo ctx DateTime.Now.Ticks
|> Views.Home.index |> Views.Home.index
|> renderHtml next ctx |> renderHtml next ctx
// GET /language/[culture]
/// GET /language/[culture] let language culture : HttpHandler = requireAccess [ AccessLevel.Public ] >=> fun next ctx ->
let language culture : HttpHandler =
requireAccess [ AccessLevel.Public ]
>=> fun next ctx ->
try try
match culture with match culture with
| null | null
| "" | ""
| "en" -> "en-US" | "en" -> "en-US"
| "es" -> "es-MX" | "es" -> "es-MX"
| _ -> sprintf "%s-%s" culture (culture.ToUpper ()) | _ -> $"{culture}-{culture.ToUpper()}"
|> (CultureInfo >> Option.ofObj) |> (CultureInfo >> Option.ofObj)
with with
| :? CultureNotFoundException | :? CultureNotFoundException
| :? ArgumentException -> None | :? ArgumentException -> None
|> function |> function
| Some c -> | Some c ->
ctx.Response.Cookies.Append ( ctx.Response.Cookies.Append(
CookieRequestCultureProvider.DefaultCookieName, CookieRequestCultureProvider.DefaultCookieName,
CookieRequestCultureProvider.MakeCookieValue (RequestCulture c), CookieRequestCultureProvider.MakeCookieValue(RequestCulture c),
CookieOptions (Expires = Nullable<DateTimeOffset> (DateTimeOffset (DateTime.Now.AddYears 1)))) CookieOptions(Expires = Nullable<DateTimeOffset>(DateTimeOffset(DateTime.Now.AddYears 1))))
| _ -> () | _ -> ()
let url = match string ctx.Request.Headers.["Referer"] with null | "" -> "/web/" | r -> r let url = match string ctx.Request.Headers["Referer"] with null | "" -> "/" | r -> r
redirectTo false url next ctx redirectTo false url next ctx
// GET /legal/privacy-policy
/// GET /legal/privacy-policy let privacyPolicy : HttpHandler = requireAccess [ AccessLevel.Public ] >=> fun next ctx ->
let privacyPolicy : HttpHandler = viewInfo ctx
requireAccess [ AccessLevel.Public ]
>=> fun next ctx ->
viewInfo ctx DateTime.Now.Ticks
|> Views.Home.privacyPolicy |> Views.Home.privacyPolicy
|> renderHtml next ctx |> renderHtml next ctx
// GET /legal/terms-of-service
/// GET /legal/terms-of-service let tos : HttpHandler = requireAccess [ AccessLevel.Public ] >=> fun next ctx ->
let tos : HttpHandler = viewInfo ctx
requireAccess [ AccessLevel.Public ]
>=> fun next ctx ->
viewInfo ctx DateTime.Now.Ticks
|> Views.Home.termsOfService |> Views.Home.termsOfService
|> renderHtml next ctx |> renderHtml next ctx
open Microsoft.AspNetCore.Authentication
open Microsoft.AspNetCore.Authentication.Cookies
/// GET /log-off // GET /log-off
let logOff : HttpHandler = let logOff : HttpHandler = requireAccess [ AccessLevel.Public ] >=> fun next ctx -> task {
requireAccess [ AccessLevel.Public ] ctx.Session.Clear()
>=> fun next ctx -> do! ctx.SignOutAsync CookieAuthenticationDefaults.AuthenticationScheme
ctx.Session.Clear () addHtmlInfo ctx ctx.Strings["Log Off Successful Have a nice day!"]
// Remove cookies if they exist return! redirectTo false "/" next ctx
Key.Cookie.logOffCookies |> List.iter ctx.Response.Cookies.Delete }
let s = Views.I18N.localizer.Force ()
addHtmlInfo ctx s.["Log Off Successful Have a nice day!"]
redirectTo false "/web/" next ctx
// GET /unauthorized
/// GET /unauthorized let unauthorized : HttpHandler = requireAccess [ AccessLevel.Public ] >=> fun next ctx ->
let unauthorized : HttpHandler = viewInfo ctx
requireAccess [ AccessLevel.Public ]
>=> fun next ctx ->
viewInfo ctx DateTime.Now.Ticks
|> Views.Home.unauthorized |> Views.Home.unauthorized
|> renderHtml next ctx |> renderHtml next ctx

View File

@@ -1,316 +1,271 @@
module PrayerTracker.Handlers.PrayerRequest module PrayerTracker.Handlers.PrayerRequest
open FSharp.Control.Tasks.V2.ContextInsensitive
open Giraffe open Giraffe
open Microsoft.AspNetCore.Http open Microsoft.AspNetCore.Http
open NodaTime
open PrayerTracker open PrayerTracker
open PrayerTracker.Data
open PrayerTracker.Entities open PrayerTracker.Entities
open PrayerTracker.ViewModels open PrayerTracker.ViewModels
open System
open System.Threading.Tasks
/// Retrieve a prayer request, and ensure that it belongs to the current class /// Retrieve a prayer request, and ensure that it belongs to the current class
let private findRequest (ctx : HttpContext) reqId = let private findRequest (ctx: HttpContext) reqId = task {
task { match! PrayerRequests.tryById reqId with
let! req = ctx.dbContext().TryRequestById reqId | Some req when req.SmallGroupId = ctx.Session.CurrentGroup.Value.Id -> return Ok req
match req with
| Some pr when pr.smallGroupId = (currentGroup ctx).smallGroupId -> return Ok pr
| Some _ -> | Some _ ->
let s = Views.I18N.localizer.Force () addError ctx ctx.Strings["The prayer request you tried to access is not assigned to your group"]
addError ctx s.["The prayer request you tried to access is not assigned to your group"] return Result.Error (redirectTo false "/unauthorized" earlyReturn ctx)
return Error (redirectTo false "/web/unauthorized") | None -> return Result.Error (fourOhFour ctx)
| None -> return Error fourOhFour }
}
/// Generate a list of requests for the given date /// Generate a list of requests for the given date
let private generateRequestList ctx date = let private generateRequestList (ctx: HttpContext) date = task {
let grp = currentGroup ctx let group = ctx.Session.CurrentGroup.Value
let clock = ctx.GetService<IClock> () let listDate = defaultArg date (group.LocalDateNow ctx.Clock)
let listDate = let! reqs =
match date with PrayerRequests.forGroup
| Some d -> d { SmallGroup = group
| None -> grp.localDateNow clock Clock = ctx.Clock
let reqs = ctx.dbContext().AllRequestsForSmallGroup grp clock (Some listDate) true 0 ListDate = Some listDate
{ requests = reqs |> List.ofSeq ActiveOnly = true
date = listDate PageNumber = 0 }
listGroup = grp return
showHeader = true { Requests = reqs
canEmail = tryCurrentUser ctx |> Option.isSome Date = listDate
recipients = [] SmallGroup = group
} ShowHeader = true
CanEmail = Option.isSome ctx.User.UserId
Recipients = [] }
}
open NodaTime.Text
/// Parse a string into a date (optionally, of course) /// Parse a string into a date (optionally, of course)
let private parseListDate (date : string option) = let private parseListDate (date: string option) =
match date with match date with
| Some dt -> match DateTime.TryParse dt with true, d -> Some d | false, _ -> None | Some dt -> match LocalDatePattern.Iso.Parse dt with it when it.Success -> Some it.Value | _ -> None
| None -> None | None -> None
open System
/// GET /prayer-request/[request-id]/edit // GET /prayer-request/[request-id]/edit
let edit (reqId : PrayerRequestId) : HttpHandler = let edit reqId : HttpHandler = requireAccess [ User ] >=> fun next ctx -> task {
requireAccess [ User ] let group = ctx.Session.CurrentGroup.Value
>=> fun next ctx -> let now = group.LocalDateNow ctx.Clock
let startTicks = DateTime.Now.Ticks let requestId = PrayerRequestId reqId
let grp = currentGroup ctx if requestId.Value = Guid.Empty then
let now = grp.localDateNow (ctx.GetService<IClock> ()) return!
task { { viewInfo ctx with HelpLink = Some Help.editRequest }
match reqId = Guid.Empty with |> Views.PrayerRequest.edit EditRequest.empty (now.ToString("R", null)) ctx
| true ->
return!
{ viewInfo ctx startTicks with script = [ "ckeditor/ckeditor" ]; helpLink = Some Help.editRequest }
|> Views.PrayerRequest.edit EditRequest.empty (now.ToString "yyyy-MM-dd") ctx
|> renderHtml next ctx |> renderHtml next ctx
| false -> else
let! result = findRequest ctx reqId match! findRequest ctx requestId with
match result with | Ok req ->
| Ok req -> let s = ctx.Strings
let s = Views.I18N.localizer.Force () if req.IsExpired now group then
match req.isExpired now grp.preferences.daysToExpire with { UserMessage.warning with
| true -> Text = htmlLocString s["This request is expired."]
{ UserMessage.Warning with Description =
text = htmlLocString s.["This request is expired."] s["To make it active again, update it as necessary, leave “{0}” and “{1}” unchecked, and it will return as an active request.",
description = s["Expire Immediately"], s["Check to not update the date"]]
s.["To make it active again, update it as necessary, leave “{0}” and “{1}” unchecked, and it will return as an active request.",
s.["Expire Immediately"], s.["Check to not update the date"]]
|> (htmlLocString >> Some) |> (htmlLocString >> Some)
} }
|> addUserMessage ctx |> addUserMessage ctx
| false -> () return!
return! { viewInfo ctx with HelpLink = Some Help.editRequest }
{ viewInfo ctx startTicks with script = [ "ckeditor/ckeditor" ]; helpLink = Some Help.editRequest }
|> Views.PrayerRequest.edit (EditRequest.fromRequest req) "" ctx |> Views.PrayerRequest.edit (EditRequest.fromRequest req) "" ctx
|> renderHtml next ctx |> renderHtml next ctx
| Error e -> return! e next ctx | Result.Error e -> return! e
} }
open Microsoft.Extensions.Configuration
/// GET /prayer-requests/email/[date] // GET /prayer-requests/email/[date]
let email date : HttpHandler = let email date : HttpHandler = requireAccess [ User ] >=> fun next ctx -> task {
requireAccess [ User ] let s = ctx.Strings
>=> fun next ctx -> let listDate = parseListDate (Some date)
let startTicks = DateTime.Now.Ticks let! list = generateRequestList ctx listDate
let s = Views.I18N.localizer.Force () let group = ctx.Session.CurrentGroup.Value
let listDate = parseListDate (Some date) let! recipients = Members.forGroup group.Id
let grp = currentGroup ctx use! client = Email.getConnection ()
task { do! Email.sendEmails
let list = generateRequestList ctx listDate { Client = client
let! recipients = ctx.dbContext().AllMembersForSmallGroup grp.smallGroupId Recipients = recipients
use! client = Email.getConnection () Group = group
do! Email.sendEmails client recipients Subject = s["Prayer Requests for {0} - {1:MMMM d, yyyy}", group.Name, list.Date].Value
grp s.["Prayer Requests for {0} - {1:MMMM d, yyyy}", grp.name, list.date].Value HtmlBody = list.AsHtml s
(list.asHtml s) (list.asText s) s PlainTextBody = list.AsText s
return! Strings = s }
viewInfo ctx startTicks do! client.DisconnectAsync true
|> Views.PrayerRequest.email { list with recipients = recipients } return!
viewInfo ctx
|> Views.PrayerRequest.email { list with Recipients = recipients }
|> renderHtml next ctx |> renderHtml next ctx
} }
// POST /prayer-request/[request-id]/delete
let delete reqId : HttpHandler = requireAccess [ User ] >=> validateCsrf >=> fun next ctx -> task {
let requestId = PrayerRequestId reqId
match! findRequest ctx requestId with
| Ok req ->
do! PrayerRequests.deleteById req.Id
addInfo ctx ctx.Strings["The prayer request was deleted successfully"]
return! redirectTo false "/prayer-requests" next ctx
| Result.Error e -> return! e
}
/// POST /prayer-request/[request-id]/delete // GET /prayer-request/[request-id]/expire
let delete reqId : HttpHandler = let expire reqId : HttpHandler = requireAccess [ User ] >=> fun next ctx -> task {
requireAccess [ User ] let requestId = PrayerRequestId reqId
>=> validateCSRF match! findRequest ctx requestId with
>=> fun next ctx -> | Ok req ->
task { do! PrayerRequests.updateExpiration { req with Expiration = Forced } false
let! result = findRequest ctx reqId addInfo ctx ctx.Strings["Successfully {0} prayer request", ctx.Strings["Expired"].Value.ToLower()]
match result with return! redirectTo false "/prayer-requests" next ctx
| Ok r -> | Result.Error e -> return! e
let db = ctx.dbContext () }
let s = Views.I18N.localizer.Force ()
db.PrayerRequests.Remove r |> ignore
let! _ = db.SaveChangesAsync ()
addInfo ctx s.["The prayer request was deleted successfully"]
return! redirectTo false "/web/prayer-requests" next ctx
| Error e -> return! e next ctx
}
// GET /prayer-requests/[group-id]/list
/// GET /prayer-request/[request-id]/expire let list groupId : HttpHandler = requireAccess [ AccessLevel.Public ] >=> fun next ctx -> task {
let expire reqId : HttpHandler = match! SmallGroups.tryById (SmallGroupId groupId) with
requireAccess [ User ] | Some group when group.Preferences.IsPublic ->
>=> fun next ctx -> let! reqs =
task { PrayerRequests.forGroup
let! result = findRequest ctx reqId { SmallGroup = group
match result with Clock = ctx.Clock
| Ok r -> ListDate = None
let db = ctx.dbContext () ActiveOnly = true
let s = Views.I18N.localizer.Force () PageNumber = 0 }
db.UpdateEntry { r with expiration = Forced } return!
let! _ = db.SaveChangesAsync () viewInfo ctx
addInfo ctx s.["Successfully {0} prayer request", s.["Expired"].Value.ToLower ()]
return! redirectTo false "/web/prayer-requests" next ctx
| Error e -> return! e next ctx
}
/// GET /prayer-requests/[group-id]/list
let list groupId : HttpHandler =
requireAccess [ AccessLevel.Public ]
>=> fun next ctx ->
let startTicks = DateTime.Now.Ticks
let db = ctx.dbContext ()
task {
let! grp = db.TryGroupById groupId
match grp with
| Some g when g.preferences.isPublic ->
let clock = ctx.GetService<IClock> ()
let reqs = db.AllRequestsForSmallGroup g clock None true 0
return!
viewInfo ctx startTicks
|> Views.PrayerRequest.list |> Views.PrayerRequest.list
{ requests = List.ofSeq reqs { Requests = reqs
date = g.localDateNow clock Date = group.LocalDateNow ctx.Clock
listGroup = g SmallGroup = group
showHeader = true ShowHeader = true
canEmail = (tryCurrentUser >> Option.isSome) ctx CanEmail = Option.isSome ctx.User.UserId
recipients = [] Recipients = [] }
}
|> renderHtml next ctx |> renderHtml next ctx
| Some _ -> | Some _ ->
let s = Views.I18N.localizer.Force () addError ctx ctx.Strings["The request list for the group you tried to view is not public."]
addError ctx s.["The request list for the group you tried to view is not public."] return! redirectTo false "/unauthorized" next ctx
return! redirectTo false "/web/unauthorized" next ctx | None -> return! fourOhFour ctx
| None -> return! fourOhFour next ctx }
}
// GET /prayer-requests/lists
/// GET /prayer-requests/lists let lists : HttpHandler = requireAccess [ AccessLevel.Public ] >=> fun next ctx -> task {
let lists : HttpHandler = let! groups = SmallGroups.listPublicAndProtected ()
requireAccess [ AccessLevel.Public ] return!
>=> fun next ctx -> viewInfo ctx
let startTicks = DateTime.Now.Ticks |> Views.PrayerRequest.lists groups
task {
let! grps = ctx.dbContext().PublicAndProtectedGroups ()
return!
viewInfo ctx startTicks
|> Views.PrayerRequest.lists grps
|> renderHtml next ctx |> renderHtml next ctx
} }
// GET /prayer-requests[/inactive?]
/// GET /prayer-requests[/inactive?] // - OR -
/// - OR - // GET /prayer-requests?search=[search-query]
/// GET /prayer-requests?search=[search-query] let maintain onlyActive : HttpHandler = requireAccess [ User ] >=> fun next ctx -> task {
let maintain onlyActive : HttpHandler = let group = ctx.Session.CurrentGroup.Value
requireAccess [ User ] let pageNbr =
>=> fun next ctx ->
let startTicks = DateTime.Now.Ticks
let db = ctx.dbContext ()
let grp = currentGroup ctx
task {
let pageNbr =
match ctx.GetQueryStringValue "page" with match ctx.GetQueryStringValue "page" with
| Ok pg -> match Int32.TryParse pg with true, p -> p | false, _ -> 1 | Ok pg -> match Int32.TryParse pg with true, p -> p | false, _ -> 1
| Error _ -> 1 | Result.Error _ -> 1
let m = let! model = backgroundTask {
match ctx.GetQueryStringValue "search" with match ctx.GetQueryStringValue "search" with
| Ok srch -> | Ok search ->
{ MaintainRequests.empty with let! reqs = PrayerRequests.searchForGroup group search pageNbr
requests = db.SearchRequestsForSmallGroup grp srch pageNbr return
searchTerm = Some srch { MaintainRequests.empty with
pageNbr = Some pageNbr Requests = reqs
} SearchTerm = Some search
| Error _ -> PageNbr = Some pageNbr }
{ MaintainRequests.empty with | Result.Error _ ->
requests = db.AllRequestsForSmallGroup grp (ctx.GetService<IClock> ()) None onlyActive pageNbr let! reqs =
onlyActive = Some onlyActive PrayerRequests.forGroup
pageNbr = match onlyActive with true -> None | false -> Some pageNbr { SmallGroup = group
} Clock = ctx.Clock
return! ListDate = None
{ viewInfo ctx startTicks with helpLink = Some Help.maintainRequests } ActiveOnly = onlyActive
|> Views.PrayerRequest.maintain { m with smallGroup = grp } ctx PageNumber = pageNbr }
return
{ MaintainRequests.empty with
Requests = reqs
OnlyActive = Some onlyActive
PageNbr = if onlyActive then None else Some pageNbr }
}
return!
{ viewInfo ctx with HelpLink = Some Help.maintainRequests }
|> Views.PrayerRequest.maintain { model with SmallGroup = group } ctx
|> renderHtml next ctx |> renderHtml next ctx
} }
// GET /prayer-request/print/[date]
/// GET /prayer-request/print/[date] let print date : HttpHandler = requireAccess [ User; Group ] >=> fun next ctx -> task {
let print date : HttpHandler = let! list = generateRequestList ctx (parseListDate (Some date))
requireAccess [ User; Group ] return!
>=> fun next ctx ->
let listDate = parseListDate (Some date)
task {
let list = generateRequestList ctx listDate
return!
Views.PrayerRequest.print list appVersion Views.PrayerRequest.print list appVersion
|> renderHtml next ctx |> renderHtml next ctx
} }
// GET /prayer-request/[request-id]/restore
let restore reqId : HttpHandler = requireAccess [ User ] >=> fun next ctx -> task {
let requestId = PrayerRequestId reqId
match! findRequest ctx requestId with
| Ok req ->
do! PrayerRequests.updateExpiration { req with Expiration = Automatic; UpdatedDate = ctx.Now } true
addInfo ctx ctx.Strings["Successfully {0} prayer request", ctx.Strings["Restored"].Value.ToLower ()]
return! redirectTo false "/prayer-requests" next ctx
| Result.Error e -> return! e
}
/// GET /prayer-request/[request-id]/restore open System.Threading.Tasks
let restore reqId : HttpHandler =
requireAccess [ User ]
>=> fun next ctx ->
task {
let! result = findRequest ctx reqId
match result with
| Ok r ->
let db = ctx.dbContext ()
let s = Views.I18N.localizer.Force ()
db.UpdateEntry { r with expiration = Automatic; updatedDate = DateTime.Now }
let! _ = db.SaveChangesAsync ()
addInfo ctx s.["Successfully {0} prayer request", s.["Restored"].Value.ToLower ()]
return! redirectTo false "/web/prayer-requests" next ctx
| Error e -> return! e next ctx
}
// POST /prayer-request/save
/// POST /prayer-request/save let save : HttpHandler = requireAccess [ User ] >=> validateCsrf >=> fun next ctx -> task {
let save : HttpHandler = match! ctx.TryBindFormAsync<EditRequest>() with
requireAccess [ User ] | Ok model ->
>=> validateCSRF let group = ctx.Session.CurrentGroup.Value
>=> fun next ctx -> let! req =
task { if model.IsNew then
match! ctx.TryBindFormAsync<EditRequest> () with { PrayerRequest.Empty with
| Ok m -> Id = (Guid.NewGuid >> PrayerRequestId) ()
let db = ctx.dbContext () SmallGroupId = group.Id
let! req = UserId = ctx.User.UserId.Value
match m.isNew () with }
| true -> Task.FromResult (Some { PrayerRequest.empty with prayerRequestId = Guid.NewGuid () }) |> (Some >> Task.FromResult)
| false -> db.TryRequestById m.requestId else PrayerRequests.tryById (idFromShort PrayerRequestId model.RequestId)
match req with match req with
| Some pr -> | Some pr when pr.SmallGroupId = group.Id ->
let upd8 = let now = group.LocalDateNow ctx.Clock
let updated =
{ pr with { pr with
requestType = PrayerRequestType.fromCode m.requestType RequestType = PrayerRequestType.Parse model.RequestType
requestor = match m.requestor with Some x when x.Trim () = "" -> None | x -> x Requestor = match model.Requestor with Some x when x.Trim() = "" -> None | x -> x
text = ckEditorToText m.text Text = ckEditorToText model.Text
expiration = Expiration.fromCode m.expiration Expiration = Expiration.Parse model.Expiration
} }
let grp = currentGroup ctx |> function
let now = grp.localDateNow (ctx.GetService<IClock> ()) | it when model.IsNew ->
match m.isNew () with let dt =
| true -> (defaultArg (parseListDate model.EnteredDate) now)
let dt = match m.enteredDate with Some x -> x | None -> now .AtStartOfDayInZone(group.TimeZone)
{ upd8 with .ToInstant()
smallGroupId = grp.smallGroupId { it with EnteredDate = dt; UpdatedDate = dt }
userId = (currentUser ctx).userId | it when defaultArg model.SkipDateUpdate false -> it
enteredDate = dt | it -> { it with UpdatedDate = ctx.Now }
updatedDate = dt do! PrayerRequests.save updated
} let act = if model.IsNew then "Added" else "Updated"
| false when Option.isSome m.skipDateUpdate && Option.get m.skipDateUpdate -> upd8 addInfo ctx ctx.Strings["Successfully {0} prayer request", ctx.Strings[act].Value.ToLower()]
| false -> { upd8 with updatedDate = now } return! redirectTo false "/prayer-requests" next ctx
|> (match m.isNew () with true -> db.AddEntry | false -> db.UpdateEntry) | Some _
let! _ = db.SaveChangesAsync () | None -> return! fourOhFour ctx
let s = Views.I18N.localizer.Force () | Result.Error e -> return! bindError e next ctx
let act = match m.isNew () with true -> "Added" | false -> "Updated" }
addInfo ctx s.["Successfully {0} prayer request", s.[act].Value.ToLower ()]
return! redirectTo false "/web/prayer-requests" next ctx
| None -> return! fourOhFour next ctx
| Error e -> return! bindError e next ctx
}
// GET /prayer-request/view/[date?]
/// GET /prayer-request/view/[date?] let view date : HttpHandler = requireAccess [ User; Group ] >=> fun next ctx -> task {
let view date : HttpHandler = let! list = generateRequestList ctx (parseListDate date)
requireAccess [ User; Group ] return!
>=> fun next ctx -> viewInfo ctx
let startTicks = DateTime.Now.Ticks |> Views.PrayerRequest.view { list with ShowHeader = false }
let listDate = parseListDate date
task {
let list = generateRequestList ctx listDate
return!
viewInfo ctx startTicks
|> Views.PrayerRequest.view { list with showHeader = false }
|> renderHtml next ctx |> renderHtml next ctx
} }

View File

@@ -1,7 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk.Web"> <Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup> <PropertyGroup>
<TargetFramework>netcoreapp3.0</TargetFramework> <OutputType>Exe</OutputType>
<PublishSingleFile>False</PublishSingleFile>
<SelfContained>False</SelfContained>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
@@ -11,10 +13,10 @@
<ItemGroup> <ItemGroup>
<None Include="appsettings.json" /> <None Include="appsettings.json" />
<Compile Include="Extensions.fs" /> <Compile Include="Extensions.fs" />
<Compile Include="Cookies.fs" />
<Compile Include="Email.fs" /> <Compile Include="Email.fs" />
<Compile Include="CommonFunctions.fs" /> <Compile Include="CommonFunctions.fs" />
<Compile Include="Church.fs" /> <Compile Include="Church.fs" />
<Compile Include="Help.fs" />
<Compile Include="Home.fs" /> <Compile Include="Home.fs" />
<Compile Include="PrayerRequest.fs" /> <Compile Include="PrayerRequest.fs" />
<Compile Include="SmallGroup.fs" /> <Compile Include="SmallGroup.fs" />
@@ -23,19 +25,15 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Giraffe" Version="4.0.1" /> <PackageReference Include="BitBadger.AspNetCore.CanonicalDomains" Version="1.1.0" />
<PackageReference Include="Giraffe.TokenRouter" Version="1.0.0" /> <PackageReference Include="Giraffe.Htmx" Version="2.0.4" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="3.0.0" /> <PackageReference Include="NeoSmart.Caching.Sqlite.AspNetCore" Version="9.0.0" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="3.0.1" /> <PackageReference Update="FSharp.Core" Version="9.0.101" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\PrayerTracker.Data\PrayerTracker.Data.fsproj" /> <ProjectReference Include="..\Data\PrayerTracker.Data.fsproj" />
<ProjectReference Include="..\PrayerTracker.UI\PrayerTracker.UI.fsproj" /> <ProjectReference Include="..\UI\PrayerTracker.UI.fsproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Update="FSharp.Core" Version="4.7.0" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@@ -1,410 +1,305 @@
module PrayerTracker.Handlers.SmallGroup module PrayerTracker.Handlers.SmallGroup
open FSharp.Control.Tasks.V2.ContextInsensitive open System
open Giraffe open Giraffe
open Giraffe.GiraffeViewEngine
open Microsoft.AspNetCore.Http
open NodaTime
open PrayerTracker open PrayerTracker
open PrayerTracker.Cookies open PrayerTracker.Data
open PrayerTracker.Entities open PrayerTracker.Entities
open PrayerTracker.ViewModels open PrayerTracker.ViewModels
open PrayerTracker.Views.CommonFunctions
open System
open System.Threading.Tasks
/// Set a small group "Remember Me" cookie // GET /small-group/announcement
let private setGroupCookie (ctx : HttpContext) pwHash = let announcement : HttpHandler = requireAccess [ User ] >=> fun next ctx ->
ctx.Response.Cookies.Append { viewInfo ctx with HelpLink = Some Help.sendAnnouncement }
(Key.Cookie.group, { GroupId = (currentGroup ctx).smallGroupId; PasswordHash = pwHash }.toPayload(), autoRefresh) |> Views.SmallGroup.announcement ctx.Session.CurrentUser.Value.IsAdmin ctx
/// GET /small-group/announcement
let announcement : HttpHandler =
requireAccess [ User ]
>=> fun next ctx ->
let startTicks = DateTime.Now.Ticks
{ viewInfo ctx startTicks with helpLink = Some Help.sendAnnouncement; script = [ "ckeditor/ckeditor" ] }
|> Views.SmallGroup.announcement (currentUser ctx).isAdmin ctx
|> renderHtml next ctx |> renderHtml next ctx
// POST /small-group/[group-id]/delete
let delete grpId : HttpHandler = requireAccess [ Admin ] >=> validateCsrf >=> fun next ctx -> task {
let groupId = SmallGroupId grpId
match! SmallGroups.tryById groupId with
| Some grp ->
let! reqs = PrayerRequests.countByGroup groupId
let! users = Users.countByGroup groupId
do! SmallGroups.deleteById groupId
addInfo ctx
ctx.Strings["The group “{0}” and its {1} prayer request(s) were deleted successfully; revoked access from {2} user(s)",
grp.Name, reqs, users]
return! redirectTo false "/small-groups" next ctx
| None -> return! fourOhFour ctx
}
/// POST /small-group/[group-id]/delete // POST /small-group/member/[member-id]/delete
let delete groupId : HttpHandler = let deleteMember mbrId : HttpHandler = requireAccess [ User ] >=> validateCsrf >=> fun next ctx -> task {
requireAccess [ Admin ] let group = ctx.Session.CurrentGroup.Value
>=> validateCSRF let memberId = MemberId mbrId
>=> fun next ctx -> match! Members.tryById memberId with
let db = ctx.dbContext () | Some mbr when mbr.SmallGroupId = group.Id ->
let s = Views.I18N.localizer.Force () do! Members.deleteById memberId
task { addHtmlInfo ctx ctx.Strings["The group member &ldquo;{0}&rdquo; was deleted successfully", mbr.Name]
let! grp = db.TryGroupById groupId return! redirectTo false "/small-group/members" next ctx
match grp with | Some _
| Some g -> | None -> return! fourOhFour ctx
let! reqs = db.CountRequestsBySmallGroup groupId }
let! usrs = db.CountUsersBySmallGroup groupId
db.RemoveEntry g
let! _ = db.SaveChangesAsync ()
addInfo ctx
s.["The group {0} and its {1} prayer request(s) were deleted successfully; revoked access from {2} user(s)",
g.name, reqs, usrs]
return! redirectTo false "/web/small-groups" next ctx
| None -> return! fourOhFour next ctx
}
// GET /small-group/[group-id]/edit
/// POST /small-group/member/[member-id]/delete let edit grpId : HttpHandler = requireAccess [ Admin ] >=> fun next ctx -> task {
let deleteMember memberId : HttpHandler = let! churches = Churches.all ()
requireAccess [ User ] let groupId = SmallGroupId grpId
>=> validateCSRF if groupId.Value = Guid.Empty then
>=> fun next ctx -> return!
let db = ctx.dbContext () viewInfo ctx
let s = Views.I18N.localizer.Force ()
task {
let! mbr = db.TryMemberById memberId
match mbr with
| Some m when m.smallGroupId = (currentGroup ctx).smallGroupId ->
db.RemoveEntry m
let! _ = db.SaveChangesAsync ()
addHtmlInfo ctx s.["The group member &ldquo;{0}&rdquo; was deleted successfully", m.memberName]
return! redirectTo false "/web/small-group/members" next ctx
| Some _
| None -> return! fourOhFour next ctx
}
/// GET /small-group/[group-id]/edit
let edit (groupId : SmallGroupId) : HttpHandler =
requireAccess [ Admin ]
>=> fun next ctx ->
let startTicks = DateTime.Now.Ticks
let db = ctx.dbContext ()
task {
let! churches = db.AllChurches ()
match groupId = Guid.Empty with
| true ->
return!
viewInfo ctx startTicks
|> Views.SmallGroup.edit EditSmallGroup.empty churches ctx |> Views.SmallGroup.edit EditSmallGroup.empty churches ctx
|> renderHtml next ctx |> renderHtml next ctx
| false -> else
let! grp = db.TryGroupById groupId match! SmallGroups.tryById groupId with
match grp with | Some grp ->
| Some g -> return!
return! viewInfo ctx
viewInfo ctx startTicks |> Views.SmallGroup.edit (EditSmallGroup.fromGroup grp) churches ctx
|> Views.SmallGroup.edit (EditSmallGroup.fromGroup g) churches ctx
|> renderHtml next ctx |> renderHtml next ctx
| None -> return! fourOhFour next ctx | None -> return! fourOhFour ctx
} }
// GET /small-group/member/[member-id]/edit
/// GET /small-group/member/[member-id]/edit let editMember mbrId : HttpHandler = requireAccess [ User ] >=> fun next ctx -> task {
let editMember (memberId : MemberId) : HttpHandler = let group = ctx.Session.CurrentGroup.Value
requireAccess [ User ] let types = ReferenceList.emailTypeList group.Preferences.DefaultEmailType ctx.Strings
>=> fun next ctx -> let memberId = MemberId mbrId
let startTicks = DateTime.Now.Ticks if memberId.Value = Guid.Empty then
let db = ctx.dbContext () return!
let s = Views.I18N.localizer.Force () viewInfo ctx
let grp = currentGroup ctx |> Views.SmallGroup.editMember EditMember.empty types ctx
let typs = ReferenceList.emailTypeList grp.preferences.defaultEmailType s
task {
match memberId = Guid.Empty with
| true ->
return!
viewInfo ctx startTicks
|> Views.SmallGroup.editMember EditMember.empty typs ctx
|> renderHtml next ctx |> renderHtml next ctx
| false -> else
let! mbr = db.TryMemberById memberId match! Members.tryById memberId with
match mbr with | Some mbr when mbr.SmallGroupId = group.Id ->
| Some m when m.smallGroupId = grp.smallGroupId -> return!
return! viewInfo ctx
viewInfo ctx startTicks |> Views.SmallGroup.editMember (EditMember.fromMember mbr) types ctx
|> Views.SmallGroup.editMember (EditMember.fromMember m) typs ctx
|> renderHtml next ctx |> renderHtml next ctx
| Some _ | Some _
| None -> return! fourOhFour next ctx | None -> return! fourOhFour ctx
} }
// GET /small-group/log-on/[group-id?]
/// GET /small-group/log-on/[group-id?] let logOn grpId : HttpHandler = requireAccess [ AccessLevel.Public ] >=> fun next ctx -> task {
let logOn (groupId : SmallGroupId option) : HttpHandler = let! groups = SmallGroups.listProtected ()
requireAccess [ AccessLevel.Public ] let groupId = match grpId with Some gid -> shortGuid gid | None -> ""
>=> fun next ctx -> return!
let startTicks = DateTime.Now.Ticks { viewInfo ctx with HelpLink = Some Help.logOn }
task { |> Views.SmallGroup.logOn groups groupId ctx
let! grps = ctx.dbContext().ProtectedGroups ()
let grpId = match groupId with Some gid -> flatGuid gid | None -> ""
return!
{ viewInfo ctx startTicks with helpLink = Some Help.logOn }
|> Views.SmallGroup.logOn grps grpId ctx
|> renderHtml next ctx |> renderHtml next ctx
} }
open System.Security.Claims
open Microsoft.AspNetCore.Authentication
open Microsoft.AspNetCore.Authentication.Cookies
/// POST /small-group/log-on/submit // POST /small-group/log-on/submit
let logOnSubmit : HttpHandler = let logOnSubmit : HttpHandler = requireAccess [ AccessLevel.Public ] >=> validateCsrf >=> fun next ctx -> task {
requireAccess [ AccessLevel.Public ] match! ctx.TryBindFormAsync<GroupLogOn>() with
>=> validateCSRF | Ok model ->
>=> fun next ctx -> match! SmallGroups.logOn (idFromShort SmallGroupId model.SmallGroupId) model.Password with
task { | Some group ->
let! result = ctx.TryBindFormAsync<GroupLogOn> () ctx.Session.CurrentGroup <- Some group
match result with let identity = ClaimsIdentity(
| Ok m -> Seq.singleton (Claim(ClaimTypes.GroupSid, shortGuid group.Id.Value)),
let s = Views.I18N.localizer.Force () CookieAuthenticationDefaults.AuthenticationScheme)
let! grp = ctx.dbContext().TryGroupLogOnByPassword m.smallGroupId m.password do! ctx.SignInAsync(
match grp with identity.AuthenticationType, ClaimsPrincipal identity,
| Some _ -> AuthenticationProperties(
ctx.Session.SetSmallGroup grp IssuedUtc = DateTimeOffset.UtcNow,
match m.rememberMe with IsPersistent = defaultArg model.RememberMe false))
| Some x when x -> (setGroupCookie ctx << Utils.sha1Hash) m.password addInfo ctx ctx.Strings["Log On Successful Welcome to {0}", ctx.Strings["PrayerTracker"]]
| _ -> () return! redirectTo false "/prayer-requests/view" next ctx
addInfo ctx s.["Log On Successful Welcome to {0}", s.["PrayerTracker"]]
return! redirectTo false "/web/prayer-requests/view" next ctx
| None -> | None ->
addError ctx s.["Password incorrect - login unsuccessful"] addError ctx ctx.Strings["Password incorrect - login unsuccessful"]
return! redirectTo false (sprintf "/web/small-group/log-on/%s" (flatGuid m.smallGroupId)) next ctx return! redirectTo false $"/small-group/log-on/{model.SmallGroupId}" next ctx
| Error e -> return! bindError e next ctx | Result.Error e -> return! bindError e next ctx
} }
// GET /small-groups
/// GET /small-groups let maintain : HttpHandler = requireAccess [ Admin ] >=> fun next ctx -> task {
let maintain : HttpHandler = let! groups = SmallGroups.infoForAll ()
requireAccess [ Admin ] return!
>=> fun next ctx -> viewInfo ctx
let startTicks = DateTime.Now.Ticks |> Views.SmallGroup.maintain groups ctx
task {
let! grps = ctx.dbContext().AllGroups ()
return!
viewInfo ctx startTicks
|> Views.SmallGroup.maintain grps ctx
|> renderHtml next ctx |> renderHtml next ctx
} }
// GET /small-group/members
/// GET /small-group/members let members : HttpHandler = requireAccess [ User ] >=> fun next ctx -> task {
let members : HttpHandler = let group = ctx.Session.CurrentGroup.Value
requireAccess [ User ] let! members = Members.forGroup group.Id
>=> fun next ctx -> let types = ReferenceList.emailTypeList group.Preferences.DefaultEmailType ctx.Strings |> Map.ofSeq
let startTicks = DateTime.Now.Ticks return!
let db = ctx.dbContext () { viewInfo ctx with HelpLink = Some Help.maintainGroupMembers }
let grp = currentGroup ctx |> Views.SmallGroup.members members types ctx
let s = Views.I18N.localizer.Force ()
task {
let! mbrs = db.AllMembersForSmallGroup grp.smallGroupId
let typs = ReferenceList.emailTypeList grp.preferences.defaultEmailType s |> Map.ofSeq
return!
{ viewInfo ctx startTicks with helpLink = Some Help.maintainGroupMembers }
|> Views.SmallGroup.members mbrs typs ctx
|> renderHtml next ctx |> renderHtml next ctx
} }
// GET /small-group
/// GET /small-group let overview : HttpHandler = requireAccess [ User ] >=> fun next ctx -> task {
let overview : HttpHandler = let group = ctx.Session.CurrentGroup.Value
requireAccess [ User ] let! reqs = PrayerRequests.forGroup
>=> fun next ctx -> { SmallGroup = group
let startTicks = DateTime.Now.Ticks Clock = ctx.Clock
let db = ctx.dbContext () ListDate = None
let clock = ctx.GetService<IClock> () ActiveOnly = true
task { PageNumber = 0 }
let reqs = db.AllRequestsForSmallGroup (currentGroup ctx) clock None true 0 |> List.ofSeq let! reqCount = PrayerRequests.countByGroup group.Id
let! reqCount = db.CountRequestsBySmallGroup (currentGroup ctx).smallGroupId let! mbrCount = Members.countByGroup group.Id
let! mbrCount = db.CountMembersForSmallGroup (currentGroup ctx).smallGroupId let! admins = Users.listByGroupId group.Id
let m = let model =
{ totalActiveReqs = List.length reqs { TotalActiveReqs = List.length reqs
allReqs = reqCount AllReqs = int reqCount
totalMbrs = mbrCount TotalMembers = int mbrCount
activeReqsByCat = ActiveReqsByType = (
(reqs reqs
|> Seq.ofList |> Seq.ofList
|> Seq.map (fun req -> req.requestType) |> Seq.map (fun req -> req.RequestType)
|> Seq.distinct |> Seq.distinct
|> Seq.map (fun reqType -> reqType, reqs |> List.filter (fun r -> r.requestType = reqType) |> List.length) |> Seq.map (fun reqType -> reqType, reqs |> List.filter (fun r -> r.RequestType = reqType) |> List.length)
|> Map.ofSeq) |> Map.ofSeq)
} Admins = admins }
return! return!
viewInfo ctx startTicks viewInfo ctx
|> Views.SmallGroup.overview m |> Views.SmallGroup.overview model
|> renderHtml next ctx |> renderHtml next ctx
} }
// GET /small-group/preferences
/// GET /small-group/preferences let preferences : HttpHandler = requireAccess [ User ] >=> fun next ctx -> task {
let preferences : HttpHandler = return!
requireAccess [ User ] { viewInfo ctx with HelpLink = Some Help.groupPreferences }
>=> fun next ctx -> |> Views.SmallGroup.preferences (EditPreferences.fromPreferences ctx.Session.CurrentGroup.Value.Preferences) ctx
let startTicks = DateTime.Now.Ticks
task {
let! tzs = ctx.dbContext().AllTimeZones ()
return!
{ viewInfo ctx startTicks with helpLink = Some Help.groupPreferences }
|> Views.SmallGroup.preferences (EditPreferences.fromPreferences (currentGroup ctx).preferences) tzs ctx
|> renderHtml next ctx |> renderHtml next ctx
} }
open System.Threading.Tasks
/// POST /small-group/save // POST /small-group/save
let save : HttpHandler = let save : HttpHandler = requireAccess [ Admin ] >=> validateCsrf >=> fun next ctx -> task {
requireAccess [ Admin ] match! ctx.TryBindFormAsync<EditSmallGroup>() with
>=> validateCSRF | Ok model ->
>=> fun next ctx -> let! tryGroup =
let s = Views.I18N.localizer.Force () if model.IsNew then Task.FromResult(Some { SmallGroup.Empty with Id = (Guid.NewGuid >> SmallGroupId) () })
task { else SmallGroups.tryById (idFromShort SmallGroupId model.SmallGroupId)
let! result = ctx.TryBindFormAsync<EditSmallGroup> () match tryGroup with
match result with | Some group ->
| Ok m -> do! SmallGroups.save (model.populateGroup group)
let db = ctx.dbContext () let act = ctx.Strings[if model.IsNew then "Added" else "Updated"].Value.ToLower()
let! grp = addHtmlInfo ctx ctx.Strings["Successfully {0} group “{1}”", act, model.Name]
match m.isNew () with return! redirectTo false "/small-groups" next ctx
| true -> Task.FromResult<SmallGroup option>(Some { SmallGroup.empty with smallGroupId = Guid.NewGuid () }) | None -> return! fourOhFour ctx
| false -> db.TryGroupById m.smallGroupId | Result.Error e -> return! bindError e next ctx
match grp with }
| Some g ->
m.populateGroup g
|> function
| g when m.isNew () ->
db.AddEntry g
db.AddEntry { g.preferences with smallGroupId = g.smallGroupId }
| g -> db.UpdateEntry g
let! _ = db.SaveChangesAsync ()
let act = s.[match m.isNew () with true -> "Added" | false -> "Updated"].Value.ToLower ()
addHtmlInfo ctx s.["Successfully {0} group “{1}”", act, m.name]
return! redirectTo false "/web/small-groups" next ctx
| None -> return! fourOhFour next ctx
| Error e -> return! bindError e next ctx
}
// POST /small-group/member/save
let saveMember : HttpHandler = requireAccess [ User ] >=> validateCsrf >=> fun next ctx -> task {
match! ctx.TryBindFormAsync<EditMember>() with
| Ok model ->
let group = ctx.Session.CurrentGroup.Value
let! tryMbr =
if model.IsNew then
Task.FromResult(Some { Member.Empty with Id = (Guid.NewGuid >> MemberId) (); SmallGroupId = group.Id })
else Members.tryById (idFromShort MemberId model.MemberId)
match tryMbr with
| Some mbr when mbr.SmallGroupId = group.Id ->
do! Members.save
{ mbr with
Name = model.Name
Email = model.Email
Format = String.noneIfBlank model.Format |> Option.map EmailFormat.Parse }
let act = ctx.Strings[if model.IsNew then "Added" else "Updated"].Value.ToLower()
addInfo ctx ctx.Strings["Successfully {0} group member", act]
return! redirectTo false "/small-group/members" next ctx
| Some _
| None -> return! fourOhFour ctx
| Result.Error e -> return! bindError e next ctx
}
/// POST /small-group/member/save // POST /small-group/preferences/save
let saveMember : HttpHandler = let savePreferences : HttpHandler = requireAccess [ User ] >=> validateCsrf >=> fun next ctx -> task {
requireAccess [ User ] match! ctx.TryBindFormAsync<EditPreferences>() with
>=> validateCSRF | Ok model ->
>=> fun next ctx -> // Since the class is stored in the session, we'll use an intermediate instance to persist it; once that works,
task { // we can repopulate the session instance. That way, if the update fails, the page should still show the
let! result = ctx.TryBindFormAsync<EditMember> () // database values, not the then out-of-sync session ones.
match result with let group = ctx.Session.CurrentGroup.Value
| Ok m -> match! SmallGroups.tryById group.Id with
let grp = currentGroup ctx | Some group ->
let db = ctx.dbContext () let pref = model.PopulatePreferences group.Preferences
let! mMbr = do! SmallGroups.savePreferences group.Id pref
match m.isNew () with // Refresh session instance
| true -> ctx.Session.CurrentGroup <- Some { group with Preferences = pref }
Task.FromResult<Member option> addInfo ctx ctx.Strings["Group preferences updated successfully"]
(Some return! redirectTo false "/small-group/preferences" next ctx
{ Member.empty with | None -> return! fourOhFour ctx
memberId = Guid.NewGuid () | Result.Error e -> return! bindError e next ctx
smallGroupId = grp.smallGroupId }
})
| false -> db.TryMemberById m.memberId
match mMbr with
| Some mbr when mbr.smallGroupId = grp.smallGroupId ->
{ mbr with
memberName = m.memberName
email = m.emailAddress
format = match m.emailType with "" | null -> None | _ -> Some m.emailType
}
|> (match m.isNew () with true -> db.AddEntry | false -> db.UpdateEntry)
let! _ = db.SaveChangesAsync ()
let s = Views.I18N.localizer.Force ()
let act = s.[match m.isNew () with true -> "Added" | false -> "Updated"].Value.ToLower ()
addInfo ctx s.["Successfully {0} group member", act]
return! redirectTo false "/web/small-group/members" next ctx
| Some _
| None -> return! fourOhFour next ctx
| Error e -> return! bindError e next ctx
}
open Giraffe.ViewEngine
open PrayerTracker.Views.CommonFunctions
/// POST /small-group/preferences/save // POST /small-group/announcement/send
let savePreferences : HttpHandler = let sendAnnouncement : HttpHandler = requireAccess [ User ] >=> validateCsrf >=> fun next ctx -> task {
requireAccess [ User ] match! ctx.TryBindFormAsync<Announcement>() with
>=> validateCSRF | Ok model ->
>=> fun next ctx -> let group = ctx.Session.CurrentGroup.Value
task { let pref = group.Preferences
let! result = ctx.TryBindFormAsync<EditPreferences> () let usr = ctx.Session.CurrentUser.Value
match result with let now = group.LocalTimeNow ctx.Clock
| Ok m -> let s = ctx.Strings
let db = ctx.dbContext () // Reformat the text to use the class's font stylings
// Since the class is stored in the session, we'll use an intermediate instance to persist it; once that let requestText = ckEditorToText model.Text
// works, we can repopulate the session instance. That way, if the update fails, the page should still show let htmlText =
// the database values, not the then out-of-sync session ones. p [ _style $"font-family:{pref.FontStack};font-size:%d{pref.TextFontSize}pt;" ] [ rawText requestText ]
let! grp = db.TryGroupById (currentGroup ctx).smallGroupId
match grp with
| Some g ->
let prefs = m.populatePreferences g.preferences
db.UpdateEntry prefs
let! _ = db.SaveChangesAsync ()
// Refresh session instance
ctx.Session.SetSmallGroup <| Some { g with preferences = prefs }
let s = Views.I18N.localizer.Force ()
addInfo ctx s.["Group preferences updated successfully"]
return! redirectTo false "/web/small-group/preferences" next ctx
| None -> return! fourOhFour next ctx
| Error e -> return! bindError e next ctx
}
/// POST /small-group/announcement/send
let sendAnnouncement : HttpHandler =
requireAccess [ User ]
>=> validateCSRF
>=> fun next ctx ->
let startTicks = DateTime.Now.Ticks
task {
let! result = ctx.TryBindFormAsync<Announcement> ()
match result with
| Ok m ->
let grp = currentGroup ctx
let usr = currentUser ctx
let db = ctx.dbContext ()
let now = grp.localTimeNow (ctx.GetService<IClock> ())
let s = Views.I18N.localizer.Force ()
// Reformat the text to use the class's font stylings
let requestText = ckEditorToText m.text
let htmlText =
p [ _style (sprintf "font-family:%s;font-size:%dpt;" grp.preferences.listFonts grp.preferences.textFontSize) ]
[ rawText requestText ]
|> renderHtmlNode |> renderHtmlNode
let plainText = (htmlToPlainText >> wordWrap 74) htmlText let plainText = (htmlToPlainText >> wordWrap 74) htmlText
// Send the e-mails // Send the e-mails
let! recipients = let! recipients = task {
match m.sendToClass with if model.SendToClass = "N" && usr.IsAdmin then
| "N" when usr.isAdmin -> db.AllUsersAsMembers () let! users = Users.all ()
| _ -> db.AllMembersForSmallGroup grp.smallGroupId return users |> List.map (fun u -> { Member.Empty with Name = u.Name; Email = u.Email })
use! client = Email.getConnection () else return! Members.forGroup group.Id
do! Email.sendEmails client recipients grp }
s.["Announcement for {0} - {1:MMMM d, yyyy} {2}", use! client = Email.getConnection ()
grp.name, now.Date, (now.ToString "h:mm tt").ToLower ()].Value do! Email.sendEmails
htmlText plainText s { Client = client
// Add to the request list if desired Recipients = recipients
match m.sendToClass, m.addToRequestList with Group = group
| "N", _ Subject = s["Announcement for {0} - {1:MMMM d, yyyy} {2}", group.Name, now.Date,
| _, None -> () now.ToString("h:mm tt", null).ToLower()].Value
| _, Some x when not x -> () HtmlBody = htmlText
| _, _ -> PlainTextBody = plainText
{ PrayerRequest.empty with Strings = s }
prayerRequestId = Guid.NewGuid () do! client.DisconnectAsync true
smallGroupId = grp.smallGroupId // Add to the request list if desired
userId = usr.userId match model.SendToClass, model.AddToRequestList with
requestType = (Option.get >> PrayerRequestType.fromCode) m.requestType | "N", _
text = requestText | _, None -> ()
enteredDate = now | _, Some x when not x -> ()
updatedDate = now | _, _ ->
} let zone = group.TimeZone
|> db.AddEntry do! PrayerRequests.save
let! _ = db.SaveChangesAsync () { PrayerRequest.Empty with
() Id = (Guid.NewGuid >> PrayerRequestId) ()
// Tell 'em what they've won, Johnny! SmallGroupId = group.Id
let toWhom = UserId = usr.Id
match m.sendToClass with RequestType = (Option.get >> PrayerRequestType.Parse) model.RequestType
| "N" -> s.["{0} users", s.["PrayerTracker"]].Value Text = requestText
| _ -> s.["Group Members"].Value.ToLower () EnteredDate = now.Date.AtStartOfDayInZone(zone).ToInstant()
let andAdded = match m.addToRequestList with Some x when x -> "and added it to the request list" | _ -> "" UpdatedDate = now.InZoneLeniently(zone).ToInstant() }
addInfo ctx s.["Successfully sent announcement to all {0} {1}", toWhom, s.[andAdded]] // Tell 'em what they've won, Johnny!
return! let toWhom =
viewInfo ctx startTicks if model.SendToClass = "N" then s["{0} users", s["PrayerTracker"]].Value
|> Views.SmallGroup.announcementSent { m with text = htmlText } else s["Group Members"].Value.ToLower()
let andAdded = match model.AddToRequestList with Some x when x -> "and added it to the request list" | _ -> ""
addInfo ctx s["Successfully sent announcement to all {0} {1}", toWhom, s[andAdded]]
return!
viewInfo ctx
|> Views.SmallGroup.announcementSent { model with Text = htmlText }
|> renderHtml next ctx |> renderHtml next ctx
| Error e -> return! bindError e next ctx | Result.Error e -> return! bindError e next ctx
} }

View File

@@ -1,340 +1,275 @@
module PrayerTracker.Handlers.User module PrayerTracker.Handlers.User
open FSharp.Control.Tasks.V2.ContextInsensitive open System
open Giraffe open Giraffe
open Microsoft.AspNetCore.Html
open Microsoft.AspNetCore.Http open Microsoft.AspNetCore.Http
open Microsoft.AspNetCore.Identity
open PrayerTracker open PrayerTracker
open PrayerTracker.Cookies open PrayerTracker.Data
open PrayerTracker.Entities open PrayerTracker.Entities
open PrayerTracker.ViewModels open PrayerTracker.ViewModels
open PrayerTracker.Views.CommonFunctions
open System
open System.Collections.Generic
open System.Net
open System.Threading.Tasks
/// Set the user's "remember me" cookie #nowarn "44" // The default Rfc2898DeriveBytes is used to identify passwords to be upgraded
let private setUserCookie (ctx : HttpContext) pwHash =
ctx.Response.Cookies.Append (
Key.Cookie.user,
{ Id = (currentUser ctx).userId; GroupId = (currentGroup ctx).smallGroupId; PasswordHash = pwHash }.toPayload(),
autoRefresh)
/// Retrieve a user from the database by password /// Password hashing implementation extending ASP.NET Core's identity implementation
// If the hashes do not match, determine if it matches a previous scheme, and upgrade them if it does [<AutoOpen>]
let private findUserByPassword m (db : AppDbContext) = module Hashing =
task {
match! db.TryUserByEmailAndGroup m.emailAddress m.smallGroupId with open System.Security.Cryptography
| Some u -> open System.Text
match u.salt with
| Some salt -> /// Custom password hasher used to verify and upgrade old password hashes
// Already upgraded; match = success type PrayerTrackerPasswordHasher() =
let pwHash = pbkdf2Hash salt m.password inherit PasswordHasher<User>()
match u.passwordHash = pwHash with
| true -> return Some { u with passwordHash = ""; salt = None; smallGroups = List<UserSmallGroup>() }, pwHash override this.VerifyHashedPassword(user, hashedPassword, providedPassword) =
| _ -> return None, "" if isNull hashedPassword then nullArg (nameof hashedPassword)
| _ -> if isNull providedPassword then nullArg (nameof providedPassword)
// Not upgraded; check against old hash
match u.passwordHash = sha1Hash m.password with let hashBytes = Convert.FromBase64String hashedPassword
| true ->
// Upgrade 'em! match hashBytes[0] with
let salt = Guid.NewGuid () | 255uy ->
let pwHash = pbkdf2Hash salt m.password // v2 hashes - PBKDF2 (RFC 2898), 1,024 rounds
let upgraded = { u with salt = Some salt; passwordHash = pwHash } if hashBytes.Length < 49 then PasswordVerificationResult.Failed
db.UpdateEntry upgraded else
let! _ = db.SaveChangesAsync () let v2Hash =
return Some { u with passwordHash = ""; salt = None; smallGroups = List<UserSmallGroup>() }, pwHash use alg = new Rfc2898DeriveBytes (
| _ -> return None, "" providedPassword, Encoding.UTF8.GetBytes ((Guid hashBytes[1..16]).ToString "N"), 1024)
| _ -> return None, "" (alg.GetBytes >> Convert.ToBase64String) 64
} if Encoding.UTF8.GetString hashBytes[17..] = v2Hash then
PasswordVerificationResult.SuccessRehashNeeded
else PasswordVerificationResult.Failed
| 254uy ->
// v1 hashes - SHA-1
let v1Hash =
use alg = SHA1.Create()
alg.ComputeHash (Encoding.ASCII.GetBytes providedPassword)
|> Seq.map (fun byt -> byt.ToString "x2")
|> String.concat ""
if Encoding.UTF8.GetString hashBytes[1..] = v1Hash then
PasswordVerificationResult.SuccessRehashNeeded
else
PasswordVerificationResult.Failed
| _ -> base.VerifyHashedPassword(user, hashedPassword, providedPassword)
/// POST /user/password/change /// Retrieve a user from the database by password, upgrading password hashes if required
let changePassword : HttpHandler = let private findUserByPassword model = task {
requireAccess [ User ] match! Users.tryByEmailAndGroup model.Email (idFromShort SmallGroupId model.SmallGroupId) with
>=> validateCSRF | Some user ->
>=> fun next ctx -> let hasher = PrayerTrackerPasswordHasher()
task { match hasher.VerifyHashedPassword(user, user.PasswordHash, model.Password) with
let! result = ctx.TryBindFormAsync<ChangePassword> () | PasswordVerificationResult.Success -> return Some user
match result with | PasswordVerificationResult.SuccessRehashNeeded ->
| Ok m -> let upgraded = { user with PasswordHash = hasher.HashPassword(user, model.Password) }
let s = Views.I18N.localizer.Force () do! Users.updatePassword upgraded
let db = ctx.dbContext () return Some upgraded
let curUsr = currentUser ctx | _ -> return None
let! dbUsr = db.TryUserById curUsr.userId | None -> return None
let! user = }
match dbUsr with
/// Return a default URL if the given URL is non-local or otherwise questionable
let sanitizeUrl providedUrl defaultUrl =
let url = match defaultArg providedUrl "" with "" -> defaultUrl | it -> it
if url.IndexOf "\\" >= 0 || url.IndexOf "//" >= 0 then defaultUrl
elif Seq.exists Char.IsControl url then defaultUrl
else url
// POST /user/password/change
let changePassword : HttpHandler = requireAccess [ User ] >=> validateCsrf >=> fun next ctx -> task {
match! ctx.TryBindFormAsync<ChangePassword>() with
| Ok model ->
let curUsr = ctx.Session.CurrentUser.Value
let hasher = PrayerTrackerPasswordHasher()
let! user = task {
match! Users.tryById curUsr.Id with
| Some usr -> | Some usr ->
// Check the old password against a possibly non-salted hash if hasher.VerifyHashedPassword(usr, usr.PasswordHash, model.OldPassword)
(match usr.salt with | Some salt -> pbkdf2Hash salt | _ -> sha1Hash) m.oldPassword = PasswordVerificationResult.Success then
|> db.TryUserLogOnByCookie curUsr.userId (currentGroup ctx).smallGroupId return Some usr
| _ -> Task.FromResult None else return None
match user with | _ -> return None
| Some _ when m.newPassword = m.newPasswordConfirm -> }
match dbUsr with match user with
| Some usr -> | Some usr when model.NewPassword = model.NewPasswordConfirm ->
// Generate salt if it has not been already do! Users.updatePassword { usr with PasswordHash = hasher.HashPassword(usr, model.NewPassword) }
let salt = match usr.salt with Some s -> s | _ -> Guid.NewGuid () addInfo ctx ctx.Strings["Your password was changed successfully"]
db.UpdateEntry { usr with passwordHash = pbkdf2Hash salt m.newPassword; salt = Some salt } return! redirectTo false "/" next ctx
let! _ = db.SaveChangesAsync () | Some _ ->
// If the user is remembered, update the cookie with the new hash addError ctx ctx.Strings["The new passwords did not match - your password was NOT changed"]
match ctx.Request.Cookies.Keys.Contains Key.Cookie.user with return! redirectTo false "/user/password" next ctx
| true -> setUserCookie ctx usr.passwordHash | None ->
| _ -> () addError ctx ctx.Strings["The old password was incorrect - your password was NOT changed"]
addInfo ctx s.["Your password was changed successfully"] return! redirectTo false "/user/password" next ctx
| None -> addError ctx s.["Unable to change password"] | Result.Error e -> return! bindError e next ctx
return! redirectTo false "/web/" next ctx }
| Some _ ->
addError ctx s.["The new passwords did not match - your password was NOT changed"]
return! redirectTo false "/web/user/password" next ctx
| None ->
addError ctx s.["The old password was incorrect - your password was NOT changed"]
return! redirectTo false "/web/user/password" next ctx
| Error e -> return! bindError e next ctx
}
// POST /user/[user-id]/delete
let delete usrId : HttpHandler = requireAccess [ Admin ] >=> validateCsrf >=> fun next ctx -> task {
let userId = UserId usrId
match! Users.tryById userId with
| Some user ->
do! Users.deleteById userId
addInfo ctx ctx.Strings["Successfully deleted user {0}", user.Name]
return! redirectTo false "/users" next ctx
| _ -> return! fourOhFour ctx
}
/// POST /user/[user-id]/delete open System.Net
let delete userId : HttpHandler = open System.Security.Claims
requireAccess [ Admin ] open Microsoft.AspNetCore.Authentication
>=> validateCSRF open Microsoft.AspNetCore.Authentication.Cookies
>=> fun next ctx -> open Microsoft.AspNetCore.Html
task {
let db = ctx.dbContext ()
let! user = db.TryUserById userId
match user with
| Some u ->
db.RemoveEntry u
let! _ = db.SaveChangesAsync ()
let s = Views.I18N.localizer.Force ()
addInfo ctx s.["Successfully deleted user {0}", u.fullName]
return! redirectTo false "/web/users" next ctx
| _ -> return! fourOhFour next ctx
}
// POST /user/log-on
let doLogOn : HttpHandler = requireAccess [ AccessLevel.Public ] >=> validateCsrf >=> fun next ctx -> task {
match! ctx.TryBindFormAsync<UserLogOn>() with
| Ok model ->
let s = ctx.Strings
match! findUserByPassword model with
| Some user ->
match! SmallGroups.tryById (idFromShort SmallGroupId model.SmallGroupId) with
| Some group ->
ctx.Session.CurrentUser <- Some user
ctx.Session.CurrentGroup <- Some group
let identity = ClaimsIdentity(
seq {
Claim(ClaimTypes.NameIdentifier, shortGuid user.Id.Value)
Claim(ClaimTypes.GroupSid, shortGuid group.Id.Value)
}, CookieAuthenticationDefaults.AuthenticationScheme)
do! ctx.SignInAsync(
identity.AuthenticationType, ClaimsPrincipal identity,
AuthenticationProperties(
IssuedUtc = DateTimeOffset.UtcNow,
IsPersistent = defaultArg model.RememberMe false))
do! Users.updateLastSeen user.Id ctx.Now
addHtmlInfo ctx s["Log On Successful Welcome to {0}", s["PrayerTracker"]]
return! redirectTo false (sanitizeUrl model.RedirectUrl "/small-group") next ctx
| None -> return! fourOhFour ctx
| None ->
{ UserMessage.error with
Text = htmlLocString s["Invalid credentials - log on unsuccessful"]
Description =
let detail =
[ "This is likely due to one of the following reasons:<ul>"
"<li>The e-mail address “{0}” is invalid.</li>"
"<li>The password entered does not match the password for the given e-mail address.</li>"
"<li>You are not authorized to administer the selected group.</li></ul>" ]
|> String.concat ""
Some (HtmlString(s[detail, WebUtility.HtmlEncode model.Email].Value)) }
|> addUserMessage ctx
return! redirectTo false "/user/log-on" next ctx
| Result.Error e -> return! bindError e next ctx
}
/// POST /user/log-on // GET /user/[user-id]/edit
let doLogOn : HttpHandler = let edit usrId : HttpHandler = requireAccess [ Admin ] >=> fun next ctx -> task {
requireAccess [ AccessLevel.Public ] let userId = UserId usrId
>=> validateCSRF if userId.Value = Guid.Empty then
>=> fun next ctx -> return!
task { viewInfo ctx
let! result = ctx.TryBindFormAsync<UserLogOn> ()
match result with
| Ok m ->
let db = ctx.dbContext ()
let s = Views.I18N.localizer.Force ()
let! usr, pwHash = findUserByPassword m db
let! grp = db.TryGroupById m.smallGroupId
let nextUrl =
match usr with
| Some _ ->
ctx.Session.SetUser usr
ctx.Session.SetSmallGroup grp
match m.rememberMe with Some x when x -> setUserCookie ctx pwHash | _ -> ()
addHtmlInfo ctx s.["Log On Successful Welcome to {0}", s.["PrayerTracker"]]
match m.redirectUrl with
| None -> "/web/small-group"
| Some x when x = "" -> "/web/small-group"
| Some x -> x
| _ ->
let grpName = match grp with Some g -> g.name | _ -> "N/A"
{ UserMessage.Error with
text = htmlLocString s.["Invalid credentials - log on unsuccessful"]
description =
[ s.["This is likely due to one of the following reasons"].Value
":<ul><li>"
s.["The e-mail address “{0}” is invalid.", WebUtility.HtmlEncode m.emailAddress].Value
"</li><li>"
s.["The password entered does not match the password for the given e-mail address."].Value
"</li><li>"
s.["You are not authorized to administer the group “{0}”.", WebUtility.HtmlEncode grpName].Value
"</li></ul>"
]
|> String.concat ""
|> (HtmlString >> Some)
}
|> addUserMessage ctx
"/web/user/log-on"
return! redirectTo false nextUrl next ctx
| Error e -> return! bindError e next ctx
}
/// GET /user/[user-id]/edit
let edit (userId : UserId) : HttpHandler =
requireAccess [ Admin ]
>=> fun next ctx ->
let startTicks = DateTime.Now.Ticks
task {
match userId = Guid.Empty with
| true ->
return!
viewInfo ctx startTicks
|> Views.User.edit EditUser.empty ctx |> Views.User.edit EditUser.empty ctx
|> renderHtml next ctx |> renderHtml next ctx
| false -> else
let! user = ctx.dbContext().TryUserById userId match! Users.tryById userId with
match user with | Some user ->
| Some u -> return!
return! viewInfo ctx
viewInfo ctx startTicks |> Views.User.edit (EditUser.fromUser user) ctx
|> Views.User.edit (EditUser.fromUser u) ctx
|> renderHtml next ctx |> renderHtml next ctx
| _ -> return! fourOhFour next ctx | _ -> return! fourOhFour ctx
} }
// GET /user/log-on
/// GET /user/log-on let logOn : HttpHandler = requireAccess [ AccessLevel.Public ] >=> fun next ctx -> task {
let logOn : HttpHandler = let! groups = SmallGroups.listAll ()
requireAccess [ AccessLevel.Public ] let url = Option.ofObj <| ctx.Session.GetString Key.Session.redirectUrl
>=> fun next ctx -> match url with
let startTicks = DateTime.Now.Ticks | Some _ ->
let s = Views.I18N.localizer.Force () ctx.Session.Remove Key.Session.redirectUrl
task { addWarning ctx ctx.Strings["The page you requested requires authentication; please log on below."]
let! groups = ctx.dbContext().GroupList () | None -> ()
let url = Option.ofObj <| ctx.Session.GetString Key.Session.redirectUrl return!
match url with { viewInfo ctx with HelpLink = Some Help.logOn }
| Some _ -> |> Views.User.logOn { UserLogOn.empty with RedirectUrl = url } groups ctx
ctx.Session.Remove Key.Session.redirectUrl
addWarning ctx s.["The page you requested requires authentication; please log on below."]
| None -> ()
return!
{ viewInfo ctx startTicks with helpLink = Some Help.logOn }
|> Views.User.logOn { UserLogOn.empty with redirectUrl = url } groups ctx
|> renderHtml next ctx |> renderHtml next ctx
} }
// GET /users
/// GET /users let maintain : HttpHandler = requireAccess [ Admin ] >=> fun next ctx -> task {
let maintain : HttpHandler = let! users = Users.all ()
requireAccess [ Admin ] return!
>=> fun next ctx -> viewInfo ctx
let startTicks = DateTime.Now.Ticks
task {
let! users = ctx.dbContext().AllUsers ()
return!
viewInfo ctx startTicks
|> Views.User.maintain users ctx |> Views.User.maintain users ctx
|> renderHtml next ctx |> renderHtml next ctx
} }
// GET /user/password
/// GET /user/password let password : HttpHandler = requireAccess [ User ] >=> fun next ctx ->
let password : HttpHandler = { viewInfo ctx with HelpLink = Some Help.changePassword }
requireAccess [ User ]
>=> fun next ctx ->
{ viewInfo ctx DateTime.Now.Ticks with helpLink = Some Help.changePassword }
|> Views.User.changePassword ctx |> Views.User.changePassword ctx
|> renderHtml next ctx |> renderHtml next ctx
open System.Threading.Tasks
/// POST /user/save // POST /user/save
let save : HttpHandler = let save : HttpHandler = requireAccess [ Admin ] >=> validateCsrf >=> fun next ctx -> task {
requireAccess [ Admin ] match! ctx.TryBindFormAsync<EditUser>() with
>=> validateCSRF | Ok model ->
>=> fun next ctx -> let! user =
task { if model.IsNew then Task.FromResult(Some { User.Empty with Id = (Guid.NewGuid >> UserId) () })
let! result = ctx.TryBindFormAsync<EditUser> () else Users.tryById (idFromShort UserId model.UserId)
match result with match user with
| Ok m -> | Some usr ->
let db = ctx.dbContext () let hasher = PrayerTrackerPasswordHasher()
let! user = let updatedUser = model.PopulateUser usr (fun pw -> hasher.HashPassword(usr, pw))
match m.isNew () with do! Users.save updatedUser
| true -> Task.FromResult (Some { User.empty with userId = Guid.NewGuid () }) let s = ctx.Strings
| false -> db.TryUserById m.userId if model.IsNew then
let saltedUser = let h = CommonFunctions.htmlString
match user with { UserMessage.info with
| Some u -> Text = h s["Successfully {0} user", s["Added"].Value.ToLower ()]
match u.salt with Description =
| None when m.password <> "" -> h s["Please select at least one group for which this user ({0}) is authorized",
// Generate salt so that a new password hash can be generated updatedUser.Name]
Some { u with salt = Some (Guid.NewGuid ()) } |> Some }
| _ -> |> addUserMessage ctx
// Leave the user with no salt, so prior hash can be validated/upgraded return! redirectTo false $"/user/{shortGuid usr.Id.Value}/small-groups" next ctx
user else
| _ -> user addInfo ctx s["Successfully {0} user", s["Updated"].Value.ToLower ()]
match saltedUser with return! redirectTo false "/users" next ctx
| Some u -> | None -> return! fourOhFour ctx
m.populateUser u (pbkdf2Hash (Option.get u.salt)) | Result.Error e -> return! bindError e next ctx
|> (match m.isNew () with true -> db.AddEntry | false -> db.UpdateEntry) }
let! _ = db.SaveChangesAsync ()
let s = Views.I18N.localizer.Force ()
match m.isNew () with
| true ->
let h = CommonFunctions.htmlString
{ UserMessage.Info with
text = h s.["Successfully {0} user", s.["Added"].Value.ToLower ()]
description =
h s.[ "Please select at least one group for which this user ({0}) is authorized", u.fullName]
|> Some
}
|> addUserMessage ctx
return! redirectTo false (sprintf "/web/user/%s/small-groups" (flatGuid u.userId)) next ctx
| false ->
addInfo ctx s.["Successfully {0} user", s.["Updated"].Value.ToLower ()]
return! redirectTo false "/web/users" next ctx
| None -> return! fourOhFour next ctx
| Error e -> return! bindError e next ctx
}
// POST /user/small-groups/save
let saveGroups : HttpHandler = requireAccess [ Admin ] >=> validateCsrf >=> fun next ctx -> task {
match! ctx.TryBindFormAsync<AssignGroups>() with
| Ok model ->
match Seq.length model.SmallGroups with
| 0 ->
addError ctx ctx.Strings["You must select at least one group to assign"]
return! redirectTo false $"/user/{model.UserId}/small-groups" next ctx
| _ ->
do! Users.updateSmallGroups (idFromShort UserId model.UserId)
(model.SmallGroups.Split ',' |> Array.map (idFromShort SmallGroupId) |> List.ofArray)
addInfo ctx ctx.Strings["Successfully updated group permissions for {0}", model.UserName]
return! redirectTo false "/users" next ctx
| Result.Error e -> return! bindError e next ctx
}
/// POST /user/small-groups/save // GET /user/[user-id]/small-groups
let saveGroups : HttpHandler = let smallGroups usrId : HttpHandler = requireAccess [ Admin ] >=> fun next ctx -> task {
requireAccess [ Admin ] let userId = UserId usrId
>=> validateCSRF match! Users.tryById userId with
>=> fun next ctx -> | Some user ->
task { let! groups = SmallGroups.listAll ()
let! result = ctx.TryBindFormAsync<AssignGroups> () let groupIds = user.SmallGroups
match result with let curGroups = groupIds |> List.map (fun g -> shortGuid g.Value)
| Ok m -> return!
let s = Views.I18N.localizer.Force () viewInfo ctx
match Seq.length m.smallGroups with |> Views.User.assignGroups (AssignGroups.fromUser user) groups curGroups ctx
| 0 ->
addError ctx s.["You must select at least one group to assign"]
return! redirectTo false (sprintf "/web/user/%s/small-groups" (flatGuid m.userId)) next ctx
| _ ->
let db = ctx.dbContext ()
let! user = db.TryUserByIdWithGroups m.userId
match user with
| Some u ->
let grps =
m.smallGroups.Split ','
|> Array.map Guid.Parse
|> List.ofArray
u.smallGroups
|> Seq.filter (fun x -> not (grps |> List.exists (fun y -> y = x.smallGroupId)))
|> db.UserGroupXref.RemoveRange
grps
|> Seq.ofList
|> Seq.filter (fun x -> not (u.smallGroups |> Seq.exists (fun y -> y.smallGroupId = x)))
|> Seq.map (fun x -> { UserSmallGroup.empty with userId = u.userId; smallGroupId = x })
|> List.ofSeq
|> List.iter db.AddEntry
let! _ = db.SaveChangesAsync ()
addInfo ctx s.["Successfully updated group permissions for {0}", m.userName]
return! redirectTo false "/web/users" next ctx
| _ -> return! fourOhFour next ctx
| Error e -> return! bindError e next ctx
}
/// GET /user/[user-id]/small-groups
let smallGroups userId : HttpHandler =
requireAccess [ Admin ]
>=> fun next ctx ->
let startTicks = DateTime.Now.Ticks
let db = ctx.dbContext ()
task {
let! user = db.TryUserByIdWithGroups userId
match user with
| Some u ->
let! grps = db.GroupList ()
let curGroups = u.smallGroups |> Seq.map (fun g -> flatGuid g.smallGroupId) |> List.ofSeq
return!
viewInfo ctx startTicks
|> Views.User.assignGroups (AssignGroups.fromUser u) grps curGroups ctx
|> renderHtml next ctx |> renderHtml next ctx
| None -> return! fourOhFour next ctx | None -> return! fourOhFour ctx
} }

View File

View File

@@ -1,11 +1,20 @@
/** /**
* This is the main stylesheet for the PrayerTracker application. * This is the main stylesheet for the PrayerTracker application.
*/ */
:root {
--dark-blue-hue: 240;
--dark-blue-sat: 100%;
--darkest: hsl(var(--dark-blue-hue), var(--dark-blue-sat), 6%);
--dark: hsl(var(--dark-blue-hue), var(--dark-blue-sat), 13%);
--lighter-dark: hsl(var(--dark-blue-hue), var(--dark-blue-sat), 25%);
--inverse-backgroud: hsl(0, 0%, 95%);
--background: hsla(0, 0%, 0%, .01);
--native-fonts: system-ui,-apple-system,"Segoe UI",Roboto,Ubuntu,"Liberation Sans",Cantarell,"Helvetica Neue",sans-serif;
}
body { body {
background-color: #222; background-color: var(--background);
margin: 0; margin: 0;
margin-bottom: 25px; font-family: var(--native-fonts);
font-family: -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Oxygen-Sans,Ubuntu,Cantarell,"Helvetica Neue",sans-serif;
font-size: 1rem; font-size: 1rem;
} }
acronym { acronym {
@@ -18,10 +27,10 @@ a,
a:link, a:link,
a:visited { a:visited {
text-decoration: none; text-decoration: none;
color: navy; color: var(--dark);
} }
a:hover { a:hover {
border-bottom: dotted 1px navy; border-bottom: dotted 1px var(--darkest);
} }
a > img { a > img {
border: 0; border: 0;
@@ -32,7 +41,7 @@ a > img {
justify-content: space-between; justify-content: space-between;
overflow: hidden; overflow: hidden;
width: 100%; width: 100%;
background-image: linear-gradient(to bottom, #222, #444); background-image: linear-gradient(to bottom, var(--darkest), var(--dark));
margin-bottom: 0; margin-bottom: 0;
} }
.pt-title-bar-left, .pt-title-bar-left,
@@ -46,7 +55,7 @@ a > img {
float: left; float: left;
font-size: 1.25rem; font-size: 1.25rem;
font-weight: bold; font-weight: bold;
padding: .5rem 1rem 0 1rem; padding: .5rem 1rem 0 .75rem;
} }
.pt-title-bar-home a:link, .pt-title-bar-home a:link,
.pt-title-bar-home a:visited { .pt-title-bar-home a:visited {
@@ -65,7 +74,7 @@ a > img {
float: left; float: left;
} }
.pt-title-bar li a, .pt-title-bar li a,
.pt-title-bar .dropbtn, .pt-title-bar .dropdown-btn,
.pt-title-bar .home-link { .pt-title-bar .home-link {
display: inline-block; display: inline-block;
color: #9d9d9d; color: #9d9d9d;
@@ -77,7 +86,7 @@ a > img {
font-size: 1.1rem; font-size: 1.1rem;
} }
.pt-title-bar li a:hover, .pt-title-bar li a:hover,
.pt-title-bar .dropdown:hover .dropbtn { .pt-title-bar .dropdown:hover .dropdown-btn {
color: white; color: white;
border-bottom: none; border-bottom: none;
} }
@@ -87,7 +96,7 @@ a > img {
.pt-title-bar .dropdown-content { .pt-title-bar .dropdown-content {
display: none; display: none;
position: absolute; position: absolute;
background-image: linear-gradient(to bottom, #444, #888); background-image: linear-gradient(to bottom, var(--dark), var(--lighter-dark));
min-width: 160px; min-width: 160px;
box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2); box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2);
z-index: 1; z-index: 1;
@@ -100,14 +109,14 @@ a > img {
text-align: left; text-align: left;
} }
.pt-title-bar .dropdown-content a:hover { .pt-title-bar .dropdown-content a:hover {
background-color: #222; background-color: var(--inverse-backgroud);
color: var(--lighter-dark);
} }
.pt-title-bar .dropdown:hover .dropdown-content { .pt-title-bar .dropdown:hover .dropdown-content {
display: block; display: block;
} }
#pt-body { #pt-body {
background-color: #fcfcfc; padding-bottom: 1rem;
padding-bottom: 10px;
} }
#pt-language { #pt-language {
background-color: lightgray; background-color: lightgray;
@@ -116,74 +125,84 @@ a > img {
justify-content: space-between; justify-content: space-between;
border-bottom: solid 1px darkgray; border-bottom: solid 1px darkgray;
border-top: solid 1px darkgray; border-top: solid 1px darkgray;
padding: 0 .75rem;
} }
#pt-page-title { #pt-page-title {
text-align: center; text-align: center;
border-bottom: dotted 1px lightgray; border-bottom: dotted 1px lightgray;
} }
.pt-content { .pt-content {
margin: auto; margin: auto auto 1.5rem auto;
max-width: 60rem; max-width: 60rem;
} }
.pt-content.pt-full-width { .pt-content.pt-full-width {
max-width: unset; max-width: unset;
margin-left: .5%; margin-left: .75rem;
margin-right: .5%; margin-right: .75rem;
} }
@media screen and (max-width: 60rem) { @media screen and (max-width: 60rem) {
.pt-content { .pt-content {
margin-left: .5%; margin-left: .75rem;
margin-right: .5%; margin-right: .75rem;
} }
} }
fieldset { fieldset {
margin: auto; margin: auto auto 1rem auto;
border: solid 1px #ccc; border: solid 1px #ccc;
border-radius: 1rem; border-radius: 1rem;
margin-bottom: 1rem;
} }
input[type=email], input[type=email],
input[type=text], input[type=text],
input[type=password], input[type=password],
input[type=date], input[type=date],
input[type=number], input[type=number],
input[type=url],
select { select {
border-radius: 5px; border-radius: .2rem;
border-color: var(--lighter-dark);
font-size: 1rem; font-size: 1rem;
padding: .2rem; padding: .25rem;
font-family: -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Oxygen-Sans,Ubuntu,Cantarell,"Helvetica Neue",sans-serif; font-family: var(--native-fonts);
} border-width: 1px;
input:nth-of-type(2) {
margin-left: 2rem;
} }
button[type=submit] { button[type=submit] {
border-radius: 10px; border-radius: .6rem;
padding: .2rem 1rem; padding: .2rem 1rem;
margin-top: .5rem; margin-top: .5rem;
background-color: #444; background-color: var(--lighter-dark);
border: none; border: solid 1px var(--lighter-dark);
color: white; color: white;
} }
button[type=submit]:hover { button[type=submit]:hover {
background-color: #222; color: var(--lighter-dark);
cursor:pointer; background-color: var(--inverse-backgroud);
cursor: pointer;
} }
footer { footer.pt-footer {
position: fixed; position: fixed;
bottom: 0; bottom: 0;
width: 100%; width: 100%;
border-bottom: solid 10px #222; padding-top: .5rem;
background-image: linear-gradient(to bottom, var(--background), var(--darkest));
display: flex;
flex-flow: row wrap;
justify-content: space-between;
align-items: end;
} }
#pt-legal { #pt-legal {
background-color: #222; padding-left: .75rem;
margin: 0 0 -30px 0;
padding-left: 10px;
} }
#pt-legal a:link, #pt-legal a:link,
#pt-legal a:visited { #pt-legal a:visited {
color: lightgray; color: white;
color: rgba(255, 255, 255, .5);
font-size: 10pt; font-size: 10pt;
background-color: var(--darkest);
padding: 0 .5rem;
border-top-left-radius: .5rem;
border-top-right-radius: .5rem;
}
#pt-legal a:hover {
background-color: var(--lighter-dark);
} }
#pt-footer { #pt-footer {
border: solid 2px navy; border: solid 2px navy;
@@ -191,15 +210,18 @@ footer {
border-top-left-radius: 7px; border-top-left-radius: 7px;
border-top-right-radius: 7px; border-top-right-radius: 7px;
padding: 2px 5px 0 5px; padding: 2px 5px 0 5px;
margin: 0 10px -11px auto; margin-right: .75rem;
font-size: 70%; font-size: 70%;
color: navy; color: navy;
background-color: #eee; background-color: #eee;
float:right; }
#pt-footer img,
#pt-footer span,
#pt-footer i {
vertical-align: bottom; vertical-align: bottom;
} }
#pt-footer img { #pt-version {
vertical-align: bottom; padding-left: .25rem;
} }
footer a:hover { footer a:hover {
border-bottom: 0; border-bottom: 0;
@@ -214,6 +236,7 @@ footer a:hover {
flex-flow: row wrap; flex-flow: row wrap;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
gap: 2rem;
} }
.pt-field { .pt-field {
display: flex; display: flex;
@@ -231,8 +254,11 @@ footer a:hover {
text-transform: uppercase; text-transform: uppercase;
color: #777; color: #777;
} }
.pt-field ~ .pt-field { .pt-group {
margin-left: 3rem; display: flex;
flex-flow: row;
gap: 1.5rem;
align-items: baseline;
} }
.pt-center-text { .pt-center-text {
text-align: center; text-align: center;
@@ -240,37 +266,49 @@ footer a:hover {
.pt-right-text { .pt-right-text {
text-align: right; text-align: right;
} }
.pt-table { .pt-table {
margin: auto; display: grid;
border-collapse: collapse; justify-content: center;
} }
.pt-table tr:hover { .pt-table .row.head,
.pt-table .row {
display: contents;
}
.pt-table .row:hover > * {
background-color: #eee; background-color: #eee;
} }
.pt-table tr th, .pt-table .row.head .cell {
.pt-table tr td { background-image: linear-gradient(to bottom, var(--dark), var(--lighter-dark));
font-weight: bold;
color: white;
text-align: center;
font-size: .85rem;
}
.pt-table .row.head .cell:first-of-type {
border-top-left-radius: .5rem;
}
.pt-table .row.head .cell:last-of-type {
border-top-right-radius: .5rem;
}
.pt-table .cell {
padding: .25rem .5rem; padding: .25rem .5rem;
border-bottom: dotted 1px var(--lighter-dark);
} }
.pt-table tr td { .pt-table .cell.actions {
border-bottom: dotted 1px #444; border-bottom-color: var(--background);
} }
.pt-action-table tr td:first-child { .pt-table .cell.actions a {
white-space: nowrap; background-color: gray;
border-bottom: 0;
}
.pt-action-table tr td:first-child a {
background-color: lightgray;
color: white; color: white;
border-radius: .5rem; border-radius: .5rem;
padding: .125rem .5rem .5rem .5rem; padding: 0 .5rem .25rem;
margin: 0 .125rem; margin: 0 .125rem;
} }
.pt-action-table tr:hover td:first-child a { .pt-table .row:hover .cell.actions a {
background-color: navy; background-color: var(--dark);
}
.pt-action-table tr td:first-child a:hover {
border-bottom: 0;
} }
/* TODO: Figure out nice CSS transitions for these; these don't work */ /* TODO: Figure out nice CSS transitions for these; these don't work */
.pt-fadeable { .pt-fadeable {
height: 0; height: 0;
@@ -300,7 +338,7 @@ article.pt-overview section header {
text-align: center; text-align: center;
border-top-left-radius: 1rem; border-top-left-radius: 1rem;
border-top-right-radius: 1rem; border-top-right-radius: 1rem;
background-image: linear-gradient(to bottom, #444, #888); background-image: linear-gradient(to bottom, var(--dark), var(--lighter-dark));
padding: .5rem 1rem; padding: .5rem 1rem;
color: white; color: white;
} }
@@ -308,7 +346,7 @@ article.pt-overview section div {
padding: .5rem; padding: .5rem;
} }
article.pt-overview section div hr { article.pt-overview section div hr {
color: #444; color: var(--dark);
margin: .5rem -.5rem; margin: .5rem -.5rem;
} }
article.pt-overview section div p { article.pt-overview section div p {
@@ -317,6 +355,12 @@ article.pt-overview section div p {
.pt-editor { .pt-editor {
width: 100%; width: 100%;
} }
.pt-messages {
display: flex;
flex-flow: column;
justify-content: center;
align-items: center;
}
.pt-msg { .pt-msg {
margin: .5rem auto; margin: .5rem auto;
border-top-right-radius: .5rem; border-top-right-radius: .5rem;
@@ -324,15 +368,12 @@ article.pt-overview section div p {
border-width: 2px; border-width: 2px;
border-style: solid; border-style: solid;
border-collapse: inherit; border-collapse: inherit;
padding: 5px 30px;
text-align: center;
} }
.pt-msg ul { .pt-msg ul {
text-align: left; text-align: left;
} }
.pt-msg td {
padding: 5px 30px;
margin-bottom: 2px;
text-align: center;
}
.pt-msg.error { .pt-msg.error {
background-color: #ffb6c1; background-color: #ffb6c1;
border-color: #ff0000; border-color: #ff0000;
@@ -399,6 +440,9 @@ article.pt-overview section div p {
.material-icons { .material-icons {
vertical-align: middle; vertical-align: middle;
} }
.pt-help-link {
padding-right: .25rem;
}
#pt-help { #pt-help {
background-color: #fcfcfc; background-color: #fcfcfc;
} }

View File

@@ -2,28 +2,14 @@
* This file contains a library of common functions used throughout the PrayerTracker website, as well as specific * This file contains a library of common functions used throughout the PrayerTracker website, as well as specific
* functions used on pages throughout the site. * functions used on pages throughout the site.
*/ */
const PT = { this.PT = {
/** /**
* Open a window with help * Open a window with help
* @param {string} url The URL for the help page. * @param {string} url The URL for the help page.
*/ */
showHelp(url) { showHelp(url) {
window.open(url, 'helpWindow', 'height=600px,width=450px,toolbar=0,menubar=0,scrollbars=1') window.open(url, "helpWindow", "height=600px,width=450px,toolbar=0,menubar=0,scrollbars=1")
return false
},
/**
* Confirm, then submit a delete action
* @param {string} action The URL for the action attribute of the delete form.
* @param {string} prompt The localized prompt for confirmation.
*/
confirmDelete(action, prompt) {
if (confirm(prompt)) {
let form = document.querySelector('#DeleteForm')
form.setAttribute('action', action)
form.submit()
}
return false return false
}, },
@@ -36,14 +22,6 @@ const PT = {
.forEach(f => document.getElementById(f).required = true) .forEach(f => document.getElementById(f).required = true)
}, },
/**
* Queue an action to occur when the DOM content is loaded
* @param {Function} func The function to run once the DOM content is loaded
*/
onLoad(func) {
document.addEventListener('DOMContentLoaded', func)
},
/** /**
* Validation that compares the values of 2 fields and fails if they do not match * Validation that compares the values of 2 fields and fails if they do not match
* @param {string} field1 The ID of the first field * @param {string} field1 The ID of the first field
@@ -55,7 +33,7 @@ const PT = {
const field1Value = document.getElementById(field1).value const field1Value = document.getElementById(field1).value
const field2Element = document.getElementById(field2) const field2Element = document.getElementById(field2)
if (field1Value === field2Element.value) { if (field1Value === field2Element.value) {
field2Element.setCustomValidity('') field2Element.setCustomValidity("")
return true return true
} }
field2Element.setCustomValidity(errorMsg) field2Element.setCustomValidity(errorMsg)
@@ -67,8 +45,8 @@ const PT = {
* @param {HTMLElement} div The div to be shown * @param {HTMLElement} div The div to be shown
*/ */
showDiv(div) { showDiv(div) {
if (div.className.indexOf(' pt-shown') === -1) { if (div.className.indexOf(" pt-shown") === -1) {
div.className += ' pt-shown' div.className += " pt-shown"
} }
}, },
@@ -77,7 +55,7 @@ const PT = {
* @param {HTMLElement} div The div to be hidden * @param {HTMLElement} div The div to be hidden
*/ */
hideDiv(div) { hideDiv(div) {
div.className = div.className.replace(' pt-shown', '') div.className = div.className.replace(" pt-shown", "")
}, },
/** /**
@@ -85,10 +63,18 @@ const PT = {
*/ */
initCKEditor() { initCKEditor() {
ClassicEditor ClassicEditor
.create(document.querySelector('#text')) .create(document.querySelector("#Text"))
.then(editor => window.ckEditor = editor)
.catch(console.error) .catch(console.error)
}, },
/**
* Instruct the current CKEditor element to update its source (needed as htmx does not fire the submit event)
*/
updateCKEditor() {
window.ckEditor.updateElement()
},
/** /**
* Scripts for pages served by the Church controller * Scripts for pages served by the Church controller
*/ */
@@ -101,9 +87,9 @@ const PT = {
* If the interface box is checked, show and require the interface URL field (if not, well... don't) * If the interface box is checked, show and require the interface URL field (if not, well... don't)
*/ */
checkInterface() { checkInterface() {
const div = document.getElementById('divInterfaceAddress') const div = document.getElementById("divInterfaceAddress")
const addr = document.getElementById('interfaceAddress') const addr = document.getElementById("InterfaceAddress")
if (document.getElementById('hasInterface').checked) { if (document.getElementById("HasInterface").checked) {
PT.showDiv(div) PT.showDiv(div)
addr.required = true addr.required = true
} }
@@ -117,30 +103,12 @@ const PT = {
*/ */
onPageLoad() { onPageLoad() {
PT.church.edit.checkInterface() PT.church.edit.checkInterface()
document.getElementById('hasInterface') document.getElementById("HasInterface")
.addEventListener('click', PT.church.edit.checkInterface) .addEventListener("click", PT.church.edit.checkInterface)
} }
} }
}, },
/**
* Scripts for pages served by the Requests controller
*/
requests: {
/**
* Script for the request view page
*/
view: {
/**
* Prompt the user to remind them that they are about to e-mail their class
* @param {string} confirmationPrompt The text to display to the user
*/
promptBeforeEmail(confirmationPrompt) {
return confirm(confirmationPrompt)
},
},
},
/** /**
* Scripts for pages served by the SmallGroup controller * Scripts for pages served by the SmallGroup controller
*/ */
@@ -154,23 +122,23 @@ const PT = {
*/ */
onPageLoad() { onPageLoad() {
PT.initCKEditor() PT.initCKEditor()
const sendNo = document.getElementById('sendN') const sendNo = document.getElementById("SendToClass_N")
const catDiv = document.getElementById('divCategory') const catDiv = document.getElementById("divCategory")
const catSel = document.getElementById('requestType') const catSel = document.getElementById("RequestType")
const addChk = document.getElementById('addToRequestList') const addChk = document.getElementById("AddToRequestList")
if (sendNo !== 'undefined') { if (sendNo !== "undefined") {
const addDiv = document.getElementById('divAddToList') const addDiv = document.getElementById("divAddToList")
sendNo.addEventListener('click', () => { sendNo.addEventListener("click", () => {
PT.hideDiv(addDiv) PT.hideDiv(addDiv)
PT.hideDiv(catDiv) PT.hideDiv(catDiv)
catSel.required = false catSel.required = false
addChk.checked = false addChk.checked = false
}) })
document.getElementById('sendY').addEventListener('click', () => { document.getElementById("SendToClass_Y").addEventListener("click", () => {
PT.showDiv(addDiv) PT.showDiv(addDiv)
}) })
} }
addChk.addEventListener('click', () => { addChk.addEventListener("click", () => {
if (addChk.checked) { if (addChk.checked) {
PT.showDiv(catDiv) PT.showDiv(catDiv)
catSel.required = true catSel.required = true
@@ -190,11 +158,11 @@ const PT = {
* Determine which field should have the focus * Determine which field should have the focus
*/ */
onPageLoad() { onPageLoad() {
const grp = document.getElementById('SmallGroupId') const grp = document.getElementById("SmallGroupId")
if (grp.options[grp.selectedIndex].value === '') { if (grp.options[grp.selectedIndex].value === '') {
grp.focus() grp.focus()
} else { } else {
document.getElementById('Password').focus() document.getElementById("Password").focus()
} }
} }
}, },
@@ -210,8 +178,8 @@ const PT = {
*/ */
toggleType(name) { toggleType(name) {
const isNamed = document.getElementById(`${name}Type_Name`) const isNamed = document.getElementById(`${name}Type_Name`)
const named = document.getElementById(`${name}Color_Select`) const named = document.getElementById(`${name}_Select`)
const custom = document.getElementById(`${name}Color_Color`) const custom = document.getElementById(`${name}_Color`)
if (isNamed.checked) { if (isNamed.checked) {
custom.disabled = true custom.disabled = true
named.disabled = false named.disabled = false
@@ -225,9 +193,9 @@ const PT = {
* Show or hide the class password based on the visibility. * Show or hide the class password based on the visibility.
*/ */
checkVisibility() { checkVisibility() {
const divPw = document.getElementById('divClassPassword') const divPw = document.getElementById("divClassPassword")
if (document.getElementById('viz_Public').checked if (document.getElementById("Visibility_Public").checked
|| document.getElementById('viz_Private').checked) { || document.getElementById("Visibility_Private").checked) {
// Disable password // Disable password
PT.hideDiv(divPw) PT.hideDiv(divPw)
} else { } else {
@@ -235,24 +203,37 @@ const PT = {
} }
}, },
/**
* Enable or disable the font list based on whether the native font stack is selected or not
*/
checkFonts() {
document.getElementById("Fonts").disabled = document.getElementById("IsNative_Y").checked
},
/** /**
* Bind the event handlers * Bind the event handlers
*/ */
onPageLoad() { onPageLoad() {
['Public', 'Private', 'Password'].map(typ => { ["Public", "Private", "Password"].map(typ => {
document.getElementById(`viz_${typ}`).addEventListener('click', document.getElementById(`Visibility_${typ}`).addEventListener("click",
PT.smallGroup.preferences.checkVisibility) PT.smallGroup.preferences.checkVisibility)
}) })
PT.smallGroup.preferences.checkVisibility() PT.smallGroup.preferences.checkVisibility()
;['headingLine', 'headingText'].map(name => { ;["LineColor", "HeadingColor"].map(name => {
document.getElementById(`${name}Type_Name`).addEventListener('click', () => { document.getElementById(`${name}Type_Name`).addEventListener("click", () => {
PT.smallGroup.preferences.toggleType(name) PT.smallGroup.preferences.toggleType(name)
}) })
document.getElementById(`${name}Type_RGB`).addEventListener('click', () => { document.getElementById(`${name}Type_RGB`).addEventListener("click", () => {
PT.smallGroup.preferences.toggleType(name) PT.smallGroup.preferences.toggleType(name)
}) })
PT.smallGroup.preferences.toggleType(name) PT.smallGroup.preferences.toggleType(name)
}) })
;["Y", "N"].map(name => {
document.getElementById(`IsNative_${name}`).addEventListener("click", () => {
PT.smallGroup.preferences.checkFonts()
})
})
PT.smallGroup.preferences.checkFonts()
}, },
}, },
}, },
@@ -270,9 +251,33 @@ const PT = {
*/ */
onPageLoad(isNew) { onPageLoad(isNew) {
if (isNew) { if (isNew) {
PT.requireFields(['password', 'passwordConfirm']) PT.requireFields(["Password", "PasswordConfirm"])
} }
} }
} }
}, },
} }
htmx.on("htmx:configRequest", function (e) {
e.detail.headers["X-Target"] = e.detail.target
})
htmx.on("htmx:responseError", function (e) {
/** @type {XMLHttpRequest} */
const xhr = e.detail.xhr
const detail = document.createElement("div")
detail.className = "description"
detail.innerHTML = `<em>(Status code ${xhr.status}: ${xhr.statusText})</em>`
const msg = document.createElement("div")
msg.className = "pt-msg error"
msg.innerHTML = `<strong>ERROR</strong> &#xbb; ${xhr.responseText}<br>`
msg.appendChild(detail)
const messages = document.createElement("div")
messages.className = "pt-messages"
messages.appendChild(msg)
const title = document.getElementById("pt-page-title")
title.parentNode.insertBefore(messages, title.nextSibling)
})

View File

@@ -0,0 +1,87 @@
(()=>{
let send = (elt, type, detail, bub)=>elt.dispatchEvent(new CustomEvent("fx:" + type, {detail, cancelable:true, bubbles:bub !== false, composed:true}))
let attr = (elt, name, defaultVal)=>elt.getAttribute(name) || defaultVal
let ignore = (elt)=>elt.matches("[fx-ignore]") || elt.closest("[fx-ignore]") != null
let init = (elt)=>{
let options = {}
if (elt.__fixi || ignore(elt) || !send(elt, "init", {options})) return
elt.__fixi = async(evt)=>{
let reqs = elt.__fixi.requests ||= new Set()
let form = elt.form || elt.closest("form")
let body = new FormData(form ?? undefined, evt.submitter)
if (!form && elt.name) body.append(elt.name, elt.value)
let ac = new AbortController()
let cfg = {
trigger:evt,
action:attr(elt, "fx-action"),
method:attr(elt, "fx-method", "GET").toUpperCase(),
target: document.querySelector(attr(elt, "fx-target")) ?? elt,
swap:attr(elt, "fx-swap", "outerHTML"),
body,
drop:reqs.size,
headers:{"FX-Request":"true"},
abort:ac.abort.bind(ac),
signal:ac.signal,
preventTrigger:true,
transition:document.startViewTransition?.bind(document),
fetch:fetch.bind(window)
}
let go = send(elt, "config", {cfg, requests:reqs})
if (cfg.preventTrigger) evt.preventDefault()
if (!go || cfg.drop) return
if (/GET|DELETE/.test(cfg.method)){
let params = new URLSearchParams(cfg.body)
if (params.size)
cfg.action += (/\?/.test(cfg.action) ? "&" : "?") + params
cfg.body = null
}
reqs.add(cfg)
try {
if (cfg.confirm){
let result = await cfg.confirm()
if (!result) return
}
if (!send(elt, "before", {cfg, requests:reqs})) return
cfg.response = await cfg.fetch(cfg.action, cfg)
cfg.text = await cfg.response.text()
if (!send(elt, "after", {cfg})) return
} catch(error) {
send(elt, "error", {cfg, error})
return
} finally {
reqs.delete(cfg)
send(elt, "finally", {cfg})
}
let doSwap = ()=>{
if (cfg.swap instanceof Function)
return cfg.swap(cfg)
else if (/(before|after)(start|end)/.test(cfg.swap))
cfg.target.insertAdjacentHTML(cfg.swap, cfg.text)
else if(cfg.swap in cfg.target)
cfg.target[cfg.swap] = cfg.text
else throw cfg.swap
}
if (cfg.transition)
await cfg.transition(doSwap).finished
else
await doSwap()
send(elt, "swapped", {cfg})
}
elt.__fixi.evt = attr(elt, "fx-trigger", elt.matches("form") ? "submit" : elt.matches("input:not([type=button]),select,textarea") ? "change" : "click")
elt.addEventListener(elt.__fixi.evt, elt.__fixi, options)
send(elt, "inited", {}, false)
}
let process = (elt)=>{
if (elt instanceof Element){
if (ignore(elt)) return
if (elt.matches("[fx-action]")) init(elt)
elt.querySelectorAll("[fx-action]").forEach(init)
}
}
document.addEventListener("fx:process", (evt)=>process(evt.target))
document.addEventListener("DOMContentLoaded", ()=>{
document.__fixi_mo = new MutationObserver((recs)=>recs.forEach((r)=>r.type === "childList" && r.addedNodes.forEach((n)=>process(n))))
document.__fixi_mo.observe(document.body, {childList:true, subtree:true})
process(document.body)
})
})()

View File

@@ -1,25 +0,0 @@
/**
* PrayerTracker Help styling
*/
.pt-content {
background-color: white;
padding: 0 .25em;
}
.pt-title-bar-left {
color: white;
font-size: 1.25rem;
font-weight: bold;
margin-left: .5rem;
}
.pt-title-bar-right {
color: white;
color: rgba(255, 255, 255, .75);
font-size: 1.1rem;
font-variant: small-caps;
margin-right: 1rem;
}
h2 {
margin-top: 0;
padding-left: .5rem;
border-bottom: solid 1px #444;
}

View File

@@ -0,0 +1,368 @@
module PrayerTracker.Entities.EntitiesTests
open Expecto
open NodaTime.Testing
open NodaTime
open System
[<Tests>]
let asOfDateDisplayTests =
testList "AsOfDateDisplay" [
testList "ToString" [
test "NoDisplay code is correct" {
Expect.equal (string NoDisplay) "N" "The code for NoDisplay should have been \"N\""
}
test "ShortDate code is correct" {
Expect.equal (string ShortDate) "S" "The code for ShortDate should have been \"S\""
}
test "LongDate code is correct" {
Expect.equal (string LongDate) "L" "The code for LongDate should have been \"N\""
}
]
testList "Parse" [
test "N should return NoDisplay" {
Expect.equal (AsOfDateDisplay.Parse "N") NoDisplay "\"N\" should have been parsed to NoDisplay"
}
test "S should return ShortDate" {
Expect.equal (AsOfDateDisplay.Parse "S") ShortDate "\"S\" should have been parsed to ShortDate"
}
test "L should return LongDate" {
Expect.equal (AsOfDateDisplay.Parse "L") LongDate "\"L\" should have been parsed to LongDate"
}
test "X should raise" {
Expect.throws (fun () -> AsOfDateDisplay.Parse "X" |> ignore)
"An unknown code should have raised an exception"
}
]
]
[<Tests>]
let churchTests =
testList "Church" [
test "Empty is as expected" {
let mt = Church.Empty
Expect.equal mt.Id.Value Guid.Empty "The church ID should have been an empty GUID"
Expect.equal mt.Name "" "The name should have been blank"
Expect.equal mt.City "" "The city should have been blank"
Expect.equal mt.State "" "The state should have been blank"
Expect.isFalse mt.HasVpsInterface "The church should not show that it has an interface"
Expect.isNone mt.InterfaceAddress "The interface address should not exist"
}
]
[<Tests>]
let emailFormatTests =
testList "EmailFormat" [
testList "ToString" [
test "HtmlFormat code is correct" {
Expect.equal (string HtmlFormat) "H" "The code for HtmlFormat should have been \"H\""
}
test "PlainTextFormat code is correct" {
Expect.equal (string PlainTextFormat) "P" "The code for PlainTextFormat should have been \"P\""
}
]
testList "Parse" [
test "H should return HtmlFormat" {
Expect.equal (EmailFormat.Parse "H") HtmlFormat "\"H\" should have been converted to HtmlFormat"
}
test "P should return ShortDate" {
Expect.equal (EmailFormat.Parse "P") PlainTextFormat
"\"P\" should have been converted to PlainTextFormat"
}
test "Z should raise" {
Expect.throws (fun () -> EmailFormat.Parse "Z" |> ignore)
"An unknown code should have raised an exception"
}
]
]
[<Tests>]
let expirationTests =
testList "Expiration" [
testList "ToString" [
test "Automatic code is correct" {
Expect.equal (string Automatic) "A" "The code for Automatic should have been \"A\""
}
test "Manual code is correct" {
Expect.equal (string Manual) "M" "The code for Manual should have been \"M\""
}
test "Forced code is correct" {
Expect.equal (string Forced) "F" "The code for Forced should have been \"F\""
}
]
testList "Parse" [
test "A should return Automatic" {
Expect.equal (Expiration.Parse "A") Automatic "\"A\" should have been converted to Automatic"
}
test "M should return Manual" {
Expect.equal (Expiration.Parse "M") Manual "\"M\" should have been converted to Manual"
}
test "F should return Forced" {
Expect.equal (Expiration.Parse "F") Forced "\"F\" should have been converted to Forced"
}
test "fromCode V should raise" {
Expect.throws (fun () -> Expiration.Parse "V" |> ignore)
"An unknown code should have raised an exception"
}
]
]
[<Tests>]
let listPreferencesTests =
testList "ListPreferences" [
test "FontStack is correct for native fonts" {
Expect.equal ListPreferences.Empty.FontStack
"""system-ui,-apple-system,"Segoe UI",Roboto,Ubuntu,"Liberation Sans",Cantarell,"Helvetica Neue",sans-serif"""
"The expected native font stack was incorrect"
}
test "FontStack is correct for specific fonts" {
Expect.equal { ListPreferences.Empty with Fonts = "Arial,sans-serif" }.FontStack "Arial,sans-serif"
"The specified fonts were not returned correctly"
}
test "Empty is as expected" {
let mt = ListPreferences.Empty
Expect.equal mt.DaysToExpire 14 "The default days to expire should have been 14"
Expect.equal mt.DaysToKeepNew 7 "The default days to keep new should have been 7"
Expect.equal mt.LongTermUpdateWeeks 4 "The default long term update weeks should have been 4"
Expect.equal mt.EmailFromName "PrayerTracker" "The default e-mail from name should have been PrayerTracker"
Expect.equal mt.EmailFromAddress "prayer@bitbadger.solutions"
"The default e-mail from address should have been prayer@bitbadger.solutions"
Expect.equal mt.Fonts "native" "The default list fonts were incorrect"
Expect.equal mt.HeadingColor "maroon" "The default heading text color should have been maroon"
Expect.equal mt.LineColor "navy" "The default heading line color should have been navy"
Expect.equal mt.HeadingFontSize 16 "The default heading font size should have been 16"
Expect.equal mt.TextFontSize 12 "The default text font size should have been 12"
Expect.equal mt.RequestSort SortByDate "The default request sort should have been by date"
Expect.equal mt.GroupPassword "" "The default group password should have been blank"
Expect.equal mt.DefaultEmailType HtmlFormat "The default e-mail type should have been HTML"
Expect.isFalse mt.IsPublic "The isPublic flag should not have been set"
Expect.equal (string mt.TimeZoneId) "America/Denver" "The default time zone should have been America/Denver"
Expect.equal mt.PageSize 100 "The default page size should have been 100"
Expect.equal mt.AsOfDateDisplay NoDisplay "The as-of date display should have been No Display"
}
]
[<Tests>]
let memberTests =
testList "Member" [
test "Empty is as expected" {
let mt = Member.Empty
Expect.equal mt.Id.Value Guid.Empty "The member ID should have been an empty GUID"
Expect.equal mt.SmallGroupId.Value Guid.Empty "The small group ID should have been an empty GUID"
Expect.equal mt.Name "" "The member name should have been blank"
Expect.equal mt.Email "" "The member e-mail address should have been blank"
Expect.isNone mt.Format "The preferred e-mail format should not exist"
}
]
[<Tests>]
let prayerRequestTests =
let instantNow = SystemClock.Instance.GetCurrentInstant
let localDateNow () = (instantNow ()).InUtc().Date
testList "PrayerRequest" [
test "Empty is as expected" {
let mt = PrayerRequest.Empty
Expect.equal mt.Id.Value Guid.Empty "The request ID should have been an empty GUID"
Expect.equal mt.RequestType CurrentRequest "The request type should have been Current"
Expect.equal mt.UserId.Value Guid.Empty "The user ID should have been an empty GUID"
Expect.equal mt.SmallGroupId.Value Guid.Empty "The small group ID should have been an empty GUID"
Expect.equal mt.EnteredDate Instant.MinValue "The entered date should have been the minimum"
Expect.equal mt.UpdatedDate Instant.MinValue "The updated date should have been the minimum"
Expect.isNone mt.Requestor "The requestor should not exist"
Expect.equal mt.Text "" "The request text should have been blank"
Expect.isFalse mt.NotifyChaplain "The notify chaplain flag should not have been set"
Expect.equal mt.Expiration Automatic "The expiration should have been Automatic"
}
test "IsExpired always returns false for expecting requests" {
{ PrayerRequest.Empty with RequestType = Expecting }.IsExpired (localDateNow ()) SmallGroup.Empty
|> Flip.Expect.isFalse "An expecting request should never be considered expired"
}
test "IsExpired always returns false for manually-expired requests" {
{ PrayerRequest.Empty with
UpdatedDate = (instantNow ()) - Duration.FromDays 1
Expiration = Manual }.IsExpired (localDateNow ()) SmallGroup.Empty
|> Flip.Expect.isFalse "A never-expired request should never be considered expired"
}
test "IsExpired always returns false for long term/recurring requests" {
{ PrayerRequest.Empty with RequestType = LongTermRequest }.IsExpired (localDateNow ()) SmallGroup.Empty
|> Flip.Expect.isFalse "A recurring/long-term request should never be considered expired"
}
test "IsExpired always returns true for force-expired requests" {
{ PrayerRequest.Empty with UpdatedDate = (instantNow ()); Expiration = Forced }.IsExpired
(localDateNow ()) SmallGroup.Empty
|> Flip.Expect.isTrue "A force-expired request should always be considered expired"
}
test "IsExpired returns false for non-expired requests" {
let now = instantNow ()
{ PrayerRequest.Empty with UpdatedDate = now - Duration.FromDays 5 }.IsExpired
(now.InUtc().Date) SmallGroup.Empty
|> Flip.Expect.isFalse "A request updated 5 days ago should not be considered expired"
}
test "IsExpired returns true for expired requests" {
let now = instantNow ()
{ PrayerRequest.Empty with UpdatedDate = now - Duration.FromDays 15 }.IsExpired
(now.InUtc().Date) SmallGroup.Empty
|> Flip.Expect.isTrue "A request updated 15 days ago should be considered expired"
}
test "IsExpired returns true for same-day expired requests" {
let now = instantNow ()
{ PrayerRequest.Empty with
UpdatedDate = now - (Duration.FromDays 14) - (Duration.FromSeconds 1L) }.IsExpired
(now.InUtc().Date) SmallGroup.Empty
|> Flip.Expect.isTrue "A request entered a second before midnight should be considered expired"
}
test "UpdateRequired returns false for expired requests" {
{ PrayerRequest.Empty with Expiration = Forced }.UpdateRequired (localDateNow ()) SmallGroup.Empty
|> Flip.Expect.isFalse "An expired request should not require an update"
}
test "UpdateRequired returns false when an update is not required for an active request" {
let now = instantNow ()
{ PrayerRequest.Empty with
RequestType = LongTermRequest
UpdatedDate = now - Duration.FromDays 14 }.UpdateRequired (localDateNow ()) SmallGroup.Empty
|> Flip.Expect.isFalse "An active request updated 14 days ago should not require an update until 28 days"
}
test "UpdateRequired returns true when an update is required for an active request" {
let now = instantNow ()
{ PrayerRequest.Empty with
RequestType = LongTermRequest
UpdatedDate = now - Duration.FromDays 34 }.UpdateRequired (localDateNow ()) SmallGroup.Empty
|> Flip.Expect.isTrue "An active request updated 34 days ago should require an update (past 28 days)"
}
]
[<Tests>]
let prayerRequestTypeTests =
testList "PrayerRequestType" [
testList "ToString" [
test "CurrentRequest code is correct" {
Expect.equal (string CurrentRequest) "C" "The code for CurrentRequest should have been \"C\""
}
test "LongTermRequest code is correct" {
Expect.equal (string LongTermRequest) "L" "The code for LongTermRequest should have been \"L\""
}
test "PraiseReport code is correct" {
Expect.equal (string PraiseReport) "P" "The code for PraiseReport should have been \"P\""
}
test "Expecting code is correct" {
Expect.equal (string Expecting) "E" "The code for Expecting should have been \"E\""
}
test "Announcement code is correct" {
Expect.equal (string Announcement) "A" "The code for Announcement should have been \"A\""
}
]
testList "Parse" [
test "C should return CurrentRequest" {
Expect.equal (PrayerRequestType.Parse "C") CurrentRequest
"\"C\" should have been converted to CurrentRequest"
}
test "L should return LongTermRequest" {
Expect.equal (PrayerRequestType.Parse "L") LongTermRequest
"\"L\" should have been converted to LongTermRequest"
}
test "P should return PraiseReport" {
Expect.equal (PrayerRequestType.Parse "P") PraiseReport
"\"P\" should have been converted to PraiseReport"
}
test "E should return Expecting" {
Expect.equal (PrayerRequestType.Parse "E") Expecting "\"E\" should have been converted to Expecting"
}
test "A should return Announcement" {
Expect.equal (PrayerRequestType.Parse "A") Announcement
"\"A\" should have been converted to Announcement"
}
test "R should raise" {
Expect.throws (fun () -> PrayerRequestType.Parse "R" |> ignore)
"An unknown code should have raised an exception"
}
]
]
[<Tests>]
let requestSortTests =
testList "RequestSort" [
testList "ToString" [
test "SortByDate code is correct" {
Expect.equal (string SortByDate) "D" "The code for SortByDate should have been \"D\""
}
test "SortByRequestor code is correct" {
Expect.equal (string SortByRequestor) "R" "The code for SortByRequestor should have been \"R\""
}
]
testList "Parse" [
test "D should return SortByDate" {
Expect.equal (RequestSort.Parse "D") SortByDate "\"D\" should have been converted to SortByDate"
}
test "R should return SortByRequestor" {
Expect.equal (RequestSort.Parse "R") SortByRequestor
"\"R\" should have been converted to SortByRequestor"
}
test "Q should raise" {
Expect.throws (fun () -> RequestSort.Parse "Q" |> ignore)
"An unknown code should have raised an exception"
}
]
]
[<Tests>]
let smallGroupTests =
testList "SmallGroup" [
let now = Instant.FromDateTimeUtc (DateTime (2017, 5, 12, 12, 15, 0, DateTimeKind.Utc))
let withFakeClock f () =
FakeClock now |> f
yield test "Empty is as expected" {
let mt = SmallGroup.Empty
Expect.equal mt.Id.Value Guid.Empty "The small group ID should have been an empty GUID"
Expect.equal mt.ChurchId.Value Guid.Empty "The church ID should have been an empty GUID"
Expect.equal mt.Name "" "The name should have been blank"
}
yield! testFixture withFakeClock [
"LocalTimeNow adjusts the time ahead of UTC",
fun clock ->
let grp =
{ SmallGroup.Empty with
Preferences = { ListPreferences.Empty with TimeZoneId = TimeZoneId "Europe/Berlin" }
}
Expect.isGreaterThan (grp.LocalTimeNow clock) (now.InUtc().LocalDateTime)
"UTC to Europe/Berlin should have added hours"
"LocalTimeNow adjusts the time behind UTC",
fun clock ->
Expect.isLessThan (SmallGroup.Empty.LocalTimeNow clock) (now.InUtc().LocalDateTime)
"UTC to America/Denver should have subtracted hours"
"LocalTimeNow returns UTC when the time zone is invalid",
fun clock ->
let grp =
{ SmallGroup.Empty with
Preferences = { ListPreferences.Empty with TimeZoneId = TimeZoneId "garbage" }
}
Expect.equal (grp.LocalTimeNow clock) (now.InUtc().LocalDateTime)
"UTC should have been returned for an invalid time zone"
]
yield test "localTimeNow fails when clock is not passed" {
Expect.throws (fun () -> SmallGroup.Empty.LocalTimeNow null |> ignore)
"Should have raised an exception for null clock"
}
yield test "LocalDateNow returns the date portion" {
let clock = FakeClock (Instant.FromDateTimeUtc (DateTime (2017, 5, 12, 1, 15, 0, DateTimeKind.Utc)))
Expect.isLessThan (SmallGroup.Empty.LocalDateNow clock) (now.InUtc().Date)
"The date should have been a day earlier"
}
]
[<Tests>]
let userTests =
testList "User" [
test "Empty is as expected" {
let mt = User.Empty
Expect.equal mt.Id.Value Guid.Empty "The user ID should have been an empty GUID"
Expect.equal mt.FirstName "" "The first name should have been blank"
Expect.equal mt.LastName "" "The last name should have been blank"
Expect.equal mt.Email "" "The e-mail address should have been blank"
Expect.isFalse mt.IsAdmin "The is admin flag should not have been set"
Expect.equal mt.PasswordHash "" "The password hash should have been blank"
}
test "Name concatenates first and last names" {
let user = { User.Empty with FirstName = "Unit"; LastName = "Test" }
Expect.equal user.Name "Unit Test" "The full name should be the first and last, separated by a space"
}
]

View File

@@ -2,7 +2,6 @@
<PropertyGroup> <PropertyGroup>
<OutputType>Exe</OutputType> <OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.0</TargetFramework>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
@@ -15,19 +14,13 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Expecto" Version="8.12.0" /> <PackageReference Include="Expecto" Version="10.2.1" />
<PackageReference Include="Expecto.VisualStudio.TestAdapter" Version="10.0.2" /> <PackageReference Include="NodaTime.Testing" Version="3.2.1" />
<PackageReference Include="NodaTime.Testing" Version="2.4.7" /> <PackageReference Update="FSharp.Core" Version="9.0.101" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\PrayerTracker.Data\PrayerTracker.Data.fsproj" />
<ProjectReference Include="..\PrayerTracker.UI\PrayerTracker.UI.fsproj" />
<ProjectReference Include="..\PrayerTracker\PrayerTracker.fsproj" /> <ProjectReference Include="..\PrayerTracker\PrayerTracker.fsproj" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<PackageReference Update="FSharp.Core" Version="4.7.0" />
</ItemGroup>
</Project> </Project>

View File

@@ -2,4 +2,4 @@
[<EntryPoint>] [<EntryPoint>]
let main argv = let main argv =
runTestsInAssembly defaultConfig argv runTestsInAssemblyWithCLIArgs [] argv

View File

@@ -0,0 +1,215 @@
module PrayerTracker.UI.CommonFunctionsTests
open System.IO
open Expecto
open Giraffe.ViewEngine
open Microsoft.AspNetCore.Mvc.Localization
open Microsoft.Extensions.Localization
open PrayerTracker.Tests.TestLocalization
open PrayerTracker.Views
[<Tests>]
let iconSizedTests =
testList "iconSized" [
test "succeeds" {
let ico = iconSized 18 "tom-&-jerry" |> renderHtmlNode
Expect.equal ico """<i class="material-icons md-18">tom-&-jerry</i>""" "icon HTML not correct"
}
]
[<Tests>]
let iconTests =
testList "icon" [
test "succeeds" {
let ico = icon "bob-&-tom" |> renderHtmlNode
Expect.equal ico """<i class="material-icons">bob-&-tom</i>""" "icon HTML not correct"
}
]
[<Tests>]
let locStrTests =
testList "locStr" [
test "succeeds" {
let enc = locStr (LocalizedString ("test", "test&")) |> renderHtmlNode
Expect.equal enc "test&amp;" "string not encoded correctly"
}
]
[<Tests>]
let namedColorListTests =
testList "namedColorList" [
test "succeeds with default values" {
let expected =
[ """<select name="the-name">"""
"""<option value="aqua" style="background-color:aqua;color:black;">aqua</option>"""
"""<option value="black" style="background-color:black;color:white;">black</option>"""
"""<option value="blue" style="background-color:blue;color:white;">blue</option>"""
"""<option value="fuchsia" style="background-color:fuchsia;color:black;">fuchsia</option>"""
"""<option value="gray" style="background-color:gray;color:white;">gray</option>"""
"""<option value="green" style="background-color:green;color:white;">green</option>"""
"""<option value="lime" style="background-color:lime;color:black;">lime</option>"""
"""<option value="maroon" style="background-color:maroon;color:white;">maroon</option>"""
"""<option value="navy" style="background-color:navy;color:white;">navy</option>"""
"""<option value="olive" style="background-color:olive;color:white;">olive</option>"""
"""<option value="purple" style="background-color:purple;color:white;">purple</option>"""
"""<option value="red" style="background-color:red;color:black;">red</option>"""
"""<option value="silver" style="background-color:silver;color:black;">silver</option>"""
"""<option value="teal" style="background-color:teal;color:white;">teal</option>"""
"""<option value="white" style="background-color:white;color:black;">white</option>"""
"""<option value="yellow" style="background-color:yellow;color:black;">yellow</option>"""
"</select>"
]
|> String.concat ""
let selectList = namedColorList "the-name" "" [] _s |> renderHtmlNode
Expect.equal expected selectList "The default select list was not generated correctly"
}
test "succeeds with a selected value" {
let selectList = namedColorList "the-name" "white" [] _s |> renderHtmlNode
Expect.stringContains selectList " selected>white</option>" "Selected option not generated correctly"
}
test "succeeds with extra attributes" {
let selectList = namedColorList "the-name" "" [ _id "myId" ] _s |> renderHtmlNode
Expect.stringStarts selectList """<select name="the-name" id="myId">""" "Attributes not included correctly"
}
]
[<Tests>]
let radioTests =
testList "radio" [
test "succeeds when not selected" {
let rad = radio "a-name" "anId" "test" "unit" |> renderHtmlNode
Expect.equal rad """<input type="radio" name="a-name" id="anId" value="test">"""
"Unselected radio button not generated correctly"
}
test "succeeds when selected" {
let rad = radio "a-name" "anId" "unit" "unit" |> renderHtmlNode
Expect.equal rad """<input type="radio" name="a-name" id="anId" value="unit" checked>"""
"Selected radio button not generated correctly"
}
]
[<Tests>]
let rawLocTextTests =
testList "rawLocText" [
test "succeeds" {
use sw = new StringWriter ()
let raw = rawLocText sw (LocalizedHtmlString ("test", "test&")) |> renderHtmlNode
Expect.equal raw "test&" "string not written correctly"
}
]
[<Tests>]
let selectDefaultTests =
testList "selectDefault" [
test "succeeds" {
Expect.equal (selectDefault "a&b") "— a&b —" "Default selection not generated correctly"
}
]
[<Tests>]
let selectListTests =
testList "selectList" [
test "succeeds with minimum options" {
let theList = selectList "a-list" "" [] [] |> renderHtmlNode
Expect.equal theList """<select name="a-list" id="a-list"></select>"""
"Empty select list not generated correctly"
}
test "succeeds with all options" {
let theList =
[ "tom", "Tom&"
"bob", "Bob"
"jan", "Jan"
]
|> selectList "the-list" "bob" [ _style "ugly" ]
|> renderHtmlNode
let expected =
[ """<select name="the-list" id="the-list" style="ugly">"""
"""<option value="tom">Tom&amp;</option>"""
"""<option value="bob" selected>Bob</option>"""
"""<option value="jan">Jan</option>"""
"""</select>"""
]
|> String.concat ""
Expect.equal theList expected "Filled select list not generated correctly"
}
]
[<Tests>]
let spaceTests =
testList "space" [
test "succeeds" {
Expect.equal (renderHtmlNode space) " " "space literal not correct"
}
]
[<Tests>]
let submitTests =
testList "submit" [
test "succeeds" {
let btn = submit [ _class "slick" ] "file-ico" _s["a&b"] |> renderHtmlNode
Expect.equal
btn
"""<button type="submit" class="slick"><i class="material-icons">file-ico</i> &nbsp;a&amp;b</button>"""
"Submit button not generated correctly"
}
]
[<Tests>]
let tableSummaryTests =
testList "tableSummary" [
test "succeeds for no entries" {
let sum = tableSummary 0 _s |> renderHtmlNode
Expect.equal sum """<div class="pt-center-text"><small>No Entries to Display</small></div>"""
"Summary for no items is incorrect"
}
test "succeeds for one entry" {
let sum = tableSummary 1 _s |> renderHtmlNode
Expect.equal sum """<div class="pt-center-text"><small>Displaying 1 Entry</small></div>"""
"Summary for one item is incorrect"
}
test "succeeds for many entries" {
let sum = tableSummary 5 _s |> renderHtmlNode
Expect.equal sum """<div class="pt-center-text"><small>Displaying 5 Entries</small></div>"""
"Summary for many items is incorrect"
}
]
module TimeZones =
open PrayerTracker.Entities
open PrayerTracker.Views.CommonFunctions.TimeZones
[<Tests>]
let nameTests =
testList "TimeZones.name" [
test "succeeds for US Eastern time" {
Expect.equal (name (TimeZoneId "America/New_York") _s |> string) "Eastern"
"US Eastern time zone not returned correctly"
}
test "succeeds for US Central time" {
Expect.equal (name (TimeZoneId "America/Chicago") _s |> string) "Central"
"US Central time zone not returned correctly"
}
test "succeeds for US Mountain time" {
Expect.equal (name (TimeZoneId "America/Denver") _s |> string) "Mountain"
"US Mountain time zone not returned correctly"
}
test "succeeds for US Mountain (AZ) time" {
Expect.equal (name (TimeZoneId "America/Phoenix") _s |> string) "Mountain (Arizona)"
"US Mountain (AZ) time zone not returned correctly"
}
test "succeeds for US Pacific time" {
Expect.equal (name (TimeZoneId "America/Los_Angeles") _s |> string) "Pacific"
"US Pacific time zone not returned correctly"
}
test "succeeds for Central European time" {
Expect.equal (name (TimeZoneId "Europe/Berlin") _s |> string) "Central European"
"Central European time zone not returned correctly"
}
test "fails for unexpected time zone" {
Expect.equal (name (TimeZoneId "Wakanda") _s |> string) "Wakanda"
"Unexpected time zone should have returned the original ID"
}
]

196
src/Tests/UI/UtilsTests.fs Normal file
View File

@@ -0,0 +1,196 @@
module PrayerTracker.UI.UtilsTests
open Expecto
open PrayerTracker
[<Tests>]
let ckEditorToTextTests =
testList "ckEditorToText" [
test "replaces newline/tab sequence with nothing" {
Expect.equal (ckEditorToText "Here is some \n\ttext") "Here is some text"
"Newline/tab sequence should have been removed"
}
test "replaces &nbsp; with a space" {
Expect.equal (ckEditorToText "Test&nbsp;text") "Test text" "&nbsp; should have been replaced with a space"
}
test "replaces double space with one non-breaking space and one regular space" {
Expect.equal (ckEditorToText "Test text") "Test&#xa0; text"
"double space should have been replaced with one non-breaking space and one regular space"
}
test "replaces paragraph break with two line breaks" {
Expect.equal (ckEditorToText "some</p><p>text") "some<br><br>text"
"paragraph break should have been replaced with two line breaks"
}
test "removes start and end paragraph tags" {
Expect.equal (ckEditorToText "<p>something something</p>") "something something"
"start/end paragraph tags should have been removed"
}
test "trims the result" {
Expect.equal (ckEditorToText " abc ") "abc" "Should have trimmed the resulting text"
}
test "does all the replacements and removals at one time" {
Expect.equal (ckEditorToText " <p>Paragraph&nbsp;1\n\t line two</p><p>Paragraph 2 x</p>")
"Paragraph 1 line two<br><br>Paragraph 2&#xa0; x"
"all replacements and removals were not made correctly"
}
]
[<Tests>]
let htmlToPlainTextTests =
testList "htmlToPlainText" [
test "decodes HTML-encoded entities" {
Expect.equal (htmlToPlainText "1 &gt; 0") "1 > 0" "HTML-encoded entities should have been decoded"
}
test "trims the input HTML" {
Expect.equal (htmlToPlainText " howdy ") "howdy" "HTML input string should have been trimmed"
}
test "replaces line breaks with new lines" {
Expect.equal (htmlToPlainText "Lots<br>of<br />new<br>lines") "Lots\nof\nnew\nlines"
"Break tags should have been converted to newline characters"
}
test "replaces non-breaking spaces with spaces" {
Expect.equal (htmlToPlainText "Here&nbsp;is&#xa0;some&nbsp;more&#xa0;text") "Here is some more text"
"Non-breaking spaces should have been replaced with spaces"
}
test "does all replacements at one time" {
Expect.equal (htmlToPlainText " &lt;&nbsp;&lt;<br>test") "< <\ntest"
"All replacements were not made correctly"
}
test "does not fail when passed null" {
Expect.equal (htmlToPlainText null) "" "Should return an empty string for null input"
}
test "does not fail when passed an empty string" {
Expect.equal (htmlToPlainText "") "" "Should return an empty string when given an empty string"
}
test "preserves blank lines for two consecutive line breaks" {
let expected = "Paragraph 1\n\nParagraph 2\n\n...and paragraph 3"
Expect.equal
(htmlToPlainText "Paragraph 1<br><br>Paragraph 2<br><br>...and <strong>paragraph</strong> <i>3</i>")
expected "Blank lines not preserved for consecutive line breaks"
}
]
[<Tests>]
let makeUrlTests =
testList "makeUrl" [
test "returns the URL when there are no parameters" {
Expect.equal (makeUrl "/test" []) "/test" "The URL should not have had any query string parameters added"
}
test "returns the URL with one query string parameter" {
Expect.equal (makeUrl "/test" [ "unit", "true" ]) "/test?unit=true" "The URL was not constructed properly"
}
test "returns the URL with multiple encoded query string parameters" {
let url = makeUrl "/test" [ "space", "a space"; "turkey", "=" ]
Expect.equal url "/test?space=a+space&turkey=%3D" "The URL was not constructed properly"
}
]
[<Tests>]
let sndAsStringTests =
testList "sndAsString" [
test "converts the second item to a string" {
Expect.equal (sndAsString ("a", 5)) "5"
"The second part of the tuple should have been converted to a string"
}
]
module StringTests =
open PrayerTracker.Utils.String
[<Tests>]
let replaceFirstTests =
testList "String.replaceFirst" [
test "replaces the first occurrence when it is found at the beginning of the string" {
let testString = "unit unit unit"
Expect.equal (replaceFirst "unit" "test" testString) "test unit unit"
"First occurrence of a substring was not replaced properly at the beginning of the string"
}
test "replaces the first occurrence when it is found in the center of the string" {
let testString = "test unit test"
Expect.equal (replaceFirst "unit" "test" testString) "test test test"
"First occurrence of a substring was not replaced properly when it is in the center of the string"
}
test "returns the original string if the replacement isn't found" {
let testString = "unit tests"
Expect.equal (replaceFirst "tested" "testing" testString) "unit tests"
"String which did not have the target substring was not returned properly"
}
]
[<Tests>]
let replaceTests =
testList "String.replace" [
test "succeeds" {
Expect.equal (replace "a" "b" "abacab") "bbbcbb" "String did not replace properly"
}
]
[<Tests>]
let trimTests =
testList "String.trim" [
test "succeeds" {
Expect.equal (trim " abc ") "abc" "Space not trimmed from string properly"
}
]
[<Tests>]
let stripTagsTests =
let testString = """<p class="testing">Here is some text<br> <br />and some more</p>"""
testList "stripTags" [
test "does nothing if all tags are allowed" {
Expect.equal (stripTags [ "p"; "br" ] testString) testString
"There should have been no replacements in the target string"
}
test "strips the start/end tag for non allowed tag" {
Expect.equal (stripTags [ "br" ] testString) "Here is some text<br> <br />and some more"
"There should have been no \"p\" tag, but all \"br\" tags, in the returned string"
}
test "strips void/self-closing tags" {
Expect.equal (stripTags [] testString) "Here is some text and some more"
"There should have been no tags; all void and self-closing tags should have been stripped"
}
]
[<Tests>]
let wordWrapTests =
testList "wordWrap" [
test "breaks where it is supposed to" {
let testString = "The quick brown fox jumps over the lazy dog\nIt does!"
Expect.equal (wordWrap 20 testString) "The quick brown fox\njumps over the lazy\ndog\nIt does!\n"
"Line not broken correctly"
}
test "wraps long line without a space" {
let testString = "Asamatteroffact, the dog does too"
Expect.equal (wordWrap 10 testString) "Asamattero\nffact, the\ndog does\ntoo\n"
"Longer line not broken correctly"
}
test "preserves blank lines" {
let testString = "Here is\n\na string with blank lines"
Expect.equal (wordWrap 80 testString) testString "Blank lines were not preserved"
}
]
[<Tests>]
let wordWrapBTests =
testList "wordWrapB" [
test "breaks where it is supposed to" {
let testString = "The quick brown fox jumps over the lazy dog\nIt does!"
Expect.equal (wordWrap 20 testString) "The quick brown fox\njumps over the lazy\ndog\nIt does!\n"
"Line not broken correctly"
}
test "wraps long line without a space and a line with exact length" {
let testString = "Asamatteroffact, the dog does too"
Expect.equal (wordWrap 10 testString) "Asamattero\nffact, the\ndog does\ntoo\n"
"Longer line not broken correctly"
}
test "wraps long line without a space and a line with non-exact length" {
let testString = "Asamatteroffact, that dog does too"
Expect.equal (wordWrap 10 testString) "Asamattero\nffact,\nthat dog\ndoes too\n"
"Longer line not broken correctly"
}
test "preserves blank lines" {
let testString = "Here is\n\na string with blank lines"
Expect.equal (wordWrap 80 testString) testString "Blank lines were not preserved"
}
]

View File

@@ -0,0 +1,736 @@
module PrayerTracker.UI.ViewModelsTests
open System
open Expecto
open Microsoft.AspNetCore.Html
open NodaTime
open PrayerTracker.Entities
open PrayerTracker.Tests.TestLocalization
open PrayerTracker.Utils
open PrayerTracker.ViewModels
/// Filter function that filters nothing
let countAll _ = true
module ReferenceListTests =
[<Tests>]
let asOfDateListTests =
testList "ReferenceList.asOfDateList" [
test "has all three options listed" {
let asOf = ReferenceList.asOfDateList _s
Expect.hasCountOf asOf 3u countAll "There should have been 3 as-of choices returned"
Expect.exists asOf (fun (x, _) -> x = string NoDisplay) "The option for no display was not found"
Expect.exists asOf (fun (x, _) -> x = string ShortDate) "The option for a short date was not found"
Expect.exists asOf (fun (x, _) -> x = string LongDate) "The option for a full date was not found"
}
]
[<Tests>]
let emailTypeListTests =
testList "ReferenceList.emailTypeList" [
test "includes default type" {
let typs = ReferenceList.emailTypeList HtmlFormat _s
Expect.hasCountOf typs 3u countAll "There should have been 3 e-mail type options returned"
let top = Seq.head typs
Expect.equal (fst top) "" "The default option should have been blank"
Expect.equal (snd top).Value "Group Default (HTML Format)" "The default option label was incorrect"
let nxt = typs |> Seq.skip 1 |> Seq.head
Expect.equal (fst nxt) (string HtmlFormat) "The 2nd option should have been HTML"
let lst = typs |> Seq.last
Expect.equal (fst lst) (string PlainTextFormat) "The 3rd option should have been plain text"
}
]
[<Tests>]
let expirationListTests =
testList "ReferenceList.expirationList" [
test "excludes immediate expiration if not required" {
let exps = ReferenceList.expirationList _s false
Expect.hasCountOf exps 2u countAll "There should have been 2 expiration types returned"
Expect.exists exps (fun (exp, _) -> exp = string Automatic)
"The option for automatic expiration was not found"
Expect.exists exps (fun (exp, _) -> exp = string Manual)
"The option for manual expiration was not found"
}
test "includes immediate expiration if required" {
let exps = ReferenceList.expirationList _s true
Expect.hasCountOf exps 3u countAll "There should have been 3 expiration types returned"
Expect.exists exps (fun (exp, _) -> exp = string Automatic)
"The option for automatic expiration was not found"
Expect.exists exps (fun (exp, _) -> exp = string Manual)
"The option for manual expiration was not found"
Expect.exists exps (fun (exp, _) -> exp = string Forced)
"The option for immediate expiration was not found"
}
]
[<Tests>]
let requestTypeListTests =
testList "ReferenceList.requestTypeList" [
let withList f () =
(ReferenceList.requestTypeList >> f) _s
yield! testFixture withList [
yield "returns 5 types",
fun typs -> Expect.hasCountOf typs 5u countAll "There should have been 5 request types returned"
yield!
[ CurrentRequest; LongTermRequest; PraiseReport; Expecting; Announcement ]
|> List.map (fun typ ->
$"contains \"%O{typ}\"",
fun typs ->
Expect.isSome (typs |> List.tryFind (fun x -> fst x = typ))
$"""The "%O{typ}" option was not found""")
]
]
[<Tests>]
let announcementTests =
let empty = { SendToClass = "N"; Text = "<p>unit testing</p>"; AddToRequestList = None; RequestType = None }
testList "Announcement" [
test "plainText strips HTML" {
let ann = { empty with Text = "<p>unit testing</p>" }
Expect.equal ann.PlainText "unit testing" "Plain text should have stripped HTML"
}
test "plainText wraps at 74 characters" {
let ann = { empty with Text = String.replicate 80 "x" }
let txt = ann.PlainText.Split "\n"
Expect.hasCountOf txt 3u countAll "There should have been two lines of plain text returned"
Expect.stringHasLength txt[0] 74 "The first line should have been wrapped at 74 characters"
Expect.stringHasLength txt[1] 6 "The second line should have had the remaining 6 characters"
Expect.stringHasLength txt[2] 0 "The third line should have been blank"
}
test "plainText wraps at 74 characters and strips HTML" {
let ann = { empty with Text = sprintf "<strong>%s</strong>" (String.replicate 80 "z") }
let txt = ann.PlainText
Expect.stringStarts txt "zzz" "HTML should have been stripped from the front of the plain text"
Expect.equal (txt.ToCharArray ()).[74] '\n' "The text should have been broken at 74 characters"
}
]
[<Tests>]
let appViewInfoTests =
testList "AppViewInfo" [
test "fresh is constructed properly" {
let vi = AppViewInfo.fresh
Expect.isEmpty vi.Style "There should have been no styles set"
Expect.isNone vi.HelpLink "The help link should have been set to none"
Expect.isEmpty vi.Messages "There should have been no messages set"
Expect.equal vi.Version "" "The version should have been blank"
Expect.equal vi.RequestStart Instant.MinValue "The request start time should have been the minimum value"
Expect.isNone vi.User "There should not have been a user"
Expect.isNone vi.Group "There should not have been a small group"
}
]
[<Tests>]
let assignGroupsTests =
testList "AssignGroups" [
test "fromUser populates correctly" {
let usr = { User.Empty with Id = (Guid.NewGuid >> UserId) (); FirstName = "Alice"; LastName = "Bob" }
let asg = AssignGroups.fromUser usr
Expect.equal asg.UserId (shortGuid usr.Id.Value) "The user ID was not filled correctly"
Expect.equal asg.UserName usr.Name "The user's name was not filled correctly"
Expect.equal asg.SmallGroups "" "The small group string was not filled correctly"
}
]
[<Tests>]
let editChurchTests =
testList "EditChurch" [
test "fromChurch populates correctly when interface exists" {
let church =
{ Church.Empty with
Id = (Guid.NewGuid >> ChurchId) ()
Name = "Unit Test"
City = "Testlandia"
State = "UT"
HasVpsInterface = true
InterfaceAddress = Some "https://test-dem-units.test"
}
let edit = EditChurch.fromChurch church
Expect.equal edit.ChurchId (shortGuid church.Id.Value) "The church ID was not filled correctly"
Expect.equal edit.Name church.Name "The church name was not filled correctly"
Expect.equal edit.City church.City "The church's city was not filled correctly"
Expect.equal edit.State church.State "The church's state was not filled correctly"
Expect.isSome edit.HasInterface "The church should show that it has an interface"
Expect.equal edit.HasInterface (Some true) "The HasVpsInterface flag should be true"
Expect.isSome edit.InterfaceAddress "The interface address should exist"
Expect.equal edit.InterfaceAddress church.InterfaceAddress "The interface address was not filled correctly"
}
test "fromChurch populates correctly when interface does not exist" {
let edit =
EditChurch.fromChurch
{ Church.Empty with
Id = (Guid.NewGuid >> ChurchId) ()
Name = "Unit Test"
City = "Testlandia"
State = "UT"
}
Expect.isNone edit.HasInterface "The church should not show that it has an interface"
Expect.isNone edit.InterfaceAddress "The interface address should not exist"
}
test "empty is as expected" {
let edit = EditChurch.empty
Expect.equal edit.ChurchId emptyGuid "The church ID should be the empty GUID"
Expect.equal edit.Name "" "The church name should be blank"
Expect.equal edit.City "" "The church's city should be blank"
Expect.equal edit.State "" "The church's state should be blank"
Expect.isNone edit.HasInterface "The church should not show that it has an interface"
Expect.isNone edit.InterfaceAddress "The interface address should not exist"
}
test "isNew works on a new church" {
Expect.isTrue EditChurch.empty.IsNew "An empty GUID should be flagged as a new church"
}
test "isNew works on an existing church" {
Expect.isFalse { EditChurch.empty with ChurchId = (Guid.NewGuid >> shortGuid) () }.IsNew
"A non-empty GUID should not be flagged as a new church"
}
test "populateChurch works correctly when an interface exists" {
let edit =
{ EditChurch.empty with
ChurchId = (Guid.NewGuid >> shortGuid) ()
Name = "Test Baptist Church"
City = "Testerville"
State = "TE"
HasInterface = Some true
InterfaceAddress = Some "https://test.units"
}
let church = edit.PopulateChurch Church.Empty
Expect.notEqual (shortGuid church.Id.Value) edit.ChurchId "The church ID should not have been modified"
Expect.equal church.Name edit.Name "The church name was not updated correctly"
Expect.equal church.City edit.City "The church's city was not updated correctly"
Expect.equal church.State edit.State "The church's state was not updated correctly"
Expect.isTrue church.HasVpsInterface "The church should show that it has an interface"
Expect.isSome church.InterfaceAddress "The interface address should exist"
Expect.equal church.InterfaceAddress edit.InterfaceAddress "The interface address was not updated correctly"
}
test "populateChurch works correctly when an interface does not exist" {
let church =
{ EditChurch.empty with
Name = "Test Baptist Church"
City = "Testerville"
State = "TE"
}.PopulateChurch Church.Empty
Expect.isFalse church.HasVpsInterface "The church should show that it has an interface"
Expect.isNone church.InterfaceAddress "The interface address should exist"
}
]
[<Tests>]
let editMemberTests =
testList "EditMember" [
test "fromMember populates with group default format" {
let mbr =
{ Member.Empty with
Id = (Guid.NewGuid >> MemberId) ()
Name = "Test Name"
Email = "test_units@example.com"
}
let edit = EditMember.fromMember mbr
Expect.equal edit.MemberId (shortGuid mbr.Id.Value) "The member ID was not filled correctly"
Expect.equal edit.Name mbr.Name "The member name was not filled correctly"
Expect.equal edit.Email mbr.Email "The e-mail address was not filled correctly"
Expect.equal edit.Format "" "The e-mail format should have been blank for group default"
}
test "fromMember populates with specific format" {
let edit = EditMember.fromMember { Member.Empty with Format = Some HtmlFormat }
Expect.equal edit.Format (string HtmlFormat) "The e-mail format was not filled correctly"
}
test "empty is as expected" {
let edit = EditMember.empty
Expect.equal edit.MemberId emptyGuid "The member ID should have been an empty GUID"
Expect.equal edit.Name "" "The member name should have been blank"
Expect.equal edit.Email "" "The e-mail address should have been blank"
Expect.equal edit.Format "" "The e-mail format should have been blank"
}
test "isNew works for a new member" {
Expect.isTrue EditMember.empty.IsNew "An empty GUID should be flagged as a new member"
}
test "isNew works for an existing member" {
Expect.isFalse { EditMember.empty with MemberId = (Guid.NewGuid >> shortGuid) () }.IsNew
"A non-empty GUID should not be flagged as a new member"
}
]
[<Tests>]
let editPreferencesTests =
testList "EditPreferences" [
test "fromPreferences succeeds for native fonts, named colors, and private list" {
let prefs = ListPreferences.Empty
let edit = EditPreferences.fromPreferences prefs
Expect.equal edit.ExpireDays prefs.DaysToExpire "The expiration days were not filled correctly"
Expect.equal edit.DaysToKeepNew prefs.DaysToKeepNew "The days to keep new were not filled correctly"
Expect.equal edit.LongTermUpdateWeeks prefs.LongTermUpdateWeeks
"The weeks for update were not filled correctly"
Expect.equal edit.RequestSort (string prefs.RequestSort) "The request sort was not filled correctly"
Expect.equal edit.EmailFromName prefs.EmailFromName "The e-mail from name was not filled correctly"
Expect.equal edit.EmailFromAddress prefs.EmailFromAddress "The e-mail from address was not filled correctly"
Expect.equal edit.DefaultEmailType (string prefs.DefaultEmailType)
"The default e-mail type was not filled correctly"
Expect.equal edit.LineColorType "Name" "The heading line color type was not derived correctly"
Expect.equal edit.LineColor prefs.LineColor "The heading line color was not filled correctly"
Expect.equal edit.HeadingColorType "Name" "The heading text color type was not derived correctly"
Expect.equal edit.HeadingColor prefs.HeadingColor "The heading text color was not filled correctly"
Expect.isTrue edit.IsNative "The IsNative flag should have been true (default value)"
Expect.isNone edit.Fonts "The list fonts should not exist for native font stack"
Expect.equal edit.HeadingFontSize prefs.HeadingFontSize "The heading font size was not filled correctly"
Expect.equal edit.ListFontSize prefs.TextFontSize "The list text font size was not filled correctly"
Expect.equal edit.TimeZone (string prefs.TimeZoneId) "The time zone was not filled correctly"
Expect.isSome edit.GroupPassword "The group password should have been set"
Expect.equal edit.GroupPassword (Some prefs.GroupPassword) "The group password was not filled correctly"
Expect.equal edit.Visibility GroupVisibility.PrivateList
"The list visibility was not derived correctly"
Expect.equal edit.PageSize prefs.PageSize "The page size was not filled correctly"
Expect.equal edit.AsOfDate (string prefs.AsOfDateDisplay) "The as-of date display was not filled correctly"
}
test "fromPreferences succeeds for RGB line color and password-protected list" {
let prefs = { ListPreferences.Empty with LineColor = "#ff0000"; GroupPassword = "pw" }
let edit = EditPreferences.fromPreferences prefs
Expect.equal edit.LineColorType "RGB" "The heading line color type was not derived correctly"
Expect.equal edit.LineColor prefs.LineColor "The heading line color was not filled correctly"
Expect.isSome edit.GroupPassword "The group password should have been set"
Expect.equal edit.GroupPassword (Some prefs.GroupPassword) "The group password was not filled correctly"
Expect.equal edit.Visibility GroupVisibility.HasPassword
"The list visibility was not derived correctly"
}
test "fromPreferences succeeds for RGB text color and public list" {
let prefs = { ListPreferences.Empty with HeadingColor = "#0000ff"; IsPublic = true }
let edit = EditPreferences.fromPreferences prefs
Expect.equal edit.HeadingColorType "RGB" "The heading text color type was not derived correctly"
Expect.equal edit.HeadingColor prefs.HeadingColor "The heading text color was not filled correctly"
Expect.isSome edit.GroupPassword "The group password should have been set"
Expect.equal edit.GroupPassword (Some "") "The group password was not filled correctly"
Expect.equal edit.Visibility GroupVisibility.PublicList
"The list visibility was not derived correctly"
}
test "fromPreferences succeeds for non-native fonts" {
let prefs = { ListPreferences.Empty with Fonts = "Arial,sans-serif" }
let edit = EditPreferences.fromPreferences prefs
Expect.isFalse edit.IsNative "The IsNative flag should have been false"
Expect.isSome edit.Fonts "The fonts should have been filled for non-native fonts"
Expect.equal edit.Fonts.Value prefs.Fonts "The fonts were not filled correctly"
}
]
[<Tests>]
let editRequestTests =
testList "EditRequest" [
test "empty is as expected" {
let mt = EditRequest.empty
Expect.equal mt.RequestId emptyGuid "The request ID should be an empty GUID"
Expect.equal mt.RequestType (string CurrentRequest) "The request type should have been \"Current\""
Expect.isNone mt.EnteredDate "The entered date should have been None"
Expect.isNone mt.SkipDateUpdate """The "skip date update" flag should have been None"""
Expect.isNone mt.Requestor "The requestor should have been None"
Expect.equal mt.Expiration (string Automatic) """The expiration should have been "A" (Automatic)"""
Expect.equal mt.Text "" "The text should have been blank"
}
test "fromRequest succeeds" {
let req =
{ PrayerRequest.Empty with
Id = (Guid.NewGuid >> PrayerRequestId) ()
RequestType = CurrentRequest
Requestor = Some "Me"
Expiration = Manual
Text = "the text"
}
let edit = EditRequest.fromRequest req
Expect.equal edit.RequestId (shortGuid req.Id.Value) "The request ID was not filled correctly"
Expect.equal edit.RequestType (string req.RequestType) "The request type was not filled correctly"
Expect.equal edit.Requestor req.Requestor "The requestor was not filled correctly"
Expect.equal edit.Expiration (string Manual) "The expiration was not filled correctly"
Expect.equal edit.Text req.Text "The text was not filled correctly"
}
test "isNew works for a new request" {
Expect.isTrue EditRequest.empty.IsNew "An empty GUID should be flagged as a new request"
}
test "isNew works for an existing request" {
Expect.isFalse { EditRequest.empty with RequestId = (Guid.NewGuid >> shortGuid) () }.IsNew
"A non-empty GUID should not be flagged as a new request"
}
]
[<Tests>]
let editSmallGroupTests =
testList "EditSmallGroup" [
test "fromGroup succeeds" {
let grp =
{ SmallGroup.Empty with
Id = (Guid.NewGuid >> SmallGroupId) ()
Name = "test group"
ChurchId = (Guid.NewGuid >> ChurchId) ()
}
let edit = EditSmallGroup.fromGroup grp
Expect.equal edit.SmallGroupId (shortGuid grp.Id.Value) "The small group ID was not filled correctly"
Expect.equal edit.Name grp.Name "The name was not filled correctly"
Expect.equal edit.ChurchId (shortGuid grp.ChurchId.Value) "The church ID was not filled correctly"
}
test "empty is as expected" {
let mt = EditSmallGroup.empty
Expect.equal mt.SmallGroupId emptyGuid "The small group ID should be an empty GUID"
Expect.equal mt.Name "" "The name should be blank"
Expect.equal mt.ChurchId emptyGuid "The church ID should be an empty GUID"
}
test "isNew works for a new small group" {
Expect.isTrue EditSmallGroup.empty.IsNew "An empty GUID should be flagged as a new small group"
}
test "isNew works for an existing small group" {
Expect.isFalse { EditSmallGroup.empty with SmallGroupId = (Guid.NewGuid >> shortGuid) () }.IsNew
"A non-empty GUID should not be flagged as a new small group"
}
test "populateGroup succeeds" {
let edit =
{ EditSmallGroup.empty with
Name = "test name"
ChurchId = (Guid.NewGuid >> shortGuid) ()
}
let grp = edit.populateGroup SmallGroup.Empty
Expect.equal grp.Name edit.Name "The name was not populated correctly"
Expect.equal grp.ChurchId (idFromShort ChurchId edit.ChurchId) "The church ID was not populated correctly"
}
]
[<Tests>]
let editUserTests =
testList "EditUser" [
test "empty is as expected" {
let mt = EditUser.empty
Expect.equal mt.UserId emptyGuid "The user ID should be an empty GUID"
Expect.equal mt.FirstName "" "The first name should be blank"
Expect.equal mt.LastName "" "The last name should be blank"
Expect.equal mt.Email "" "The e-mail address should be blank"
Expect.equal mt.Password "" "The password should be blank"
Expect.equal mt.PasswordConfirm "" "The confirmed password should be blank"
Expect.isNone mt.IsAdmin "The IsAdmin flag should be None"
}
test "fromUser succeeds" {
let usr =
{ User.Empty with
Id = (Guid.NewGuid >> UserId) ()
FirstName = "user"
LastName = "test"
Email = "a@b.c"
}
let edit = EditUser.fromUser usr
Expect.equal edit.UserId (shortGuid usr.Id.Value) "The user ID was not filled correctly"
Expect.equal edit.FirstName usr.FirstName "The first name was not filled correctly"
Expect.equal edit.LastName usr.LastName "The last name was not filled correctly"
Expect.equal edit.Email usr.Email "The e-mail address was not filled correctly"
Expect.isNone edit.IsAdmin "The IsAdmin flag was not filled correctly"
}
test "isNew works for a new user" {
Expect.isTrue EditUser.empty.IsNew "An empty GUID should be flagged as a new user"
}
test "isNew works for an existing user" {
Expect.isFalse { EditUser.empty with UserId = (Guid.NewGuid >> shortGuid) () }.IsNew
"A non-empty GUID should not be flagged as a new user"
}
test "populateUser succeeds" {
let edit =
{ EditUser.empty with
FirstName = "name"
LastName = "eman"
Email = "n@m.e"
IsAdmin = Some true
Password = "testpw"
}
let hasher = fun x -> x + "+"
let usr = edit.PopulateUser User.Empty hasher
Expect.equal usr.FirstName edit.FirstName "The first name was not populated correctly"
Expect.equal usr.LastName edit.LastName "The last name was not populated correctly"
Expect.equal usr.Email edit.Email "The e-mail address was not populated correctly"
Expect.isTrue usr.IsAdmin "The isAdmin flag was not populated correctly"
Expect.equal usr.PasswordHash (hasher edit.Password) "The password hash was not populated correctly"
}
]
[<Tests>]
let groupLogOnTests =
testList "GroupLogOn" [
test "empty is as expected" {
let mt = GroupLogOn.empty
Expect.equal mt.SmallGroupId emptyGuid "The small group ID should be an empty GUID"
Expect.equal mt.Password "" "The password should be blank"
Expect.isNone mt.RememberMe "Remember Me should be None"
}
]
[<Tests>]
let maintainRequestsTests =
testList "MaintainRequests" [
test "empty is as expected" {
let mt = MaintainRequests.empty
Expect.isEmpty mt.Requests "The requests for the model should have been empty"
Expect.equal mt.SmallGroup.Id.Value Guid.Empty "The small group should have been an empty one"
Expect.isNone mt.OnlyActive "The only active flag should have been None"
Expect.isNone mt.SearchTerm "The search term should have been None"
Expect.isNone mt.PageNbr "The page number should have been None"
}
]
[<Tests>]
let messageLevelTests =
testList "MessageLevel" [
test "toString for Info is as expected" {
Expect.equal (MessageLevel.toString Info) "Info" """The string value of "Info" is incorrect"""
}
test "toString for Warning is as expected" {
Expect.equal (MessageLevel.toString Warning) "WARNING" """The string value of "Warning" is incorrect"""
}
test "toString for Error is as expected" {
Expect.equal (MessageLevel.toString Error) "ERROR" """The string value of "Error" is incorrect"""
}
test "toCssClass for Info is as expected" {
Expect.equal (MessageLevel.toCssClass Info) "info" """The string value of "Info" is incorrect"""
}
test "toCssClass for Warning is as expected" {
Expect.equal (MessageLevel.toCssClass Warning) "warning" """The string value of "Warning" is incorrect"""
}
test "toCssClass for Error is as expected" {
Expect.equal (MessageLevel.toCssClass Error) "error" """The string value of "Error" is incorrect"""
}
]
[<Tests>]
let requestListTests =
testList "RequestList" [
let withRequestList f () =
let today = SystemClock.Instance.GetCurrentInstant ()
{ Requests = [
{ PrayerRequest.Empty with
RequestType = CurrentRequest
Requestor = Some "Zeb"
Text = "zyx"
UpdatedDate = today
}
{ PrayerRequest.Empty with
RequestType = CurrentRequest
Requestor = Some "Aaron"
Text = "abc"
UpdatedDate = today - Duration.FromDays 9
}
{ PrayerRequest.Empty with
RequestType = PraiseReport
Text = "nmo"
UpdatedDate = today
}
]
Date = today.InUtc().Date
SmallGroup = SmallGroup.Empty
ShowHeader = false
Recipients = []
CanEmail = false
}
|> f
yield! testFixture withRequestList [
"AsHtml succeeds without header or as-of date",
fun reqList ->
let htmlList = { reqList with SmallGroup = { reqList.SmallGroup with Name = "Test HTML Group" } }
let html = htmlList.AsHtml _s
let fonts = reqList.SmallGroup.Preferences.FontStack.Replace ("\"", "&quot;")
Expect.equal -1 (html.IndexOf "Test HTML Group")
"The small group name should not have existed (no header)"
let curReqHeading =
[ $"""<table style="font-family:{fonts};page-break-inside:avoid;">"""
"<tr>"
"""<td style="font-size:16pt;color:maroon;padding:3px 0;border-top:solid 3px navy;border-bottom:solid 3px navy;font-weight:bold;">"""
"&nbsp; &nbsp; Current Requests&nbsp; &nbsp; </td></tr></table>"
]
|> String.concat ""
Expect.stringContains html curReqHeading """Heading for category "Current Requests" not found"""
let curReqHtml =
[ $"""<ul style="font-family:{fonts};font-size:12pt">"""
"""<li style="list-style-type:circle;padding-bottom:.25em;">"""
"<strong>Zeb</strong> &ndash; zyx</li>"
"""<li style="list-style-type:disc;padding-bottom:.25em;">"""
"<strong>Aaron</strong> &ndash; abc</li></ul>"
]
|> String.concat ""
Expect.stringContains html curReqHtml """Expected HTML for "Current Requests" requests not found"""
let praiseHeading =
[ $"""<table style="font-family:{fonts};page-break-inside:avoid;">"""
"<tr>"
"""<td style="font-size:16pt;color:maroon;padding:3px 0;border-top:solid 3px navy;border-bottom:solid 3px navy;font-weight:bold;">"""
"&nbsp; &nbsp; Praise Reports&nbsp; &nbsp; </td></tr></table>"
]
|> String.concat ""
Expect.stringContains html praiseHeading """Heading for category "Praise Reports" not found"""
let praiseHtml =
[ $"""<ul style="font-family:{fonts};font-size:12pt">"""
"""<li style="list-style-type:circle;padding-bottom:.25em;">"""
"nmo</li></ul>"
]
|> String.concat ""
Expect.stringContains html praiseHtml """Expected HTML for "Praise Reports" requests not found"""
"AsHtml succeeds with header",
fun reqList ->
let htmlList =
{ reqList with
SmallGroup = { reqList.SmallGroup with Name = "Test HTML Group" }
ShowHeader = true
}
let html = htmlList.AsHtml _s
let fonts = reqList.SmallGroup.Preferences.FontStack.Replace ("\"", "&quot;")
let lstHeading =
[ $"""<div style="text-align:center;font-family:{fonts}">"""
"""<span style="font-size:16pt;"><strong>Prayer Requests</strong></span><br>"""
"""<span style="font-size:12pt;"><strong>Test HTML Group</strong><br>"""
htmlList.Date.ToString ("MMMM d, yyyy", null)
"</span></div><br>"
]
|> String.concat ""
Expect.stringContains html lstHeading "Expected HTML for the list heading not found"
// spot check; without header test tests this exhaustively
Expect.stringContains html "<strong>Zeb</strong> &ndash; zyx</li>" "Expected requests not found"
"AsHtml succeeds with short as-of date",
fun reqList ->
let htmlList =
{ reqList with
SmallGroup =
{ reqList.SmallGroup with
Preferences = { reqList.SmallGroup.Preferences with AsOfDateDisplay = ShortDate }
}
}
let html = htmlList.AsHtml _s
let expected =
htmlList.Requests[0].UpdatedDate.InZone(reqList.SmallGroup.TimeZone).Date.ToString ("d", null)
|> sprintf """<strong>Zeb</strong> &ndash; zyx<i style="font-size:9.60pt">&nbsp; (as of %s)</i>"""
// spot check; if one request has it, they all should
Expect.stringContains html expected "Expected short as-of date not found"
"AsHtml succeeds with long as-of date",
fun reqList ->
let htmlList =
{ reqList with
SmallGroup =
{ reqList.SmallGroup with
Preferences = { reqList.SmallGroup.Preferences with AsOfDateDisplay = LongDate }
}
}
let html = htmlList.AsHtml _s
let expected =
htmlList.Requests[0].UpdatedDate.InZone(reqList.SmallGroup.TimeZone).Date.ToString ("D", null)
|> sprintf """<strong>Zeb</strong> &ndash; zyx<i style="font-size:9.60pt">&nbsp; (as of %s)</i>"""
// spot check; if one request has it, they all should
Expect.stringContains html expected "Expected long as-of date not found"
"AsText succeeds with no as-of date",
fun reqList ->
let textList = { reqList with SmallGroup = { reqList.SmallGroup with Name = "Test Group" } }
let text = textList.AsText _s
Expect.stringContains text $"{textList.SmallGroup.Name}\n" "Small group name not found"
Expect.stringContains text "Prayer Requests\n" "List heading not found"
Expect.stringContains text ((textList.Date.ToString ("MMMM d, yyyy", null)) + "\n \n")
"List date not found"
Expect.stringContains text "--------------------\n CURRENT REQUESTS\n--------------------\n"
"""Heading for category "Current Requests" not found"""
Expect.stringContains text " + Zeb - zyx\n" "First request not found"
Expect.stringContains text " - Aaron - abc\n \n"
"Second request not found; should have been end of category"
Expect.stringContains text "------------------\n PRAISE REPORTS\n------------------\n"
"""Heading for category "Praise Reports" not found"""
Expect.stringContains text " + nmo\n \n" "Last request not found"
"AsText succeeds with short as-of date",
fun reqList ->
let textList =
{ reqList with
SmallGroup =
{ reqList.SmallGroup with
Preferences = { reqList.SmallGroup.Preferences with AsOfDateDisplay = ShortDate }
}
}
let text = textList.AsText _s
let expected =
textList.Requests[0].UpdatedDate.InZone(reqList.SmallGroup.TimeZone).Date.ToString ("d", null)
|> sprintf " + Zeb - zyx (as of %s)"
// spot check; if one request has it, they all should
Expect.stringContains text expected "Expected short as-of date not found"
"AsText succeeds with long as-of date",
fun reqList ->
let textList =
{ reqList with
SmallGroup =
{ reqList.SmallGroup with
Preferences = { reqList.SmallGroup.Preferences with AsOfDateDisplay = LongDate }
}
}
let text = textList.AsText _s
let expected =
textList.Requests[0].UpdatedDate.InZone(reqList.SmallGroup.TimeZone).Date.ToString ("D", null)
|> sprintf " + Zeb - zyx (as of %s)"
// spot check; if one request has it, they all should
Expect.stringContains text expected "Expected long as-of date not found"
"IsNew succeeds for both old and new requests",
fun reqList ->
let allReqs = reqList.RequestsByType _s
let _, _, reqs = allReqs |> List.find (fun (typ, _, _) -> typ = CurrentRequest)
Expect.hasCountOf reqs 2u countAll "There should have been two requests"
Expect.isTrue (reqList.IsNew (List.head reqs)) "The first request should have been new"
Expect.isFalse (reqList.IsNew (List.last reqs)) "The second request should not have been new"
"RequestsByType succeeds",
fun reqList ->
let allReqs = reqList.RequestsByType _s
Expect.hasLength allReqs 2 "There should have been two types of request groupings"
let maybeCurrent = allReqs |> List.tryFind (fun (typ, _, _) -> typ = CurrentRequest)
Expect.isSome maybeCurrent "There should have been current requests"
let _, _, reqs = Option.get maybeCurrent
Expect.hasCountOf reqs 2u countAll "There should have been two requests"
let first = List.head reqs
Expect.equal first.Text "zyx" "The requests should be sorted by updated date descending"
Expect.isTrue (allReqs |> List.exists (fun (typ, _, _) -> typ = PraiseReport))
"There should have been praise reports"
Expect.isFalse (allReqs |> List.exists (fun (typ, _, _) -> typ = Announcement))
"There should not have been announcements"
"RequestsByType succeeds and sorts by requestor",
fun reqList ->
let newList =
{ reqList with
SmallGroup =
{ reqList.SmallGroup with
Preferences = { reqList.SmallGroup.Preferences with RequestSort = SortByRequestor }
}
}
let allReqs = newList.RequestsByType _s
let _, _, reqs = allReqs |> List.find (fun (typ, _, _) -> typ = CurrentRequest)
Expect.hasCountOf reqs 2u countAll "There should have been two requests"
let first = List.head reqs
Expect.equal first.Text "abc" "The requests should be sorted by requestor"
]
]
[<Tests>]
let userLogOnTests =
testList "UserLogOn" [
test "empty is as expected" {
let mt = UserLogOn.empty
Expect.equal mt.Email "" "The e-mail address should be blank"
Expect.equal mt.Password "" "The password should be blank"
Expect.equal mt.SmallGroupId emptyGuid "The small group ID should be an empty GUID"
Expect.isNone mt.RememberMe "Remember Me should be None"
Expect.isNone mt.RedirectUrl "Redirect URL should be None"
}
]
[<Tests>]
let userMessageTests =
testList "UserMessage" [
test "Error is constructed properly" {
let msg = UserMessage.error
Expect.equal msg.Level Error "Incorrect message level"
Expect.equal msg.Text HtmlString.Empty "Text should have been blank"
Expect.isNone msg.Description "Description should have been None"
}
test "Warning is constructed properly" {
let msg = UserMessage.warning
Expect.equal msg.Level Warning "Incorrect message level"
Expect.equal msg.Text HtmlString.Empty "Text should have been blank"
Expect.isNone msg.Description "Description should have been None"
}
test "Info is constructed properly" {
let msg = UserMessage.info
Expect.equal msg.Level Info "Incorrect message level"
Expect.equal msg.Text HtmlString.Empty "Text should have been blank"
Expect.isNone msg.Description "Description should have been None"
}
]

122
src/UI/Church.fs Normal file
View File

@@ -0,0 +1,122 @@
module PrayerTracker.Views.Church
open Giraffe.ViewEngine
open Giraffe.ViewEngine.Accessibility
open Giraffe.ViewEngine.Htmx
open PrayerTracker
open PrayerTracker.Entities
open PrayerTracker.ViewModels
/// View for the church edit page
let edit (model : EditChurch) ctx viewInfo =
let pageTitle = if model.IsNew then "Add a New Church" else "Edit Church"
let s = I18N.localizer.Force ()
let vi =
viewInfo
|> AppViewInfo.withScopedStyles [
$"#{nameof model.Name} {{ width: 20rem; }}"
$"#{nameof model.City} {{ width: 10rem; }}"
$"#{nameof model.State} {{ width: 3rem; }}"
$"#{nameof model.InterfaceAddress} {{ width: 30rem; }}"
]
|> AppViewInfo.withOnLoadScript "PT.church.edit.onPageLoad"
form [ _action "/church/save"; _method "post"; _class "pt-center-columns"; Target.content ] [
csrfToken ctx
input [ _type "hidden"; _name (nameof model.ChurchId); _value model.ChurchId ]
div [ _fieldRow ] [
div [ _inputField ] [
label [ _for (nameof model.Name) ] [ locStr s["Church Name"] ]
inputField "text" (nameof model.Name) model.Name [ _required; _autofocus ]
]
div [ _inputField ] [
label [ _for (nameof model.City) ] [ locStr s["City"] ]
inputField "text" (nameof model.City) model.City [ _required ]
]
div [ _inputField ] [
label [ _for (nameof model.State) ] [ locStr s["State or Province"] ]
inputField "text" (nameof model.State) model.State [ _minlength "2"; _maxlength "2"; _required ]
]
]
div [ _fieldRow ] [
div [ _checkboxField ] [
inputField "checkbox" (nameof model.HasInterface) "True"
[ if defaultArg model.HasInterface false then _checked ]
label [ _for (nameof model.HasInterface) ] [
locStr s["Has an Interface with “{0}”", "Virtual Prayer Space"]
]
]
]
div [ _fieldRowWith [ "pt-fadeable" ]; _id "divInterfaceAddress" ] [
div [ _inputField ] [
label [ _for (nameof model.InterfaceAddress) ] [ locStr s["Interface URL"] ]
inputField "url" (nameof model.InterfaceAddress) (defaultArg model.InterfaceAddress "") []
]
]
div [ _fieldRow ] [ submit [] "save" s["Save Church"] ]
]
|> List.singleton
|> Layout.Content.standard
|> Layout.standard vi pageTitle
/// View for church maintenance page
let maintain (churches : Church list) (stats : Map<string, ChurchStats>) ctx viewInfo =
let s = I18N.localizer.Force ()
let vi = AppViewInfo.withScopedStyles [ "#churchList { grid-template-columns: repeat(7, auto); }" ] viewInfo
let churchTable =
match churches with
| [] -> space
| _ ->
section [ _id "churchList"; _class "pt-table"; _ariaLabel "Church list" ] [
div [ _class "row head" ] [
header [ _class "cell" ] [ locStr s["Actions"] ]
header [ _class "cell" ] [ locStr s["Name"] ]
header [ _class "cell" ] [ locStr s["Location"] ]
header [ _class "cell" ] [ locStr s["Groups"] ]
header [ _class "cell" ] [ locStr s["Requests"] ]
header [ _class "cell" ] [ locStr s["Users"] ]
header [ _class "cell" ] [ locStr s["Interface?"] ]
]
for church in churches do
let churchId = shortGuid church.Id.Value
let delAction = $"/church/{churchId}/delete"
let delPrompt = s["Are you sure you want to delete this {0}? This action cannot be undone.",
$"""{s["Church"].Value.ToLower ()} ({church.Name})"""]
div [ _class "row" ] [
div [ _class "cell actions" ] [
a [ _href $"/church/{churchId}/edit"; _title s["Edit This Church"].Value ] [
iconSized 18 "edit"
]
a [ _href delAction
_title s["Delete This Church"].Value
_hxPost delAction
_hxConfirm delPrompt.Value ] [
iconSized 18 "delete_forever"
]
]
div [ _class "cell" ] [ str church.Name ]
div [ _class "cell" ] [ str church.City; rawText ", "; str church.State ]
div [ _class "cell pt-right-text" ] [ rawText (stats[churchId].SmallGroups.ToString "N0") ]
div [ _class "cell pt-right-text" ] [ rawText (stats[churchId].PrayerRequests.ToString "N0") ]
div [ _class "cell pt-right-text" ] [ rawText (stats[churchId].Users.ToString "N0") ]
div [ _class "cell pt-center-text" ] [
locStr s[if church.HasVpsInterface then "Yes" else "No"]
]
]
]
[ div [ _class "pt-center-text" ] [
br []
a [ _href $"/church/{emptyGuid}/edit"; _title s["Add a New Church"].Value ] [
icon "add_circle"; rawText " &nbsp;"; locStr s["Add a New Church"]
]
br []
br []
]
tableSummary churches.Length s
form [ _method "post" ] [
csrfToken ctx
churchTable
]
]
|> Layout.Content.wide
|> Layout.standard vi "Maintain Churches"

231
src/UI/CommonFunctions.fs Normal file
View File

@@ -0,0 +1,231 @@
[<AutoOpen>]
module PrayerTracker.Views.CommonFunctions
open System.IO
open System.Text.Encodings.Web
open Giraffe.ViewEngine
open Microsoft.AspNetCore.Mvc.Localization
open Microsoft.Extensions.Localization
/// Encoded text for a localized string
let locStr (text: LocalizedString) =
str text.Value
/// Raw text for a localized HTML string
let rawLocText (writer: StringWriter) (text: LocalizedHtmlString) =
text.WriteTo(writer, HtmlEncoder.Default)
let txt = string writer
writer.GetStringBuilder().Clear() |> ignore
rawText txt
/// A space (used for back-to-back localization string breaks)
let space = rawText " "
/// Generate a Material Design icon
let icon name =
i [ _class "material-icons" ] [ rawText name ]
/// Generate a Material Design icon, specifying the point size (must be defined in CSS)
let iconSized size name =
i [ _class $"material-icons md-%i{size}" ] [ rawText name ]
open Giraffe
open Microsoft.AspNetCore.Antiforgery
open Microsoft.AspNetCore.Http
/// Generate a CSRF prevention token
let csrfToken (ctx: HttpContext) =
let antiForgery = ctx.GetService<IAntiforgery>()
let tokenSet = antiForgery.GetAndStoreTokens ctx
input [ _type "hidden"; _name tokenSet.FormFieldName; _value tokenSet.RequestToken ]
/// Create a summary for a table of items
let tableSummary itemCount (s: IStringLocalizer) =
div [ _class "pt-center-text" ] [
small [] [
match itemCount with
| 0 -> s["No Entries to Display"]
| 1 -> s["Displaying {0} Entry", itemCount]
| _ -> s["Displaying {0} Entries", itemCount]
|> locStr
]
]
/// Generate a list of named HTML colors
let namedColorList name selected attrs (s: IStringLocalizer) =
// The list of HTML named colors (name, display, text color)
seq {
("aqua", s["Aqua"], "black")
("black", s["Black"], "white")
("blue", s["Blue"], "white")
("fuchsia", s["Fuchsia"], "black")
("gray", s["Gray"], "white")
("green", s["Green"], "white")
("lime", s["Lime"], "black")
("maroon", s["Maroon"], "white")
("navy", s["Navy"], "white")
("olive", s["Olive"], "white")
("purple", s["Purple"], "white")
("red", s["Red"], "black")
("silver", s["Silver"], "black")
("teal", s["Teal"], "white")
("white", s["White"], "black")
("yellow", s["Yellow"], "black")
}
|> Seq.map (fun color ->
let colorName, text, txtColor = color
option
[ _value colorName
_style $"background-color:{colorName};color:{txtColor};"
if colorName = selected then _selected
] [ encodedText (text.Value.ToLower ()) ])
|> List.ofSeq
|> select (_name name :: attrs)
/// Convert a named color to its hex notation
let colorToHex (color: string) =
match color with
| it when it.StartsWith "#" -> color
| "aqua" -> "#00ffff"
| "black" -> "#000000"
| "blue" -> "#0000ff"
| "fuchsia" -> "#ff00ff"
| "gray" -> "#808080"
| "green" -> "#008000"
| "lime" -> "#00ff00"
| "maroon" -> "#800000"
| "navy" -> "#000080"
| "olive" -> "#808000"
| "purple" -> "#800080"
| "red" -> "#ff0000"
| "silver" -> "#c0c0c0"
| "teal" -> "#008080"
| "white" -> "#ffffff"
| "yellow" -> "#ffff00"
| it -> it
/// <summary>Generate an <c>input type=radio</c> that is selected if its value is the current value</summary>
let radio name domId value current =
input [ _type "radio"
_name name
if domId <> "" then _id domId
_value value
if value = current then _checked ]
/// <summary>Generate a <c>select</c> list with the current value selected</summary>
let selectList name selected attrs items =
items
|> Seq.map (fun (value, text) ->
option
[ _value value
if value = selected then _selected
] [ encodedText text ])
|> List.ofSeq
|> select (List.concat [ [ _name name; _id name ]; attrs ])
/// <summary>Generate the text for a default entry at the top of a <c>select</c> list</summary>
let selectDefault text =
$"— %s{text} —"
/// <summary>Generate a standard <c>button type=submit</c> with icon and text</summary>
let submit attrs ico text =
button (_type "submit" :: attrs) [ icon ico; rawText " &nbsp;"; locStr text ]
/// Create an HTML onsubmit event handler
let _onsubmit = attr "onsubmit"
/// <summary>A <c>rel="noopener"</c> attribute</summary>
let _relNoOpener = _rel "noopener"
/// A class attribute that designates a row of fields, with the additional classes passed
let _fieldRowWith classes =
let extraClasses = if List.isEmpty classes then "" else $""" {classes |> String.concat " "}"""
_class $"pt-field-row{extraClasses}"
/// The class that designates a row of fields
let _fieldRow = _fieldRowWith []
/// A class attribute that designates an input field, with the additional classes passed
let _inputFieldWith classes =
let extraClasses = if List.isEmpty classes then "" else $""" {classes |> String.concat " "}"""
_class $"pt-field{extraClasses}"
/// The class that designates an input field / label pair
let _inputField = _inputFieldWith []
/// The class that designates a checkbox / label pair
let _checkboxField = _class "pt-checkbox-field"
/// A group of related fields, inputs, links, etc., displayed in a row
let _group = _class "pt-group"
/// <summary>
/// Create an <c>input</c> field of the given <c>type</c>, with matching name and ID and the given value
/// </summary>
let inputField typ name value attrs =
List.concat [ [ _type typ; _name name; _id name; if value <> "" then _value value ]; attrs ] |> input
/// Generate a table heading with the given localized column names
let tableHeadings (s: IStringLocalizer) (headings: string list) =
headings
|> List.map (fun heading -> th [ _scope "col" ] [ locStr s[heading] ])
|> tr []
|> List.singleton
|> thead []
/// For a list of strings, prepend a pound sign and string them together with commas (CSS selector by ID)
let toHtmlIds it =
it |> List.map (fun x -> $"#%s{x}") |> String.concat ", "
/// The name this function used to have when the view engine was part of Giraffe
let renderHtmlNode = RenderView.AsString.htmlNode
open Microsoft.AspNetCore.Html
/// Render an HTML node, then return the value as an HTML string
let renderHtmlString = renderHtmlNode >> HtmlString
/// Utility methods to help with time zones (and localization of their names)
module TimeZones =
open PrayerTracker.Entities
/// Cross-reference between time zone Ids and their English names
let private xref = [
TimeZoneId "America/Chicago", "Central"
TimeZoneId "America/Denver", "Mountain"
TimeZoneId "America/Los_Angeles", "Pacific"
TimeZoneId "America/New_York", "Eastern"
TimeZoneId "America/Phoenix", "Mountain (Arizona)"
TimeZoneId "Europe/Berlin", "Central European"
]
/// Get the name of a time zone, given its Id
let name timeZoneId (s: IStringLocalizer) =
match xref |> List.tryFind (fun it -> fst it = timeZoneId) with
| Some tz -> s[snd tz]
| None ->
let tzId = string timeZoneId
LocalizedString (tzId, tzId)
/// All known time zones in their defined order
let all = xref |> List.map fst
open Giraffe.ViewEngine.Htmx
/// Create a page link that will make the request with fixi
let pageLink href attrs content =
a (List.append [ _href href; _hxGet href ] attrs) content
/// Known htmx targets
module Target =
/// htmx links target the body element
let body = _hxTarget "body"
/// htmx links target the #pt-body element
let content = _hxTarget "#pt-body"

300
src/UI/Help.fs Normal file
View File

@@ -0,0 +1,300 @@
/// Help content for PrayerTracker
module PrayerTracker.Views.Help
open System.IO
open Giraffe.ViewEngine
open PrayerTracker.ViewModels
/// The help index page
let index () =
let s = I18N.localizer.Force()
let l = I18N.forView "Help/Index"
use sw = new StringWriter()
let raw = rawLocText sw
[ p [] [
raw l["Throughout PrayerTracker, you'll see an icon (a question mark in a circle) next to the title on each page."]; space
raw l["Clicking this will open a new, small window with directions on using that page."]; space
raw l["If you are looking for a quick overview of PrayerTracker, start with the “Add / Edit a Request” and “Change Preferences” entries."] ]
hr []
p [ _class "pt-center-text" ] [ strong [] [ locStr s["Help Topics"] ] ]
p [] [ a [ _href "/help/small-group/preferences" ] [ locStr s["Change Preferences"] ] ]
p [] [ a [ _href "/help/small-group/announcement" ] [ locStr s["Send Announcement"] ] ]
p [] [ a [ _href "/help/small-group/members" ] [ locStr s["Maintain Group Members"] ] ]
p [] [ a [ _href "/help/requests/edit" ] [ locStr s["Add / Edit a Request"] ] ]
p [] [ a [ _href "/help/requests/maintain" ] [ locStr s["Maintain Requests"] ] ]
p [] [ a [ _href "/help/requests/view" ] [ locStr s["View Request List"] ] ]
p [] [ a [ _href "/help/user/log-on" ] [ locStr s["Log On"] ] ]
p [] [ a [ _href "/help/user/password" ] [ locStr s["Change Your Password"] ] ] ]
/// Help for prayer requests
module Requests =
/// Add / Edit a Request
let edit () =
let s = I18N.localizer.Force()
let l = I18N.forView "Help/Requests/Edit"
use sw = new StringWriter()
let raw = rawLocText sw
[ p [] [ raw l["This page allows you to enter or update a new prayer request."] ]
h2 [ _id "request-type" ] [ locStr s["Request Type"] ]
p [] [
raw l["There are 5 request types in PrayerTracker."]; space
raw l["“Current Requests” are your regular requests that people may have regarding things happening over the next week or so."]; space
raw l["“Long-Term Requests” are requests that may occur repeatedly or continue indefinitely."]; space
raw l["“Praise Reports” are like “Current Requests”, but they are answers to prayer to share with your group."]; space
raw l["“Expecting” is for those who are pregnant."]; space
raw l["“Announcements” are like “Current Requests”, but instead of a request, they are simply passing information along about something coming up."] ]
p [] [
raw l["The order above is the order in which the request types appear on the list."]; space
raw l["“Long-Term Requests” and “Expecting” are not subject to the automatic expiration (set on the “Change Preferences” page) that the other requests are."] ]
h2 [ _id "date" ] [ locStr s["Date"] ]
p [] [
raw l["For new requests, this is a box with a calendar date picker."]; space
raw l["Click or tab into the box to display the calendar, which will be preselected to today's date."]; space
raw l["For existing requests, there will be a check box labeled “Check to not update the date”."]; space
raw l["This can be used if you are correcting spelling or punctuation, and do not have an actual update to make to the request."]
]
h2 [ _id "requestor-subject" ] [ locStr s["Requestor / Subject"] ]
p [] [
raw l["For requests or praises, this field is for the name of the person who made the request or offered the praise report."]; space
raw l["For announcements, this should contain the subject of the announcement."]; space
raw l["For all types, it is optional; I used to have an announcement with no subject that ran every week, telling where to send requests and updates."] ]
h2 [ _id "expiration" ] [ locStr s["Expiration"] ]
p [] [
raw l["“Expire Normally” means that the request is subject to the expiration days in the group preferences."]; space
raw l["“Request Never Expires” can be used to make a request never expire (note that this is redundant for “Long-Term Requests” and “Expecting”)."]; space
raw l["If you are editing an existing request, a third option appears."]; space
raw l["“Expire Immediately” will make the request expire when it is saved."]; space
raw l["Apart from the icons on the request maintenance page, this is the only way to expire “Long-Term Requests” and “Expecting” requests, but it can be used for any request type."] ]
h2 [ _id "request" ] [ locStr s["Request"] ]
p [] [
raw l["This is the text of the request."]; space
raw l["The editor provides many formatting capabilities, including “Spell Check as you Type” (enabled by default), “Paste from Word”, and “Paste Plain”, as well as “Source” view, if you want to edit the HTML yourself."]; space
raw l["It also supports undo and redo, and the editor supports full-screen mode. Hover over each icon to see what each button does."] ] ]
/// Maintain Requests
let maintain () =
let s = I18N.localizer.Force()
let l = I18N.forView "Help/Requests/Maintain"
use sw = new StringWriter()
let raw = rawLocText sw
[ p [] [
raw l["From this page, you can add, edit, and delete your current requests."]; space
raw l["You can also restore requests that may have expired, but should be made active once again."] ]
h2 [ _id "add-a-new-request" ] [ locStr s["Add a New Request"] ]
p [] [
raw l["To add a request, click the icon or text in the center of the page, below the title and above the list of requests for your group."] ]
h2 [ _id "search-requests" ] [ locStr s["Search Requests"] ]
p [] [
raw l["If you are looking for a particular requests, enter some text in the search box and click “Search”."]; space
raw l["PrayerTracker will search the Requestor/Subject and Request Text fields (case-insensitively) of both active and inactive requests."]; space
raw l["The results will be displayed in the same format as the original Maintain Requests page, so the buttons described below will work the same for those requests as well."]; space
raw l["They will also be displayed in pages, if there are a lot of results; the number per page is configurable by small group."] ]
h2 [ _id "edit-request" ] [ locStr s["Edit Request"] ]
p [] [
raw l["To edit a request, click the pencil icon; it's the first icon under the “Actions” column heading."] ]
h2 [ _id "expire-a-request" ] [ locStr s["Expire a Request"] ]
p [] [
raw l["For active requests, the second icon is an eye with a slash through it; clicking this icon will expire the request immediately."]; space
raw l["This is equivalent to editing the request, selecting “Expire Immediately”, and saving it."] ]
h2 [ _id "restore-an-inactive-request" ] [ locStr s["Restore an Inactive Request"] ]
p [] [
raw l["When the page is first displayed, it does not display inactive requests."]; space
raw l["However, clicking the link at the bottom of the page will refresh the page with the inactive requests shown."]; space
raw l["The middle icon will look like an eye; clicking it will restore the request as an active request."]; space
raw l["The last updated date will be current, and the request is set to expire normally."] ]
h2 [ _id "delete-a-request" ] [ locStr s["Delete a Request"] ]
p [] [
raw l["Deleting a request is contrary to the intent of PrayerTracker, as you can retrieve requests that have expired."]; space
raw l["However, if there is a request that needs to be deleted, clicking the trash can icon in the “Actions” column will allow you to do it."]; space
raw l["Use this option carefully, as these deletions cannot be undone; once a request is deleted, it is gone for good."] ] ]
/// View Request List
let view () =
let s = I18N.localizer.Force()
let l = I18N.forView "Help/Requests/View"
use sw = new StringWriter()
let raw = rawLocText sw
[ p [] [
raw l["From this page, you can view the request list (for today or for the next Sunday), view a printable version of the list, and e-mail the list to the members of your group."]; space
raw l["(NOTE: If you are logged in as a group member, the only option you will see is to view a printable list.)"] ]
h2 [ _id "list-for-next-sunday" ] [ locStr s["List for Next Sunday"] ]
p [] [
raw l["This will modify the date for the list, so it will look like it is currently next Sunday."]; space
raw l["This can be used, for example, to see what requests will expire, or allow you to print a list with Sunday's date on Saturday evening."]; space
raw l["Note that this link does not appear if it is Sunday."] ]
h2 [ _id "view-printable" ] [ locStr s["View Printable"] ]
p [] [
raw l["Clicking this link will display the list in a format that is suitable for printing; it does not have the normal PrayerTracker header across the top."]; space
raw l["Once you have clicked the link, you can print it using your browser's standard “Print” functionality."] ]
h2 [ _id "send-via-e-mail" ] [ locStr s["Send via E-mail"] ]
p [] [
raw l["Clicking this link will send the list you are currently viewing to your group members."]; space
raw l["The page will remind you that you are about to do that, and ask for your confirmation."]; space
raw l["If you proceed, you will see a page that shows to whom the list was sent, and what the list looked like."]; space
raw l["You may safely use your browser's “Back” button to navigate away from the page."] ] ]
/// Help for small group pages
module SmallGroup =
/// Send an Announcement
let announcement () =
let s = I18N.localizer.Force()
let l = I18N.forView "Help/SmallGroup/Announcement"
use sw = new StringWriter()
let raw = rawLocText sw
[ h2 [ _id "announcement-text" ] [ locStr s["Announcement Text"] ]
p [] [
raw l["This is the text of the announcement you would like to send."]; space
raw l["""It functions the same way as the text box on the <a href="../requests/edit#request">“Edit Request” page</a>."""] ]
h2 [ _id "add-to-request-list" ] [ locStr s["Add to Request List"] ]
p [] [
raw l["Without this box checked, the text of the announcement will only be e-mailed to your group members."]; space
raw l["If you check this box, however, the text of the announcement will be added to your prayer list under the section you have selected."] ] ]
/// Maintain Group Members
let members () =
let s = I18N.localizer.Force()
let l = I18N.forView "Help/SmallGroup/Members"
use sw = new StringWriter()
let raw = rawLocText sw
[ p [] [ raw l["From this page, you can add, edit, and delete the e-mail addresses for your group."] ]
h2 [ _id "add-a-new-group-member" ] [ locStr s["Add a New Group Member"] ]
p [] [
raw l["To add an e-mail address, click the icon or text in the center of the page, below the title and above the list of addresses for your group."] ]
h2 [ _id "edit-group-member" ] [ locStr s["Edit Group Member"] ]
p [] [
raw l["To edit an e-mail address, click the pencil icon; it's the first icon under the “Actions” column heading."]; space
raw l["This will allow you to update the name and/or the e-mail address for that member."] ]
h2 [ _id "delete-a-group-member" ] [ locStr s["Delete a Group Member"] ]
p [] [
raw l["To delete an e-mail address, click the trash can icon in the “Actions” column."]; space
raw l["Note that once an e-mail address has been deleted, it is gone."]; space
raw l["(Of course, if you delete it in error, you can enter it again using the “Add” instructions above.)"] ] ]
/// Change Preferences
let preferences () =
let s = I18N.localizer.Force()
let l = I18N.forView "Help/SmallGroup/Preferences"
use sw = new StringWriter()
let raw = rawLocText sw
[ p [] [
raw l["This page allows you to change how your prayer request list looks and behaves."]; space
raw l["Each section is addressed below."] ]
h2 [ _id "requests-expire-after" ] [ locStr s["Requests Expire After"] ]
p [] [
raw l["When a regular request goes this many days without being updated, it expires and no longer appears on the request list."]; space
raw l["Note that the categories “Long-Term Requests” and “Expecting” never expire automatically."] ]
h2 [ _id "requests-new-for" ] [ locStr s["Requests “New” For"] ]
p [] [
raw l["Requests that have been updated within this many days are identified by a hollow circle for their bullet, as opposed to a filled circle for other requests."]; space
raw l["All categories respect this setting."]; space
raw l["If you do a typo correction on a request, if you do not check the box to update the date, this setting will change the bullet."]; space
raw l["(NOTE: In the plain-text e-mail, new requests are bulleted with a “+” symbol, and old are bulleted with a “-” symbol.)"] ]
h2 [ _id "long-term-requests-alerted-for-update" ] [ locStr s["Long-Term Requests Alerted for Update"] ]
p [] [
raw l["Requests that have not been updated in this many weeks are identified by an italic font on the “Maintain Requests” page, to remind you to seek updates on these requests so that your prayers can stay relevant and current."] ]
h2 [ _id "request-sorting" ] [ locStr s["Request Sorting"] ]
p [] [
raw l["By default, requests are sorted within each group by the last updated date, with the most recent on top."]; space
raw l["If you would prefer to have the list sorted by requestor or subject rather than by date, select “Sort by Requestor Name” instead."] ]
h2 [ _id "e-mail-from-name-and-address" ] [ locStr s["E-mail “From” Name and Address"] ]
p [] [
raw l["PrayerTracker must put an name and e-mail address in the “from” position of each e-mail it sends."]; space
raw l["The default name is “PrayerTracker”, and the default e-mail address is “prayer@bitbadger.solutions”."]; space
raw l["This will work, but any bounced e-mails and out-of-office replies will be sent to that address (which is not even a real address)."]; space
raw l["Changing at least the e-mail address to your address will ensure that you receive these e-mails, and can prune your e-mail list accordingly."] ]
h2 [ _id "e-mail-format" ] [ locStr s["E-mail Format"] ]
p [] [
raw l["This is the default e-mail format for your group."]; space
raw l["The PrayerTracker default is HTML, which sends the list just as you see it online."]; space
raw l["However, some e-mail clients may not display this properly, so you can choose to default the email to a plain-text format, which does not have colors, italics, or other formatting."]; space
raw l["The setting on this page is the group default; you can select a format for each recipient on the “Maintain Group Members” page."] ]
h2 [ _id "colors" ] [ locStr s["Colors"] ]
p [] [
raw l["You can customize the colors that are used for the headings and lines in your request list."]; space
raw l["You can select one of the 16 named colors in the drop down lists, or you can “mix your own” using red, green, and blue (RGB) values between 0 and 255."]; space
raw l["There is a link on the bottom of the page to a color list with more names and their RGB values, if you're really feeling artistic."]; space
raw l["The background color cannot be changed."] ]
h2 [ _id "fonts-for-list" ] [ locStr s["Fonts for List"] ]
p [] [ raw l["There are two options for fonts that will be used in the prayer request list."] ]
ul [] [
li [] [
raw l["“Native Fonts” uses a list of fonts that will render the prayer requests in the best available font for their device, whether that is a desktop or laptop computer, mobile device, or tablet."]; space
raw l["(This is the default for new small groups.)"] ]
li [] [
raw l["“Named Fonts” uses a comma-separated list of fonts that you specify."]; space
raw l["A warning is good here; just because you have an obscure font and like the way that it looks does not mean that others have that same font."]; space
raw l["It is generally best to stick with the fonts that come with Windows - fonts like “Arial”, “Times New Roman”, “Tahoma”, and “Comic Sans MS”."]; space
raw l["You should also end the font list with either “serif” or “sans-serif”, which will use the browser's default serif (like “Times New Roman”) or sans-serif (like “Arial”) font."] ] ]
h2 [ _id "heading-list-text-size" ] [ locStr s["Heading / List Text Size"] ]
p [] [
raw l["This is the point size to use for each."]; space
raw l["The default for the heading is 16pt, and the default for the text is 12pt."] ]
h2 [ _id "making-a-large-print-list" ] [ locStr s["Making a “Large Print” List"] ]
p [] [
raw l["If your group is comprised mostly of people who prefer large print, the following settings will make your list look like the typical large-print publication:"] ]
blockquote [] [
p [] [ strong [] [ locStr s["Fonts"] ]; br []; raw l["""Named Fonts: "Times New Roman",serif"""] ]
p [] [ strong [] [ locStr s["Heading Text Size"] ]; br []; rawText "18pt" ]
p [] [ strong [] [ locStr s["List Text Size"] ]; br []; rawText "16pt" ] ]
h2 [ _id "request-list-visibility" ] [ locStr s["Request List Visibility"] ]
p [] [
raw l["The group's request list can be either public, private, or password-protected."]; space
raw l["Public lists are available without logging in, and private lists are only available online to administrators (though the list can still be sent via e-mail by an administrator)."]; space
raw l["Password-protected lists allow group members to log in and view the current request list online, using the “Group Log On” link and providing this password."]; space
raw l["As this is a shared password, it is stored in plain text, so you can easily see what it is."]; space
raw l["If you select “Password Protected” but do not enter a password, the list remains private, which is also the default value."]; space
raw l["(Changing this password will force all members of the group who logged in with the “Remember Me” box checked to provide the new password.)"] ]
h2 [ _id "time-zone" ] [ locStr s["Time Zone"] ]
p [] [
raw l["This is the time zone that you would like to use for your group."]; space
raw l["""If you do not see your time zone listed, just <a href="mailto:daniel@bitbadger.solutions?subject=PrayerTracker+Time+Zone">contact Daniel</a> and tell him what time zone you need."""] ]
h2 [ _id "page-size" ] [ locStr s["Page Size"] ]
p [] [
raw l["As small groups use PrayerTracker, they accumulate many expired requests."]; space
raw l["When lists of requests include expired requests, the results will be broken up into pages."]; space
raw l["The default value is 100 requests per page, but may be set as low as 10 or as high as 255."] ]
h2 [ _id "as-of-date-display" ] [ locStr s["“As of” Date Display"] ]
p [] [
raw l["PrayerTracker can display the last date a request was updated, at the end of the request text."]; space
raw l["By default, it does not."]; space
raw l["If you select a short date, it will show “(as of 10/11/2015)” (for October 11, 2015); if you select a long date, it will show “(as of Sunday, October 11, 2015)”."] ] ]
/// Help for user pages
module User =
/// Log On
let logOn () =
let s = I18N.localizer.Force()
let l = I18N.forView "Help/User/LogOn"
use sw = new StringWriter()
let raw = rawLocText sw
[ p [] [
raw l["This page allows you to log on to PrayerTracker."]; space
raw l["There are two different levels of access for PrayerTracker - user and group."] ]
h2 [ _id "user-log-on" ] [ locStr s["User Log On"] ]
p [] [
raw l["Enter your e-mail address and password into the appropriate boxes, then select your group."]; space
raw l["If you want PrayerTracker to remember you on your computer, click the “Remember Me” box before clicking the “Log On” button."] ]
h2 [ _id "group-log-on" ] [ locStr s["Group Log On"] ]
p [] [
raw l["If your group has defined a password to use to allow you to view their request list online, select your group from the drop down list, then enter the group password into the appropriate box."]; space
raw l["If you want PrayerTracker to remember your group, click the “Remember Me” box before clicking the “Log On” button."] ] ]
/// Change Your Password
let password () =
let s = I18N.localizer.Force()
let l = I18N.forView "Help/User/Password"
use sw = new StringWriter()
let raw = rawLocText sw
[ p [] [
raw l["This page will let you change your password."]; space
raw l["Enter your existing password in the top box, then enter your new password in the bottom two boxes."]; space
raw l["Entering your existing password is a security measure; with the “Remember Me” box on the log in page, this will prevent someone else who may be using your computer from being able to simply go to the site and change your password."] ]
p [] [
raw l["If you cannot remember your existing password, we cannot retrieve it, but we can set it to something known so that you can then change it to your password."]; space
a [ _href $"""mailto:daniel@bitbadger.solutions?subject={l["PrayerTracker+Password+Help"].Value}""" ] [
raw l["Click here to request help resetting your password."] ] ] ]

259
src/UI/Home.fs Normal file
View File

@@ -0,0 +1,259 @@
/// Views associated with the home page, or those that don't fit anywhere else
module PrayerTracker.Views.Home
open System.IO
open Giraffe.ViewEngine
open PrayerTracker.ViewModels
/// The error page
let error code viewInfo =
let s = I18N.localizer.Force ()
let l = I18N.forView "Home/Error"
use sw = new StringWriter ()
let raw = rawLocText sw
let is404 = "404" = code
let pageTitle = if is404 then "Page Not Found" else "Server Error"
[ yield!
if is404 then
[ p [] [
raw l["The page you requested cannot be found."]
raw l["Please use your &ldquo;Back&rdquo; button to return to {0}.", s["PrayerTracker"]]
]
p [] [
raw l["If you reached this page from a link within {0}, please copy the link from the browser's address bar, and send it to support, along with the group for which you were currently authenticated (if any).",
s["PrayerTracker"]]
]
]
else
[ p [] [
raw l["An error ({0}) has occurred.", code]
raw l["Please use your &ldquo;Back&rdquo; button to return to {0}.", s["PrayerTracker"]]
]
]
br []
hr []
div [ _style "font-size:70%;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Oxygen-Sans,Ubuntu,Cantarell,'Helvetica Neue',sans-serif" ] [
img [ _src $"""/img/%A{s["footer_en"]}.png"""
_alt $"""%A{s["PrayerTracker"]} %A{s["from Bit Badger Solutions"]}"""
_title $"""%A{s["PrayerTracker"]} %A{s["from Bit Badger Solutions"]}"""
_style "vertical-align:text-bottom;" ]
str viewInfo.Version
]
]
|> div []
|> Layout.bare pageTitle
/// The home page
let index viewInfo =
let s = I18N.localizer.Force ()
let l = I18N.forView "Home/Index"
use sw = new StringWriter ()
let raw = rawLocText sw
[ p [] [
raw l["Welcome to <strong>{0}</strong>!", s["PrayerTracker"]]
space
raw l["{0} is an interactive website that provides churches, Sunday School classes, and other organizations an easy way to keep up with their prayer requests.",
s["PrayerTracker"]]
space
raw l["It is provided at no charge, as a ministry and a community service."]
]
h4 [] [ raw l["What Does It Do?"] ]
p [] [
raw l["{0} has what you need to make maintaining a prayer request list a breeze.", s["PrayerTracker"]]
space
raw l["Some of the things it can do..."]
]
ul [] [
li [] [
raw l["It drops old requests off the list automatically."]
space
raw l["Requests other than “{0}” requests will expire at 14 days, though this can be changed by the organization.",
s["Long-Term Requests"]]
space
raw l["This expiration is based on the last update, not the initial request."]
space
raw l["(And, once requests do “drop off”, they are not gone - they may be recovered if needed.)"]
]
li [] [
raw l["Requests can be viewed any time."]
space
raw l["Lists can be made public, or they can be secured with a password, if desired."]
]
li [] [
raw l["Lists can be e-mailed to a pre-defined list of members."]
space
raw l["This can be useful for folks who may not be able to write down all the requests during class, but want a list so that they can pray for them the rest of week."]
space
raw l["E-mails are sent individually to each person, which keeps the e-mail list private and keeps the messages from being flagged as spam."]
]
li [] [
raw l["The look and feel of the list can be configured for each group."]
space
raw l["All fonts, colors, and sizes can be customized."]
space
raw l["This allows for configuration of large-print lists, among other things."]
]
]
h4 [] [ raw l["How Can Your Organization Use {0}?", s["PrayerTracker"]] ]
p [] [
raw l["Like Gods gift of salvation, {0} is free for the asking for any church, Sunday School class, or other organization who wishes to use it.",
s["PrayerTracker"]]
space
raw l["If your organization would like to get set up, just <a href=\"mailto:daniel@djs-consulting.com?subject=New%20{0}%20Class\">e-mail</a> Daniel and let him know.",
s["PrayerTracker"]]
]
h4 [] [ raw l["Do I Have to Register to See the Requests?"] ]
p [] [
raw l["This depends on the group."]
space
raw l["Lists can be configured to be password-protected, but they do not have to be."]
space
raw l["If you click on the “{0}” link above, you will see a list of groups - those that do not indicate that they require logging in are publicly viewable.",
s["View Request List"]]
]
h4 [] [ raw l["How Does It Work?"] ]
p [] [
raw l["Check out the “{0}” link above - it details each of the processes and how they work.", s["Help"]]
]
]
|> Layout.Content.standard
|> Layout.standard viewInfo "Welcome!"
/// Privacy Policy page
let privacyPolicy viewInfo =
let s = I18N.localizer.Force ()
let l = I18N.forView "Home/PrivacyPolicy"
use sw = new StringWriter ()
let raw = rawLocText sw
[ p [ _class "pt-right-text" ] [ small [] [ em [] [ raw l["(as of July 31, 2018)"] ] ] ]
p [] [
raw l["The nature of the service is one where privacy is a must."]
space
raw l["The items below will help you understand the data we collect, access, and store on your behalf as you use this service."]
]
h3 [] [ raw l["What We Collect"] ]
ul [] [
li [] [
strong [] [ raw l["Identifying Data"] ]
rawText " &ndash; "
raw l["{0} stores the first and last names, e-mail addresses, and hashed passwords of all authorized users.",
s["PrayerTracker"]]
space
raw l["Users are also associated with one or more small groups."]
]
li [] [
strong [] [ raw l["User Provided Data"] ]
rawText " &ndash; "
raw l["{0} stores the text of prayer requests.", s["PrayerTracker"]]
space
raw l["It also stores names and e-mail addresses of small group members, and plain-text passwords for small groups with password-protected lists."]
]
]
h3 [] [ raw l["How Your Data Is Accessed / Secured"] ]
ul [] [
li [] [
raw l["While you are signed in, {0} utilizes a session cookie, and transmits that cookie to the server to establish your identity.",
s["PrayerTracker"]]
space
raw l["If you utilize the “{0}” box on sign in, a second cookie is stored, and transmitted to establish a session; this cookie is removed by clicking the “{1}” link.",
s["Remember Me"], s["Log Off"]]
space
raw l["Both of these cookies are encrypted, both in your browser and in transit."]
space
raw l["Finally, a third cookie is used to maintain your currently selected language, so that this selection is maintained across browser sessions."]
]
li [] [
raw l["Data for your small group is returned to you, as required, to display and edit."]
space
raw l["{0} also sends e-mails on behalf of the configured owner of a small group; these e-mails are sent from prayer@djs-consulting.com, with the “Reply To” header set to the configured owner of the small group.",
s["PrayerTracker"]]
space
raw l["Distinct e-mails are sent to each user, as to not disclose the other recipients."]
space
raw l["On the server, all data is stored in a controlled-access database."]
]
li [] [
raw l["Your data is backed up, along with other Bit Badger Solutions hosted systems, in a rolling manner; backups are preserved for the prior 7 days, and backups from the 1st and 15th are preserved for 3 months."]
space
raw l["These backups are stored in a private cloud data repository."]
]
li [] [
raw l["Access to servers and backups is strictly controlled and monitored for unauthorized access attempts."]
]
]
h3 [] [ raw l["Removing Your Data"] ]
p [] [
raw l["At any time, you may choose to discontinue using {0}; just e-mail Daniel, as you did to register, and request deletion of your small group.",
s["PrayerTracker"]]
]
]
|> Layout.Content.standard
|> Layout.standard viewInfo "Privacy Policy"
/// Terms of Service page
let termsOfService viewInfo =
let s = I18N.localizer.Force ()
let l = I18N.forView "Home/TermsOfService"
use sw = new StringWriter ()
let raw = rawLocText sw
let ppLink =
a [ _href "/legal/privacy-policy" ] [ str (s["Privacy Policy"].Value.ToLower ()) ]
|> renderHtmlString
[ p [ _class "pt-right-text" ] [ small [] [ em [] [ raw l["(as of May 24, 2018)"] ] ] ]
h3 [] [ str "1. "; raw l["Acceptance of Terms"] ]
p [] [
raw l["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."]
space
raw l["Your continued use of this site implies your acceptance of these terms."]
]
h3 [] [ str "2. "; raw l["Description of Service and Registration"] ]
p [] [
raw l["{0} is a service that allows individuals to enter and amend prayer requests on behalf of organizations.",
s["PrayerTracker"]]
space
raw l["Registration is accomplished via e-mail to Daniel Summers (daniel at bitbadger dot solutions, substituting punctuation)."]
space
raw l["See our {0} for details on the personal (user) information we maintain.", ppLink]
]
h3 [] [ str "3. "; raw l["Liability"] ]
p [] [
raw l["This service is provided “as is”, and no warranty (express or implied) exists."]
space
raw l["The service and its developers may not be held liable for any damages that may arise through the use of this service."]
]
h3 [] [ str "4. "; raw l["Updates to Terms"] ]
p [] [
raw l["These terms and conditions may be updated at any time."]
space
raw l["When these terms are updated, users will be notified by a system-generated announcement."]
space
raw l["Additionally, the date at the top of this page will be updated."]
]
hr []
p [] [ raw l["You may also wish to review our {0} to learn how we handle your data.", ppLink] ]
]
|> Layout.Content.standard
|> Layout.standard viewInfo "Terms of Service"
/// View for unauthorized page
let unauthorized viewInfo =
let s = I18N.localizer.Force ()
let l = I18N.forView "Home/Unauthorized"
use sw = new StringWriter ()
let raw = rawLocText sw
[ p [] [
raw l["If you feel you have reached this page in error, please <a href=\"mailto:daniel@djs-consulting.com?Subject={0}%20Unauthorized%20Access\">contact Daniel</a> and provide the details as to what you were doing (i.e., what link did you click, where had you been, etc.).",
s["PrayerTracker"]]
]
p [] [
raw l["Otherwise, you may select one of the links above to get back into an authorized portion of {0}.",
s["PrayerTracker"]]
]
]
|> Layout.Content.standard
|> Layout.standard viewInfo "Unauthorized Access"

View File

@@ -11,12 +11,12 @@ let private resAsmName = typeof<Common>.Assembly.GetName().Name
/// Set up the string and HTML localizer factories /// Set up the string and HTML localizer factories
let setUpFactories fac = let setUpFactories fac =
stringLocFactory <- fac stringLocFactory <- fac
htmlLocFactory <- HtmlLocalizerFactory stringLocFactory htmlLocFactory <- HtmlLocalizerFactory stringLocFactory
/// An instance of the common string localizer /// An instance of the common string localizer
let localizer = lazy (stringLocFactory.Create ("Common", resAsmName)) let localizer = lazy stringLocFactory.Create("Common", resAsmName)
/// Get a view localizer /// Get a view localizer
let forView (view : string) = let forView (view: string) =
htmlLocFactory.Create (sprintf "Views.%s" (view.Replace ('/', '.')), resAsmName) htmlLocFactory.Create($"Views.{view.Replace('/', '.')}", resAsmName)

350
src/UI/Layout.fs Normal file
View File

@@ -0,0 +1,350 @@
/// Layout items for PrayerTracker
module PrayerTracker.Views.Layout
open Giraffe.ViewEngine
open Giraffe.ViewEngine.Accessibility
open PrayerTracker.ViewModels
open System.Globalization
/// Get the two-character language code for the current request
let langCode () = if CultureInfo.CurrentCulture.Name.StartsWith "es" then "es" else "en"
/// Navigation items
module Navigation =
/// Top navigation bar
let top m =
let s = I18N.localizer.Force()
let menuSpacer = rawText "&nbsp; "
let _dropdown = _class "dropdown-btn"
let leftLinks = [
match m.User with
| Some u ->
li [ _class "dropdown" ] [
a [ _dropdown; _ariaLabel s["Requests"].Value; _title s["Requests"].Value; _roleButton ] [
icon "question_answer"; space; locStr s["Requests"]; space; icon "keyboard_arrow_down" ]
div [ _class "dropdown-content"; _roleMenuBar ] [
pageLink "/prayer-requests"
[ _roleMenuItem ]
[ icon "compare_arrows"; menuSpacer; locStr s["Maintain"] ]
pageLink "/prayer-requests/view"
[ _roleMenuItem ]
[ icon "list"; menuSpacer; locStr s["View List"] ] ] ]
li [ _class "dropdown" ] [
a [ _dropdown; _ariaLabel s["Group"].Value; _title s["Group"].Value; _roleButton ] [
icon "group"; space; locStr s["Group"]; space; icon "keyboard_arrow_down" ]
div [ _class "dropdown-content"; _roleMenuBar ] [
pageLink "/small-group/members"
[ _roleMenuItem ]
[ icon "email"; menuSpacer; locStr s["Maintain Group Members"] ]
pageLink "/small-group/announcement"
[ _roleMenuItem ]
[ icon "send"; menuSpacer; locStr s["Send Announcement"] ]
pageLink "/small-group/preferences"
[ _roleMenuItem ]
[ icon "build"; menuSpacer; locStr s["Change Preferences"] ] ] ]
if u.IsAdmin then
li [ _class "dropdown" ] [
a [ _dropdown
_ariaLabel s["Administration"].Value
_title s["Administration"].Value
_roleButton ] [
icon "settings"; space; locStr s["Administration"]; space; icon "keyboard_arrow_down" ]
div [ _class "dropdown-content"; _roleMenuBar ] [
pageLink "/churches" [ _roleMenuItem ] [ icon "home"; menuSpacer; locStr s["Churches"] ]
pageLink "/small-groups"
[ _roleMenuItem ]
[ icon "send"; menuSpacer; locStr s["Groups"] ]
pageLink "/users" [ _roleMenuItem ] [ icon "build"; menuSpacer; locStr s["Users"] ] ] ]
| None ->
match m.Group with
| Some _ ->
li [] [
pageLink "/prayer-requests/view"
[ _ariaLabel s["View Request List"].Value; _title s["View Request List"].Value ]
[ icon "list"; space; locStr s["View Request List"] ] ]
| None ->
li [ _class "dropdown" ] [
a [ _dropdown; _ariaLabel s["Log On"].Value; _title s["Log On"].Value; _roleButton ] [
icon "security"; space; locStr s["Log On"]; space; icon "keyboard_arrow_down" ]
div [ _class "dropdown-content"; _roleMenuBar ] [
pageLink "/user/log-on" [ _roleMenuItem ] [ icon "person"; menuSpacer; locStr s["User"] ]
pageLink "/small-group/log-on"
[ _roleMenuItem ]
[ icon "group"; menuSpacer; locStr s["Group"] ] ] ]
li [] [
pageLink "/prayer-requests/lists"
[ _ariaLabel s["View Request List"].Value; _title s["View Request List"].Value ]
[ icon "list"; space; locStr s["View Request List"] ] ]
li [] [
a [ _href "/help"; _ariaLabel s["Help"].Value; _title s["View Help"].Value; _target "_blank" ] [
icon "help"; space; locStr s["Help"] ] ] ]
let rightLinks =
match m.Group with
| Some _ -> [
match m.User with
| Some _ ->
li [] [
pageLink "/user/password"
[ _ariaLabel s["Change Your Password"].Value; _title s["Change Your Password"].Value ]
[ icon "lock"; space; locStr s["Change Your Password"] ] ]
| None -> ()
li [] [
pageLink "/log-off"
[ _ariaLabel s["Log Off"].Value; _title s["Log Off"].Value; Target.body ]
[ icon "power_settings_new"; space; locStr s["Log Off"] ] ] ]
| None -> []
header [ _class "pt-title-bar"; Target.content ] [
section [ _class "pt-title-bar-left"; _ariaLabel "Left side of top menu" ] [
span [ _class "pt-title-bar-home" ] [
pageLink "/" [ _title s["Home"].Value ] [ locStr s["PrayerTracker"] ] ]
ul [] leftLinks ]
section [ _class "pt-title-bar-center"; _ariaLabel "Empty center space in top menu" ] []
section [ _class "pt-title-bar-right"; _roleToolBar; _ariaLabel "Right side of top menu" ] [
ul [] rightLinks ] ]
/// Identity bar (below top nav)
let identity m =
let s = I18N.localizer.Force()
header [ _id "pt-language"; Target.body ] [
div [] [
span [ _title s["Language"].Value ] [ icon "record_voice_over"; space ]
match langCode () with
| "es" ->
strong [] [ locStr s["Spanish"] ]
rawText " &nbsp; &nbsp; "
pageLink "/language/en" [] [ locStr s["Change to English"] ]
| _ ->
strong [] [ locStr s["English"] ]
rawText " &nbsp; &nbsp; "
pageLink "/language/es" [] [ locStr s["Cambie a Español"] ] ]
match m.Group with
| Some g ->
[ match m.User with
| Some u ->
span [ _class "u" ] [ locStr s["Currently Logged On"] ]
rawText "&nbsp; &nbsp;"
icon "person"
strong [] [ str u.Name ]
rawText "&nbsp; &nbsp; "
| None ->
locStr s["Logged On as a Member of"]
rawText "&nbsp; "
icon "group"
space
match m.User with
| Some _ -> pageLink "/small-group" [] [ strong [] [ str g.Name ] ]
| None -> strong [] [ str g.Name ] ]
| None -> []
|> div [] ]
/// Content layouts
module Content =
/// Content layout that tops at 60rem
let standard = div [ _class "pt-content" ]
/// Content layout that uses the full width of the browser window
let wide = div [ _class "pt-content pt-full-width" ]
/// Separator for parts of the title
let private titleSep = rawText " &#xab; "
/// Common HTML head tag items
let private commonHead = [
meta [ _name "viewport"; _content "width=device-width, initial-scale=1" ]
meta [ _name "generator"; _content "Giraffe" ]
link [ _rel "stylesheet"; _href "https://fonts.googleapis.com/icon?family=Material+Icons" ]
link [ _rel "stylesheet"; _href "/_/app.css" ] ]
/// Render the <head> portion of the page
let private htmlHead viewInfo pgTitle =
let s = I18N.localizer.Force()
head [] [
meta [ _charset "UTF-8" ]
title [] [ locStr pgTitle; titleSep; locStr s["PrayerTracker"] ]
yield! commonHead
for cssFile in viewInfo.Style do
link [ _rel "stylesheet"; _href $"/_/{cssFile}.css"; _type "text/css" ] ]
/// Render a link to the help page for the current page
let private helpLink link =
let s = I18N.localizer.Force()
sup [ _class "pt-help-link" ] [
a [ _href link
_title s["Click for Help on This Page"].Value
_onclick $"return PT.showHelp('{link}')" ] [ iconSized 18 "help_outline" ] ]
/// Render the page title, and optionally a help link
let private renderPageTitle viewInfo pgTitle =
h2 [ _id "pt-page-title" ] [
match viewInfo.HelpLink with
| Some link -> helpLink $"/help/{link}"
| None -> ()
locStr pgTitle ]
/// Render the messages that may need to be displayed to the user
let private messages viewInfo =
let s = I18N.localizer.Force()
if List.isEmpty viewInfo.Messages then []
else
viewInfo.Messages
|> List.map (fun msg ->
div [ _class $"pt-msg {MessageLevel.toCssClass msg.Level}" ] [
match msg.Level with
| Info -> ()
| lvl ->
strong [] [ locStr s[MessageLevel.toString lvl] ]
rawText " &#xbb; "
rawText msg.Text.Value
match msg.Description with
| Some desc ->
br []
div [ _class "description" ] [ rawText desc.Value ]
| None -> () ])
|> div [ _class "pt-messages" ]
|> List.singleton
open NodaTime
/// Render the <footer> at the bottom of the page
let private htmlFooter viewInfo =
let s = I18N.localizer.Force()
let imgText = $"""%O{s["PrayerTracker"]} %O{s["from Bit Badger Solutions"]}"""
let resultTime = (SystemClock.Instance.GetCurrentInstant() - viewInfo.RequestStart).TotalSeconds
footer [ _class "pt-footer" ] [
div [ _id "pt-legal" ] [
pageLink "/legal/privacy-policy" [] [ locStr s["Privacy Policy"] ]
rawText " &nbsp; "
pageLink "/legal/terms-of-service" [] [ locStr s["Terms of Service"] ]
rawText " &nbsp; "
a [ _href "https://git.bitbadger.solutions/bit-badger/PrayerTracker"
_title s["View source code and get technical support"].Value
_target "_blank"
_relNoOpener ] [
locStr s["Source & Support"] ] ]
div [ _id "pt-footer" ] [
pageLink "/" [ _style "line-height:28px;" ] [
img [ _src $"""/img/%O{s["footer_en"]}.png"""
_alt imgText
_title imgText
_width "331"; _height "28" ] ]
span [ _id "pt-version" ] [ str viewInfo.Version ]
space
i [ _title s["This page loaded in {0:N3} seconds", resultTime].Value; _class "material-icons md-18" ] [
str "schedule" ] ] ]
/// The content portion of the PrayerTracker layout
let private contentSection viewInfo pgTitle (content: XmlNode) =
[ Navigation.identity viewInfo
renderPageTitle viewInfo pgTitle
yield! messages viewInfo
match viewInfo.ScopedStyle with
| [] -> ()
| styles -> style [] [ rawText (styles |> String.concat " ") ]
content
htmlFooter viewInfo
match viewInfo.OnLoadScript with
| Some onLoad ->
let doCall = if onLoad.EndsWith ")" then "" else "()"
script [] [
rawText $"
window.doOnLoad = () => {{
if (window.PT) {{
{onLoad}{doCall}
delete window.doOnLoad
}} else {{ setTimeout(window.doOnLoad, 500) }}
}}
window.doOnLoad()" ]
| None -> () ]
/// The HTML head element for partial responses
let private partialHead pgTitle =
let s = I18N.localizer.Force()
head [] [
meta [ _charset "UTF-8" ]
title [] [ locStr pgTitle; titleSep; locStr s["PrayerTracker"] ] ]
/// The body of the PrayerTracker layout
let private pageLayout viewInfo pgTitle content =
body [] [
Navigation.top viewInfo
div [ _id "pt-body"; Target.content ] (contentSection viewInfo pgTitle content)
match viewInfo.Layout with
| FullPage ->
script [ _src "/js/ckeditor/ckeditor.js" ] []
Htmx.Script.minified
script [ _src "/_/app.js" ] []
| _ -> () ]
/// The standard layout(s) for PrayerTracker
let standard viewInfo pageTitle content =
let s = I18N.localizer.Force()
let pgTitle = s[pageTitle]
html [ _lang (langCode ()) ] [
match viewInfo.Layout with
| FullPage ->
htmlHead viewInfo pgTitle
pageLayout viewInfo pgTitle content
| PartialPage ->
partialHead pgTitle
pageLayout viewInfo pgTitle content
| ContentOnly ->
partialHead pgTitle
body [] (contentSection viewInfo pgTitle content) ]
/// A layout with nothing but a title and content
let bare pageTitle content =
let s = I18N.localizer.Force()
html [ _lang (langCode ()) ] [
partialHead s[pageTitle]
body [] [ content ] ]
/// Help page layout
let help pageTitle isHome content =
let s = I18N.localizer.Force()
let pgTitle = s[pageTitle]
html [ _lang (langCode ()) ] [
head [] [
meta [ _charset "UTF-8" ]
meta [ _name "viewport"; _content "width=device-width, initial-scale=1" ]
title [] [ locStr pgTitle; titleSep; locStr s["PrayerTracker Help"] ]
link [ _href "https://fonts.googleapis.com/icon?family=Material+Icons"; _rel "stylesheet" ]
link [ _href "/_/app.css"; _rel "stylesheet" ]
link [ _href "/_/help.css"; _rel "stylesheet" ] ]
body [] [
header [ _class "pt-title-bar" ] [
section [ _class "pt-title-bar-left" ] [
span [ _class "pt-title-bar-home" ] [
a [ _href "/help"; _title "Home" ] [ locStr s["PrayerTracker"] ] ] ]
section [ _class "pt-title-bar-right" ] [ locStr s["Help"] ] ]
div [ _id "pt-body" ] [
header [ _id "pt-language" ] [
div [] [
locStr s["Language"]; rawText ": "
match langCode () with
| "es" ->
locStr s["Spanish"]; rawText " &bull; "
a [ _href "/language/en" ] [ locStr s["Change to English"] ]
| _ ->
locStr s["English"]; rawText " &bull; "
a [ _href "/language/es" ] [ locStr s["Cambie a Español"] ] ] ]
h2 [ _id "pt-page-title" ] [ locStr pgTitle ]
div [ _class "pt-content" ] [
yield! content
div [ _class "pt-close-window" ] [
p [ _class "pt-center-text" ] [
a [ _href "#"; _title s["Click to Close This Window"].Value
_onclick "window.close(); return false" ] [
i [ _class "material-icons"] [ rawText "cancel" ]
space; locStr s["Close Window"] ] ] ]
if not isHome then
div [ _class "pt-help-index" ] [
p [ _class "pt-center-text" ] [
a [ _href "/help"; _title s["Help Index"].Value ] [
rawText "&#xab; "; locStr s["Back to Help Index"] ] ] ] ] ] ] ]

353
src/UI/PrayerRequest.fs Normal file
View File

@@ -0,0 +1,353 @@
module PrayerTracker.Views.PrayerRequest
open System.Globalization
open System.IO
open Giraffe
open Giraffe.ViewEngine
open Giraffe.ViewEngine.Accessibility
open Giraffe.ViewEngine.Htmx
open Microsoft.AspNetCore.Http
open NodaTime
open PrayerTracker
open PrayerTracker.Entities
open PrayerTracker.ViewModels
/// View for the prayer request edit page
let edit (model : EditRequest) today ctx viewInfo =
let s = I18N.localizer.Force ()
let pageTitle = if model.IsNew then "Add a New Request" else "Edit Request"
let vi = AppViewInfo.withOnLoadScript "PT.initCKEditor" viewInfo
form [ _action "/prayer-request/save"
_method "post"
_class "pt-center-columns"
_onsubmit "PT.updateCKEditor()"
Target.content ] [
csrfToken ctx
inputField "hidden" (nameof model.RequestId) model.RequestId []
div [ _fieldRow ] [
div [ _inputField ] [
label [ _for (nameof model.RequestType) ] [ locStr s["Request Type"] ]
ReferenceList.requestTypeList s
|> Seq.ofList
|> Seq.map (fun (typ, desc) -> string typ, desc.Value)
|> selectList (nameof model.RequestType) model.RequestType [ _required; _autofocus ]
]
div [ _inputField ] [
label [ _for (nameof model.Requestor) ] [ locStr s["Requestor / Subject"] ]
inputField "text" (nameof model.Requestor) (defaultArg model.Requestor "") []
]
if model.IsNew then
div [ _inputField ] [
label [ _for (nameof model.EnteredDate) ] [ locStr s["Date"] ]
inputField "date" (nameof model.EnteredDate) "" [ _placeholder today ]
]
else
div [ _inputField ] [
br []
div [ _checkboxField ] [
inputField "checkbox" (nameof model.SkipDateUpdate) "True" []
label [ _for (nameof model.SkipDateUpdate) ] [ locStr s["Check to not update the date"] ]
]
small [] [ em [] [ str (s["Typo Corrections"].Value.ToLower ()); rawText ", etc." ] ]
]
]
div [ _fieldRow ] [
div [ _inputField ] [
label [] [ locStr s["Expiration"] ]
span [ _group ] [
for code, name in ReferenceList.expirationList s (not model.IsNew) do
label [] [ radio (nameof model.Expiration) "" code model.Expiration; locStr name ]
]
]
]
div [ _fieldRow ] [
div [ _inputFieldWith [ "pt-editor" ] ] [
label [ _for (nameof model.Text) ] [ locStr s["Request"] ]
textarea [ _name (nameof model.Text); _id (nameof model.Text) ] [ str model.Text ]
]
]
div [ _fieldRow ] [ submit [] "save" s["Save Request"] ]
]
|> List.singleton
|> Layout.Content.standard
|> Layout.standard vi pageTitle
/// View for the request e-mail results page
let email model viewInfo =
let s = I18N.localizer.Force ()
let pageTitle = $"""{s["Prayer Requests"].Value} {model.SmallGroup.Name}"""
let prefs = model.SmallGroup.Preferences
let addresses = model.Recipients |> List.map (fun mbr -> $"{mbr.Name} <{mbr.Email}>") |> String.concat ", "
[ p [ _style $"font-family:{prefs.FontStack};font-size:%i{prefs.TextFontSize}pt;" ] [
locStr s["The request list was sent to the following people, via individual e-mails"]
rawText ":"
br []
small [] [ str addresses ]
]
span [ _class "pt-email-heading" ] [ locStr s["HTML Format"]; rawText ":" ]
div [ _class "pt-email-canvas" ] [ rawText (model.AsHtml s) ]
br []
br []
span [ _class "pt-email-heading" ] [ locStr s["Plain-Text Format"]; rawText ":" ]
div [ _class "pt-email-canvas" ] [ pre [] [ str (model.AsText s) ] ]
]
|> Layout.Content.standard
|> Layout.standard viewInfo pageTitle
/// View for a small group's public prayer request list
let list (model : RequestList) viewInfo =
[ br []
I18N.localizer.Force () |> (model.AsHtml >> rawText)
]
|> Layout.Content.standard
|> Layout.standard viewInfo "View Request List"
/// View for the prayer request lists page
let lists (groups : SmallGroupInfo list) viewInfo =
let s = I18N.localizer.Force ()
let l = I18N.forView "Requests/Lists"
use sw = new StringWriter ()
let raw = rawLocText sw
let vi = AppViewInfo.withScopedStyles [ "#groupList { grid-template-columns: repeat(3, auto); }" ] viewInfo
[ p [] [
raw l["The groups listed below have either public or password-protected request lists."]
space
raw l["Those with list icons are public, and those with log on icons are password-protected."]
space
raw l["Click the appropriate icon to log on or view the request list."]
]
match groups.Length with
| 0 -> p [] [ raw l["There are no groups with public or password-protected request lists."] ]
| count ->
tableSummary count s
section [ _id "groupList"; _class "pt-table"; _ariaLabel "Small group list" ] [
div [ _class "row head" ] [
header [ _class "cell" ] [ locStr s["Actions"] ]
header [ _class "cell" ] [ locStr s["Church"] ]
header [ _class "cell" ] [ locStr s["Group"] ]
]
for group in groups do
div [ _class "row" ] [
div [ _class "cell actions" ] [
if group.IsPublic then
a [ _href $"/prayer-requests/{group.Id}/list"; _title s["View"].Value ] [
iconSized 18 "list"
]
else
a [ _href $"/small-group/log-on/{group.Id}"; _title s["Log On"].Value ] [
iconSized 18 "verified_user"
]
]
div [ _class "cell" ] [ str group.ChurchName ]
div [ _class "cell" ] [ str group.Name ]
]
]
]
|> Layout.Content.standard
|> Layout.standard vi "Request Lists"
/// View for the prayer request maintenance page
let maintain (model : MaintainRequests) (ctx : HttpContext) viewInfo =
let s = I18N.localizer.Force ()
let l = I18N.forView "Requests/Maintain"
use sw = new StringWriter ()
let raw = rawLocText sw
let group = model.SmallGroup
let now = group.LocalDateNow (ctx.GetService<IClock>())
let types = ReferenceList.requestTypeList s |> Map.ofList
let vi = AppViewInfo.withScopedStyles [ "#requestList { grid-template-columns: repeat(5, auto); }" ] viewInfo
/// Iterate the sequence once, before we render, so we can get the count of it at the top of the table
let requests =
model.Requests
|> List.map (fun req ->
let updateClass =
_class (if req.UpdateRequired now group then "cell pt-request-update" else "cell")
let isExpired = req.IsExpired now group
let expiredClass = _class (if isExpired then "cell pt-request-expired" else "cell")
let reqId = shortGuid req.Id.Value
let reqText = htmlToPlainText req.Text
let delAction = $"/prayer-request/{reqId}/delete"
let delPrompt =
[ s["Are you sure you want to delete this {0}? This action cannot be undone.",
s["Prayer Request"].Value.ToLower() ].Value
"\\n"
l["(If the prayer request has been answered, or an event has passed, consider inactivating it instead.)"]
.Value
]
|> String.concat ""
div [ _class "row" ] [
div [ _class "cell actions" ] [
a [ _href $"/prayer-request/{reqId}/edit"; _title l["Edit This Prayer Request"].Value ] [
iconSized 18 "edit"
]
if isExpired then
a [ _href $"/prayer-request/{reqId}/restore"
_title l["Restore This Inactive Request"].Value ] [
iconSized 18 "visibility"
]
else
a [ _href $"/prayer-request/{reqId}/expire"
_title l["Expire This Request Immediately"].Value ] [
iconSized 18 "visibility_off"
]
a [ _href delAction
_title l["Delete This Request"].Value
_hxPost delAction
_hxConfirm delPrompt ] [
iconSized 18 "delete_forever"
]
]
div [ updateClass ] [
str (req.UpdatedDate.ToString(s["MMMM d, yyyy"].Value, CultureInfo.CurrentUICulture))
]
div [ _class "cell" ] [ locStr types[req.RequestType] ]
div [ expiredClass ] [ str (match req.Requestor with Some r -> r | None -> " ") ]
div [ _class "cell" ] [
match reqText.Length with
| len when len < 60 -> rawText reqText
| _ -> rawText $"{reqText[0..59]}&hellip;"
]
])
|> List.ofSeq
[ br []
div [ _fieldRow ] [
span [ _group ] [
a [ _href $"/prayer-request/{emptyGuid}/edit"; _title s["Add a New Request"].Value ] [
icon "add_circle"; rawText " &nbsp;"; locStr s["Add a New Request"]
]
a [ _href "/prayer-requests/view"; _title s["View Prayer Request List"].Value ] [
icon "list"; rawText " &nbsp;"; locStr s["View Prayer Request List"]
]
match model.SearchTerm with
| Some _ ->
a [ _href "/prayer-requests"; _title l["Clear Search Criteria"].Value ] [
icon "highlight_off"; rawText " &nbsp;"; raw l["Clear Search Criteria"]
]
| None -> ()
]
]
form [ _action "/prayer-requests"; _method "get"; _class "pt-center-text pt-search-form"; Target.content ] [
inputField "text" "search" (defaultArg model.SearchTerm "") [ _placeholder l["Search requests..."].Value ]
space
submit [] "search" s["Search"]
]
br []
tableSummary requests.Length s
match requests.Length with
| 0 -> ()
| _ ->
form [ _method "post" ] [
csrfToken ctx
section [ _id "requestList"; _class "pt-table"; _ariaLabel "Prayer request list" ] [
div [ _class "row head" ] [
header [ _class "cell" ] [ locStr s["Actions"] ]
header [ _class "cell" ] [ locStr s["Updated Date"] ]
header [ _class "cell" ] [ locStr s["Type"] ]
header [ _class "cell" ] [ locStr s["Requestor"] ]
header [ _class "cell" ] [ locStr s["Request"] ]
]
yield! requests
]
]
div [ _class "pt-center-text" ] [
br []
match model.OnlyActive with
| Some true ->
raw l["Inactive requests are currently not shown"]
br []
a [ _href "/prayer-requests/inactive" ] [ raw l["Show Inactive Requests"] ]
| _ ->
if Option.isSome model.OnlyActive then
raw l["Inactive requests are currently shown"]
br []
a [ _href "/prayer-requests" ] [ raw l["Do Not Show Inactive Requests"] ]
br []
br []
let search = [ match model.SearchTerm with Some s -> "search", s | None -> () ]
let pg = defaultArg model.PageNbr 1
let url =
match model.OnlyActive with Some true | None -> "" | _ -> "/inactive"
|> sprintf "/prayer-requests%s"
match pg with
| 1 -> ()
| _ ->
// button (_type "submit" :: attrs) [ icon ico; rawText " &nbsp;"; locStr text ]
let withPage = match pg with 2 -> search | _ -> ("page", string (pg - 1)) :: search
a [ _href (makeUrl url withPage) ] [ icon "keyboard_arrow_left"; space; raw l["Previous Page"] ]
rawText " &nbsp; &nbsp; "
match requests.Length = model.SmallGroup.Preferences.PageSize with
| true ->
a [ _href (makeUrl url (("page", string (pg + 1)) :: search)) ] [
raw l["Next Page"]; space; icon "keyboard_arrow_right"
]
| false -> ()
]
]
|> Layout.Content.wide
|> Layout.standard vi (match model.SearchTerm with Some _ -> "Search Results" | None -> "Maintain Requests")
/// View for the printable prayer request list
let print model version =
let s = I18N.localizer.Force ()
let pageTitle = $"""{s["Prayer Requests"].Value} {model.SmallGroup.Name}"""
let imgAlt = $"""{s["PrayerTracker"].Value} {s["from Bit Badger Solutions"].Value}"""
article [] [
rawText (model.AsHtml s)
br []
hr []
div [ _style $"font-size:70%%;font-family:{model.SmallGroup.Preferences.FontStack};" ] [
img [ _src $"""/img/{s["footer_en"].Value}.png"""
_style "vertical-align:text-bottom;"
_alt imgAlt
_title imgAlt ]
space
str version
]
]
|> Layout.bare pageTitle
/// View for the prayer request list
let view model viewInfo =
let s = I18N.localizer.Force ()
let pageTitle = $"""{s["Prayer Requests"].Value} {model.SmallGroup.Name}"""
let dtString = model.Date.ToString ("yyyy-MM-dd", CultureInfo.InvariantCulture)
[ br []
div [ _fieldRow ] [
span [ _group ] [
a [ _class "pt-icon-link"
_href $"/prayer-requests/print/{dtString}"
_target "_blank"
_title s["View Printable"].Value ] [
icon "print"; rawText " &nbsp;"; locStr s["View Printable"]
]
if model.CanEmail then
if model.Date.DayOfWeek <> IsoDayOfWeek.Sunday then
let rec findSunday (date : LocalDate) =
if date.DayOfWeek = IsoDayOfWeek.Sunday then date else findSunday (date.PlusDays 1)
let sunday = findSunday model.Date
a [ _class "pt-icon-link"
_href $"""/prayer-requests/view/{sunday.ToString ("yyyy-MM-dd", CultureInfo.InvariantCulture)}"""
_title s["List for Next Sunday"].Value ] [
icon "update"; rawText " &nbsp;"; locStr s["List for Next Sunday"]
]
a [ _class "pt-icon-link"
_href $"/prayer-requests/email/{dtString}"
_title s["Send via E-mail"].Value
_hxConfirm s["This will e-mail the current list to every member of your group, without further prompting. Are you sure this is what you are ready to do?"].Value ] [
icon "mail_outline"; rawText " &nbsp;"; locStr s["Send via E-mail"]
]
a [ _class "pt-icon-link"; _href "/prayer-requests"; _title s["Maintain Prayer Requests"].Value ] [
icon "compare_arrows"; rawText " &nbsp;"; locStr s["Maintain Prayer Requests"]
]
]
]
br []
rawText (model.AsHtml s)
]
|> Layout.Content.standard
|> Layout.standard viewInfo pageTitle

View File

@@ -1,9 +1,5 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.1</TargetFramework>
</PropertyGroup>
<ItemGroup> <ItemGroup>
<Compile Include="Utils.fs" /> <Compile Include="Utils.fs" />
<Compile Include="ViewModels.fs" /> <Compile Include="ViewModels.fs" />
@@ -11,6 +7,7 @@
<Compile Include="CommonFunctions.fs" /> <Compile Include="CommonFunctions.fs" />
<Compile Include="Layout.fs" /> <Compile Include="Layout.fs" />
<Compile Include="Church.fs" /> <Compile Include="Church.fs" />
<Compile Include="Help.fs" />
<Compile Include="Home.fs" /> <Compile Include="Home.fs" />
<Compile Include="PrayerRequest.fs" /> <Compile Include="PrayerRequest.fs" />
<Compile Include="SmallGroup.fs" /> <Compile Include="SmallGroup.fs" />
@@ -18,23 +15,47 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Giraffe" Version="4.0.1" /> <PackageReference Include="Giraffe.ViewEngine" Version="1.4.0" />
<PackageReference Include="MailKit" Version="2.3.2" /> <PackageReference Include="Giraffe.ViewEngine.Htmx" Version="2.0.4" />
<PackageReference Include="Microsoft.AspNetCore.Html.Abstractions" Version="2.2.0" /> <PackageReference Include="MailKit" Version="4.10.0" />
<PackageReference Include="Microsoft.AspNetCore.Http" Version="2.2.2" /> <PackageReference Update="FSharp.Core" Version="9.0.101" />
<PackageReference Include="Microsoft.AspNetCore.Http.Extensions" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.2.0" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.2" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\PrayerTracker.Data\PrayerTracker.Data.fsproj" /> <ProjectReference Include="..\Data\PrayerTracker.Data.fsproj" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<EmbeddedResource Update="Resources\Common.es.resx"> <EmbeddedResource Update="Resources\Common.es.resx">
<Generator>ResXFileCodeGenerator</Generator> <Generator>ResXFileCodeGenerator</Generator>
</EmbeddedResource> </EmbeddedResource>
<EmbeddedResource Update="Resources\Help\Index.es.resx">
<Generator>ResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Help\Requests\Edit.es.resx">
<Generator>ResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Help\Requests\Maintain.es.resx">
<Generator>ResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Help\Requests\View.es.resx">
<Generator>ResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Help\SmallGroup\Announcement.es.resx">
<Generator>ResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Help\SmallGroup\Members.es.resx">
<Generator>ResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Help\SmallGroup\Preferences.es.resx">
<Generator>ResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Help\User\LogOn.es.resx">
<Generator>ResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Help\User\Password.es.resx">
<Generator>ResXFileCodeGenerator</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Resources\Views\Home\Error.es.resx"> <EmbeddedResource Update="Resources\Views\Home\Error.es.resx">
<Generator>ResXFileCodeGenerator</Generator> <Generator>ResXFileCodeGenerator</Generator>
</EmbeddedResource> </EmbeddedResource>
@@ -61,8 +82,4 @@
</EmbeddedResource> </EmbeddedResource>
</ItemGroup> </ItemGroup>
<ItemGroup>
<PackageReference Update="FSharp.Core" Version="4.7.0" />
</ItemGroup>
</Project> </Project>

View File

@@ -396,8 +396,8 @@
<data name="The group member “{0}” was deleted successfully" xml:space="preserve"> <data name="The group member “{0}” was deleted successfully" xml:space="preserve">
<value>El miembro del grupo “{0}” se eliminó con éxito</value> <value>El miembro del grupo “{0}” se eliminó con éxito</value>
</data> </data>
<data name="The group {0} and its {1} prayer request(s) was deleted successfully (revoked access from {2} user(s))" xml:space="preserve"> <data name="The group {0} and its {1} prayer request(s) were deleted successfully; revoked access from {2} user(s)" xml:space="preserve">
<value>El grupo {0} y sus {1} peticion(es) de oración se ha eliminado correctamente (acceso revocada por {2} usuario(s))</value> <value>El grupo {0} y sus {1} peticion(es) de oración se ha eliminado correctamente; acceso revocada por {2} usuario(s)</value>
</data> </data>
<data name="The old password was incorrect - your password was NOT changed" xml:space="preserve"> <data name="The old password was incorrect - your password was NOT changed" xml:space="preserve">
<value>La contraseña antigua es incorrecta - la contraseña NO ha cambiado</value> <value>La contraseña antigua es incorrecta - la contraseña NO ha cambiado</value>
@@ -417,8 +417,8 @@
<data name="There are no classes with passwords defined" xml:space="preserve"> <data name="There are no classes with passwords defined" xml:space="preserve">
<value>No hay clases con contraseñas se define</value> <value>No hay clases con contraseñas se define</value>
</data> </data>
<data name="This is likely due to one of the following reasons:&lt;ul&gt;&lt;li&gt;The e-mail address “{0}” is invalid.&lt;/li&gt;&lt;li&gt;The password entered does not match the password for the given e-mail address.&lt;/li&gt;&lt;li&gt;You are not authorized to administer the group “{1}”.&lt;/li&gt;&lt;/ul&gt;" xml:space="preserve"> <data name="This is likely due to one of the following reasons:&lt;ul&gt;&lt;li&gt;The e-mail address “{0}” is invalid.&lt;/li&gt;&lt;li&gt;The password entered does not match the password for the given e-mail address.&lt;/li&gt;&lt;li&gt;You are not authorized to administer the selected group.&lt;/li&gt;&lt;/ul&gt;" xml:space="preserve">
<value>Esto es probablemente debido a una de las siguientes razones:&lt;ul&gt;&lt;li&gt;La dirección de correo electrónico “{0}” no es válida.&lt;/li&gt;&lt;li&gt;La contraseña introducida no coincide con la contraseña de la determinada dirección de correo electrónico.&lt;/li&gt;&lt;li&gt;Usted no está autorizado para administrar el grupo “{1}”.&lt;/li&gt;&lt;/ul&gt;</value> <value>Esto es probablemente debido a una de las siguientes razones:&lt;ul&gt;&lt;li&gt;La dirección de correo electrónico “{0}” no es válida.&lt;/li&gt;&lt;li&gt;La contraseña introducida no coincide con la contraseña de la determinada dirección de correo electrónico.&lt;/li&gt;&lt;li&gt;Usted no está autorizado para administrar el grupo seleccionado.&lt;/li&gt;&lt;/ul&gt;</value>
</data> </data>
<data name="This page loaded in {0:N3} seconds" xml:space="preserve"> <data name="This page loaded in {0:N3} seconds" xml:space="preserve">
<value>Esta página cargada en {0:N3} segundos</value> <value>Esta página cargada en {0:N3} segundos</value>
@@ -742,7 +742,7 @@
<value>Este</value> <value>Este</value>
</data> </data>
<data name="MMMM d, yyyy" xml:space="preserve"> <data name="MMMM d, yyyy" xml:space="preserve">
<value>d \de MMMM yyyy</value> <value>d \d\e MMMM yyyy</value>
</data> </data>
<data name="Mountain" xml:space="preserve"> <data name="Mountain" xml:space="preserve">
<value>Montaña</value> <value>Montaña</value>
@@ -822,4 +822,100 @@
<data name="as of" xml:space="preserve"> <data name="as of" xml:space="preserve">
<value>como de</value> <value>como de</value>
</data> </data>
<data name="State or Province" xml:space="preserve">
<value>Estado o Provincia</value>
</data>
<data name="Last Seen" xml:space="preserve">
<value>Ultima vez Visto</value>
</data>
<data name="Administrators" xml:space="preserve">
<value>Administradores</value>
</data>
<data name="Native Fonts" xml:space="preserve">
<value>Fuentes Nativas</value>
</data>
<data name="Named Fonts" xml:space="preserve">
<value>Fuentes con Nombre</value>
</data>
<data name="Select Church" xml:space="preserve">
<value>Seleccione una Iglesia</value>
</data>
<data name="Select Group" xml:space="preserve">
<value>Seleccione un Grupo</value>
</data>
<data name="Member Name" xml:space="preserve">
<value>Nombre de Miembro</value>
</data>
<data name="Custom Color" xml:space="preserve">
<value>Color Personalizado</value>
</data>
<data name="Church Name" xml:space="preserve">
<value>Nombre de la Iglesia</value>
</data>
<data name="City" xml:space="preserve">
<value>Ciudad</value>
</data>
<data name="Has an Interface with “{0}”" xml:space="preserve">
<value>Tiene una Interfaz con “{0}”</value>
</data>
<data name="Interface URL" xml:space="preserve">
<value>URL de la Interfaz</value>
</data>
<data name="Successfully {0} church “{1}”" xml:space="preserve">
<value>Iglesia “{1}” {0} con éxito</value>
</data>
<data name="The church “{0}” and its {1} small group(s) (with {2} prayer request(s)) were deleted successfully; revoked access from {3} user(s)" xml:space="preserve">
<value>La iglesia "{0}" y sus {1} grupo(s) (con {2} peticion(es) de oración) se eliminaron correctamente; acceso revocado de {3} usuario(s)</value>
</data>
<data name="Successfully {0} group “{1}”" xml:space="preserve">
<value>El grupo “{1}” {0} con éxito</value>
</data>
<data name="First Name" xml:space="preserve">
<value>Primer Nombre</value>
</data>
<data name="Last Name" xml:space="preserve">
<value>Apellido</value>
</data>
<data name="Password Again" xml:space="preserve">
<value>Contraseña otra Vez</value>
</data>
<data name="This User Is a {0} Administrator" xml:space="preserve">
<value>Este Usuario Es un Administrador de {0}</value>
</data>
<data name="PrayerTracker Help" xml:space="preserve">
<value>Ayuda de SeguidorOración</value>
</data>
<data name="Click to Close This Window" xml:space="preserve">
<value>Haga Clic para Cerrar Esta Ventana</value>
</data>
<data name="Close Window" xml:space="preserve">
<value>Cerrar Esta Ventana</value>
</data>
<data name="Help Index" xml:space="preserve">
<value>Índice de Ayuda</value>
</data>
<data name="Back to Help Index" xml:space="preserve">
<value>Volver al Índice de Ayuda</value>
</data>
<data name="Add / Edit a Request" xml:space="preserve">
<value>Agregar o Editar una Petición</value>
</data>
<data name="Search Requests" xml:space="preserve">
<value>Peticiones de Búsqueda</value>
</data>
<data name="Expire a Request" xml:space="preserve">
<value>Expirar un Petición</value>
</data>
<data name="Restore an Inactive Request" xml:space="preserve">
<value>Restaurar un Petición Inactiva</value>
</data>
<data name="E-mail “From” Name and Address" xml:space="preserve">
<value>Correo Electrónico “De” Nombre y Dirección</value>
</data>
<data name="Fonts for List" xml:space="preserve">
<value>Fuentes de la Lista</value>
</data>
<data name="Making a “Large Print” List" xml:space="preserve">
<value>Realización de una Lista de “Letra Grande”</value>
</data>
</root> </root>

View File

@@ -0,0 +1,70 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="Throughout PrayerTracker, you'll see an icon (a question mark in a circle) next to the title on each page." xml:space="preserve">
<value>En todo el sistema, verá un icono (un signo de interrogación en un círculo) junto al título de cada página.</value>
</data>
<data name="Clicking this will open a new, small window with directions on using that page." xml:space="preserve">
<value>Al hacer clic en esta opción, se abrirá una nueva y pequeña ventana con instrucciones sobre cómo usar esa página.</value>
</data>
<data name="If you are looking for a quick overview of PrayerTracker, start with the “Add / Edit a Request” and “Change Preferences” entries." xml:space="preserve">
<value>Si está buscando una descripción rápida de SeguidorOración, comience con las entradas “Agregar o Editar una Petición” y “Cambiar las Preferencias”.</value>
</data>
</root>

View File

@@ -0,0 +1,133 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="This page allows you to enter or update a new prayer request." xml:space="preserve">
<value>Esta página le permite introducir o actualizar una petición de oración nueva.</value>
</data>
<data name="There are 5 request types in PrayerTracker." xml:space="preserve">
<value>Hay 5 tipos de peticiones en SeguidorOración.</value>
</data>
<data name="“Current Requests” are your regular requests that people may have regarding things happening over the next week or so." xml:space="preserve">
<value>“Peticiones Actuales” son sus peticiones habituales que la gente pueda tener acerca de las cosas que suceden durante la próxima semana o así.</value>
</data>
<data name="“Long-Term Requests” are requests that may occur repeatedly or continue indefinitely." xml:space="preserve">
<value>“Peticiones a Largo Plazo” son peticiones que pueden ocurrir varias veces, o continuar indefinidamente.</value>
</data>
<data name="“Praise Reports” are like “Current Requests”, but they are answers to prayer to share with your group." xml:space="preserve">
<value>“Informes de Alabanza” son como “Peticiones Actuales”, pero son respuestas a la oración para compartir con su grupo.</value>
</data>
<data name="“Expecting” is for those who are pregnant." xml:space="preserve">
<value>“Embarazada” es para aquellos que están embarazadas.</value>
</data>
<data name="“Announcements” are like “Current Requests”, but instead of a request, they are simply passing information along about something coming up." xml:space="preserve">
<value>“Anuncios” son como “Peticiones Actuales”, pero en lugar de una petición, simplemente se pasa la información a lo largo de algo por venir.</value>
</data>
<data name="The order above is the order in which the request types appear on the list." xml:space="preserve">
<value>El orden anterior es el orden en que los tipos de peticiones aparecen en la lista.</value>
</data>
<data name="“Long-Term Requests” and “Expecting” are not subject to the automatic expiration (set on the “Change Preferences” page) that the other requests are." xml:space="preserve">
<value>“Peticiones a Largo Plazo” y “Embarazada” no están sujetos a la caducidad automática (establecida en el “Cambiar las Preferencias” de la página) que las peticiones son otros.</value>
</data>
<data name="For new requests, this is a box with a calendar date picker." xml:space="preserve">
<value>Para nuevas peticiones, se trata de una caja con un selector de fechas del calendario.</value>
</data>
<data name="Click or tab into the box to display the calendar, which will be preselected to today's date." xml:space="preserve">
<value>Haga clic en la pestaña o en la caja para mostrar el calendario, que será preseleccionada para la fecha de hoy.</value>
</data>
<data name="For existing requests, there will be a check box labeled “Check to not update the date”." xml:space="preserve">
<value>Para peticiones existentes, habrá una casilla de verificación “Seleccionar para no actualizar la fecha”.</value>
</data>
<data name="This can be used if you are correcting spelling or punctuation, and do not have an actual update to make to the request." xml:space="preserve">
<value>Esto puede ser usado si corrige la ortografía ni la puntuacion, y no tienen una actualización real de hacer la petición.</value>
</data>
<data name="For requests or praises, this field is for the name of the person who made the request or offered the praise report." xml:space="preserve">
<value>Para las peticiones o alabanzas, este campo es el nombre de la persona que hizo la petición o que ofrece el informe de alabanza.</value>
</data>
<data name="For announcements, this should contain the subject of the announcement." xml:space="preserve">
<value>Para los anuncios, este debe contener el objeto del anuncio.</value>
</data>
<data name="For all types, it is optional; I used to have an announcement with no subject that ran every week, telling where to send requests and updates." xml:space="preserve">
<value>Para todos los tipos, es opcional, yo solía tener un anuncio con ningún tema que iba todas las semanas, diciendo a dónde enviar peticiones y actualizaciones.</value>
</data>
<data name="“Expire Normally” means that the request is subject to the expiration days in the group preferences." xml:space="preserve">
<value>“Expirará Normalmente” significa que la petición está sujeta a los días de vencimiento de las preferencias del grupo.</value>
</data>
<data name="“Request Never Expires” can be used to make a request never expire (note that this is redundant for “Long-Term Requests” and “Expecting”)." xml:space="preserve">
<value>“Petición no Expira Nunca” se puede utilizar para hacer una petición que no caduque nunca (nótese que esto es redundante para los tipos “Peticiones a Largo Plazo” y “Embarazada”).</value>
</data>
<data name="If you are editing an existing request, a third option appears." xml:space="preserve">
<value>Si está editando una petición existente, aparece una tercera opción.</value>
</data>
<data name="“Expire Immediately” will make the request expire when it is saved." xml:space="preserve">
<value>“Expirará Inmediatamente” hará que la petición expirará cuando se guarda.</value>
</data>
<data name="Apart from the icons on the request maintenance page, this is the only way to expire “Long-Term Requests” and “Expecting” requests, but it can be used for any request type." xml:space="preserve">
<value>Aparte de los iconos de la página de mantenimiento de las peticiones, ésta es la única otra forma de expirar peticiones del tipos “Peticiones a Largo Plazo” y “Embarazada”, pero puede ser utilizada para cualquier tipo de petición.</value>
</data>
<data name="This is the text of the request." xml:space="preserve">
<value>Este es el texto de la petición.</value>
</data>
<data name="The editor provides many formatting capabilities, including “Spell Check as you Type” (enabled by default), “Paste from Word”, and “Paste Plain”, as well as “Source” view, if you want to edit the HTML yourself." xml:space="preserve">
<value>El editor ofrece muchas capacidades de formato, como "El Corrector Ortográfico al Escribir" (habilitado predeterminado), "Pegar desde Word" y "Pegar sin formato", así como "Código Fuente" punto de vista, si quieres editar el código HTML usted mismo.</value>
</data>
<data name="It also supports undo and redo, and the editor supports full-screen mode. Hover over each icon to see what each button does." xml:space="preserve">
<value>También es compatible con deshacer y rehacer, y el editor soporta modo de pantalla completa. Pase el ratón sobre cada icono para ver qué hace cada botón.</value>
</data>
</root>

View File

@@ -0,0 +1,112 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="From this page, you can add, edit, and delete your current requests." xml:space="preserve">
<value>Desde esta página, usted puede agregar, editar y borrar sus peticiones actuales.</value>
</data>
<data name="You can also restore requests that may have expired, but should be made active once again." xml:space="preserve">
<value>También puede restaurar peticiones que han caducado, sino que debe ser activa, una vez más.</value>
</data>
<data name="To add a request, click the icon or text in the center of the page, below the title and above the list of requests for your group." xml:space="preserve">
<value>Para agregar una petición, haga clic en el icono o el texto en el centro de la página, debajo del título y por encima de la lista de peticiones para su grupo.</value>
</data>
<data name="If you are looking for a particular requests, enter some text in the search box and click “Search”." xml:space="preserve">
<value>Si está buscando una solicitud en particular, ingrese un texto en el cuadro de búsqueda y haga clic en “Buscar”.</value>
</data>
<data name="PrayerTracker will search the Requestor/Subject and Request Text fields (case-insensitively) of both active and inactive requests." xml:space="preserve">
<value>SeguidorOración buscará los campos de Solicitante / Asunto y Texto de solicitud (sin distinción de mayúsculas y minúsculas) de solicitudes activas e inactivas.</value>
</data>
<data name="The results will be displayed in the same format as the original Maintain Requests page, so the buttons described below will work the same for those requests as well." xml:space="preserve">
<value>Los resultados se mostrarán en el mismo formato que la página de solicitudes de mantenimiento original, por lo que los botones que se describen a continuación funcionarán igual para esas solicitudes.</value>
</data>
<data name="They will also be displayed in pages, if there are a lot of results; the number per page is configurable by small group." xml:space="preserve">
<value>También se mostrarán en las páginas, si hay muchos resultados; el número por página es configurable por grupos pequeños.</value>
</data>
<data name="To edit a request, click the pencil icon; it's the first icon under the “Actions” column heading." xml:space="preserve">
<value>Para editar una petición, haga clic en el icono de lápiz, el primer icono bajo el título de columna “Acciones”.</value>
</data>
<data name="For active requests, the second icon is an eye with a slash through it; clicking this icon will expire the request immediately." xml:space="preserve">
<value>Para las peticiones activas, el segundo icono es un ojo con una barra a través de él; Si hace clic en este icono, la petición se cancelará inmediatamente.</value>
</data>
<data name="This is equivalent to editing the request, selecting “Expire Immediately”, and saving it." xml:space="preserve">
<value>Esto equivale a editar la petición, seleccionar "Expirará Inmediatamente" y guardarla.</value>
</data>
<data name="When the page is first displayed, it does not display inactive requests." xml:space="preserve">
<value>Cuando la página se muestra por primera vez, que no muestra peticiones inactivos.</value>
</data>
<data name="However, clicking the link at the bottom of the page will refresh the page with the inactive requests shown." xml:space="preserve">
<value>Sin embargo, al hacer clic en el vínculo en la parte inferior de la página se actualizará la página con las peticiones se muestran inactivos.</value>
</data>
<data name="The middle icon will look like an eye; clicking it will restore the request as an active request." xml:space="preserve">
<value>El icono del centro se verá como un ojo; Haciendo clic en él, restaurará la petición como una petición activa.</value>
</data>
<data name="The last updated date will be current, and the request is set to expire normally." xml:space="preserve">
<value>La última fecha actualizada será actual, y la petición se establece para caducar normalmente.</value>
</data>
<data name="Deleting a request is contrary to the intent of PrayerTracker, as you can retrieve requests that have expired." xml:space="preserve">
<value>Eliminación de una petición es contraria a la intención de SeguidorOración, como se puede recuperar peticiones que han expirado.</value>
</data>
<data name="However, if there is a request that needs to be deleted, clicking the trash can icon in the “Actions” column will allow you to do it." xml:space="preserve">
<value>Sin embargo, si hay una solicitud que debe ser eliminado, haga clic en el icono de la papelera en la columna “Acciones” le permitirá hacerlo.</value>
</data>
<data name="Use this option carefully, as these deletions cannot be undone; once a request is deleted, it is gone for good." xml:space="preserve">
<value>Utilice esta opción con cuidado, ya que estas supresiones no se puede deshacer, una vez a la petición se ha borrado, ha desaparecido para siempre.</value>
</data>
</root>

View File

@@ -0,0 +1,94 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="From this page, you can view the request list (for today or for the next Sunday), view a printable version of the list, and e-mail the list to the members of your group." xml:space="preserve">
<value>Desde esta página, puede ver la lista de peticiones (para hoy o para el próximo Domingo), ver una versión imprimible de la lista, y por correo electrónico la lista de los miembros de su grupo.</value>
</data>
<data name="(NOTE: If you are logged in as a group member, the only option you will see is to view a printable list.)" xml:space="preserve">
<value>(NOTA: Si usted está registrado como miembro de la clase, la única opción que se ve es para ver una lista para imprimir.)</value>
</data>
<data name="This will modify the date for the list, so it will look like it is currently next Sunday." xml:space="preserve">
<value>Esto modificará la fecha de la lista, por lo que se verá como es en la actualidad el próximo Domingo.</value>
</data>
<data name="This can be used, for example, to see what requests will expire, or allow you to print a list with Sunday's date on Saturday evening." xml:space="preserve">
<value>Esto puede ser usado, por ejemplo, para ver lo que peticiones de caducidad, ni le permite imprimir una lista con la fecha del Domingo en la noche del Sábado.</value>
</data>
<data name="Note that this link does not appear if it is Sunday." xml:space="preserve">
<value>Tenga en cuenta que este enlace no aparece si es Domingo.</value>
</data>
<data name="Clicking this link will display the list in a format that is suitable for printing; it does not have the normal PrayerTracker header across the top." xml:space="preserve">
<value>Hacer clic en este vínculo, se muestra la lista en un formato que sea adecuado para imprimir, sino que no tiene el encabezado normal de SeguidorOración en la parte superior.</value>
</data>
<data name="Once you have clicked the link, you can print it using your browser's standard “Print” functionality." xml:space="preserve">
<value>Una vez que haya hecho clic en el enlace, se puede imprimir con el navegador estándar de “Imprimir” funcionalidad.</value>
</data>
<data name="Clicking this link will send the list you are currently viewing to your group members." xml:space="preserve">
<value>Al hacer clic en este enlace le enviará la lista que está viendo en ese momento a los miembros del grupo.</value>
</data>
<data name="The page will remind you that you are about to do that, and ask for your confirmation." xml:space="preserve">
<value>La página te recordará que estás a punto de hacerlo, y pedir su confirmación.</value>
</data>
<data name="If you proceed, you will see a page that shows to whom the list was sent, and what the list looked like." xml:space="preserve">
<value>Si continúa, usted verá una página que muestra a la que la lista fue enviado, y lo que la lista parecía.</value>
</data>
<data name="You may safely use your browser's “Back” button to navigate away from the page." xml:space="preserve">
<value>Usted puede utilizar con seguridad de su navegador botón “Atrás” para navegar fuera de la página.</value>
</data>
</root>

View File

@@ -0,0 +1,73 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="This is the text of the announcement you would like to send." xml:space="preserve">
<value>Este es el texto del anuncio que desea enviar.</value>
</data>
<data name="It functions the same way as the text box on the &lt;a href=&quot;../requests/edit#request&quot;&gt;“Edit Request” page&lt;/a&gt;." xml:space="preserve">
<value>Funciona de la misma forma que el cuadro de texto en &lt;a href="../requests/edit#request"&gt;la página “Editar la Petición”&lt;/a&gt;.</value>
</data>
<data name="Without this box checked, the text of the announcement will only be e-mailed to your group members." xml:space="preserve">
<value>Sin esta caja marcada, el texto del anuncio sólo será por correo electrónico a los miembros del su grupo.</value>
</data>
<data name="If you check this box, however, the text of the announcement will be added to your prayer list under the section you have selected." xml:space="preserve">
<value>Si marca esta caja, sin embargo, el texto del anuncio será añadido a su lista de oración en la sección que ha seleccionado.</value>
</data>
</root>

View File

@@ -0,0 +1,82 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="From this page, you can add, edit, and delete the e-mail addresses for your group." xml:space="preserve">
<value>Desde esta página, usted puede agregar, editar y eliminar las direcciones de correo electrónico para su grupo.</value>
</data>
<data name="To add an e-mail address, click the icon or text in the center of the page, below the title and above the list of addresses for your group." xml:space="preserve">
<value>Para agregar una dirección de correo electrónico, haga clic en el icono o el texto en el centro de la página, debajo del título y por encima de la lista de direcciones para su grupo.</value>
</data>
<data name="To edit an e-mail address, click the pencil icon; it's the first icon under the “Actions” column heading." xml:space="preserve">
<value>Para editar una dirección de correo electrónico, haga clic en el icono de lápiz, es el primer icono bajo el título de columna “Acciones”.</value>
</data>
<data name="This will allow you to update the name and/or the e-mail address for that member." xml:space="preserve">
<value>Esto le permitirá actualizar el nombre y / o la dirección de correo electrónico para ese miembro.</value>
</data>
<data name="To delete an e-mail address, click the trash can icon in the “Actions” column." xml:space="preserve">
<value>Para eliminar una dirección de correo electrónico, haga clic en el icono de la papelera en la columna “Acciones”.</value>
</data>
<data name="Note that once an e-mail address has been deleted, it is gone." xml:space="preserve">
<value>Tenga en cuenta que una vez que la dirección de correo electrónico se ha eliminado, se ha ido.</value>
</data>
<data name="(Of course, if you delete it in error, you can enter it again using the “Add” instructions above.)" xml:space="preserve">
<value>(Por supuesto, si usted lo elimine por error, se puede entrar de nuevo utilizando la opción “Agregar” instrucciones de arriba.)</value>
</data>
</root>

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