Compare commits

...

16 Commits
v8 ... main

Author SHA1 Message Date
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
68 changed files with 2342 additions and 2193 deletions

3
.gitignore vendored
View File

@ -334,4 +334,5 @@ src/PrayerTracker/appsettings.json
docs/_site docs/_site
**/*.db* **/*.db*
.ionide .ionide
.vscode

View File

@ -26,7 +26,7 @@ Target.create "Test" (fun _ ->
let testPath = $"{projPath}.Tests" let testPath = $"{projPath}.Tests"
DotNet.build (fun opts -> { opts with NoLogo = true }) $"{testPath}/PrayerTracker.Tests.fsproj" DotNet.build (fun opts -> { opts with NoLogo = true }) $"{testPath}/PrayerTracker.Tests.fsproj"
Expecto.run Expecto.run
(fun opts -> { opts with WorkingDirectory = $"{testPath}/bin/Release/net6.0" }) (fun opts -> { opts with WorkingDirectory = $"{testPath}/bin/Release/net7.0" })
[ "PrayerTracker.Tests.dll" ]) [ "PrayerTracker.Tests.dll" ])
Target.create "Publish" (fun _ -> Target.create "Publish" (fun _ ->

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,267 +0,0 @@
GEM
remote: https://rubygems.org/
specs:
activesupport (3.2.22.5)
i18n (~> 0.6, >= 0.6.4)
multi_json (~> 1.0)
addressable (2.8.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.7)
dnsruby (1.61.5)
simpleidn (~> 0.1)
em-websocket (0.5.2)
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 (1.1.0)
multipart-post (>= 1.2, < 3)
ruby2_keywords
ffi (1.13.1)
ffi (1.13.1-x64-mingw32)
forwardable-extended (2.6.0)
gemoji (3.0.1)
github-pages (209)
github-pages-health-check (= 1.16.1)
jekyll (= 3.9.0)
jekyll-avatar (= 0.7.0)
jekyll-coffeescript (= 1.1.1)
jekyll-commonmark-ghpages (= 0.1.6)
jekyll-default-layout (= 0.1.4)
jekyll-feed (= 0.15.1)
jekyll-gist (= 1.5.0)
jekyll-github-metadata (= 2.13.0)
jekyll-mentions (= 1.6.0)
jekyll-optional-front-matter (= 0.3.2)
jekyll-paginate (= 1.1.0)
jekyll-readme-index (= 0.3.0)
jekyll-redirect-from (= 0.16.0)
jekyll-relative-links (= 0.6.1)
jekyll-remote-theme (= 0.4.2)
jekyll-sass-converter (= 1.5.2)
jekyll-seo-tag (= 2.6.1)
jekyll-sitemap (= 1.4.0)
jekyll-swiss (= 1.0.0)
jekyll-theme-architect (= 0.1.1)
jekyll-theme-cayman (= 0.1.1)
jekyll-theme-dinky (= 0.1.1)
jekyll-theme-hacker (= 0.1.2)
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.4)
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.3)
jemoji (= 0.12.0)
kramdown (= 2.3.0)
kramdown-parser-gfm (= 1.1.0)
liquid (= 4.0.3)
mercenary (~> 0.3)
minima (= 2.5.1)
nokogiri (>= 1.10.4, < 2.0)
rouge (= 3.23.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.14.0)
activesupport (>= 2)
nokogiri (>= 1.4)
http_parser.rb (0.6.0)
i18n (0.9.5)
concurrent-ruby (~> 1.0)
jekyll (3.9.0)
addressable (~> 2.4)
colorator (~> 1.0)
em-websocket (~> 0.5)
i18n (~> 0.7)
jekyll-sass-converter (~> 1.0)
jekyll-watch (~> 2.0)
kramdown (>= 1.17, < 3)
liquid (~> 4.0)
mercenary (~> 0.3.3)
pathutil (~> 0.9)
rouge (>= 1.7, < 4)
safe_yaml (~> 1.0)
jekyll-avatar (0.7.0)
jekyll (>= 3.0, < 5.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.15.1)
jekyll (>= 3.7, < 5.0)
jekyll-gist (1.5.0)
octokit (~> 4.2)
jekyll-github-metadata (2.13.0)
jekyll (>= 3.4, < 5.0)
octokit (~> 4.0, != 4.4.0)
jekyll-mentions (1.6.0)
html-pipeline (~> 2.3)
jekyll (>= 3.7, < 5.0)
jekyll-optional-front-matter (0.3.2)
jekyll (>= 3.0, < 5.0)
jekyll-paginate (1.1.0)
jekyll-readme-index (0.3.0)
jekyll (>= 3.0, < 5.0)
jekyll-redirect-from (0.16.0)
jekyll (>= 3.3, < 5.0)
jekyll-relative-links (0.6.1)
jekyll (>= 3.3, < 5.0)
jekyll-remote-theme (0.4.2)
addressable (~> 2.0)
jekyll (>= 3.5, < 5.0)
jekyll-sass-converter (>= 1.0, <= 3.0.0, != 2.0.0)
rubyzip (>= 1.3.0, < 3.0)
jekyll-sass-converter (1.5.2)
sass (~> 3.4)
jekyll-seo-tag (2.6.1)
jekyll (>= 3.3, < 5.0)
jekyll-sitemap (1.4.0)
jekyll (>= 3.7, < 5.0)
jekyll-swiss (1.0.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.2)
jekyll (> 3.5, < 5.0)
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.4)
jekyll (> 3.5, < 5.0)
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.3)
jekyll (>= 3.3, < 5.0)
jekyll-watch (2.2.1)
listen (~> 3.0)
jemoji (0.12.0)
gemoji (~> 3.0)
html-pipeline (~> 2.2)
jekyll (>= 3.0, < 5.0)
kramdown (2.3.0)
rexml
kramdown-parser-gfm (1.1.0)
kramdown (~> 2.0)
liquid (4.0.3)
listen (3.3.1)
rb-fsevent (~> 0.10, >= 0.10.3)
rb-inotify (~> 0.9, >= 0.9.10)
mercenary (0.3.6)
mini_portile2 (2.8.0)
minima (2.5.1)
jekyll (>= 3.5, < 5.0)
jekyll-feed (~> 0.9)
jekyll-seo-tag (~> 2.1)
multi_json (1.15.0)
multipart-post (2.1.1)
nokogiri (1.13.6)
mini_portile2 (~> 2.8.0)
racc (~> 1.4)
nokogiri (1.13.6-x64-mingw32)
racc (~> 1.4)
octokit (4.19.0)
faraday (>= 0.9)
sawyer (~> 0.8.0, >= 0.5.3)
pathutil (0.16.2)
forwardable-extended (~> 2.6)
public_suffix (3.1.1)
racc (1.6.0)
rb-fsevent (0.10.4)
rb-inotify (0.10.1)
ffi (~> 1.0)
rexml (3.2.5)
rouge (3.23.0)
ruby-enum (0.8.0)
i18n
ruby2_keywords (0.0.2)
rubyzip (2.3.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)
simpleidn (0.1.1)
unf (~> 0.1.4)
terminal-table (1.8.0)
unicode-display_width (~> 1.1, >= 1.1.1)
typhoeus (1.4.0)
ethon (>= 0.9.0)
tzinfo (2.0.3)
concurrent-ruby (~> 1.0)
tzinfo-data (1.2020.4)
tzinfo (>= 1.0.0)
unf (0.1.4)
unf_ext
unf_ext (0.0.7.7)
unf_ext (0.0.7.7-x64-mingw32)
unicode-display_width (1.7.0)
PLATFORMS
ruby
x64-mingw32
DEPENDENCIES
github-pages
tzinfo-data
BUNDLED WITH
2.1.4

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,43 +0,0 @@
/**
* PrayerTracker Help styling
*/
.pt-content {
background-color: white;
padding: 0 .25em;
}
.pt-title-bar-home {
height: 2rem;
}
.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;
align-self: center;
}
h2 {
margin-top: 0;
padding-left: .5rem;
border-bottom: solid 1px #444;
}
.pt-close-window, .pt-help-index {
font-size: 1.25rem;
}
.pt-help-index {
display: none;
}
@media screen and (min-width:451px) {
.pt-close-window {
display: none;
}
.pt-help-index {
display: block;
}
}

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 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 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 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 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,73 +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
There are two options for fonts that will be used in the prayer request list.
* “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. (This is the default for new small groups.)
* “Named Fonts” uses a comma-separated list of fonts that you specify. 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>
> Named Fonts: "Times New Roman",serif
>
> **Heading Text Size**<br>
> 18pt
>
> **List Text Size**<br>
> 16pt
## 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.)
## 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@bitbadger.solutions?subject=PrayerTracker%20Time%20Zone) and tell him what time zone you need.
## 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@bitbadger.solutions?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, 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 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, 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 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,73 +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
Hay dos opciones para las fuentes que se utilizarán en la lista de peticiones de oración.
* “Fuentes Nativas” utiliza una lista de fuentes que representarán las peticiones de oración en la mejor fuente disponible para su dispositivo, ya sea una computadora de escritorio o portátil, un dispositivo móvil o una tableta. (Este es el valor predeterminado para los nuevos grupos pequeños).
* “Fuentes con Nombre” utiliza una lista de fuentes separadas por comas que usted especifica. 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>
> Fuentes con Nombre: "Times New Roman",serif
>
> **Partida el Tamaño del Texto**<br>
> 18pt
>
> **Lista el Tamaño del Texto**<br>
> 16pt
## 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.)
## 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@bitbadger.solutions?subject=Zona%20Horaria%20por%20SeguidorOración) y decirle lo que la zona horaria que usted necesita.
## 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@bitbadger.solutions?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.*

View File

@ -1,11 +1,11 @@
<Project> <Project>
<PropertyGroup> <PropertyGroup>
<TargetFramework>net6.0</TargetFramework> <TargetFramework>net8.0</TargetFramework>
<AssemblyVersion>8.0.0.0</AssemblyVersion> <AssemblyVersion>8.4.0.0</AssemblyVersion>
<FileVersion>8.0.0.0</FileVersion> <FileVersion>8.4.0.0</FileVersion>
<Authors>danieljsummers</Authors> <Authors>danieljsummers</Authors>
<Company>Bit Badger Solutions</Company> <Company>Bit Badger Solutions</Company>
<Version>8.0.0</Version> <Version>8.4.0</Version>
<DebugType>Embedded</DebugType> <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 ./PrayerTracker/PrayerTracker.fsproj ./PrayerTracker/
COPY ./PrayerTracker.Data/PrayerTracker.Data.fsproj ./PrayerTracker.Data/
COPY ./PrayerTracker.Tests/PrayerTracker.Tests.fsproj ./PrayerTracker.Tests/
COPY ./PrayerTracker.UI/PrayerTracker.UI.fsproj ./PrayerTracker.UI/
RUN dotnet restore
COPY . ./
WORKDIR /pt/PrayerTracker.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

@ -103,126 +103,93 @@ module private Helpers =
} }
open BitBadger.Documents.Postgres
/// Functions to manipulate churches /// Functions to manipulate churches
module Churches = module Churches =
/// Get a list of all churches /// Get a list of all churches
let all conn = let all () =
Sql.existingConnection conn Custom.list "SELECT * FROM pt.church ORDER BY church_name" [] mapToChurch
|> Sql.query "SELECT * FROM pt.church ORDER BY church_name"
|> Sql.executeAsync mapToChurch
/// Delete a church by its ID /// Delete a church by its ID
let deleteById (churchId : ChurchId) conn = backgroundTask { let deleteById (churchId : ChurchId) = backgroundTask {
let idParam = [ [ "@churchId", Sql.uuid churchId.Value ] ] let idParam = [ [ "@churchId", Sql.uuid churchId.Value ] ]
let where = "WHERE small_group_id IN (SELECT id FROM pt.small_group WHERE church_id = @churchId)" let where = "WHERE small_group_id IN (SELECT id FROM pt.small_group WHERE church_id = @churchId)"
let! _ = let! _ =
Sql.existingConnection conn Configuration.dataSource ()
|> Sql.fromDataSource
|> Sql.executeTransactionAsync |> Sql.executeTransactionAsync
[ $"DELETE FROM pt.prayer_request {where}", idParam [ $"DELETE FROM pt.prayer_request {where}", idParam
$"DELETE FROM pt.user_small_group {where}", idParam $"DELETE FROM pt.user_small_group {where}", idParam
$"DELETE FROM pt.list_preference {where}", idParam $"DELETE FROM pt.list_preference {where}", idParam
"DELETE FROM pt.small_group WHERE church_id = @churchId", idParam "DELETE FROM pt.small_group WHERE church_id = @churchId", idParam
"DELETE FROM pt.church WHERE id = @churchId", idParam ] "DELETE FROM pt.church WHERE id = @churchId", idParam ]
return () ()
} }
/// Save a church's information /// Save a church's information
let save (church : Church) conn = backgroundTask { let save (church : Church) =
let! _ = Custom.nonQuery
Sql.existingConnection conn "INSERT INTO pt.church (
|> Sql.query """ id, church_name, city, state, has_vps_interface, interface_address
INSERT INTO pt.church ( ) VALUES (
id, church_name, city, state, has_vps_interface, interface_address @id, @name, @city, @state, @hasVpsInterface, @interfaceAddress
) VALUES ( ) ON CONFLICT (id) DO UPDATE
@id, @name, @city, @state, @hasVpsInterface, @interfaceAddress SET church_name = EXCLUDED.church_name,
) ON CONFLICT (id) DO UPDATE city = EXCLUDED.city,
SET church_name = EXCLUDED.church_name, state = EXCLUDED.state,
city = EXCLUDED.city, has_vps_interface = EXCLUDED.has_vps_interface,
state = EXCLUDED.state, interface_address = EXCLUDED.interface_address"
has_vps_interface = EXCLUDED.has_vps_interface, [ "@id", Sql.uuid church.Id.Value
interface_address = EXCLUDED.interface_address""" "@name", Sql.string church.Name
|> Sql.parameters "@city", Sql.string church.City
[ "@id", Sql.uuid church.Id.Value "@state", Sql.string church.State
"@name", Sql.string church.Name "@hasVpsInterface", Sql.bool church.HasVpsInterface
"@city", Sql.string church.City "@interfaceAddress", Sql.stringOrNone church.InterfaceAddress ]
"@state", Sql.string church.State
"@hasVpsInterface", Sql.bool church.HasVpsInterface
"@interfaceAddress", Sql.stringOrNone church.InterfaceAddress ]
|> Sql.executeNonQueryAsync
return ()
}
/// Find a church by its ID /// Find a church by its ID
let tryById (churchId : ChurchId) conn = backgroundTask { let tryById (churchId : ChurchId) =
let! church = Custom.single "SELECT * FROM pt.church WHERE id = @id" [ "@id", Sql.uuid churchId.Value ] mapToChurch
Sql.existingConnection conn
|> Sql.query "SELECT * FROM pt.church WHERE id = @id"
|> Sql.parameters [ "@id", Sql.uuid churchId.Value ]
|> Sql.executeAsync mapToChurch
return List.tryHead church
}
/// Functions to manipulate small group members /// Functions to manipulate small group members
module Members = module Members =
/// Count members for the given small group /// Count members for the given small group
let countByGroup (groupId : SmallGroupId) conn = let countByGroup (groupId : SmallGroupId) =
Sql.existingConnection conn Custom.scalar "SELECT COUNT(id) AS mbr_count FROM pt.member WHERE small_group_id = @groupId"
|> Sql.query "SELECT COUNT(id) AS mbr_count FROM pt.member WHERE small_group_id = @groupId" [ "@groupId", Sql.uuid groupId.Value ] (fun row -> row.int "mbr_count")
|> Sql.parameters [ "@groupId", Sql.uuid groupId.Value ]
|> Sql.executeRowAsync (fun row -> row.int "mbr_count")
/// Delete a small group member by its ID /// Delete a small group member by its ID
let deleteById (memberId : MemberId) conn = backgroundTask { let deleteById (memberId : MemberId) =
let! _ = Custom.nonQuery "DELETE FROM pt.member WHERE id = @id" [ "@id", Sql.uuid memberId.Value ]
Sql.existingConnection conn
|> Sql.query "DELETE FROM pt.member WHERE id = @id"
|> Sql.parameters [ "@id", Sql.uuid memberId.Value ]
|> Sql.executeNonQueryAsync
return ()
}
/// Retrieve all members for a given small group /// Retrieve all members for a given small group
let forGroup (groupId : SmallGroupId) conn = let forGroup (groupId : SmallGroupId) =
Sql.existingConnection conn Custom.list "SELECT * FROM pt.member WHERE small_group_id = @groupId ORDER BY member_name"
|> Sql.query "SELECT * FROM pt.member WHERE small_group_id = @groupId ORDER BY member_name" [ "@groupId", Sql.uuid groupId.Value ] mapToMember
|> Sql.parameters [ "@groupId", Sql.uuid groupId.Value ]
|> Sql.executeAsync mapToMember
/// Save a small group member /// Save a small group member
let save (mbr : Member) conn = backgroundTask { let save (mbr : Member) =
let! _ = Custom.nonQuery
Sql.existingConnection conn "INSERT INTO pt.member (
|> Sql.query """ id, small_group_id, member_name, email, email_format
INSERT INTO pt.member ( ) VALUES (
id, small_group_id, member_name, email, email_format @id, @groupId, @name, @email, @format
) VALUES ( ) ON CONFLICT (id) DO UPDATE
@id, @groupId, @name, @email, @format SET member_name = EXCLUDED.member_name,
) ON CONFLICT (id) DO UPDATE email = EXCLUDED.email,
SET member_name = EXCLUDED.member_name, email_format = EXCLUDED.email_format"
email = EXCLUDED.email, [ "@id", Sql.uuid mbr.Id.Value
email_format = EXCLUDED.email_format""" "@groupId", Sql.uuid mbr.SmallGroupId.Value
|> Sql.parameters "@name", Sql.string mbr.Name
[ "@id", Sql.uuid mbr.Id.Value "@email", Sql.string mbr.Email
"@groupId", Sql.uuid mbr.SmallGroupId.Value "@format", Sql.stringOrNone (mbr.Format |> Option.map EmailFormat.toCode) ]
"@name", Sql.string mbr.Name
"@email", Sql.string mbr.Email
"@format", Sql.stringOrNone (mbr.Format |> Option.map EmailFormat.toCode) ]
|> Sql.executeNonQueryAsync
return ()
}
/// Retrieve a small group member by its ID /// Retrieve a small group member by its ID
let tryById (memberId : MemberId) conn = backgroundTask { let tryById (memberId : MemberId) =
let! mbr = Custom.single "SELECT * FROM pt.member WHERE id = @id" [ "@id", Sql.uuid memberId.Value ] mapToMember
Sql.existingConnection conn
|> Sql.query "SELECT * FROM pt.member WHERE id = @id"
|> Sql.parameters [ "@id", Sql.uuid memberId.Value ]
|> Sql.executeAsync mapToMember
return List.tryHead mbr
}
/// Options to retrieve a list of requests /// Options to retrieve a list of requests
@ -258,34 +225,24 @@ module PrayerRequests =
if pageNbr > 0 then $"LIMIT {pageSize} OFFSET {(pageNbr - 1) * pageSize}" else "" if pageNbr > 0 then $"LIMIT {pageSize} OFFSET {(pageNbr - 1) * pageSize}" else ""
/// Count the number of prayer requests for a church /// Count the number of prayer requests for a church
let countByChurch (churchId : ChurchId) conn = let countByChurch (churchId : ChurchId) =
Sql.existingConnection conn Custom.scalar
|> Sql.query """ "SELECT COUNT(id) AS req_count
SELECT COUNT(id) AS req_count FROM pt.prayer_request
FROM pt.prayer_request WHERE small_group_id IN (SELECT id FROM pt.small_group WHERE church_id = @churchId)"
WHERE small_group_id IN (SELECT id FROM pt.small_group WHERE church_id = @churchId)""" [ "@churchId", Sql.uuid churchId.Value ] (fun row -> row.int "req_count")
|> Sql.parameters [ "@churchId", Sql.uuid churchId.Value ]
|> Sql.executeRowAsync (fun row -> row.int "req_count")
/// Count the number of prayer requests for a small group /// Count the number of prayer requests for a small group
let countByGroup (groupId : SmallGroupId) conn = let countByGroup (groupId : SmallGroupId) =
Sql.existingConnection conn Custom.scalar "SELECT COUNT(id) AS req_count FROM pt.prayer_request WHERE small_group_id = @groupId"
|> Sql.query "SELECT COUNT(id) AS req_count FROM pt.prayer_request WHERE small_group_id = @groupId" [ "@groupId", Sql.uuid groupId.Value ] (fun row -> row.int "req_count")
|> Sql.parameters [ "@groupId", Sql.uuid groupId.Value ]
|> Sql.executeRowAsync (fun row -> row.int "req_count")
/// Delete a prayer request by its ID /// Delete a prayer request by its ID
let deleteById (reqId : PrayerRequestId) conn = backgroundTask { let deleteById (reqId : PrayerRequestId) =
let! _ = Custom.nonQuery "DELETE FROM pt.prayer_request WHERE id = @id" [ "@id", Sql.uuid reqId.Value ]
Sql.existingConnection conn
|> Sql.query "DELETE FROM pt.prayer_request WHERE id = @id"
|> Sql.parameters [ "@id", Sql.uuid reqId.Value ]
|> Sql.executeNonQueryAsync
return ()
}
/// Get all (or active) requests for a small group as of now or the specified date /// Get all (or active) requests for a small group as of now or the specified date
let forGroup (opts : PrayerRequestOptions) conn = let forGroup (opts : PrayerRequestOptions) =
let theDate = defaultArg opts.ListDate (SmallGroup.localDateNow opts.Clock opts.SmallGroup) let theDate = defaultArg opts.ListDate (SmallGroup.localDateNow opts.Clock opts.SmallGroup)
let where, parameters = let where, parameters =
if opts.ActiveOnly then if opts.ActiveOnly then
@ -294,198 +251,167 @@ module PrayerRequests =
(theDate.AtStartOfDayInZone(SmallGroup.timeZone opts.SmallGroup) (theDate.AtStartOfDayInZone(SmallGroup.timeZone opts.SmallGroup)
- Duration.FromDays opts.SmallGroup.Preferences.DaysToExpire) - Duration.FromDays opts.SmallGroup.Preferences.DaysToExpire)
.ToInstant ()) .ToInstant ())
""" AND ( updated_date > @asOf " AND ( updated_date > @asOf
OR expiration = @manual OR expiration = @manual
OR request_type = @longTerm OR request_type = @longTerm
OR request_type = @expecting) OR request_type = @expecting)
AND expiration <> @forced""", AND expiration <> @forced",
[ "@asOf", Sql.parameter asOf [ "@asOf", Sql.parameter asOf
"@manual", Sql.string (Expiration.toCode Manual) "@manual", Sql.string (Expiration.toCode Manual)
"@longTerm", Sql.string (PrayerRequestType.toCode LongTermRequest) "@longTerm", Sql.string (PrayerRequestType.toCode LongTermRequest)
"@expecting", Sql.string (PrayerRequestType.toCode Expecting) "@expecting", Sql.string (PrayerRequestType.toCode Expecting)
"@forced", Sql.string (Expiration.toCode Forced) ] "@forced", Sql.string (Expiration.toCode Forced) ]
else "", [] else "", []
Sql.existingConnection conn Custom.list
|> Sql.query $""" $"SELECT *
SELECT * FROM pt.prayer_request
FROM pt.prayer_request WHERE small_group_id = @groupId {where}
WHERE small_group_id = @groupId {where} ORDER BY {orderBy opts.SmallGroup.Preferences.RequestSort}
ORDER BY {orderBy opts.SmallGroup.Preferences.RequestSort} {paginate opts.PageNumber opts.SmallGroup.Preferences.PageSize}"
{paginate opts.PageNumber opts.SmallGroup.Preferences.PageSize}""" (("@groupId", Sql.uuid opts.SmallGroup.Id.Value) :: parameters) mapToPrayerRequest
|> Sql.parameters (("@groupId", Sql.uuid opts.SmallGroup.Id.Value) :: parameters)
|> Sql.executeAsync mapToPrayerRequest
/// Save a prayer request /// Save a prayer request
let save (req : PrayerRequest) conn = backgroundTask { let save (req : PrayerRequest) =
let! _ = Custom.nonQuery
Sql.existingConnection conn "INSERT into pt.prayer_request (
|> Sql.query """ id, request_type, user_id, small_group_id, entered_date, updated_date, requestor, request_text,
INSERT into pt.prayer_request ( notify_chaplain, expiration
id, request_type, user_id, small_group_id, entered_date, updated_date, requestor, request_text, ) VALUES (
notify_chaplain, expiration @id, @type, @userId, @groupId, @entered, @updated, @requestor, @text,
) VALUES ( @notifyChaplain, @expiration
@id, @type, @userId, @groupId, @entered, @updated, @requestor, @text, ) ON CONFLICT (id) DO UPDATE
@notifyChaplain, @expiration SET request_type = EXCLUDED.request_type,
) ON CONFLICT (id) DO UPDATE updated_date = EXCLUDED.updated_date,
SET request_type = EXCLUDED.request_type, requestor = EXCLUDED.requestor,
updated_date = EXCLUDED.updated_date, request_text = EXCLUDED.request_text,
requestor = EXCLUDED.requestor, notify_chaplain = EXCLUDED.notify_chaplain,
request_text = EXCLUDED.request_text, expiration = EXCLUDED.expiration"
notify_chaplain = EXCLUDED.notify_chaplain, [ "@id", Sql.uuid req.Id.Value
expiration = EXCLUDED.expiration""" "@type", Sql.string (PrayerRequestType.toCode req.RequestType)
|> Sql.parameters "@userId", Sql.uuid req.UserId.Value
[ "@id", Sql.uuid req.Id.Value "@groupId", Sql.uuid req.SmallGroupId.Value
"@type", Sql.string (PrayerRequestType.toCode req.RequestType) "@entered", Sql.parameter (NpgsqlParameter ("@entered", req.EnteredDate))
"@userId", Sql.uuid req.UserId.Value "@updated", Sql.parameter (NpgsqlParameter ("@updated", req.UpdatedDate))
"@groupId", Sql.uuid req.SmallGroupId.Value "@requestor", Sql.stringOrNone req.Requestor
"@entered", Sql.parameter (NpgsqlParameter ("@entered", req.EnteredDate)) "@text", Sql.string req.Text
"@updated", Sql.parameter (NpgsqlParameter ("@updated", req.UpdatedDate)) "@notifyChaplain", Sql.bool req.NotifyChaplain
"@requestor", Sql.stringOrNone req.Requestor "@expiration", Sql.string (Expiration.toCode req.Expiration) ]
"@text", Sql.string req.Text
"@notifyChaplain", Sql.bool req.NotifyChaplain
"@expiration", Sql.string (Expiration.toCode req.Expiration)
]
|> Sql.executeNonQueryAsync
return ()
}
/// Search prayer requests for the given term /// Search prayer requests for the given term
let searchForGroup group searchTerm pageNbr conn = let searchForGroup group searchTerm pageNbr =
Sql.existingConnection conn Custom.list
|> Sql.query $""" $"SELECT * FROM pt.prayer_request WHERE small_group_id = @groupId AND request_text ILIKE @search
SELECT * FROM pt.prayer_request WHERE small_group_id = @groupId AND request_text ILIKE @search UNION
UNION SELECT * FROM pt.prayer_request WHERE small_group_id = @groupId AND COALESCE(requestor, '') ILIKE @search
SELECT * FROM pt.prayer_request WHERE small_group_id = @groupId AND COALESCE(requestor, '') ILIKE @search ORDER BY {orderBy group.Preferences.RequestSort}
ORDER BY {orderBy group.Preferences.RequestSort} {paginate pageNbr group.Preferences.PageSize}"
{paginate pageNbr group.Preferences.PageSize}""" [ "@groupId", Sql.uuid group.Id.Value; "@search", Sql.string $"%%%s{searchTerm}%%" ] mapToPrayerRequest
|> Sql.parameters [ "@groupId", Sql.uuid group.Id.Value; "@search", Sql.string $"%%%s{searchTerm}%%" ]
|> Sql.executeAsync mapToPrayerRequest
/// Retrieve a prayer request by its ID /// Retrieve a prayer request by its ID
let tryById (reqId : PrayerRequestId) conn = backgroundTask { let tryById (reqId : PrayerRequestId) =
let! req = Custom.single "SELECT * FROM pt.prayer_request WHERE id = @id" [ "@id", Sql.uuid reqId.Value ]
Sql.existingConnection conn mapToPrayerRequest
|> Sql.query "SELECT * FROM pt.prayer_request WHERE id = @id"
|> Sql.parameters [ "@id", Sql.uuid reqId.Value ]
|> Sql.executeAsync mapToPrayerRequest
return List.tryHead req
}
/// Update the expiration for the given prayer request /// Update the expiration for the given prayer request
let updateExpiration (req : PrayerRequest) withTime conn = backgroundTask { let updateExpiration (req : PrayerRequest) withTime =
let sql, parameters = let sql, parameters =
if withTime then if withTime then
", updated_date = @updated", ", updated_date = @updated",
[ "@updated", Sql.parameter (NpgsqlParameter ("@updated", req.UpdatedDate)) ] [ "@updated", Sql.parameter (NpgsqlParameter ("@updated", req.UpdatedDate)) ]
else "", [] else "", []
let! _ = Custom.nonQuery $"UPDATE pt.prayer_request SET expiration = @expiration{sql} WHERE id = @id"
Sql.existingConnection conn ([ "@expiration", Sql.string (Expiration.toCode req.Expiration)
|> Sql.query $"UPDATE pt.prayer_request SET expiration = @expiration{sql} WHERE id = @id" "@id", Sql.uuid req.Id.Value ]
|> Sql.parameters |> List.append parameters)
([ "@expiration", Sql.string (Expiration.toCode req.Expiration)
"@id", Sql.uuid req.Id.Value ]
|> List.append parameters)
|> Sql.executeNonQueryAsync
return ()
}
/// Functions to retrieve small group information /// Functions to retrieve small group information
module SmallGroups = module SmallGroups =
/// Count the number of small groups for a church /// Count the number of small groups for a church
let countByChurch (churchId : ChurchId) conn = let countByChurch (churchId : ChurchId) =
Sql.existingConnection conn Custom.scalar "SELECT COUNT(id) AS group_count FROM pt.small_group WHERE church_id = @churchId"
|> Sql.query "SELECT COUNT(id) AS group_count FROM pt.small_group WHERE church_id = @churchId" [ "@churchId", Sql.uuid churchId.Value ] (fun row -> row.int "group_count")
|> Sql.parameters [ "@churchId", Sql.uuid churchId.Value ]
|> Sql.executeRowAsync (fun row -> row.int "group_count")
/// Delete a small group by its ID /// Delete a small group by its ID
let deleteById (groupId : SmallGroupId) conn = backgroundTask { let deleteById (groupId : SmallGroupId) = backgroundTask {
let idParam = [ [ "@groupId", Sql.uuid groupId.Value ] ] let idParam = [ [ "@groupId", Sql.uuid groupId.Value ] ]
let! _ = let! _ =
Sql.existingConnection conn Configuration.dataSource ()
|> Sql.fromDataSource
|> Sql.executeTransactionAsync |> Sql.executeTransactionAsync
[ "DELETE FROM pt.prayer_request WHERE small_group_id = @groupId", idParam [ "DELETE FROM pt.prayer_request WHERE small_group_id = @groupId", idParam
"DELETE FROM pt.user_small_group WHERE small_group_id = @groupId", idParam "DELETE FROM pt.user_small_group WHERE small_group_id = @groupId", idParam
"DELETE FROM pt.list_preference WHERE small_group_id = @groupId", idParam "DELETE FROM pt.list_preference WHERE small_group_id = @groupId", idParam
"DELETE FROM pt.small_group WHERE id = @groupId", idParam ] "DELETE FROM pt.small_group WHERE id = @groupId", idParam ]
return () ()
} }
/// Get information for all small groups /// Get information for all small groups
let infoForAll conn = let infoForAll () =
Sql.existingConnection conn Custom.list
|> Sql.query """ "SELECT sg.id, sg.group_name, c.church_name, lp.time_zone_id, lp.is_public
SELECT sg.id, sg.group_name, c.church_name, lp.time_zone_id, lp.is_public FROM pt.small_group sg
FROM pt.small_group sg INNER JOIN pt.church c ON c.id = sg.church_id
INNER JOIN pt.church c ON c.id = sg.church_id INNER JOIN pt.list_preference lp ON lp.small_group_id = sg.id
INNER JOIN pt.list_preference lp ON lp.small_group_id = sg.id ORDER BY sg.group_name"
ORDER BY sg.group_name""" [] mapToSmallGroupInfo
|> Sql.executeAsync mapToSmallGroupInfo
/// Get a list of small group IDs along with a description that includes the church name /// Get a list of small group IDs along with a description that includes the church name
let listAll conn = let listAll () =
Sql.existingConnection conn Custom.list
|> Sql.query """ "SELECT g.group_name, g.id, c.church_name
SELECT g.group_name, g.id, c.church_name FROM pt.small_group g
FROM pt.small_group g INNER JOIN pt.church c ON c.id = g.church_id
INNER JOIN pt.church c ON c.id = g.church_id ORDER BY c.church_name, g.group_name"
ORDER BY c.church_name, g.group_name""" [] mapToSmallGroupItem
|> Sql.executeAsync mapToSmallGroupItem
/// Get a list of small group IDs and descriptions for groups with a group password /// Get a list of small group IDs and descriptions for groups with a group password
let listProtected conn = let listProtected () =
Sql.existingConnection conn Custom.list
|> Sql.query """ "SELECT g.group_name, g.id, c.church_name, lp.is_public
SELECT g.group_name, g.id, c.church_name, lp.is_public FROM pt.small_group g
FROM pt.small_group g INNER JOIN pt.church c ON c.id = g.church_id
INNER JOIN pt.church c ON c.id = g.church_id INNER JOIN pt.list_preference lp ON lp.small_group_id = g.id
INNER JOIN pt.list_preference lp ON lp.small_group_id = g.id WHERE COALESCE(lp.group_password, '') <> ''
WHERE COALESCE(lp.group_password, '') <> '' ORDER BY c.church_name, g.group_name"
ORDER BY c.church_name, g.group_name""" [] mapToSmallGroupItem
|> Sql.executeAsync mapToSmallGroupItem
/// Get a list of small group IDs and descriptions for groups that are public or have a group password /// Get a list of small group IDs and descriptions for groups that are public or have a group password
let listPublicAndProtected conn = let listPublicAndProtected () =
Sql.existingConnection conn Custom.list
|> Sql.query """ "SELECT g.group_name, g.id, c.church_name, lp.time_zone_id, lp.is_public
SELECT g.group_name, g.id, c.church_name, lp.time_zone_id, lp.is_public FROM pt.small_group g
FROM pt.small_group g INNER JOIN pt.church c ON c.id = g.church_id
INNER JOIN pt.church c ON c.id = g.church_id INNER JOIN pt.list_preference lp ON lp.small_group_id = g.id
INNER JOIN pt.list_preference lp ON lp.small_group_id = g.id WHERE lp.is_public = TRUE
WHERE lp.is_public = TRUE OR COALESCE(lp.group_password, '') <> ''
OR COALESCE(lp.group_password, '') <> '' ORDER BY c.church_name, g.group_name"
ORDER BY c.church_name, g.group_name""" [] mapToSmallGroupInfo
|> Sql.executeAsync mapToSmallGroupInfo
/// Log on for a small group (includes list preferences) /// Log on for a small group (includes list preferences)
let logOn (groupId : SmallGroupId) password conn = backgroundTask { let logOn (groupId : SmallGroupId) password =
let! group = Custom.single
Sql.existingConnection conn "SELECT sg.*, lp.*
|> Sql.query """ FROM pt.small_group sg
SELECT sg.*, lp.* INNER JOIN pt.list_preference lp ON lp.small_group_id = sg.id
FROM pt.small_group sg WHERE sg.id = @id
INNER JOIN pt.list_preference lp ON lp.small_group_id = sg.id AND lp.group_password = @password"
WHERE sg.id = @id [ "@id", Sql.uuid groupId.Value; "@password", Sql.string password ] mapToSmallGroupWithPreferences
AND lp.group_password = @password"""
|> Sql.parameters [ "@id", Sql.uuid groupId.Value; "@password", Sql.string password ]
|> Sql.executeAsync mapToSmallGroupWithPreferences
return List.tryHead group
}
/// Save a small group /// Save a small group
let save (group : SmallGroup) isNew conn = backgroundTask { let save (group : SmallGroup) isNew = backgroundTask {
let! _ = let! _ =
Sql.existingConnection conn Configuration.dataSource ()
|> Sql.fromDataSource
|> Sql.executeTransactionAsync [ |> Sql.executeTransactionAsync [
""" INSERT INTO pt.small_group ( "INSERT INTO pt.small_group (
id, church_id, group_name id, church_id, group_name
) VALUES ( ) VALUES (
@id, @churchId, @name @id, @churchId, @name
) ON CONFLICT (id) DO UPDATE ) ON CONFLICT (id) DO UPDATE
SET church_id = EXCLUDED.church_id, SET church_id = EXCLUDED.church_id,
group_name = EXCLUDED.group_name""", group_name = EXCLUDED.group_name",
[ [ "@id", Sql.uuid group.Id.Value [ [ "@id", Sql.uuid group.Id.Value
"@churchId", Sql.uuid group.ChurchId.Value "@churchId", Sql.uuid group.ChurchId.Value
"@name", Sql.string group.Name ] ] "@name", Sql.string group.Name ] ]
@ -493,216 +419,154 @@ module SmallGroups =
"INSERT INTO pt.list_preference (small_group_id) VALUES (@id)", "INSERT INTO pt.list_preference (small_group_id) VALUES (@id)",
[ [ "@id", Sql.uuid group.Id.Value ] ] [ [ "@id", Sql.uuid group.Id.Value ] ]
] ]
return () ()
} }
/// Save a small group's list preferences /// Save a small group's list preferences
let savePreferences (pref : ListPreferences) conn = backgroundTask { let savePreferences (pref : ListPreferences) =
let! _ = Custom.nonQuery
Sql.existingConnection conn "UPDATE pt.list_preference
|> Sql.query """ SET days_to_keep_new = @daysToKeepNew,
UPDATE pt.list_preference days_to_expire = @daysToExpire,
SET days_to_keep_new = @daysToKeepNew, long_term_update_weeks = @longTermUpdateWeeks,
days_to_expire = @daysToExpire, email_from_name = @emailFromName,
long_term_update_weeks = @longTermUpdateWeeks, email_from_address = @emailFromAddress,
email_from_name = @emailFromName, fonts = @fonts,
email_from_address = @emailFromAddress, heading_color = @headingColor,
fonts = @fonts, line_color = @lineColor,
heading_color = @headingColor, heading_font_size = @headingFontSize,
line_color = @lineColor, text_font_size = @textFontSize,
heading_font_size = @headingFontSize, request_sort = @requestSort,
text_font_size = @textFontSize, group_password = @groupPassword,
request_sort = @requestSort, default_email_type = @defaultEmailType,
group_password = @groupPassword, is_public = @isPublic,
default_email_type = @defaultEmailType, time_zone_id = @timeZoneId,
is_public = @isPublic, page_size = @pageSize,
time_zone_id = @timeZoneId, as_of_date_display = @asOfDateDisplay
page_size = @pageSize, WHERE small_group_id = @groupId"
as_of_date_display = @asOfDateDisplay [ "@groupId", Sql.uuid pref.SmallGroupId.Value
WHERE small_group_id = @groupId""" "@daysToKeepNew", Sql.int pref.DaysToKeepNew
|> Sql.parameters "@daysToExpire", Sql.int pref.DaysToExpire
[ "@groupId", Sql.uuid pref.SmallGroupId.Value "@longTermUpdateWeeks", Sql.int pref.LongTermUpdateWeeks
"@daysToKeepNew", Sql.int pref.DaysToKeepNew "@emailFromName", Sql.string pref.EmailFromName
"@daysToExpire", Sql.int pref.DaysToExpire "@emailFromAddress", Sql.string pref.EmailFromAddress
"@longTermUpdateWeeks", Sql.int pref.LongTermUpdateWeeks "@fonts", Sql.string pref.Fonts
"@emailFromName", Sql.string pref.EmailFromName "@headingColor", Sql.string pref.HeadingColor
"@emailFromAddress", Sql.string pref.EmailFromAddress "@lineColor", Sql.string pref.LineColor
"@fonts", Sql.string pref.Fonts "@headingFontSize", Sql.int pref.HeadingFontSize
"@headingColor", Sql.string pref.HeadingColor "@textFontSize", Sql.int pref.TextFontSize
"@lineColor", Sql.string pref.LineColor "@requestSort", Sql.string (RequestSort.toCode pref.RequestSort)
"@headingFontSize", Sql.int pref.HeadingFontSize "@groupPassword", Sql.string pref.GroupPassword
"@textFontSize", Sql.int pref.TextFontSize "@defaultEmailType", Sql.string (EmailFormat.toCode pref.DefaultEmailType)
"@requestSort", Sql.string (RequestSort.toCode pref.RequestSort) "@isPublic", Sql.bool pref.IsPublic
"@groupPassword", Sql.string pref.GroupPassword "@timeZoneId", Sql.string (TimeZoneId.toString pref.TimeZoneId)
"@defaultEmailType", Sql.string (EmailFormat.toCode pref.DefaultEmailType) "@pageSize", Sql.int pref.PageSize
"@isPublic", Sql.bool pref.IsPublic "@asOfDateDisplay", Sql.string (AsOfDateDisplay.toCode pref.AsOfDateDisplay) ]
"@timeZoneId", Sql.string (TimeZoneId.toString pref.TimeZoneId)
"@pageSize", Sql.int pref.PageSize
"@asOfDateDisplay", Sql.string (AsOfDateDisplay.toCode pref.AsOfDateDisplay)
]
|> Sql.executeNonQueryAsync
return ()
}
/// Get a small group by its ID /// Get a small group by its ID
let tryById (groupId : SmallGroupId) conn = backgroundTask { let tryById (groupId : SmallGroupId) =
let! group = Custom.single "SELECT * FROM pt.small_group WHERE id = @id" [ "@id", Sql.uuid groupId.Value ] mapToSmallGroup
Sql.existingConnection conn
|> Sql.query "SELECT * FROM pt.small_group WHERE id = @id"
|> Sql.parameters [ "@id", Sql.uuid groupId.Value ]
|> Sql.executeAsync mapToSmallGroup
return List.tryHead group
}
/// Get a small group by its ID with its list preferences populated /// Get a small group by its ID with its list preferences populated
let tryByIdWithPreferences (groupId : SmallGroupId) conn = backgroundTask { let tryByIdWithPreferences (groupId : SmallGroupId) =
let! group = Custom.single
Sql.existingConnection conn "SELECT sg.*, lp.*
|> Sql.query """ FROM pt.small_group sg
SELECT sg.*, lp.* INNER JOIN pt.list_preference lp ON lp.small_group_id = sg.id
FROM pt.small_group sg WHERE sg.id = @id"
INNER JOIN pt.list_preference lp ON lp.small_group_id = sg.id [ "@id", Sql.uuid groupId.Value ] mapToSmallGroupWithPreferences
WHERE sg.id = @id"""
|> Sql.parameters [ "@id", Sql.uuid groupId.Value ]
|> Sql.executeAsync mapToSmallGroupWithPreferences
return List.tryHead group
}
/// Functions to manipulate users /// Functions to manipulate users
module Users = module Users =
/// Retrieve all PrayerTracker users /// Retrieve all PrayerTracker users
let all conn = let all () =
Sql.existingConnection conn Custom.list "SELECT * FROM pt.pt_user ORDER BY last_name, first_name" [] mapToUser
|> Sql.query "SELECT * FROM pt.pt_user ORDER BY last_name, first_name"
|> Sql.executeAsync mapToUser
/// Count the number of users for a church /// Count the number of users for a church
let countByChurch (churchId : ChurchId) conn = let countByChurch (churchId : ChurchId) =
Sql.existingConnection conn Custom.scalar
|> Sql.query """ "SELECT COUNT(u.id) AS user_count
SELECT COUNT(u.id) AS user_count FROM pt.pt_user u
FROM pt.pt_user u WHERE EXISTS (
WHERE EXISTS ( SELECT 1
SELECT 1 FROM pt.user_small_group usg
FROM pt.user_small_group usg INNER JOIN pt.small_group sg ON sg.id = usg.small_group_id
INNER JOIN pt.small_group sg ON sg.id = usg.small_group_id WHERE usg.user_id = u.id
WHERE usg.user_id = u.id AND sg.church_id = @churchId)"
AND sg.church_id = @churchId)""" [ "@churchId", Sql.uuid churchId.Value ] (fun row -> row.int "user_count")
|> Sql.parameters [ "@churchId", Sql.uuid churchId.Value ]
|> Sql.executeRowAsync (fun row -> row.int "user_count")
/// Count the number of users for a small group /// Count the number of users for a small group
let countByGroup (groupId : SmallGroupId) conn = let countByGroup (groupId : SmallGroupId) =
Sql.existingConnection conn Custom.scalar "SELECT COUNT(user_id) AS user_count FROM pt.user_small_group WHERE small_group_id = @groupId"
|> Sql.query "SELECT COUNT(user_id) AS user_count FROM pt.user_small_group WHERE small_group_id = @groupId" [ "@groupId", Sql.uuid groupId.Value ] (fun row -> row.int "user_count")
|> Sql.parameters [ "@groupId", Sql.uuid groupId.Value ]
|> Sql.executeRowAsync (fun row -> row.int "user_count")
/// Delete a user by its database ID /// Delete a user by its database ID
let deleteById (userId : UserId) conn = backgroundTask { let deleteById (userId : UserId) =
let! _ = Custom.nonQuery "DELETE FROM pt.pt_user WHERE id = @id" [ "@id", Sql.uuid userId.Value ]
Sql.existingConnection conn
|> Sql.query "DELETE FROM pt.pt_user WHERE id = @id"
|> Sql.parameters [ "@id", Sql.uuid userId.Value ]
|> Sql.executeNonQueryAsync
return ()
}
/// Get the IDs of the small groups for which the given user is authorized /// Get the IDs of the small groups for which the given user is authorized
let groupIdsByUserId (userId : UserId) conn = let groupIdsByUserId (userId : UserId) =
Sql.existingConnection conn Custom.list "SELECT small_group_id FROM pt.user_small_group WHERE user_id = @id"
|> Sql.query "SELECT small_group_id FROM pt.user_small_group WHERE user_id = @id" [ "@id", Sql.uuid userId.Value ] (fun row -> SmallGroupId (row.uuid "small_group_id"))
|> Sql.parameters [ "@id", Sql.uuid userId.Value ]
|> Sql.executeAsync (fun row -> SmallGroupId (row.uuid "small_group_id"))
/// Get a list of users authorized to administer the given small group /// Get a list of users authorized to administer the given small group
let listByGroupId (groupId : SmallGroupId) conn = let listByGroupId (groupId : SmallGroupId) =
Sql.existingConnection conn Custom.list
|> Sql.query """ "SELECT u.*
SELECT u.* FROM pt.pt_user u
FROM pt.pt_user u INNER JOIN pt.user_small_group usg ON usg.user_id = u.id
INNER JOIN pt.user_small_group usg ON usg.user_id = u.id WHERE usg.small_group_id = @groupId
WHERE usg.small_group_id = @groupId ORDER BY u.last_name, u.first_name"
ORDER BY u.last_name, u.first_name""" [ "@groupId", Sql.uuid groupId.Value ] mapToUser
|> Sql.parameters [ "@groupId", Sql.uuid groupId.Value ]
|> Sql.executeAsync mapToUser
/// Save a user's information /// Save a user's information
let save (user : User) conn = backgroundTask { let save (user : User) =
let! _ = Custom.nonQuery
Sql.existingConnection conn "INSERT INTO pt.pt_user (
|> Sql.query """ id, first_name, last_name, email, is_admin, password_hash
INSERT INTO pt.pt_user ( ) VALUES (
id, first_name, last_name, email, is_admin, password_hash @id, @firstName, @lastName, @email, @isAdmin, @passwordHash
) VALUES ( ) ON CONFLICT (id) DO UPDATE
@id, @firstName, @lastName, @email, @isAdmin, @passwordHash SET first_name = EXCLUDED.first_name,
) ON CONFLICT (id) DO UPDATE last_name = EXCLUDED.last_name,
SET first_name = EXCLUDED.first_name, email = EXCLUDED.email,
last_name = EXCLUDED.last_name, is_admin = EXCLUDED.is_admin,
email = EXCLUDED.email, password_hash = EXCLUDED.password_hash"
is_admin = EXCLUDED.is_admin, [ "@id", Sql.uuid user.Id.Value
password_hash = EXCLUDED.password_hash""" "@firstName", Sql.string user.FirstName
|> Sql.parameters "@lastName", Sql.string user.LastName
[ "@id", Sql.uuid user.Id.Value "@email", Sql.string user.Email
"@firstName", Sql.string user.FirstName "@isAdmin", Sql.bool user.IsAdmin
"@lastName", Sql.string user.LastName "@passwordHash", Sql.string user.PasswordHash ]
"@email", Sql.string user.Email
"@isAdmin", Sql.bool user.IsAdmin
"@passwordHash", Sql.string user.PasswordHash
]
|> Sql.executeNonQueryAsync
return ()
}
/// Find a user by its e-mail address and authorized small group /// Find a user by its e-mail address and authorized small group
let tryByEmailAndGroup email (groupId : SmallGroupId) conn = backgroundTask { let tryByEmailAndGroup email (groupId : SmallGroupId) =
let! user = Custom.single
Sql.existingConnection conn "SELECT u.*
|> Sql.query """ FROM pt.pt_user u
SELECT u.* INNER JOIN pt.user_small_group usg ON usg.user_id = u.id AND usg.small_group_id = @groupId
FROM pt.pt_user u WHERE u.email = @email"
INNER JOIN pt.user_small_group usg ON usg.user_id = u.id AND usg.small_group_id = @groupId [ "@email", Sql.string email; "@groupId", Sql.uuid groupId.Value ] mapToUser
WHERE u.email = @email"""
|> Sql.parameters [ "@email", Sql.string email; "@groupId", Sql.uuid groupId.Value ]
|> Sql.executeAsync mapToUser
return List.tryHead user
}
/// Find a user by their database ID /// Find a user by their database ID
let tryById (userId : UserId) conn = backgroundTask { let tryById (userId : UserId) =
let! user = Custom.single "SELECT * FROM pt.pt_user WHERE id = @id" [ "@id", Sql.uuid userId.Value ] mapToUser
Sql.existingConnection conn
|> Sql.query "SELECT * FROM pt.pt_user WHERE id = @id"
|> Sql.parameters [ "@id", Sql.uuid userId.Value ]
|> Sql.executeAsync mapToUser
return List.tryHead user
}
/// Update a user's last seen date/time /// Update a user's last seen date/time
let updateLastSeen (userId : UserId) (now : Instant) conn = backgroundTask { let updateLastSeen (userId : UserId) (now : Instant) =
let! _ = Custom.nonQuery "UPDATE pt.pt_user SET last_seen = @now WHERE id = @id"
Sql.existingConnection conn [ "@id", Sql.uuid userId.Value; "@now", Sql.parameter (NpgsqlParameter ("@now", now)) ]
|> Sql.query "UPDATE pt.pt_user SET last_seen = @now WHERE id = @id"
|> Sql.parameters [ "@id", Sql.uuid userId.Value; "@now", Sql.parameter (NpgsqlParameter ("@now", now)) ]
|> Sql.executeNonQueryAsync
return ()
}
/// Update a user's password hash /// Update a user's password hash
let updatePassword (user : User) conn = backgroundTask { let updatePassword (user : User) =
let! _ = Custom.nonQuery "UPDATE pt.pt_user SET password_hash = @passwordHash WHERE id = @id"
Sql.existingConnection conn [ "@id", Sql.uuid user.Id.Value; "@passwordHash", Sql.string user.PasswordHash ]
|> Sql.query "UPDATE pt.pt_user SET password_hash = @passwordHash WHERE id = @id"
|> Sql.parameters [ "@id", Sql.uuid user.Id.Value; "@passwordHash", Sql.string user.PasswordHash ]
|> Sql.executeNonQueryAsync
return ()
}
/// Update a user's authorized small groups /// Update a user's authorized small groups
let updateSmallGroups (userId : UserId) groupIds conn = backgroundTask { let updateSmallGroups (userId : UserId) groupIds = backgroundTask {
let! existingGroupIds = groupIdsByUserId userId conn let! existingGroupIds = groupIdsByUserId userId
let toAdd = let toAdd =
groupIds |> List.filter (fun it -> existingGroupIds |> List.exists (fun grpId -> grpId = it) |> not) groupIds |> List.filter (fun it -> existingGroupIds |> List.exists (fun grpId -> grpId = it) |> not)
let toDelete = let toDelete =
@ -718,7 +582,8 @@ module Users =
} }
if not (Seq.isEmpty queries) then if not (Seq.isEmpty queries) then
let! _ = let! _ =
Sql.existingConnection conn Configuration.dataSource ()
|> Sql.fromDataSource
|> Sql.executeTransactionAsync (List.ofSeq queries) |> Sql.executeTransactionAsync (List.ofSeq queries)
() ()
} }

View File

@ -47,33 +47,30 @@ module private CacheHelpers =
p.ParameterName, Sql.parameter p p.ParameterName, Sql.parameter p
open BitBadger.Documents.Postgres
/// A distributed cache implementation in PostgreSQL used to handle sessions for myWebLog /// A distributed cache implementation in PostgreSQL used to handle sessions for myWebLog
type DistributedCache (connStr : string) = type DistributedCache () =
// ~~~ INITIALIZATION ~~~ // ~~~ INITIALIZATION ~~~
do do
task { task {
let! exists = let! exists =
Sql.connect connStr Custom.scalar
|> Sql.query $" $"SELECT EXISTS
SELECT EXISTS (SELECT 1 FROM pg_tables WHERE schemaname = 'public' AND tablename = 'session')
(SELECT 1 FROM pg_tables WHERE schemaname = 'public' AND tablename = 'session') AS does_exist"
AS does_exist" [] (fun row -> row.bool "does_exist")
|> Sql.executeRowAsync (fun row -> row.bool "does_exist")
if not exists then if not exists then
let! _ = do! Custom.nonQuery
Sql.connect connStr
|> Sql.query
"CREATE TABLE session ( "CREATE TABLE session (
id TEXT NOT NULL PRIMARY KEY, id TEXT NOT NULL PRIMARY KEY,
payload BYTEA NOT NULL, payload BYTEA NOT NULL,
expire_at TIMESTAMPTZ NOT NULL, expire_at TIMESTAMPTZ NOT NULL,
sliding_expiration INTERVAL, sliding_expiration INTERVAL,
absolute_expiration TIMESTAMPTZ); absolute_expiration TIMESTAMPTZ);
CREATE INDEX idx_session_expiration ON session (expire_at)" CREATE INDEX idx_session_expiration ON session (expire_at)" []
|> Sql.executeNonQueryAsync
()
} |> sync } |> sync
// ~~~ SUPPORT FUNCTIONS ~~~ // ~~~ SUPPORT FUNCTIONS ~~~
@ -82,16 +79,14 @@ type DistributedCache (connStr : string) =
let getEntry key = backgroundTask { let getEntry key = backgroundTask {
let idParam = "@id", Sql.string key let idParam = "@id", Sql.string key
let! tryEntry = let! tryEntry =
Sql.connect connStr Custom.single "SELECT * FROM session WHERE id = @id" [ idParam ]
|> Sql.query "SELECT * FROM session WHERE id = @id" (fun row ->
|> Sql.parameters [ idParam ] { Id = row.string "id"
|> Sql.executeAsync (fun row -> Payload = row.bytea "payload"
{ Id = row.string "id" ExpireAt = row.fieldValue<Instant> "expire_at"
Payload = row.bytea "payload" SlidingExpiration = row.fieldValueOrNone<Duration> "sliding_expiration"
ExpireAt = row.fieldValue<Instant> "expire_at" AbsoluteExpiration = row.fieldValueOrNone<Instant> "absolute_expiration" })
SlidingExpiration = row.fieldValueOrNone<Duration> "sliding_expiration" match tryEntry with
AbsoluteExpiration = row.fieldValueOrNone<Instant> "absolute_expiration" })
match List.tryHead tryEntry with
| Some entry -> | Some entry ->
let now = getNow () let now = getNow ()
let slideExp = defaultArg entry.SlidingExpiration Duration.MinValue let slideExp = defaultArg entry.SlidingExpiration Duration.MinValue
@ -103,12 +98,8 @@ type DistributedCache (connStr : string) =
true, { entry with ExpireAt = absExp } true, { entry with ExpireAt = absExp }
else true, { entry with ExpireAt = now.Plus slideExp } else true, { entry with ExpireAt = now.Plus slideExp }
if needsRefresh then if needsRefresh then
let! _ = do! Custom.nonQuery "UPDATE session SET expire_at = @expireAt WHERE id = @id"
Sql.connect connStr [ expireParam item.ExpireAt; idParam ]
|> Sql.query "UPDATE session SET expire_at = @expireAt WHERE id = @id"
|> Sql.parameters [ expireParam item.ExpireAt; idParam ]
|> Sql.executeNonQueryAsync
()
return if item.ExpireAt > now then Some entry else None return if item.ExpireAt > now then Some entry else None
| None -> return None | None -> return None
} }
@ -120,26 +111,16 @@ type DistributedCache (connStr : string) =
let purge () = backgroundTask { let purge () = backgroundTask {
let now = getNow () let now = getNow ()
if lastPurge.Plus (Duration.FromMinutes 30L) < now then if lastPurge.Plus (Duration.FromMinutes 30L) < now then
let! _ = do! Custom.nonQuery "DELETE FROM session WHERE expire_at < @expireAt" [ expireParam now ]
Sql.connect connStr
|> Sql.query "DELETE FROM session WHERE expire_at < @expireAt"
|> Sql.parameters [ expireParam now ]
|> Sql.executeNonQueryAsync
lastPurge <- now lastPurge <- now
} }
/// Remove a cache entry /// Remove a cache entry
let removeEntry key = backgroundTask { let removeEntry key =
let! _ = Custom.nonQuery "DELETE FROM session WHERE id = @id" [ "@id", Sql.string key ]
Sql.connect connStr
|> Sql.query "DELETE FROM session WHERE id = @id"
|> Sql.parameters [ "@id", Sql.string key ]
|> Sql.executeNonQueryAsync
()
}
/// Save an entry /// Save an entry
let saveEntry (opts : DistributedCacheEntryOptions) key payload = backgroundTask { let saveEntry (opts : DistributedCacheEntryOptions) key payload =
let now = getNow () let now = getNow ()
let expireAt, slideExp, absExp = let expireAt, slideExp, absExp =
if opts.SlidingExpiration.HasValue then if opts.SlidingExpiration.HasValue then
@ -155,27 +136,21 @@ type DistributedCache (connStr : string) =
// Default to 2 hour sliding expiration // Default to 2 hour sliding expiration
let slide = Duration.FromHours 2 let slide = Duration.FromHours 2
now.Plus slide, Some slide, None now.Plus slide, Some slide, None
let! _ = Custom.nonQuery
Sql.connect connStr "INSERT INTO session (
|> Sql.query id, payload, expire_at, sliding_expiration, absolute_expiration
"INSERT INTO session ( ) VALUES (
id, payload, expire_at, sliding_expiration, absolute_expiration @id, @payload, @expireAt, @slideExp, @absExp
) VALUES ( ) ON CONFLICT (id) DO UPDATE
@id, @payload, @expireAt, @slideExp, @absExp SET payload = EXCLUDED.payload,
) ON CONFLICT (id) DO UPDATE expire_at = EXCLUDED.expire_at,
SET payload = EXCLUDED.payload, sliding_expiration = EXCLUDED.sliding_expiration,
expire_at = EXCLUDED.expire_at, absolute_expiration = EXCLUDED.absolute_expiration"
sliding_expiration = EXCLUDED.sliding_expiration, [ "@id", Sql.string key
absolute_expiration = EXCLUDED.absolute_expiration" "@payload", Sql.bytea payload
|> Sql.parameters expireParam expireAt
[ "@id", Sql.string key optParam "slideExp" slideExp
"@payload", Sql.bytea payload optParam "absExp" absExp ]
expireParam expireAt
optParam "slideExp" slideExp
optParam "absExp" absExp ]
|> Sql.executeNonQueryAsync
()
}
// ~~~ IMPLEMENTATION FUNCTIONS ~~~ // ~~~ IMPLEMENTATION FUNCTIONS ~~~

View File

@ -1,9 +1,5 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
</PropertyGroup>
<ItemGroup> <ItemGroup>
<Compile Include="Entities.fs" /> <Compile Include="Entities.fs" />
<Compile Include="Access.fs" /> <Compile Include="Access.fs" />
@ -11,11 +7,12 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Giraffe" Version="6.0.0" /> <PackageReference Include="BitBadger.Documents.Postgres" Version="3.1.0" />
<PackageReference Include="NodaTime" Version="3.1.2" /> <PackageReference Include="Giraffe" Version="6.4.0" />
<PackageReference Update="FSharp.Core" Version="6.0.5" /> <PackageReference Include="NodaTime" Version="3.1.11" />
<PackageReference Include="Npgsql.FSharp" Version="5.3.0" /> <PackageReference Include="Npgsql.FSharp" Version="5.7.0" />
<PackageReference Include="Npgsql.NodaTime" Version="6.0.6" /> <PackageReference Include="Npgsql.NodaTime" Version="8.0.3" />
<PackageReference Update="FSharp.Core" Version="8.0.300" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@ -2,7 +2,6 @@
<PropertyGroup> <PropertyGroup>
<OutputType>Exe</OutputType> <OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
@ -15,9 +14,9 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Expecto" Version="9.0.4" /> <PackageReference Include="Expecto" Version="10.2.1" />
<PackageReference Include="NodaTime.Testing" Version="3.1.2" /> <PackageReference Include="NodaTime.Testing" Version="3.1.11" />
<PackageReference Update="FSharp.Core" Version="6.0.5" /> <PackageReference Update="FSharp.Core" Version="8.0.300" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View File

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

View File

@ -604,7 +604,7 @@ let requestListTests =
} }
let html = htmlList.AsHtml _s let html = htmlList.AsHtml _s
let expected = let expected =
htmlList.Requests[0].UpdatedDate.InUtc().Date.ToString ("d", null) htmlList.Requests[0].UpdatedDate.InZone(SmallGroup.timeZone reqList.SmallGroup).Date.ToString ("d", null)
|> sprintf """<strong>Zeb</strong> &ndash; zyx<i style="font-size:9.60pt">&nbsp; (as of %s)</i>""" |> 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 // spot check; if one request has it, they all should
Expect.stringContains html expected "Expected short as-of date not found" Expect.stringContains html expected "Expected short as-of date not found"
@ -619,7 +619,7 @@ let requestListTests =
} }
let html = htmlList.AsHtml _s let html = htmlList.AsHtml _s
let expected = let expected =
htmlList.Requests[0].UpdatedDate.InUtc().Date.ToString ("D", null) htmlList.Requests[0].UpdatedDate.InZone(SmallGroup.timeZone reqList.SmallGroup).Date.ToString ("D", null)
|> sprintf """<strong>Zeb</strong> &ndash; zyx<i style="font-size:9.60pt">&nbsp; (as of %s)</i>""" |> 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 // spot check; if one request has it, they all should
Expect.stringContains html expected "Expected long as-of date not found" Expect.stringContains html expected "Expected long as-of date not found"
@ -650,7 +650,7 @@ let requestListTests =
} }
let text = textList.AsText _s let text = textList.AsText _s
let expected = let expected =
textList.Requests[0].UpdatedDate.InUtc().Date.ToString ("d", null) textList.Requests[0].UpdatedDate.InZone(SmallGroup.timeZone reqList.SmallGroup).Date.ToString ("d", null)
|> sprintf " + Zeb - zyx (as of %s)" |> sprintf " + Zeb - zyx (as of %s)"
// spot check; if one request has it, they all should // spot check; if one request has it, they all should
Expect.stringContains text expected "Expected short as-of date not found" Expect.stringContains text expected "Expected short as-of date not found"
@ -665,7 +665,7 @@ let requestListTests =
} }
let text = textList.AsText _s let text = textList.AsText _s
let expected = let expected =
textList.Requests[0].UpdatedDate.InUtc().Date.ToString ("D", null) textList.Requests[0].UpdatedDate.InZone(SmallGroup.timeZone reqList.SmallGroup).Date.ToString ("D", null)
|> sprintf " + Zeb - zyx (as of %s)" |> sprintf " + Zeb - zyx (as of %s)"
// spot check; if one request has it, they all should // spot check; if one request has it, they all should
Expect.stringContains text expected "Expected long as-of date not found" Expect.stringContains text expected "Expected long as-of date not found"

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."] ] ] ]

View File

@ -19,4 +19,4 @@ 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 ($"""Views.{view.Replace ('/', '.')}""", resAsmName) htmlLocFactory.Create ($"Views.{view.Replace ('/', '.')}", resAsmName)

View File

@ -15,55 +15,42 @@ module Navigation =
/// Top navigation bar /// Top navigation bar
let top m = let top m =
let s = I18N.localizer.Force () let s = I18N.localizer.Force()
let menuSpacer = rawText "&nbsp; " let menuSpacer = rawText "&nbsp; "
let _dropdown = _class "dropdown-btn" let _dropdown = _class "dropdown-btn"
let leftLinks = [ let leftLinks = [
match m.User with match m.User with
| Some u -> | Some u ->
li [ _class "dropdown" ] [ li [ _class "dropdown" ] [
a [ _dropdown; _ariaLabel s["Requests"].Value; _title s["Requests"].Value; _roleButton ] [ a [ _dropdown; _ariaLabel s["Requests"].Value; _title s["Requests"].Value; _roleButton ] [
icon "question_answer"; space; locStr s["Requests"]; space; icon "keyboard_arrow_down" icon "question_answer"; space; locStr s["Requests"]; space; icon "keyboard_arrow_down" ]
]
div [ _class "dropdown-content"; _roleMenuBar ] [ div [ _class "dropdown-content"; _roleMenuBar ] [
a [ _href "/prayer-requests"; _roleMenuItem ] [ a [ _href "/prayer-requests"; _roleMenuItem ] [
icon "compare_arrows"; menuSpacer; locStr s["Maintain"] icon "compare_arrows"; menuSpacer; locStr s["Maintain"] ]
]
a [ _href "/prayer-requests/view"; _roleMenuItem ] [ a [ _href "/prayer-requests/view"; _roleMenuItem ] [
icon "list"; menuSpacer; locStr s["View List"] icon "list"; menuSpacer; locStr s["View List"] ] ] ]
]
]
]
li [ _class "dropdown" ] [ li [ _class "dropdown" ] [
a [ _dropdown; _ariaLabel s["Group"].Value; _title s["Group"].Value; _roleButton ] [ a [ _dropdown; _ariaLabel s["Group"].Value; _title s["Group"].Value; _roleButton ] [
icon "group"; space; locStr s["Group"]; space; icon "keyboard_arrow_down" icon "group"; space; locStr s["Group"]; space; icon "keyboard_arrow_down" ]
]
div [ _class "dropdown-content"; _roleMenuBar ] [ div [ _class "dropdown-content"; _roleMenuBar ] [
a [ _href "/small-group/members"; _roleMenuItem ] [ a [ _href "/small-group/members"; _roleMenuItem ] [
icon "email"; menuSpacer; locStr s["Maintain Group Members"] icon "email"; menuSpacer; locStr s["Maintain Group Members"] ]
]
a [ _href "/small-group/announcement"; _roleMenuItem ] [ a [ _href "/small-group/announcement"; _roleMenuItem ] [
icon "send"; menuSpacer; locStr s["Send Announcement"] icon "send"; menuSpacer; locStr s["Send Announcement"] ]
]
a [ _href "/small-group/preferences"; _roleMenuItem ] [ a [ _href "/small-group/preferences"; _roleMenuItem ] [
icon "build"; menuSpacer; locStr s["Change Preferences"] icon "build"; menuSpacer; locStr s["Change Preferences"] ] ] ]
]
]
]
if u.IsAdmin then if u.IsAdmin then
li [ _class "dropdown" ] [ li [ _class "dropdown" ] [
a [ _dropdown a [ _dropdown
_ariaLabel s["Administration"].Value _ariaLabel s["Administration"].Value
_title s["Administration"].Value _title s["Administration"].Value
_roleButton ] [ _roleButton ] [
icon "settings"; space; locStr s["Administration"]; space; icon "keyboard_arrow_down" icon "settings"; space; locStr s["Administration"]; space; icon "keyboard_arrow_down" ]
]
div [ _class "dropdown-content"; _roleMenuBar ] [ div [ _class "dropdown-content"; _roleMenuBar ] [
a [ _href "/churches"; _roleMenuItem ] [ icon "home"; menuSpacer; locStr s["Churches"] ] a [ _href "/churches"; _roleMenuItem ] [ icon "home"; menuSpacer; locStr s["Churches"] ]
a [ _href "/small-groups"; _roleMenuItem ] [ icon "send"; menuSpacer; locStr s["Groups"] ] a [ _href "/small-groups"; _roleMenuItem ] [
a [ _href "/users"; _roleMenuItem ] [ icon "build"; menuSpacer; locStr s["Users"] ] icon "send"; menuSpacer; locStr s["Groups"] ]
] a [ _href "/users"; _roleMenuItem ] [ icon "build"; menuSpacer; locStr s["Users"] ] ] ]
]
| None -> | None ->
match m.Group with match m.Group with
| Some _ -> | Some _ ->
@ -71,74 +58,50 @@ module Navigation =
a [ _href "/prayer-requests/view" a [ _href "/prayer-requests/view"
_ariaLabel s["View Request List"].Value _ariaLabel s["View Request List"].Value
_title s["View Request List"].Value ] [ _title s["View Request List"].Value ] [
icon "list"; space; locStr s["View Request List"] icon "list"; space; locStr s["View Request List"] ] ]
]
]
| None -> | None ->
li [ _class "dropdown" ] [ li [ _class "dropdown" ] [
a [ _dropdown; _ariaLabel s["Log On"].Value; _title s["Log On"].Value; _roleButton ] [ 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" icon "security"; space; locStr s["Log On"]; space; icon "keyboard_arrow_down" ]
]
div [ _class "dropdown-content"; _roleMenuBar ] [ div [ _class "dropdown-content"; _roleMenuBar ] [
a [ _href "/user/log-on"; _roleMenuItem ] [ icon "person"; menuSpacer; locStr s["User"] ] a [ _href "/user/log-on"; _roleMenuItem ] [ icon "person"; menuSpacer; locStr s["User"] ]
a [ _href "/small-group/log-on"; _roleMenuItem ] [ a [ _href "/small-group/log-on"; _roleMenuItem ] [
icon "group"; menuSpacer; locStr s["Group"] icon "group"; menuSpacer; locStr s["Group"] ] ] ]
]
]
]
li [] [ li [] [
a [ _href "/prayer-requests/lists" a [ _href "/prayer-requests/lists"
_ariaLabel s["View Request List"].Value _ariaLabel s["View Request List"].Value
_title s["View Request List"].Value ] [ _title s["View Request List"].Value ] [
icon "list"; space; locStr s["View Request List"] icon "list"; space; locStr s["View Request List"] ] ]
]
]
li [] [ li [] [
a [ _href $"https://docs.prayer.bitbadger.solutions/{langCode ()}" a [ _href "/help"; _ariaLabel s["Help"].Value; _title s["View Help"].Value; _target "_blank" ] [
_ariaLabel s["Help"].Value icon "help"; space; locStr s["Help"] ] ] ]
_title s["View Help"].Value
_target "_blank"
_relNoOpener ] [
icon "help"; space; locStr s["Help"]
]
]
]
let rightLinks = let rightLinks =
match m.Group with match m.Group with
| Some _ -> | Some _ -> [
[ match m.User with match m.User with
| Some _ -> | Some _ ->
li [] [
a [ _href "/user/password"
_ariaLabel s["Change Your Password"].Value
_title s["Change Your Password"].Value ] [
icon "lock"; space; locStr s["Change Your Password"]
]
]
| None -> ()
li [] [ li [] [
a [ _href "/log-off"; _ariaLabel s["Log Off"].Value; _title s["Log Off"].Value; Target.body ] [ a [ _href "/user/password"
icon "power_settings_new"; space; locStr s["Log Off"] _ariaLabel s["Change Your Password"].Value
] _title s["Change Your Password"].Value ] [
] icon "lock"; space; locStr s["Change Your Password"] ] ]
] | None -> ()
li [] [
a [ _href "/log-off"; _ariaLabel s["Log Off"].Value; _title s["Log Off"].Value; Target.body ] [
icon "power_settings_new"; space; locStr s["Log Off"] ] ] ]
| None -> [] | None -> []
header [ _class "pt-title-bar"; Target.content ] [ header [ _class "pt-title-bar"; Target.content ] [
section [ _class "pt-title-bar-left"; _ariaLabel "Left side of top menu" ] [ section [ _class "pt-title-bar-left"; _ariaLabel "Left side of top menu" ] [
span [ _class "pt-title-bar-home" ] [ span [ _class "pt-title-bar-home" ] [
a [ _href "/"; _title s["Home"].Value ] [ locStr s["PrayerTracker"] ] a [ _href "/"; _title s["Home"].Value ] [ locStr s["PrayerTracker"] ] ]
] ul [] leftLinks ]
ul [] leftLinks
]
section [ _class "pt-title-bar-center"; _ariaLabel "Empty center space in top menu" ] [] 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" ] [ section [ _class "pt-title-bar-right"; _roleToolBar; _ariaLabel "Right side of top menu" ] [
ul [] rightLinks ul [] rightLinks ] ]
]
]
/// Identity bar (below top nav) /// Identity bar (below top nav)
let identity m = let identity m =
let s = I18N.localizer.Force () let s = I18N.localizer.Force()
header [ _id "pt-language"; Target.body ] [ header [ _id "pt-language"; Target.body ] [
div [] [ div [] [
span [ _title s["Language"].Value ] [ icon "record_voice_over"; space ] span [ _title s["Language"].Value ] [ icon "record_voice_over"; space ]
@ -150,29 +113,26 @@ module Navigation =
| _ -> | _ ->
strong [] [ locStr s["English"] ] strong [] [ locStr s["English"] ]
rawText " &nbsp; &nbsp; " rawText " &nbsp; &nbsp; "
a [ _href "/language/es" ] [ locStr s["Cambie a Español"] ] a [ _href "/language/es" ] [ locStr s["Cambie a Español"] ] ]
]
match m.Group with match m.Group with
| Some g -> | Some g ->
[ match m.User with [ match m.User with
| Some u -> | Some u ->
span [ _class "u" ] [ locStr s["Currently Logged On"] ] span [ _class "u" ] [ locStr s["Currently Logged On"] ]
rawText "&nbsp; &nbsp;" rawText "&nbsp; &nbsp;"
icon "person" icon "person"
strong [] [ str u.Name ] strong [] [ str u.Name ]
rawText "&nbsp; &nbsp; " rawText "&nbsp; &nbsp; "
| None -> | None ->
locStr s["Logged On as a Member of"] locStr s["Logged On as a Member of"]
rawText "&nbsp; " rawText "&nbsp; "
icon "group" icon "group"
space space
match m.User with match m.User with
| Some _ -> a [ _href "/small-group"; Target.content ] [ strong [] [ str g.Name ] ] | Some _ -> a [ _href "/small-group"; Target.content ] [ strong [] [ str g.Name ] ]
| None -> strong [] [ str g.Name ] | None -> strong [] [ str g.Name ] ]
]
| None -> [] | None -> []
|> div [] |> div [] ]
]
/// Content layouts /// Content layouts
@ -193,47 +153,41 @@ let private commonHead = [
meta [ _name "viewport"; _content "width=device-width, initial-scale=1" ] meta [ _name "viewport"; _content "width=device-width, initial-scale=1" ]
meta [ _name "generator"; _content "Giraffe" ] meta [ _name "generator"; _content "Giraffe" ]
link [ _rel "stylesheet"; _href "https://fonts.googleapis.com/icon?family=Material+Icons" ] link [ _rel "stylesheet"; _href "https://fonts.googleapis.com/icon?family=Material+Icons" ]
link [ _rel "stylesheet"; _href "/css/app.css" ] link [ _rel "stylesheet"; _href "/css/app.css" ] ]
]
/// Render the <head> portion of the page /// Render the <head> portion of the page
let private htmlHead viewInfo pgTitle = let private htmlHead viewInfo pgTitle =
let s = I18N.localizer.Force () let s = I18N.localizer.Force()
head [] [ head [] [
meta [ _charset "UTF-8" ] meta [ _charset "UTF-8" ]
title [] [ locStr pgTitle; titleSep; locStr s["PrayerTracker"] ] title [] [ locStr pgTitle; titleSep; locStr s["PrayerTracker"] ]
yield! commonHead yield! commonHead
for cssFile in viewInfo.Style do for cssFile in viewInfo.Style do
link [ _rel "stylesheet"; _href $"/css/{cssFile}.css"; _type "text/css" ] link [ _rel "stylesheet"; _href $"/css/{cssFile}.css"; _type "text/css" ] ]
]
open Giraffe.ViewEngine.Htmx open Giraffe.ViewEngine.Htmx
/// Render a link to the help page for the current page /// Render a link to the help page for the current page
let private helpLink link = let private helpLink link =
let s = I18N.localizer.Force () let s = I18N.localizer.Force()
sup [ _class "pt-help-link" ] [ sup [ _class "pt-help-link" ] [
a [ _href link a [ _href link
_title s["Click for Help on This Page"].Value _title s["Click for Help on This Page"].Value
_onclick $"return PT.showHelp('{link}')" _onclick $"return PT.showHelp('{link}')"
_hxNoBoost ] [ _hxNoBoost ] [ iconSized 18 "help_outline" ] ]
iconSized 18 "help_outline"
]
]
/// Render the page title, and optionally a help link /// Render the page title, and optionally a help link
let private renderPageTitle viewInfo pgTitle = let private renderPageTitle viewInfo pgTitle =
h2 [ _id "pt-page-title" ] [ h2 [ _id "pt-page-title" ] [
match viewInfo.HelpLink with match viewInfo.HelpLink with
| Some link -> PrayerTracker.Utils.Help.fullLink (langCode ()) link |> helpLink | Some link -> helpLink $"/help/{link}"
| None -> () | None -> ()
locStr pgTitle locStr pgTitle ]
]
/// Render the messages that may need to be displayed to the user /// Render the messages that may need to be displayed to the user
let private messages viewInfo = let private messages viewInfo =
let s = I18N.localizer.Force () let s = I18N.localizer.Force()
if List.isEmpty viewInfo.Messages then [] if List.isEmpty viewInfo.Messages then []
else else
viewInfo.Messages viewInfo.Messages
@ -249,8 +203,7 @@ let private messages viewInfo =
| Some desc -> | Some desc ->
br [] br []
div [ _class "description" ] [ rawText desc.Value ] div [ _class "description" ] [ rawText desc.Value ]
| None -> () | None -> () ])
])
|> div [ _class "pt-messages" ] |> div [ _class "pt-messages" ]
|> List.singleton |> List.singleton
@ -259,70 +212,61 @@ open NodaTime
/// Render the <footer> at the bottom of the page /// Render the <footer> at the bottom of the page
let private htmlFooter viewInfo = let private htmlFooter viewInfo =
let s = I18N.localizer.Force () let s = I18N.localizer.Force()
let imgText = $"""%O{s["PrayerTracker"]} %O{s["from Bit Badger Solutions"]}""" let imgText = $"""%O{s["PrayerTracker"]} %O{s["from Bit Badger Solutions"]}"""
let resultTime = (SystemClock.Instance.GetCurrentInstant () - viewInfo.RequestStart).TotalSeconds let resultTime = (SystemClock.Instance.GetCurrentInstant() - viewInfo.RequestStart).TotalSeconds
footer [ _class "pt-footer" ] [ footer [ _class "pt-footer" ] [
div [ _id "pt-legal" ] [ div [ _id "pt-legal" ] [
a [ _href "/legal/privacy-policy" ] [ locStr s["Privacy Policy"] ] a [ _href "/legal/privacy-policy" ] [ locStr s["Privacy Policy"] ]
rawText " &nbsp; " rawText " &nbsp; "
a [ _href "/legal/terms-of-service" ] [ locStr s["Terms of Service"] ] a [ _href "/legal/terms-of-service" ] [ locStr s["Terms of Service"] ]
rawText " &nbsp; " rawText " &nbsp; "
a [ _href "https://github.com/bit-badger/PrayerTracker" a [ _href "https://git.bitbadger.solutions/bit-badger/PrayerTracker"
_title s["View source code and get technical support"].Value _title s["View source code and get technical support"].Value
_target "_blank" _target "_blank"
_relNoOpener ] [ _relNoOpener ] [
locStr s["Source & Support"] locStr s["Source & Support"] ] ]
]
]
div [ _id "pt-footer" ] [ div [ _id "pt-footer" ] [
a [ _href "/"; _style "line-height:28px;" ] [ a [ _href "/"; _style "line-height:28px;" ] [
img [ _src $"""/img/%O{s["footer_en"]}.png""" img [ _src $"""/img/%O{s["footer_en"]}.png"""
_alt imgText _alt imgText
_title imgText _title imgText
_width "331"; _height "28" ] _width "331"; _height "28" ] ]
]
span [ _id "pt-version" ] [ str viewInfo.Version ] span [ _id "pt-version" ] [ str viewInfo.Version ]
space space
i [ _title s["This page loaded in {0:N3} seconds", resultTime].Value; _class "material-icons md-18" ] [ i [ _title s["This page loaded in {0:N3} seconds", resultTime].Value; _class "material-icons md-18" ] [
str "schedule" str "schedule" ] ] ]
]
]
]
/// The content portion of the PrayerTracker layout /// The content portion of the PrayerTracker layout
let private contentSection viewInfo pgTitle (content : XmlNode) = [ let private contentSection viewInfo pgTitle (content: XmlNode) =
Navigation.identity viewInfo [ Navigation.identity viewInfo
renderPageTitle viewInfo pgTitle renderPageTitle viewInfo pgTitle
yield! messages viewInfo yield! messages viewInfo
match viewInfo.ScopedStyle with match viewInfo.ScopedStyle with
| [] -> () | [] -> ()
| styles -> style [] [ rawText (styles |> String.concat " ") ] | styles -> style [] [ rawText (styles |> String.concat " ") ]
content content
htmlFooter viewInfo htmlFooter viewInfo
match viewInfo.OnLoadScript with match viewInfo.OnLoadScript with
| Some onLoad -> | Some onLoad ->
let doCall = if onLoad.EndsWith ")" then "" else "()" let doCall = if onLoad.EndsWith ")" then "" else "()"
script [] [ script [] [
rawText $""" rawText $"
window.doOnLoad = () => {{ window.doOnLoad = () => {{
if (window.PT) {{ if (window.PT) {{
{onLoad}{doCall} {onLoad}{doCall}
delete window.doOnLoad delete window.doOnLoad
}} else {{ setTimeout(window.doOnLoad, 500) }} }} else {{ setTimeout(window.doOnLoad, 500) }}
}} }}
window.doOnLoad()""" window.doOnLoad()" ]
] | None -> () ]
| None -> ()
]
/// The HTML head element for partial responses /// The HTML head element for partial responses
let private partialHead pgTitle = let private partialHead pgTitle =
let s = I18N.localizer.Force () let s = I18N.localizer.Force()
head [] [ head [] [
meta [ _charset "UTF-8" ] meta [ _charset "UTF-8" ]
title [] [ locStr pgTitle; titleSep; locStr s["PrayerTracker"] ] title [] [ locStr pgTitle; titleSep; locStr s["PrayerTracker"] ] ]
]
open Giraffe.Htmx.Common open Giraffe.Htmx.Common
@ -337,12 +281,11 @@ let private pageLayout viewInfo pgTitle content =
Script.minified Script.minified
script [ _src "/js/ckeditor/ckeditor.js" ] [] script [ _src "/js/ckeditor/ckeditor.js" ] []
script [ _src "/js/app.js" ] [] script [ _src "/js/app.js" ] []
| _ -> () | _ -> () ]
]
/// The standard layout(s) for PrayerTracker /// The standard layout(s) for PrayerTracker
let standard viewInfo pageTitle content = let standard viewInfo pageTitle content =
let s = I18N.localizer.Force () let s = I18N.localizer.Force()
let pgTitle = s[pageTitle] let pgTitle = s[pageTitle]
html [ _lang (langCode ()) ] [ html [ _lang (langCode ()) ] [
match viewInfo.Layout with match viewInfo.Layout with
@ -354,13 +297,56 @@ let standard viewInfo pageTitle content =
pageLayout viewInfo pgTitle content pageLayout viewInfo pgTitle content
| ContentOnly -> | ContentOnly ->
partialHead pgTitle partialHead pgTitle
body [] (contentSection viewInfo pgTitle content) body [] (contentSection viewInfo pgTitle content) ]
]
/// A layout with nothing but a title and content /// A layout with nothing but a title and content
let bare pageTitle content = let bare pageTitle content =
let s = I18N.localizer.Force () let s = I18N.localizer.Force()
html [ _lang (langCode ()) ] [ html [ _lang (langCode ()) ] [
partialHead s[pageTitle] partialHead s[pageTitle]
body [] [ content ] 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 "/css/app.css"; _rel "stylesheet" ]
link [ _href "/css/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"] ] ] ] ] ] ] ]

View File

@ -1,9 +1,5 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</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,16 +15,15 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Giraffe" Version="6.0.0" />
<PackageReference Include="Giraffe.ViewEngine" Version="1.4.0" /> <PackageReference Include="Giraffe.ViewEngine" Version="1.4.0" />
<PackageReference Include="Giraffe.ViewEngine.Htmx" Version="1.8.0" /> <PackageReference Include="Giraffe.ViewEngine.Htmx" Version="2.0.0" />
<PackageReference Include="MailKit" Version="3.3.0" /> <PackageReference Include="MailKit" Version="4.6.0" />
<PackageReference Include="Microsoft.AspNetCore.Html.Abstractions" Version="2.2.0" /> <PackageReference Include="Microsoft.AspNetCore.Html.Abstractions" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Http" Version="2.2.2" /> <PackageReference Include="Microsoft.AspNetCore.Http" Version="2.2.2" />
<PackageReference Include="Microsoft.AspNetCore.Http.Extensions" Version="2.2.0" /> <PackageReference Include="Microsoft.AspNetCore.Http.Extensions" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.2.0" /> <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.2.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" /> <PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Update="FSharp.Core" Version="6.0.5" /> <PackageReference Update="FSharp.Core" Version="8.0.300" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
@ -38,6 +34,33 @@
<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>

View File

@ -882,4 +882,40 @@
<data name="This User Is a {0} Administrator" xml:space="preserve"> <data name="This User Is a {0} Administrator" xml:space="preserve">
<value>Este Usuario Es un Administrador de {0}</value> <value>Este Usuario Es un Administrador de {0}</value>
</data> </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>

View File

@ -0,0 +1,205 @@
<?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 change how your prayer request list looks and behaves." xml:space="preserve">
<value>Esta página le permite cambiar la forma en que su lista de peticiones de la oración se ve y se comporta.</value>
</data>
<data name="Each section is addressed below." xml:space="preserve">
<value>Cada sección se aborda más adelante.</value>
</data>
<data name="When a regular request goes this many days without being updated, it expires and no longer appears on the request list." xml:space="preserve">
<value>Cuando una petición regular va esta cantidad de días sin actualizar, caduca y ya no aparece en la lista de peticiones.</value>
</data>
<data name="Note that the categories “Long-Term Requests” and “Expecting” never expire automatically." xml:space="preserve">
<value>Tenga en cuenta que las categorías “Peticiones a Largo Plazo” y “Embarazada” no expirará automáticamente.</value>
</data>
<data name="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." xml:space="preserve">
<value>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.</value>
</data>
<data name="All categories respect this setting." xml:space="preserve">
<value>Todas las categorías respetar esta opción.</value>
</data>
<data name="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." xml:space="preserve">
<value>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.</value>
</data>
<data name="(NOTE: In the plain-text e-mail, new requests are bulleted with a “+” symbol, and old are bulleted with a “-” symbol.)" xml:space="preserve">
<value>(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 “-”.)</value>
</data>
<data name="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." xml:space="preserve">
<value>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.</value>
</data>
<data name="By default, requests are sorted within each group by the last updated date, with the most recent on top." xml:space="preserve">
<value>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.</value>
</data>
<data name="If you would prefer to have the list sorted by requestor or subject rather than by date, select “Sort by Requestor Name” instead." xml:space="preserve">
<value>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.</value>
</data>
<data name="PrayerTracker must put an name and e-mail address in the “from” position of each e-mail it sends." xml:space="preserve">
<value>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.</value>
</data>
<data name="The default name is “PrayerTracker”, and the default e-mail address is “prayer@bitbadger.solutions”." xml:space="preserve">
<value>El nombre predeterminado es “PrayerTracker”, y el valor predeterminado dirección de correo electrónico es “prayer@bitbadger.solutions”.</value>
</data>
<data name="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)." xml:space="preserve">
<value>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).</value>
</data>
<data name="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." xml:space="preserve">
<value>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.</value>
</data>
<data name="This is the default e-mail format for your group." xml:space="preserve">
<value>Este es el valor predeterminado formato de correo electrónico para su grupo.</value>
</data>
<data name="The PrayerTracker default is HTML, which sends the list just as you see it online." xml:space="preserve">
<value>El valor predeterminado de SeguidorOración es HTML, el cual envía la lista al igual que usted lo ve en el sitio.</value>
</data>
<data name="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." xml:space="preserve">
<value>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.</value>
</data>
<data name="The setting on this page is the group default; you can select a format for each recipient on the “Maintain Group Members” page." xml:space="preserve">
<value>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”.</value>
</data>
<data name="You can customize the colors that are used for the headings and lines in your request list." xml:space="preserve">
<value>Usted puede personalizar los colores que se utilizan para las partidas y líneas en su lista de peticiones.</value>
</data>
<data name="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." xml:space="preserve">
<value>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.</value>
</data>
<data name="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." xml:space="preserve">
<value>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.</value>
</data>
<data name="The background color cannot be changed." xml:space="preserve">
<value>El color de fondo no puede ser cambiado.</value>
</data>
<data name="There are two options for fonts that will be used in the prayer request list." xml:space="preserve">
<value>Hay dos opciones para las fuentes que se utilizarán en la lista de peticiones de oración.</value>
</data>
<data name="“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." xml:space="preserve">
<value>“Fuentes Nativas” utiliza una lista de fuentes que representarán las peticiones de oración en la mejor fuente disponible para su dispositivo, ya sea una computadora de escritorio o portátil, un dispositivo móvil o una tableta.</value>
</data>
<data name="(This is the default for new small groups.)" xml:space="preserve">
<value>(Este es el valor predeterminado para los nuevos grupos pequeños).</value>
</data>
<data name="“Named Fonts” uses a comma-separated list of fonts that you specify." xml:space="preserve">
<value>“Fuentes con Nombre” utiliza una lista de fuentes separadas por comas que usted especifica.</value>
</data>
<data name="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." xml:space="preserve">
<value>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.</value>
</data>
<data name="It is generally best to stick with the fonts that come with Windows - fonts like “Arial”, “Times New Roman”, “Tahoma”, and “Comic Sans MS”." xml:space="preserve">
<value>Generalmente es mejor quedarse con las fuentes que vienen con Windows - Fuentes como “Arial”, “Times New Roman”, “Tahoma”, y “Comic Sans MS”.</value>
</data>
<data name="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." xml:space="preserve">
<value>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”).</value>
</data>
<data name="This is the point size to use for each." xml:space="preserve">
<value>Este es el tamaño de punto a utilizar para cada uno.</value>
</data>
<data name="The default for the heading is 16pt, and the default for the text is 12pt." xml:space="preserve">
<value>El valor predeterminado para el título es 16 puntos, y el valor por defecto para el texto es 12 puntos.</value>
</data>
<data name="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:" xml:space="preserve">
<value>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”:</value>
</data>
<data name="Named Fonts: &quot;Times New Roman&quot;,serif" xml:space="preserve">
<value>Fuentes con Nombre: "Times New Roman",serif</value>
</data>
<data name="The group's request list can be either public, private, or password-protected." xml:space="preserve">
<value>La lista de peticiones del grupo puede ser pública, privada o protegida por contraseña.</value>
</data>
<data name="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)." xml:space="preserve">
<value>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).</value>
</data>
<data name="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." xml:space="preserve">
<value>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.</value>
</data>
<data name="As this is a shared password, it is stored in plain text, so you can easily see what it is." xml:space="preserve">
<value>Como se trata de una contraseña compartida, se almacena en texto plano, así que usted puede ver fácilmente lo que es.</value>
</data>
<data name="If you select “Password Protected” but do not enter a password, the list remains private, which is also the default value." xml:space="preserve">
<value>Si selecciona "Protegido por Contraseña" pero no introduce una contraseña, la lista sigue siendo privado, que también es el valor predeterminado.</value>
</data>
<data name="(Changing this password will force all members of the group who logged in with the “Remember Me” box checked to provide the new password.)" xml:space="preserve">
<value>(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.)</value>
</data>
<data name="This is the time zone that you would like to use for your group." xml:space="preserve">
<value>Esta es la zona horaria que desea utilizar para su clase.</value>
</data>
<data name="If you do not see your time zone listed, just &lt;a href=&quot;mailto:daniel@bitbadger.solutions?subject=PrayerTracker+Time+Zone&quot;&gt;contact Daniel&lt;/a&gt; and tell him what time zone you need." xml:space="preserve">
<value>Si no puede ver la zona horaria en la lista, ponte en &lt;a href="daniel@bitbadger.solutions?subject=Zona+Horaria+por+SeguidorOración"&gt;contacto con Daniel&lt;/a&gt; y decirle lo que la zona horaria que usted necesita.</value>
</data>
<data name="As small groups use PrayerTracker, they accumulate many expired requests." xml:space="preserve">
<value>A medida que los grupos pequeños utilizan SeguidorOración, acumulan muchas solicitudes caducadas.</value>
</data>
<data name="When lists of requests include expired requests, the results will be broken up into pages." xml:space="preserve">
<value>Cuando las listas de solicitudes que incluyen solicitudes caducadas, los resultados se dividirán en páginas.</value>
</data>
<data name="The default value is 100 requests per page, but may be set as low as 10 or as high as 255." xml:space="preserve">
<value>El valor predeterminado es de 100 solicitudes por página, pero se puede establecer tan bajo como 10 o tan alto como 255.</value>
</data>
<data name="PrayerTracker can display the last date a request was updated, at the end of the request text." xml:space="preserve">
<value>SeguidorOración puede mostrar la última fecha en que se actualizó una solicitud, al final del texto de solicitud.</value>
</data>
<data name="By default, it does not." xml:space="preserve">
<value>Por defecto, no lo hace.</value>
</data>
<data name="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)”." xml:space="preserve">
<value>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)”.</value>
</data>
</root>

View File

@ -0,0 +1,79 @@
<?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 log on to PrayerTracker." xml:space="preserve">
<value>Esta página le permite acceder a SeguidorOración.</value>
</data>
<data name="There are two different levels of access for PrayerTracker - user and group." xml:space="preserve">
<value>Hay dos diferentes niveles de acceso para SeguidorOración - el usuario y el grupo.</value>
</data>
<data name="Enter your e-mail address and password into the appropriate boxes, then select your group." xml:space="preserve">
<value>Introduzca su dirección de correo electrónico y contraseña en las cajas apropiadas y seleccione su grupo.</value>
</data>
<data name="If you want PrayerTracker to remember you on your computer, click the “Remember Me” box before clicking the “Log On” button." xml:space="preserve">
<value>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.</value>
</data>
<data name="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." xml:space="preserve">
<value>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.</value>
</data>
<data name="If you want PrayerTracker to remember your group, click the “Remember Me” box before clicking the “Log On” button." xml:space="preserve">
<value>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.</value>
</data>
</root>

View File

@ -0,0 +1,79 @@
<?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 will let you change your password." xml:space="preserve">
<value>Esta página le permitirá cambiar su contraseña.</value>
</data>
<data name="Enter your existing password in the top box, then enter your new password in the bottom two boxes." xml:space="preserve">
<value>Ingrese su contraseña actual en la caja superior y introduzca la nueva contraseña en la parte inferior dos cajas.</value>
</data>
<data name="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." xml:space="preserve">
<value>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.</value>
</data>
<data name="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." xml:space="preserve">
<value>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.</value>
</data>
<data name="PrayerTracker+Password+Help" xml:space="preserve">
<value>Ayuda+de+Contraseña+de+SeguidorOración</value>
</data>
<data name="Click here to request help resetting your password." xml:space="preserve">
<value>Haga clic aquí para solicitar ayuda para restablecer su contraseña.</value>
</data>
</root>

View File

@ -2,13 +2,10 @@
module PrayerTracker.Utils module PrayerTracker.Utils
open System open System
open System.Security.Cryptography
open System.Text
open Giraffe open Giraffe
/// Parse a short-GUID-based ID from a string /// Parse a short-GUID-based ID from a string
let idFromShort<'T> (f : Guid -> 'T) strValue = let idFromShort<'T> (f: Guid -> 'T) strValue =
(ShortGuid.toGuid >> f) strValue (ShortGuid.toGuid >> f) strValue
/// Format a GUID as a short GUID /// Format a GUID as a short GUID
@ -22,19 +19,19 @@ let emptyGuid = shortGuid Guid.Empty
module String = module String =
/// string.Trim() /// string.Trim()
let trim (str: string) = str.Trim () let trim (str: string) = str.Trim()
/// string.Replace() /// string.Replace()
let replace (find : string) repl (str : string) = str.Replace (find, repl) 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 /// Replace the first occurrence of a string with a second string within a given string
let replaceFirst (needle : string) replacement (haystack : string) = let replaceFirst (needle: string) replacement (haystack: string) =
match haystack.IndexOf needle with match haystack.IndexOf needle with
| -1 -> haystack | -1 -> haystack
| idx -> String.concat "" [ haystack[0..idx - 1]; replacement; haystack[idx + needle.Length..] ] | idx -> String.concat "" [ haystack[0..idx - 1]; replacement; haystack[idx + needle.Length..] ]
/// Convert a string to an option, with null, blank, and whitespace becoming None /// Convert a string to an option, with null, blank, and whitespace becoming None
let noneIfBlank (str : string) = let noneIfBlank (str: string) =
match str with match str with
| null -> None | null -> None
| it when it.Trim () = "" -> None | it when it.Trim () = "" -> None
@ -49,7 +46,7 @@ let stripTags allowedTags input =
let stripHtmlExp = Regex @"(<\/?[^>]+>)" let stripHtmlExp = Regex @"(<\/?[^>]+>)"
let mutable output = input let mutable output = input
for tag in stripHtmlExp.Matches input do for tag in stripHtmlExp.Matches input do
let htmlTag = tag.Value.ToLower () let htmlTag = tag.Value.ToLower()
let shouldReplace = let shouldReplace =
allowedTags allowedTags
|> List.fold (fun acc t -> |> List.fold (fun acc t ->
@ -103,7 +100,7 @@ let ckEditorToText (text : string) =
"</p>", "" "</p>", ""
"<p>", "" "<p>", ""
] ]
|> List.fold (fun (txt : string) (x, y) -> String.replace x y txt) text |> List.fold (fun (txt: string) (x, y) -> String.replace x y txt) text
|> String.trim |> String.trim

View File

@ -3,9 +3,9 @@ namespace PrayerTracker
open Microsoft.AspNetCore.Http open Microsoft.AspNetCore.Http
/// Middleware to add the starting ticks for the request /// Middleware to add the starting ticks for the request
type RequestStartMiddleware (next : RequestDelegate) = type RequestStartMiddleware (next: RequestDelegate) =
member this.InvokeAsync (ctx : HttpContext) = task { member this.InvokeAsync (ctx: HttpContext) = task {
ctx.Items[Key.startTime] <- ctx.Now ctx.Items[Key.startTime] <- ctx.Now
return! next.Invoke ctx return! next.Invoke ctx
} }
@ -21,7 +21,7 @@ open Microsoft.Extensions.Configuration
module Configure = module Configure =
/// 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.SetBasePath(ctx.HostingEnvironment.ContentRootPath)
.AddJsonFile("appsettings.json", optional = true, reloadOnChange = true) .AddJsonFile("appsettings.json", optional = true, reloadOnChange = true)
.AddJsonFile($"appsettings.{ctx.HostingEnvironment.EnvironmentName}.json", optional = true) .AddJsonFile($"appsettings.{ctx.HostingEnvironment.EnvironmentName}.json", optional = true)
@ -31,10 +31,11 @@ module Configure =
open Microsoft.AspNetCore.Server.Kestrel.Core open Microsoft.AspNetCore.Server.Kestrel.Core
/// Configure Kestrel from appsettings.json /// Configure Kestrel from appsettings.json
let kestrel (ctx : WebHostBuilderContext) (opts : KestrelServerOptions) = let kestrel (ctx: WebHostBuilderContext) (opts: KestrelServerOptions) =
(ctx.Configuration.GetSection >> opts.Configure >> ignore) "Kestrel" (ctx.Configuration.GetSection >> opts.Configure >> ignore) "Kestrel"
open System.Globalization open System.Globalization
open BitBadger.Documents.Postgres
open Microsoft.AspNetCore.Authentication.Cookies open Microsoft.AspNetCore.Authentication.Cookies
open Microsoft.AspNetCore.Localization open Microsoft.AspNetCore.Localization
open Microsoft.Extensions.Caching.Distributed open Microsoft.Extensions.Caching.Distributed
@ -45,39 +46,38 @@ module Configure =
/// Configure ASP.NET Core's service collection (dependency injection container) /// Configure ASP.NET Core's service collection (dependency injection container)
let services (svc : IServiceCollection) = let services (svc : IServiceCollection) =
let _ = svc.AddOptions () let _ = svc.AddOptions()
let _ = svc.AddLocalization (fun options -> options.ResourcesPath <- "Resources") let _ = svc.AddLocalization(fun options -> options.ResourcesPath <- "Resources")
let _ = let _ =
svc.Configure<RequestLocalizationOptions> (fun (opts : RequestLocalizationOptions) -> svc.Configure<RequestLocalizationOptions>(fun (opts: RequestLocalizationOptions) ->
let supportedCultures =[| let supportedCultures = [|
CultureInfo "en-US"; CultureInfo "en-GB"; CultureInfo "en-AU"; CultureInfo "en" CultureInfo "en-US"; CultureInfo "en-GB"; CultureInfo "en-AU"; CultureInfo "en"
CultureInfo "es-MX"; CultureInfo "es-ES"; CultureInfo "es" CultureInfo "es-MX"; CultureInfo "es-ES"; CultureInfo "es" |]
|] opts.DefaultRequestCulture <- RequestCulture("en-US", "en-US")
opts.DefaultRequestCulture <- RequestCulture ("en-US", "en-US")
opts.SupportedCultures <- supportedCultures opts.SupportedCultures <- supportedCultures
opts.SupportedUICultures <- supportedCultures) opts.SupportedUICultures <- supportedCultures)
let _ = let _ =
svc.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) svc.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie (fun opts -> .AddCookie(fun opts ->
opts.ExpireTimeSpan <- TimeSpan.FromMinutes 120. opts.ExpireTimeSpan <- TimeSpan.FromMinutes 120.
opts.SlidingExpiration <- true opts.SlidingExpiration <- true
opts.AccessDeniedPath <- "/error/403") opts.AccessDeniedPath <- "/error/403")
let _ = svc.AddAuthorization () let _ = svc.AddAuthorization()
let _ =
svc.AddSingleton<IDistributedCache> (fun sp -> let cfg = svc.BuildServiceProvider().GetService<IConfiguration>()
let cfg = sp.GetService<IConfiguration> () let dsb = NpgsqlDataSourceBuilder(cfg.GetConnectionString "PrayerTracker")
DistributedCache (cfg.GetConnectionString "PrayerTracker") :> IDistributedCache) let _ = dsb.UseNodaTime()
let _ = svc.AddSession () dsb.Build() |> Configuration.useDataSource
let _ = svc.AddAntiforgery ()
let _ = svc.AddRouting () let emailCfg = cfg.GetSection "Email"
if (emailCfg.GetChildren >> Seq.isEmpty >> not) () then ConfigurationBinder.Bind(emailCfg, Email.smtpOptions)
let _ = svc.AddSingleton<IDistributedCache, DistributedCache>()
let _ = svc.AddSession()
let _ = svc.AddAntiforgery()
let _ = svc.AddRouting()
let _ = svc.AddSingleton<IClock> SystemClock.Instance let _ = svc.AddSingleton<IClock> SystemClock.Instance
let _ =
svc.AddScoped<NpgsqlConnection>(fun sp ->
let cfg = sp.GetService<IConfiguration> ()
let conn = new NpgsqlConnection (cfg.GetConnectionString "PrayerTracker")
conn.OpenAsync () |> Async.AwaitTask |> Async.RunSynchronously
conn)
let _ = NpgsqlConnection.GlobalTypeMapper.UseNodaTime ()
() ()
open Giraffe open Giraffe
@ -93,15 +93,26 @@ module Configure =
GET_HEAD [ GET_HEAD [
subRoute "/church" [ subRoute "/church" [
route "es" Handlers.Church.maintain route "es" Handlers.Church.maintain
routef "/%O/edit" Handlers.Church.edit routef "/%O/edit" Handlers.Church.edit ]
]
route "/class/logon" (redirectTo true "/small-group/log-on") route "/class/logon" (redirectTo true "/small-group/log-on")
routef "/error/%s" Handlers.Home.error 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 routef "/language/%s" Handlers.Home.language
subRoute "/legal" [ subRoute "/legal" [
route "/privacy-policy" Handlers.Home.privacyPolicy route "/privacy-policy" Handlers.Home.privacyPolicy
route "/terms-of-service" Handlers.Home.tos route "/terms-of-service" Handlers.Home.tos ]
]
route "/log-off" Handlers.Home.logOff route "/log-off" Handlers.Home.logOff
subRoute "/prayer-request" [ subRoute "/prayer-request" [
route "s" (Handlers.PrayerRequest.maintain true) route "s" (Handlers.PrayerRequest.maintain true)
@ -115,8 +126,7 @@ module Configure =
routef "s/view/%s" (Some >> Handlers.PrayerRequest.view) routef "s/view/%s" (Some >> Handlers.PrayerRequest.view)
routef "/%O/edit" Handlers.PrayerRequest.edit routef "/%O/edit" Handlers.PrayerRequest.edit
routef "/%O/expire" Handlers.PrayerRequest.expire routef "/%O/expire" Handlers.PrayerRequest.expire
routef "/%O/restore" Handlers.PrayerRequest.restore routef "/%O/restore" Handlers.PrayerRequest.restore ]
]
subRoute "/small-group" [ subRoute "/small-group" [
route "" Handlers.SmallGroup.overview route "" Handlers.SmallGroup.overview
route "s" Handlers.SmallGroup.maintain route "s" Handlers.SmallGroup.maintain
@ -127,8 +137,7 @@ module Configure =
route "/logon" (redirectTo true "/small-group/log-on") route "/logon" (redirectTo true "/small-group/log-on")
routef "/member/%O/edit" Handlers.SmallGroup.editMember routef "/member/%O/edit" Handlers.SmallGroup.editMember
route "/members" Handlers.SmallGroup.members route "/members" Handlers.SmallGroup.members
route "/preferences" Handlers.SmallGroup.preferences route "/preferences" Handlers.SmallGroup.preferences ]
]
route "/unauthorized" Handlers.Home.unauthorized route "/unauthorized" Handlers.Home.unauthorized
subRoute "/user" [ subRoute "/user" [
route "s" Handlers.User.maintain route "s" Handlers.User.maintain
@ -136,19 +145,15 @@ module Configure =
routef "/%O/small-groups" Handlers.User.smallGroups routef "/%O/small-groups" Handlers.User.smallGroups
route "/log-on" Handlers.User.logOn route "/log-on" Handlers.User.logOn
route "/logon" (redirectTo true "/user/log-on") route "/logon" (redirectTo true "/user/log-on")
route "/password" Handlers.User.password route "/password" Handlers.User.password ]
] route "/" Handlers.Home.homePage ]
route "/" Handlers.Home.homePage
]
POST [ POST [
subRoute "/church" [ subRoute "/church" [
routef "/%O/delete" Handlers.Church.delete routef "/%O/delete" Handlers.Church.delete
route "/save" Handlers.Church.save route "/save" Handlers.Church.save ]
]
subRoute "/prayer-request" [ subRoute "/prayer-request" [
routef "/%O/delete" Handlers.PrayerRequest.delete routef "/%O/delete" Handlers.PrayerRequest.delete
route "/save" Handlers.PrayerRequest.save route "/save" Handlers.PrayerRequest.save ]
]
subRoute "/small-group" [ subRoute "/small-group" [
route "/announcement/send" Handlers.SmallGroup.sendAnnouncement route "/announcement/send" Handlers.SmallGroup.sendAnnouncement
routef "/%O/delete" Handlers.SmallGroup.delete routef "/%O/delete" Handlers.SmallGroup.delete
@ -156,122 +161,76 @@ module Configure =
routef "/member/%O/delete" Handlers.SmallGroup.deleteMember routef "/member/%O/delete" Handlers.SmallGroup.deleteMember
route "/member/save" Handlers.SmallGroup.saveMember route "/member/save" Handlers.SmallGroup.saveMember
route "/preferences/save" Handlers.SmallGroup.savePreferences route "/preferences/save" Handlers.SmallGroup.savePreferences
route "/save" Handlers.SmallGroup.save route "/save" Handlers.SmallGroup.save ]
]
subRoute "/user" [ subRoute "/user" [
routef "/%O/delete" Handlers.User.delete routef "/%O/delete" Handlers.User.delete
route "/edit/save" Handlers.User.save route "/edit/save" Handlers.User.save
route "/log-on" Handlers.User.doLogOn route "/log-on" Handlers.User.doLogOn
route "/password/change" Handlers.User.changePassword route "/password/change" Handlers.User.changePassword
route "/small-groups/save" Handlers.User.saveGroups route "/small-groups/save" Handlers.User.saveGroups ] ] ]
]
]
]
open Microsoft.Extensions.Logging open Microsoft.Extensions.Logging
/// Giraffe error handler /// Giraffe error handler
let errorHandler (ex : exn) (logger : ILogger) = let errorHandler (ex: exn) (logger: ILogger) =
logger.LogError (EventId(), ex, "An unhandled exception has occurred while executing the request.") logger.LogError(EventId(), ex, "An unhandled exception has occurred while executing the request.")
clearResponse >=> setStatusCode 500 >=> text ex.Message clearResponse >=> setStatusCode 500 >=> text ex.Message
open Microsoft.Extensions.Hosting open Microsoft.Extensions.Hosting
/// Configure logging /// Configure logging
let logging (log : ILoggingBuilder) = let logging (log: ILoggingBuilder) =
let env = log.Services.BuildServiceProvider().GetService<IWebHostEnvironment> () let env = log.Services.BuildServiceProvider().GetService<IWebHostEnvironment>()
if env.IsDevelopment () then log else log.AddFilter (fun l -> l > LogLevel.Information) if env.IsDevelopment() then log else log.AddFilter(fun l -> l > LogLevel.Information)
|> function l -> l.AddConsole().AddDebug() |> function l -> l.AddConsole().AddDebug()
|> ignore |> ignore
open BitBadger.AspNetCore.CanonicalDomains
open Microsoft.Extensions.Localization open Microsoft.Extensions.Localization
open Microsoft.Extensions.Options open Microsoft.Extensions.Options
/// Configure the application /// Configure the application
let app (app : IApplicationBuilder) = let app (app : IApplicationBuilder) =
let env = app.ApplicationServices.GetRequiredService<IWebHostEnvironment>() let env = app.ApplicationServices.GetRequiredService<IWebHostEnvironment>()
if env.IsDevelopment () then if env.IsDevelopment() then
let _ = app.UseDeveloperExceptionPage () app.UseDeveloperExceptionPage()
()
else else
let _ = app.UseGiraffeErrorHandler errorHandler app.UseGiraffeErrorHandler errorHandler
() |> ignore
let _ = app.UseForwardedHeaders()
let _ = app.UseCanonicalDomains()
let _ = app.UseStatusCodePagesWithReExecute "/error/{0}" let _ = app.UseStatusCodePagesWithReExecute "/error/{0}"
let _ = app.UseStaticFiles () let _ = app.UseStaticFiles()
let _ = app.UseCookiePolicy (CookiePolicyOptions (MinimumSameSitePolicy = SameSiteMode.Strict)) let _ = app.UseCookiePolicy(CookiePolicyOptions(MinimumSameSitePolicy = SameSiteMode.Strict))
let _ = app.UseMiddleware<RequestStartMiddleware> () let _ = app.UseMiddleware<RequestStartMiddleware>()
let _ = app.UseRouting () let _ = app.UseRouting()
let _ = app.UseSession () let _ = app.UseSession()
let _ = app.UseRequestLocalization let _ = app.UseRequestLocalization(
(app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>().Value) app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>().Value)
let _ = app.UseAuthentication () let _ = app.UseAuthentication()
let _ = app.UseAuthorization () let _ = app.UseAuthorization()
let _ = app.UseEndpoints (fun e -> e.MapGiraffeEndpoints routes) let _ = app.UseEndpoints(fun e -> e.MapGiraffeEndpoints routes)
Views.I18N.setUpFactories <| app.ApplicationServices.GetRequiredService<IStringLocalizerFactory> () app.ApplicationServices.GetRequiredService<IStringLocalizerFactory>() |> Views.I18N.setUpFactories
/// The web application /// The web application
module App = module App =
open System.Text
open Microsoft.Extensions.DependencyInjection
open Npgsql
open Npgsql.FSharp
open PrayerTracker.Entities
let migratePasswords (app : IWebHost) =
task {
let config = app.Services.GetService<IConfiguration> ()
use conn = new NpgsqlConnection (config.GetConnectionString "PrayerTracker")
do! conn.OpenAsync ()
let! v1Users =
Sql.existingConnection conn
|> Sql.query "SELECT id, password_hash FROM pt.pt_user WHERE salt IS NULL"
|> Sql.executeAsync (fun row -> UserId (row.uuid "id"), row.string "password_hash")
for userId, oldHash in v1Users do
let pw = Convert.ToBase64String [| 254uy; yield! (Encoding.UTF8.GetBytes oldHash) |]
let! _ =
Sql.existingConnection conn
|> Sql.query "UPDATE pt.pt_user SET password_hash = @hash WHERE id = @id"
|> Sql.parameters [ "@id", Sql.uuid userId.Value; "@hash", Sql.string pw ]
|> Sql.executeNonQueryAsync
()
printfn $"Updated {v1Users.Length} users with version 1 password"
let! v2Users =
Sql.existingConnection conn
|> Sql.query "SELECT id, password_hash, salt FROM pt.pt_user WHERE salt IS NOT NULL"
|> Sql.executeAsync (fun row -> UserId (row.uuid "id"), row.string "password_hash", row.uuid "salt")
for userId, oldHash, salt in v2Users do
let pw =
Convert.ToBase64String
[| 255uy; yield! (salt.ToByteArray ()); yield! (Encoding.UTF8.GetBytes oldHash) |]
let! _ =
Sql.existingConnection conn
|> Sql.query "UPDATE pt.pt_user SET password_hash = @hash WHERE id = @id"
|> Sql.parameters [ "@id", Sql.uuid userId.Value; "@hash", Sql.string pw ]
|> Sql.executeNonQueryAsync
()
printfn $"Updated {v2Users.Length} users with version 2 password"
} |> Async.AwaitTask |> Async.RunSynchronously
open System.IO open System.IO
[<EntryPoint>] [<EntryPoint>]
let main args = let main args =
let contentRoot = Directory.GetCurrentDirectory () let contentRoot = Directory.GetCurrentDirectory()
let app = let app =
WebHostBuilder() WebHostBuilder()
.UseContentRoot(contentRoot) .UseContentRoot(contentRoot)
.ConfigureAppConfiguration(Configure.configuration) .ConfigureAppConfiguration(Configure.configuration)
.UseKestrel(Configure.kestrel) .UseKestrel(Configure.kestrel)
.UseWebRoot(Path.Combine (contentRoot, "wwwroot")) .UseWebRoot(Path.Combine(contentRoot, "wwwroot"))
.ConfigureServices(Configure.services) .ConfigureServices(Configure.services)
.ConfigureLogging(Configure.logging) .ConfigureLogging(Configure.logging)
.Configure(System.Action<IApplicationBuilder> Configure.app) .Configure(System.Action<IApplicationBuilder> Configure.app)
.Build() .Build()
if args.Length > 0 then if args.Length > 0 then printfn $"Unrecognized option {args[0]}" else app.Run()
if args[0] = "migrate-passwords" then migratePasswords app
else printfn $"Unrecognized option {args[0]}"
else app.Run ()
0 0

View File

@ -8,21 +8,20 @@ open PrayerTracker.Entities
open PrayerTracker.ViewModels open PrayerTracker.ViewModels
/// Find statistics for the given church /// Find statistics for the given church
let private findStats churchId conn = task { let private findStats churchId = task {
let! groups = SmallGroups.countByChurch churchId conn let! groups = SmallGroups.countByChurch churchId
let! requests = PrayerRequests.countByChurch churchId conn let! requests = PrayerRequests.countByChurch churchId
let! users = Users.countByChurch churchId conn let! users = Users.countByChurch churchId
return shortGuid churchId.Value, { SmallGroups = groups; PrayerRequests = requests; Users = users } return shortGuid churchId.Value, { SmallGroups = groups; PrayerRequests = requests; Users = users }
} }
/// POST /church/[church-id]/delete // POST /church/[church-id]/delete
let delete chId : HttpHandler = requireAccess [ Admin ] >=> validateCsrf >=> fun next ctx -> task { let delete chId : HttpHandler = requireAccess [ Admin ] >=> validateCsrf >=> fun next ctx -> task {
let churchId = ChurchId chId let churchId = ChurchId chId
let conn = ctx.Conn match! Churches.tryById churchId with
match! Churches.tryById churchId conn with
| Some church -> | Some church ->
let! _, stats = findStats churchId conn let! _, stats = findStats churchId
do! Churches.deleteById churchId conn do! Churches.deleteById churchId
addInfo ctx 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)", 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] church.Name, stats.SmallGroups, stats.PrayerRequests, stats.Users]
@ -32,7 +31,7 @@ let delete chId : HttpHandler = requireAccess [ Admin ] >=> validateCsrf >=> fun
open System open System
/// GET /church/[church-id]/edit // GET /church/[church-id]/edit
let edit churchId : HttpHandler = requireAccess [ Admin ] >=> fun next ctx -> task { let edit churchId : HttpHandler = requireAccess [ Admin ] >=> fun next ctx -> task {
if churchId = Guid.Empty then if churchId = Guid.Empty then
return! return!
@ -40,7 +39,7 @@ let edit churchId : HttpHandler = requireAccess [ Admin ] >=> fun next ctx -> ta
|> Views.Church.edit EditChurch.empty ctx |> Views.Church.edit EditChurch.empty ctx
|> renderHtml next ctx |> renderHtml next ctx
else else
match! Churches.tryById (ChurchId churchId) ctx.Conn with match! Churches.tryById (ChurchId churchId) with
| Some church -> | Some church ->
return! return!
viewInfo ctx viewInfo ctx
@ -49,28 +48,27 @@ let edit churchId : HttpHandler = requireAccess [ Admin ] >=> fun next ctx -> ta
| None -> return! fourOhFour ctx | None -> return! fourOhFour ctx
} }
/// GET /churches // GET /churches
let maintain : HttpHandler = requireAccess [ Admin ] >=> fun next ctx -> task { let maintain : HttpHandler = requireAccess [ Admin ] >=> fun next ctx -> task {
let conn = ctx.Conn let! churches = Churches.all ()
let! churches = Churches.all conn let stats = churches |> List.map (fun c -> findStats c.Id |> Async.AwaitTask |> Async.RunSynchronously)
let stats = churches |> List.map (fun c -> findStats c.Id conn |> Async.AwaitTask |> Async.RunSynchronously)
return! return!
viewInfo ctx viewInfo ctx
|> 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 = requireAccess [ Admin ] >=> validateCsrf >=> fun next ctx -> task {
match! ctx.TryBindFormAsync<EditChurch> () with match! ctx.TryBindFormAsync<EditChurch> () with
| Ok model -> | Ok model ->
let! church = let! church =
if model.IsNew then Task.FromResult (Some { Church.empty with Id = (Guid.NewGuid >> ChurchId) () }) if model.IsNew then Task.FromResult(Some { Church.empty with Id = (Guid.NewGuid >> ChurchId) () })
else Churches.tryById (idFromShort ChurchId model.ChurchId) ctx.Conn else Churches.tryById (idFromShort ChurchId model.ChurchId)
match church with match church with
| Some ch -> | Some ch ->
do! Churches.save (model.PopulateChurch ch) ctx.Conn do! Churches.save (model.PopulateChurch ch)
let act = ctx.Strings[if model.IsNew then "Added" else "Updated"].Value.ToLower () let act = ctx.Strings[if model.IsNew then "Added" else "Updated"].Value.ToLower()
addInfo ctx ctx.Strings["Successfully {0} church “{1}”", act, model.Name] addInfo ctx ctx.Strings["Successfully {0} church “{1}”", act, model.Name]
return! redirectTo false "/churches" next ctx return! redirectTo false "/churches" next ctx
| None -> return! fourOhFour ctx | None -> return! fourOhFour ctx

View File

@ -5,22 +5,21 @@ module PrayerTracker.Handlers.CommonFunctions
open Microsoft.AspNetCore.Mvc.Rendering open Microsoft.AspNetCore.Mvc.Rendering
/// 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) =
if isNull items then nullArg (nameof 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()
SelectListItem ($"""&mdash; %A{s[emptyText]} &mdash;""", "") 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
@ -49,7 +48,7 @@ open PrayerTracker
open PrayerTracker.ViewModels open PrayerTracker.ViewModels
/// Create the common view information heading /// Create the common view information heading
let viewInfo (ctx : HttpContext) = let viewInfo (ctx: HttpContext) =
let msg = let msg =
match ctx.Session.Messages with match ctx.Session.Messages with
| [] -> [] | [] -> []
@ -67,8 +66,7 @@ let viewInfo (ctx : HttpContext) =
RequestStart = ctx.Items[Key.startTime] :?> Instant RequestStart = ctx.Items[Key.startTime] :?> Instant
User = ctx.Session.CurrentUser User = ctx.Session.CurrentUser
Group = ctx.Session.CurrentGroup Group = ctx.Session.CurrentGroup
Layout = layout Layout = layout }
}
/// 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 =
@ -77,24 +75,24 @@ let renderHtml next ctx view =
open Microsoft.Extensions.Logging open Microsoft.Extensions.Logging
/// Display an error regarding form submission /// Display an error regarding form submission
let bindError (msg : string) = let bindError (msg: string) =
handleContext (fun ctx -> handleContext (fun ctx ->
ctx.GetService<ILoggerFactory>().CreateLogger("PrayerTracker.Handlers").LogError msg ctx.GetService<ILoggerFactory>().CreateLogger("PrayerTracker.Handlers").LogError msg
(setStatusCode 400 >=> text msg) earlyReturn 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 (ctx : HttpContext) = let fourOhFour (ctx: HttpContext) =
(setStatusCode 404 >=> text "Not Found") earlyReturn ctx (setStatusCode 404 >=> text "Not Found") earlyReturn ctx
/// Handler to validate CSRF prevention token /// Handler to validate CSRF prevention token
let validateCsrf : HttpHandler = fun next ctx -> task { let validateCsrf : HttpHandler = fun next ctx -> task {
match! (ctx.GetService<Microsoft.AspNetCore.Antiforgery.IAntiforgery> ()).IsRequestValidAsync ctx with match! ctx.GetService<Microsoft.AspNetCore.Antiforgery.IAntiforgery>().IsRequestValidAsync ctx with
| true -> return! next ctx | true -> return! next ctx
| false -> return! (clearResponse >=> setStatusCode 400 >=> text "Quit hacking...") earlyReturn ctx | false -> return! (clearResponse >=> setStatusCode 400 >=> text "Quit hacking...") earlyReturn ctx
} }
/// Add a message to the session /// Add a message to the session
let addUserMessage (ctx : HttpContext) msg = let addUserMessage (ctx: HttpContext) msg =
ctx.Session.Messages <- msg :: ctx.Session.Messages ctx.Session.Messages <- msg :: ctx.Session.Messages
@ -102,10 +100,10 @@ open Microsoft.AspNetCore.Html
open Microsoft.Extensions.Localization 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) =
(System.Net.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
@ -143,8 +141,8 @@ open PrayerTracker.Entities
/// Require one of the given access roles /// Require one of the given access roles
let requireAccess levels : HttpHandler = fun next ctx -> task { let requireAccess levels : HttpHandler = fun next ctx -> task {
// These calls fill the user and group in the session, making .Value safe to use for the rest of the request // These calls fill the user and group in the session, making .Value safe to use for the rest of the request
let! user = ctx.CurrentUser () let! user = ctx.CurrentUser()
let! group = ctx.CurrentGroup () let! group = ctx.CurrentGroup()
match user, group with match user, group with
| _, _ when List.contains Public levels -> return! next ctx | _, _ when List.contains Public levels -> return! next ctx
| Some _, _ when List.contains User levels -> return! next ctx | Some _, _ when List.contains User levels -> return! next ctx
@ -155,7 +153,7 @@ let requireAccess levels : HttpHandler = fun next ctx -> task {
return! redirectTo false "/unauthorized" next ctx return! redirectTo false "/unauthorized" next ctx
| _, _ when List.contains User levels -> | _, _ when List.contains User levels ->
// Redirect to the user log on page // Redirect to the user log on page
ctx.Session.SetString (Key.Session.redirectUrl, ctx.Request.GetEncodedPathAndQuery ()) ctx.Session.SetString(Key.Session.redirectUrl, ctx.Request.GetEncodedPathAndQuery())
return! redirectTo false "/user/log-on" next ctx return! redirectTo false "/user/log-on" next ctx
| _, _ when List.contains Group levels -> | _, _ when List.contains Group levels ->
// Redirect to the small group log on page // Redirect to the small group log on page

View File

@ -2,83 +2,98 @@
module PrayerTracker.Email module PrayerTracker.Email
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
/// Parameters required to send an e-mail /// Parameters required to send an e-mail
type EmailOptions = type EmailOptions =
{ /// The SMTP client { /// The SMTP client
Client : SmtpClient Client: SmtpClient
/// The people who should receive the e-mail /// The people who should receive the e-mail
Recipients : Member list Recipients: Member list
/// The small group for which this e-mail is being sent /// The small group for which this e-mail is being sent
Group : SmallGroup Group: SmallGroup
/// The subject of the e-mail /// The subject of the e-mail
Subject : string Subject: string
/// The body of the e-mail in HTML /// The body of the e-mail in HTML
HtmlBody : string HtmlBody: string
/// The body of the e-mail in plain text /// The body of the e-mail in plain text
PlainTextBody : string PlainTextBody: string
/// Use the current user's preferred language /// Use the current user's preferred language
Strings : IStringLocalizer Strings: IStringLocalizer }
}
/// The e-mail address from which e-mail is sent /// Options to use when sending e-mail
let private fromAddress = "prayer@bitbadger.solutions" 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 () = task {
let client = new SmtpClient () let client = new SmtpClient()
do! client.ConnectAsync ("127.0.0.1", 25, SecureSocketOptions.None) do! client.ConnectAsync(smtpOptions.SmtpHost, smtpOptions.Port, smtpOptions.UseSsl)
do! client.AuthenticateAsync(smtpOptions.FromAddress, smtpOptions.Authentication)
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 opts = let createMessage opts =
let msg = new MimeMessage () let msg = new MimeMessage()
msg.From.Add (MailboxAddress (opts.Group.Preferences.EmailFromName, fromAddress)) msg.From.Add(MailboxAddress(opts.Group.Preferences.EmailFromName, smtpOptions.FromAddress))
msg.Subject <- opts.Subject msg.Subject <- opts.Subject
msg.ReplyTo.Add (MailboxAddress (opts.Group.Preferences.EmailFromName, opts.Group.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 opts = 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>"""
opts.HtmlBody 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;">"""
opts.Strings["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>"
opts.Strings["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 opts
msg.Body <- new TextPart (TextFormat.Html, Text = bodyText) msg.Body <- new 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 opts = let createTextMessage opts =
let bodyText = let bodyText =
[ opts.PlainTextBody [ opts.PlainTextBody
"\n\n--\n" "\n\n--\n"
opts.Strings["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"
opts.Strings["from Bit Badger Solutions"].Value opts.Strings["from Bit Badger Solutions"].Value ]
]
|> String.concat "" |> String.concat ""
let msg = createMessage opts let msg = createMessage opts
msg.Body <- new TextPart (TextFormat.Plain, Text = bodyText) msg.Body <- new TextPart(TextFormat.Plain, Text = bodyText)
msg msg
/// Send e-mails to a class /// Send e-mails to a class
@ -87,14 +102,14 @@ let sendEmails opts = task {
use plainTextMsg = createTextMessage opts use plainTextMsg = createTextMessage opts
for mbr in opts.Recipients do for mbr in opts.Recipients do
let emailTo = MailboxAddress (mbr.Name, mbr.Email) let emailTo = MailboxAddress(mbr.Name, mbr.Email)
match defaultArg mbr.Format opts.Group.Preferences.DefaultEmailType with match defaultArg mbr.Format opts.Group.Preferences.DefaultEmailType with
| HtmlFormat -> | HtmlFormat ->
htmlMsg.To.Add emailTo htmlMsg.To.Add emailTo
let! _ = opts.Client.SendAsync htmlMsg let! _ = opts.Client.SendAsync htmlMsg
htmlMsg.To.Clear () htmlMsg.To.Clear()
| PlainTextFormat -> | PlainTextFormat ->
plainTextMsg.To.Add emailTo plainTextMsg.To.Add emailTo
let! _ = opts.Client.SendAsync plainTextMsg let! _ = opts.Client.SendAsync plainTextMsg
plainTextMsg.To.Clear () plainTextMsg.To.Clear()
} }

View File

@ -16,19 +16,19 @@ let private jsonSettings = JsonSerializerSettings().ConfigureForNodaTime DateTim
type ISession with type ISession with
/// Set an object in the session /// Set an object in the session
member this.SetObject<'T> key (value : 'T) = member this.SetObject<'T> key (value: 'T) =
this.SetString (key, JsonConvert.SerializeObject (value, jsonSettings)) this.SetString(key, JsonConvert.SerializeObject(value, jsonSettings))
/// Get an object from the session /// Get an object from the session
member this.TryGetObject<'T> key = member this.TryGetObject<'T> key =
match this.GetString key with match this.GetString key with
| null -> None | null -> None
| v -> Some (JsonConvert.DeserializeObject<'T> (v, jsonSettings)) | v -> Some (JsonConvert.DeserializeObject<'T>(v, jsonSettings))
/// The currently logged on small group /// The currently logged on small group
member this.CurrentGroup member this.CurrentGroup
with get () = this.TryGetObject<SmallGroup> Key.Session.currentGroup with get () = this.TryGetObject<SmallGroup> Key.Session.currentGroup
and set (v : SmallGroup option) = and set (v: SmallGroup option) =
match v with match v with
| Some group -> this.SetObject Key.Session.currentGroup group | Some group -> this.SetObject Key.Session.currentGroup group
| None -> this.Remove Key.Session.currentGroup | None -> this.Remove Key.Session.currentGroup
@ -36,7 +36,7 @@ type ISession with
/// The currently logged on user /// The currently logged on user
member this.CurrentUser member this.CurrentUser
with get () = this.TryGetObject<User> Key.Session.currentUser with get () = this.TryGetObject<User> Key.Session.currentUser
and set (v : User option) = and set (v: User option) =
match v with match v with
| Some user -> this.SetObject Key.Session.currentUser { user with PasswordHash = "" } | Some user -> this.SetObject Key.Session.currentUser { user with PasswordHash = "" }
| None -> this.Remove Key.Session.currentUser | None -> this.Remove Key.Session.currentUser
@ -46,7 +46,7 @@ type ISession with
with get () = with get () =
this.TryGetObject<UserMessage list> Key.Session.userMessages this.TryGetObject<UserMessage list> Key.Session.userMessages
|> Option.defaultValue List.empty<UserMessage> |> Option.defaultValue List.empty<UserMessage>
and set (v : UserMessage list) = this.SetObject Key.Session.userMessages v and set (v: UserMessage list) = this.SetObject Key.Session.userMessages v
open System.Security.Claims open System.Security.Claims
@ -74,16 +74,13 @@ open Npgsql
type HttpContext with type HttpContext with
/// The system clock (via DI) /// The system clock (via DI)
member this.Clock = this.GetService<IClock> () member this.Clock = this.GetService<IClock>()
/// The PostgreSQL connection (configured via DI)
member this.Conn = this.GetService<NpgsqlConnection> ()
/// The current instant /// The current instant
member this.Now = this.Clock.GetCurrentInstant () member this.Now = this.Clock.GetCurrentInstant()
/// The common string localizer /// The common string localizer
member this.Strings = Views.I18N.localizer.Force () member _.Strings = Views.I18N.localizer.Force()
/// The currently logged on small group (sets the value in the session if it is missing) /// The currently logged on small group (sets the value in the session if it is missing)
member this.CurrentGroup () = task { member this.CurrentGroup () = task {
@ -92,7 +89,7 @@ type HttpContext with
| None -> | None ->
match this.User.SmallGroupId with match this.User.SmallGroupId with
| Some groupId -> | Some groupId ->
match! SmallGroups.tryByIdWithPreferences groupId this.Conn with match! SmallGroups.tryByIdWithPreferences groupId with
| Some group -> | Some group ->
this.Session.CurrentGroup <- Some group this.Session.CurrentGroup <- Some group
return Some group return Some group
@ -107,10 +104,10 @@ type HttpContext with
| None -> | None ->
match this.User.UserId with match this.User.UserId with
| Some userId -> | Some userId ->
match! Users.tryById userId this.Conn with match! Users.tryById userId with
| Some user -> | Some user ->
// Set last seen for user // Set last seen for user
do! Users.updateLastSeen userId this.Now this.Conn do! Users.updateLastSeen userId this.Now
this.Session.CurrentUser <- Some user this.Session.CurrentUser <- Some user
return 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

@ -7,19 +7,19 @@ open Microsoft.AspNetCore.Http
open Microsoft.AspNetCore.Localization open Microsoft.AspNetCore.Localization
open PrayerTracker open PrayerTracker
/// GET /error/[error-code] // GET /error/[error-code]
let error code : HttpHandler = requireAccess [ AccessLevel.Public ] >=> fun next ctx -> let error code : HttpHandler = requireAccess [ AccessLevel.Public ] >=> fun next ctx ->
viewInfo ctx viewInfo ctx
|> 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 = requireAccess [ AccessLevel.Public ] >=> fun next ctx ->
viewInfo ctx viewInfo ctx
|> 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
@ -27,28 +27,28 @@ let language culture : HttpHandler = requireAccess [ AccessLevel.Public ] >=> fu
| "" | ""
| "en" -> "en-US" | "en" -> "en-US"
| "es" -> "es-MX" | "es" -> "es-MX"
| _ -> $"{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 | "" -> "/" | 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 = requireAccess [ AccessLevel.Public ] >=> fun next ctx ->
viewInfo ctx viewInfo ctx
|> 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 = requireAccess [ AccessLevel.Public ] >=> fun next ctx ->
viewInfo ctx viewInfo ctx
|> Views.Home.termsOfService |> Views.Home.termsOfService
@ -57,15 +57,15 @@ let tos : HttpHandler = requireAccess [ AccessLevel.Public ] >=> fun next ctx ->
open Microsoft.AspNetCore.Authentication open Microsoft.AspNetCore.Authentication
open Microsoft.AspNetCore.Authentication.Cookies open Microsoft.AspNetCore.Authentication.Cookies
/// GET /log-off // GET /log-off
let logOff : HttpHandler = requireAccess [ AccessLevel.Public ] >=> fun next ctx -> task { let logOff : HttpHandler = requireAccess [ AccessLevel.Public ] >=> fun next ctx -> task {
ctx.Session.Clear () ctx.Session.Clear()
do! ctx.SignOutAsync CookieAuthenticationDefaults.AuthenticationScheme do! ctx.SignOutAsync CookieAuthenticationDefaults.AuthenticationScheme
addHtmlInfo ctx ctx.Strings["Log Off Successful Have a nice day!"] addHtmlInfo ctx ctx.Strings["Log Off Successful Have a nice day!"]
return! redirectTo false "/" next ctx return! redirectTo false "/" next ctx
} }
/// GET /unauthorized // GET /unauthorized
let unauthorized : HttpHandler = requireAccess [ AccessLevel.Public ] >=> fun next ctx -> let unauthorized : HttpHandler = requireAccess [ AccessLevel.Public ] >=> fun next ctx ->
viewInfo ctx viewInfo ctx
|> Views.Home.unauthorized |> Views.Home.unauthorized

View File

@ -8,8 +8,8 @@ open PrayerTracker.Entities
open PrayerTracker.ViewModels open PrayerTracker.ViewModels
/// 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 = task { let private findRequest (ctx: HttpContext) reqId = task {
match! PrayerRequests.tryById reqId ctx.Conn with match! PrayerRequests.tryById reqId with
| Some req when req.SmallGroupId = ctx.Session.CurrentGroup.Value.Id -> return Ok req | Some req when req.SmallGroupId = ctx.Session.CurrentGroup.Value.Id -> return Ok req
| Some _ -> | Some _ ->
addError ctx ctx.Strings["The prayer request you tried to access is not assigned to your group"] addError ctx ctx.Strings["The prayer request you tried to access is not assigned to your group"]
@ -18,38 +18,36 @@ let private findRequest (ctx : HttpContext) reqId = task {
} }
/// Generate a list of requests for the given date /// Generate a list of requests for the given date
let private generateRequestList (ctx : HttpContext) date = task { let private generateRequestList (ctx: HttpContext) date = task {
let group = ctx.Session.CurrentGroup.Value let group = ctx.Session.CurrentGroup.Value
let listDate = match date with Some d -> d | None -> SmallGroup.localDateNow ctx.Clock group let listDate = match date with Some d -> d | None -> SmallGroup.localDateNow ctx.Clock group
let! reqs = let! reqs =
PrayerRequests.forGroup PrayerRequests.forGroup
{ SmallGroup = group { SmallGroup = group
Clock = ctx.Clock Clock = ctx.Clock
ListDate = Some listDate ListDate = Some listDate
ActiveOnly = true ActiveOnly = true
PageNumber = 0 PageNumber = 0 }
} ctx.Conn
return return
{ Requests = reqs { Requests = reqs
Date = listDate Date = listDate
SmallGroup = group SmallGroup = group
ShowHeader = true ShowHeader = true
CanEmail = Option.isSome ctx.User.UserId CanEmail = Option.isSome ctx.User.UserId
Recipients = [] Recipients = [] }
}
} }
open NodaTime.Text 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 LocalDatePattern.Iso.Parse dt with it when it.Success -> Some it.Value | _ -> None | Some dt -> match LocalDatePattern.Iso.Parse dt with it when it.Success -> Some it.Value | _ -> None
| None -> None | None -> None
open System open System
/// GET /prayer-request/[request-id]/edit // GET /prayer-request/[request-id]/edit
let edit reqId : HttpHandler = requireAccess [ User ] >=> fun next ctx -> task { let edit reqId : HttpHandler = requireAccess [ User ] >=> fun next ctx -> task {
let group = ctx.Session.CurrentGroup.Value let group = ctx.Session.CurrentGroup.Value
let now = SmallGroup.localDateNow ctx.Clock group let now = SmallGroup.localDateNow ctx.Clock group
@ -57,7 +55,7 @@ let edit reqId : HttpHandler = requireAccess [ User ] >=> fun next ctx -> task {
if requestId.Value = Guid.Empty then if requestId.Value = Guid.Empty then
return! return!
{ viewInfo ctx with HelpLink = Some Help.editRequest } { viewInfo ctx with HelpLink = Some Help.editRequest }
|> Views.PrayerRequest.edit EditRequest.empty (now.ToString ("R", null)) ctx |> Views.PrayerRequest.edit EditRequest.empty (now.ToString("R", null)) ctx
|> renderHtml next ctx |> renderHtml next ctx
else else
match! findRequest ctx requestId with match! findRequest ctx requestId with
@ -79,73 +77,73 @@ let edit reqId : HttpHandler = requireAccess [ User ] >=> fun next ctx -> task {
| Result.Error e -> return! e | Result.Error e -> return! e
} }
/// GET /prayer-requests/email/[date] open Microsoft.Extensions.Configuration
// GET /prayer-requests/email/[date]
let email date : HttpHandler = requireAccess [ User ] >=> fun next ctx -> task { let email date : HttpHandler = requireAccess [ User ] >=> fun next ctx -> task {
let s = ctx.Strings let s = ctx.Strings
let listDate = parseListDate (Some date) let listDate = parseListDate (Some date)
let! list = generateRequestList ctx listDate let! list = generateRequestList ctx listDate
let group = ctx.Session.CurrentGroup.Value let group = ctx.Session.CurrentGroup.Value
let! recipients = Members.forGroup group.Id ctx.Conn let! recipients = Members.forGroup group.Id
use! client = Email.getConnection () use! client = Email.getConnection ()
do! Email.sendEmails do! Email.sendEmails
{ Client = client { Client = client
Recipients = recipients Recipients = recipients
Group = group Group = group
Subject = s["Prayer Requests for {0} - {1:MMMM d, yyyy}", group.Name, list.Date].Value Subject = s["Prayer Requests for {0} - {1:MMMM d, yyyy}", group.Name, list.Date].Value
HtmlBody = list.AsHtml s HtmlBody = list.AsHtml s
PlainTextBody = list.AsText s PlainTextBody = list.AsText s
Strings = s Strings = s }
} do! client.DisconnectAsync true
return! return!
viewInfo ctx viewInfo ctx
|> Views.PrayerRequest.email { list with Recipients = recipients } |> Views.PrayerRequest.email { list with Recipients = recipients }
|> renderHtml next ctx |> renderHtml next ctx
} }
/// POST /prayer-request/[request-id]/delete // POST /prayer-request/[request-id]/delete
let delete reqId : HttpHandler = requireAccess [ User ] >=> validateCsrf >=> fun next ctx -> task { let delete reqId : HttpHandler = requireAccess [ User ] >=> validateCsrf >=> fun next ctx -> task {
let requestId = PrayerRequestId reqId let requestId = PrayerRequestId reqId
match! findRequest ctx requestId with match! findRequest ctx requestId with
| Ok req -> | Ok req ->
do! PrayerRequests.deleteById req.Id ctx.Conn do! PrayerRequests.deleteById req.Id
addInfo ctx ctx.Strings["The prayer request was deleted successfully"] addInfo ctx ctx.Strings["The prayer request was deleted successfully"]
return! redirectTo false "/prayer-requests" next ctx return! redirectTo false "/prayer-requests" next ctx
| Result.Error e -> return! e | Result.Error e -> return! e
} }
/// GET /prayer-request/[request-id]/expire // GET /prayer-request/[request-id]/expire
let expire reqId : HttpHandler = requireAccess [ User ] >=> fun next ctx -> task { let expire reqId : HttpHandler = requireAccess [ User ] >=> fun next ctx -> task {
let requestId = PrayerRequestId reqId let requestId = PrayerRequestId reqId
match! findRequest ctx requestId with match! findRequest ctx requestId with
| Ok req -> | Ok req ->
do! PrayerRequests.updateExpiration { req with Expiration = Forced } false ctx.Conn do! PrayerRequests.updateExpiration { req with Expiration = Forced } false
addInfo ctx ctx.Strings["Successfully {0} prayer request", ctx.Strings["Expired"].Value.ToLower ()] addInfo ctx ctx.Strings["Successfully {0} prayer request", ctx.Strings["Expired"].Value.ToLower()]
return! redirectTo false "/prayer-requests" next ctx return! redirectTo false "/prayer-requests" next ctx
| Result.Error e -> return! e | Result.Error e -> return! e
} }
/// GET /prayer-requests/[group-id]/list // GET /prayer-requests/[group-id]/list
let list groupId : HttpHandler = requireAccess [ AccessLevel.Public ] >=> fun next ctx -> task { let list groupId : HttpHandler = requireAccess [ AccessLevel.Public ] >=> fun next ctx -> task {
match! SmallGroups.tryByIdWithPreferences (SmallGroupId groupId) ctx.Conn with match! SmallGroups.tryByIdWithPreferences (SmallGroupId groupId) with
| Some group when group.Preferences.IsPublic -> | Some group when group.Preferences.IsPublic ->
let! reqs = let! reqs =
PrayerRequests.forGroup PrayerRequests.forGroup
{ SmallGroup = group { SmallGroup = group
Clock = ctx.Clock Clock = ctx.Clock
ListDate = None ListDate = None
ActiveOnly = true ActiveOnly = true
PageNumber = 0 PageNumber = 0 }
} ctx.Conn
return! return!
viewInfo ctx viewInfo ctx
|> Views.PrayerRequest.list |> Views.PrayerRequest.list
{ Requests = reqs { Requests = reqs
Date = SmallGroup.localDateNow ctx.Clock group Date = SmallGroup.localDateNow ctx.Clock group
SmallGroup = group SmallGroup = group
ShowHeader = true ShowHeader = true
CanEmail = Option.isSome ctx.User.UserId CanEmail = Option.isSome ctx.User.UserId
Recipients = [] Recipients = [] }
}
|> renderHtml next ctx |> renderHtml next ctx
| Some _ -> | Some _ ->
addError ctx ctx.Strings["The request list for the group you tried to view is not public."] addError ctx ctx.Strings["The request list for the group you tried to view is not public."]
@ -153,18 +151,18 @@ let list groupId : HttpHandler = requireAccess [ AccessLevel.Public ] >=> fun ne
| None -> return! fourOhFour ctx | None -> return! fourOhFour ctx
} }
/// GET /prayer-requests/lists // GET /prayer-requests/lists
let lists : HttpHandler = requireAccess [ AccessLevel.Public ] >=> fun next ctx -> task { let lists : HttpHandler = requireAccess [ AccessLevel.Public ] >=> fun next ctx -> task {
let! groups = SmallGroups.listPublicAndProtected ctx.Conn let! groups = SmallGroups.listPublicAndProtected ()
return! return!
viewInfo ctx viewInfo ctx
|> Views.PrayerRequest.lists groups |> Views.PrayerRequest.lists groups
|> 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 = requireAccess [ User ] >=> fun next ctx -> task {
let group = ctx.Session.CurrentGroup.Value let group = ctx.Session.CurrentGroup.Value
let pageNbr = let pageNbr =
@ -174,28 +172,25 @@ let maintain onlyActive : HttpHandler = requireAccess [ User ] >=> fun next ctx
let! model = backgroundTask { let! model = backgroundTask {
match ctx.GetQueryStringValue "search" with match ctx.GetQueryStringValue "search" with
| Ok search -> | Ok search ->
let! reqs = PrayerRequests.searchForGroup group search pageNbr ctx.Conn let! reqs = PrayerRequests.searchForGroup group search pageNbr
return return
{ MaintainRequests.empty with { MaintainRequests.empty with
Requests = reqs Requests = reqs
SearchTerm = Some search SearchTerm = Some search
PageNbr = Some pageNbr PageNbr = Some pageNbr }
}
| Result.Error _ -> | Result.Error _ ->
let! reqs = let! reqs =
PrayerRequests.forGroup PrayerRequests.forGroup
{ SmallGroup = group { SmallGroup = group
Clock = ctx.Clock Clock = ctx.Clock
ListDate = None ListDate = None
ActiveOnly = onlyActive ActiveOnly = onlyActive
PageNumber = pageNbr PageNumber = pageNbr }
} ctx.Conn
return return
{ MaintainRequests.empty with { MaintainRequests.empty with
Requests = reqs Requests = reqs
OnlyActive = Some onlyActive OnlyActive = Some onlyActive
PageNbr = if onlyActive then None else Some pageNbr PageNbr = if onlyActive then None else Some pageNbr }
}
} }
return! return!
{ viewInfo ctx with HelpLink = Some Help.maintainRequests } { viewInfo ctx with HelpLink = Some Help.maintainRequests }
@ -203,7 +198,7 @@ let maintain onlyActive : HttpHandler = requireAccess [ User ] >=> fun next 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 = requireAccess [ User; Group ] >=> fun next ctx -> task {
let! list = generateRequestList ctx (parseListDate (Some date)) let! list = generateRequestList ctx (parseListDate (Some date))
return! return!
@ -211,12 +206,12 @@ let print date : HttpHandler = requireAccess [ User; Group ] >=> fun next ctx ->
|> renderHtml next ctx |> renderHtml next ctx
} }
/// GET /prayer-request/[request-id]/restore // GET /prayer-request/[request-id]/restore
let restore reqId : HttpHandler = requireAccess [ User ] >=> fun next ctx -> task { let restore reqId : HttpHandler = requireAccess [ User ] >=> fun next ctx -> task {
let requestId = PrayerRequestId reqId let requestId = PrayerRequestId reqId
match! findRequest ctx requestId with match! findRequest ctx requestId with
| Ok req -> | Ok req ->
do! PrayerRequests.updateExpiration { req with Expiration = Automatic; UpdatedDate = ctx.Now } true ctx.Conn do! PrayerRequests.updateExpiration { req with Expiration = Automatic; UpdatedDate = ctx.Now } true
addInfo ctx ctx.Strings["Successfully {0} prayer request", ctx.Strings["Restored"].Value.ToLower ()] addInfo ctx ctx.Strings["Successfully {0} prayer request", ctx.Strings["Restored"].Value.ToLower ()]
return! redirectTo false "/prayer-requests" next ctx return! redirectTo false "/prayer-requests" next ctx
| Result.Error e -> return! e | Result.Error e -> return! e
@ -224,9 +219,9 @@ let restore reqId : HttpHandler = requireAccess [ User ] >=> fun next ctx -> tas
open System.Threading.Tasks open System.Threading.Tasks
/// POST /prayer-request/save // POST /prayer-request/save
let save : HttpHandler = requireAccess [ User ] >=> validateCsrf >=> fun next ctx -> task { let save : HttpHandler = requireAccess [ User ] >=> validateCsrf >=> fun next ctx -> task {
match! ctx.TryBindFormAsync<EditRequest> () with match! ctx.TryBindFormAsync<EditRequest>() with
| Ok model -> | Ok model ->
let group = ctx.Session.CurrentGroup.Value let group = ctx.Session.CurrentGroup.Value
let! req = let! req =
@ -237,14 +232,14 @@ let save : HttpHandler = requireAccess [ User ] >=> validateCsrf >=> fun next ct
UserId = ctx.User.UserId.Value UserId = ctx.User.UserId.Value
} }
|> (Some >> Task.FromResult) |> (Some >> Task.FromResult)
else PrayerRequests.tryById (idFromShort PrayerRequestId model.RequestId) ctx.Conn else PrayerRequests.tryById (idFromShort PrayerRequestId model.RequestId)
match req with match req with
| Some pr when pr.SmallGroupId = group.Id -> | Some pr when pr.SmallGroupId = group.Id ->
let now = SmallGroup.localDateNow ctx.Clock group let now = SmallGroup.localDateNow ctx.Clock group
let updated = let updated =
{ pr with { pr with
RequestType = PrayerRequestType.fromCode model.RequestType RequestType = PrayerRequestType.fromCode model.RequestType
Requestor = match model.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 model.Text Text = ckEditorToText model.Text
Expiration = Expiration.fromCode model.Expiration Expiration = Expiration.fromCode model.Expiration
} }
@ -257,16 +252,16 @@ let save : HttpHandler = requireAccess [ User ] >=> validateCsrf >=> fun next ct
{ it with EnteredDate = dt; UpdatedDate = dt } { it with EnteredDate = dt; UpdatedDate = dt }
| it when defaultArg model.SkipDateUpdate false -> it | it when defaultArg model.SkipDateUpdate false -> it
| it -> { it with UpdatedDate = ctx.Now } | it -> { it with UpdatedDate = ctx.Now }
do! PrayerRequests.save updated ctx.Conn do! PrayerRequests.save updated
let act = if model.IsNew then "Added" else "Updated" let act = if model.IsNew then "Added" else "Updated"
addInfo ctx ctx.Strings["Successfully {0} prayer request", ctx.Strings[act].Value.ToLower ()] addInfo ctx ctx.Strings["Successfully {0} prayer request", ctx.Strings[act].Value.ToLower()]
return! redirectTo false "/prayer-requests" next ctx return! redirectTo false "/prayer-requests" next ctx
| Some _ | Some _
| None -> return! fourOhFour ctx | None -> return! fourOhFour ctx
| Result.Error e -> return! bindError e next ctx | Result.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 = requireAccess [ User; Group ] >=> fun next ctx -> task {
let! list = generateRequestList ctx (parseListDate date) let! list = generateRequestList ctx (parseListDate date)
return! return!

View File

@ -2,7 +2,7 @@
<PropertyGroup> <PropertyGroup>
<OutputType>Exe</OutputType> <OutputType>Exe</OutputType>
<PublishSingleFile>True</PublishSingleFile> <PublishSingleFile>False</PublishSingleFile>
<SelfContained>False</SelfContained> <SelfContained>False</SelfContained>
</PropertyGroup> </PropertyGroup>
@ -16,6 +16,7 @@
<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" />
@ -24,10 +25,10 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Giraffe" Version="6.0.0" /> <PackageReference Include="BitBadger.AspNetCore.CanonicalDomains" Version="1.0.0" />
<PackageReference Include="Giraffe.Htmx" Version="1.8.0" /> <PackageReference Include="Giraffe.Htmx" Version="2.0.0" />
<PackageReference Include="NodaTime.Serialization.JsonNet" Version="3.0.0" /> <PackageReference Include="NodaTime.Serialization.JsonNet" Version="3.1.0" />
<PackageReference Update="FSharp.Core" Version="6.0.5" /> <PackageReference Update="FSharp.Core" Version="8.0.300" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View File

@ -7,21 +7,20 @@ open PrayerTracker.Data
open PrayerTracker.Entities open PrayerTracker.Entities
open PrayerTracker.ViewModels open PrayerTracker.ViewModels
/// GET /small-group/announcement // GET /small-group/announcement
let announcement : HttpHandler = requireAccess [ User ] >=> fun next ctx -> let announcement : HttpHandler = requireAccess [ User ] >=> fun next ctx ->
{ viewInfo ctx with HelpLink = Some Help.sendAnnouncement } { viewInfo ctx with HelpLink = Some Help.sendAnnouncement }
|> Views.SmallGroup.announcement ctx.Session.CurrentUser.Value.IsAdmin ctx |> Views.SmallGroup.announcement ctx.Session.CurrentUser.Value.IsAdmin ctx
|> renderHtml next ctx |> renderHtml next ctx
/// POST /small-group/[group-id]/delete // POST /small-group/[group-id]/delete
let delete grpId : HttpHandler = requireAccess [ Admin ] >=> validateCsrf >=> fun next ctx -> task { let delete grpId : HttpHandler = requireAccess [ Admin ] >=> validateCsrf >=> fun next ctx -> task {
let groupId = SmallGroupId grpId let groupId = SmallGroupId grpId
let conn = ctx.Conn match! SmallGroups.tryById groupId with
match! SmallGroups.tryById groupId conn with
| Some grp -> | Some grp ->
let! reqs = PrayerRequests.countByGroup groupId conn let! reqs = PrayerRequests.countByGroup groupId
let! users = Users.countByGroup groupId conn let! users = Users.countByGroup groupId
do! SmallGroups.deleteById groupId conn do! SmallGroups.deleteById groupId
addInfo ctx addInfo ctx
ctx.Strings["The group “{0}” and its {1} prayer request(s) were deleted successfully; revoked access from {2} user(s)", ctx.Strings["The group “{0}” and its {1} prayer request(s) were deleted successfully; revoked access from {2} user(s)",
grp.Name, reqs, users] grp.Name, reqs, users]
@ -29,22 +28,22 @@ let delete grpId : HttpHandler = requireAccess [ Admin ] >=> validateCsrf >=> fu
| None -> return! fourOhFour ctx | None -> return! fourOhFour ctx
} }
/// POST /small-group/member/[member-id]/delete // POST /small-group/member/[member-id]/delete
let deleteMember mbrId : HttpHandler = requireAccess [ User ] >=> validateCsrf >=> fun next ctx -> task { let deleteMember mbrId : HttpHandler = requireAccess [ User ] >=> validateCsrf >=> fun next ctx -> task {
let group = ctx.Session.CurrentGroup.Value let group = ctx.Session.CurrentGroup.Value
let memberId = MemberId mbrId let memberId = MemberId mbrId
match! Members.tryById memberId ctx.Conn with match! Members.tryById memberId with
| Some mbr when mbr.SmallGroupId = group.Id -> | Some mbr when mbr.SmallGroupId = group.Id ->
do! Members.deleteById memberId ctx.Conn do! Members.deleteById memberId
addHtmlInfo ctx ctx.Strings["The group member &ldquo;{0}&rdquo; was deleted successfully", mbr.Name] addHtmlInfo ctx ctx.Strings["The group member &ldquo;{0}&rdquo; was deleted successfully", mbr.Name]
return! redirectTo false "/small-group/members" next ctx return! redirectTo false "/small-group/members" next ctx
| Some _ | Some _
| None -> return! fourOhFour ctx | None -> return! fourOhFour ctx
} }
/// GET /small-group/[group-id]/edit // GET /small-group/[group-id]/edit
let edit grpId : HttpHandler = requireAccess [ Admin ] >=> fun next ctx -> task { let edit grpId : HttpHandler = requireAccess [ Admin ] >=> fun next ctx -> task {
let! churches = Churches.all ctx.Conn let! churches = Churches.all ()
let groupId = SmallGroupId grpId let groupId = SmallGroupId grpId
if groupId.Value = Guid.Empty then if groupId.Value = Guid.Empty then
return! return!
@ -52,7 +51,7 @@ let edit grpId : HttpHandler = requireAccess [ Admin ] >=> fun next ctx -> task
|> Views.SmallGroup.edit EditSmallGroup.empty churches ctx |> Views.SmallGroup.edit EditSmallGroup.empty churches ctx
|> renderHtml next ctx |> renderHtml next ctx
else else
match! SmallGroups.tryById groupId ctx.Conn with match! SmallGroups.tryById groupId with
| Some grp -> | Some grp ->
return! return!
viewInfo ctx viewInfo ctx
@ -61,7 +60,7 @@ let edit grpId : HttpHandler = requireAccess [ Admin ] >=> fun next ctx -> task
| None -> return! fourOhFour 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 mbrId : HttpHandler = requireAccess [ User ] >=> fun next ctx -> task {
let group = ctx.Session.CurrentGroup.Value let group = ctx.Session.CurrentGroup.Value
let types = ReferenceList.emailTypeList group.Preferences.DefaultEmailType ctx.Strings let types = ReferenceList.emailTypeList group.Preferences.DefaultEmailType ctx.Strings
@ -72,7 +71,7 @@ let editMember mbrId : HttpHandler = requireAccess [ User ] >=> fun next ctx ->
|> Views.SmallGroup.editMember EditMember.empty types ctx |> Views.SmallGroup.editMember EditMember.empty types ctx
|> renderHtml next ctx |> renderHtml next ctx
else else
match! Members.tryById memberId ctx.Conn with match! Members.tryById memberId with
| Some mbr when mbr.SmallGroupId = group.Id -> | Some mbr when mbr.SmallGroupId = group.Id ->
return! return!
viewInfo ctx viewInfo ctx
@ -82,9 +81,9 @@ let editMember mbrId : HttpHandler = requireAccess [ User ] >=> fun next ctx ->
| None -> return! fourOhFour 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 grpId : HttpHandler = requireAccess [ AccessLevel.Public ] >=> fun next ctx -> task {
let! groups = SmallGroups.listProtected ctx.Conn let! groups = SmallGroups.listProtected ()
let groupId = match grpId with Some gid -> shortGuid gid | None -> "" let groupId = match grpId with Some gid -> shortGuid gid | None -> ""
return! return!
{ viewInfo ctx with HelpLink = Some Help.logOn } { viewInfo ctx with HelpLink = Some Help.logOn }
@ -96,19 +95,19 @@ open System.Security.Claims
open Microsoft.AspNetCore.Authentication open Microsoft.AspNetCore.Authentication
open Microsoft.AspNetCore.Authentication.Cookies open Microsoft.AspNetCore.Authentication.Cookies
/// POST /small-group/log-on/submit // POST /small-group/log-on/submit
let logOnSubmit : HttpHandler = requireAccess [ AccessLevel.Public ] >=> validateCsrf >=> fun next ctx -> task { let logOnSubmit : HttpHandler = requireAccess [ AccessLevel.Public ] >=> validateCsrf >=> fun next ctx -> task {
match! ctx.TryBindFormAsync<GroupLogOn> () with match! ctx.TryBindFormAsync<GroupLogOn>() with
| Ok model -> | Ok model ->
match! SmallGroups.logOn (idFromShort SmallGroupId model.SmallGroupId) model.Password ctx.Conn with match! SmallGroups.logOn (idFromShort SmallGroupId model.SmallGroupId) model.Password with
| Some group -> | Some group ->
ctx.Session.CurrentGroup <- Some group ctx.Session.CurrentGroup <- Some group
let identity = ClaimsIdentity ( let identity = ClaimsIdentity(
Seq.singleton (Claim (ClaimTypes.GroupSid, shortGuid group.Id.Value)), Seq.singleton (Claim(ClaimTypes.GroupSid, shortGuid group.Id.Value)),
CookieAuthenticationDefaults.AuthenticationScheme) CookieAuthenticationDefaults.AuthenticationScheme)
do! ctx.SignInAsync ( do! ctx.SignInAsync(
identity.AuthenticationType, ClaimsPrincipal identity, identity.AuthenticationType, ClaimsPrincipal identity,
AuthenticationProperties ( AuthenticationProperties(
IssuedUtc = DateTimeOffset.UtcNow, IssuedUtc = DateTimeOffset.UtcNow,
IsPersistent = defaultArg model.RememberMe false)) IsPersistent = defaultArg model.RememberMe false))
addInfo ctx ctx.Strings["Log On Successful Welcome to {0}", ctx.Strings["PrayerTracker"]] addInfo ctx ctx.Strings["Log On Successful Welcome to {0}", ctx.Strings["PrayerTracker"]]
@ -119,19 +118,19 @@ let logOnSubmit : HttpHandler = requireAccess [ AccessLevel.Public ] >=> validat
| Result.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 = requireAccess [ Admin ] >=> fun next ctx -> task {
let! groups = SmallGroups.infoForAll ctx.Conn let! groups = SmallGroups.infoForAll ()
return! return!
viewInfo ctx viewInfo ctx
|> Views.SmallGroup.maintain groups ctx |> Views.SmallGroup.maintain groups 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 = requireAccess [ User ] >=> fun next ctx -> task {
let group = ctx.Session.CurrentGroup.Value let group = ctx.Session.CurrentGroup.Value
let! members = Members.forGroup group.Id ctx.Conn let! members = Members.forGroup group.Id
let types = ReferenceList.emailTypeList group.Preferences.DefaultEmailType ctx.Strings |> Map.ofSeq let types = ReferenceList.emailTypeList group.Preferences.DefaultEmailType ctx.Strings |> Map.ofSeq
return! return!
{ viewInfo ctx with HelpLink = Some Help.maintainGroupMembers } { viewInfo ctx with HelpLink = Some Help.maintainGroupMembers }
@ -139,41 +138,37 @@ let members : HttpHandler = requireAccess [ User ] >=> fun next ctx -> task {
|> renderHtml next ctx |> renderHtml next ctx
} }
/// GET /small-group // GET /small-group
let overview : HttpHandler = requireAccess [ User ] >=> fun next ctx -> task { let overview : HttpHandler = requireAccess [ User ] >=> fun next ctx -> task {
let group = ctx.Session.CurrentGroup.Value let group = ctx.Session.CurrentGroup.Value
let conn = ctx.Conn
let! reqs = PrayerRequests.forGroup let! reqs = PrayerRequests.forGroup
{ SmallGroup = group { SmallGroup = group
Clock = ctx.Clock Clock = ctx.Clock
ListDate = None ListDate = None
ActiveOnly = true ActiveOnly = true
PageNumber = 0 PageNumber = 0 }
} conn let! reqCount = PrayerRequests.countByGroup group.Id
let! reqCount = PrayerRequests.countByGroup group.Id conn let! mbrCount = Members.countByGroup group.Id
let! mbrCount = Members.countByGroup group.Id conn let! admins = Users.listByGroupId group.Id
let! admins = Users.listByGroupId group.Id conn
let model = let model =
{ TotalActiveReqs = List.length reqs { TotalActiveReqs = List.length reqs
AllReqs = reqCount AllReqs = reqCount
TotalMembers = mbrCount TotalMembers = mbrCount
ActiveReqsByType = ( 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 -> |> Seq.map (fun reqType -> reqType, reqs |> List.filter (fun r -> r.RequestType = reqType) |> List.length)
reqType, reqs |> List.filter (fun r -> r.RequestType = reqType) |> List.length) |> Map.ofSeq)
|> Map.ofSeq) Admins = admins }
Admins = admins
}
return! return!
viewInfo ctx viewInfo ctx
|> Views.SmallGroup.overview model |> 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 = requireAccess [ User ] >=> fun next ctx -> task {
return! return!
{ viewInfo ctx with HelpLink = Some Help.groupPreferences } { viewInfo ctx with HelpLink = Some Help.groupPreferences }
@ -183,41 +178,40 @@ let preferences : HttpHandler = requireAccess [ User ] >=> fun next ctx -> task
open System.Threading.Tasks open System.Threading.Tasks
/// POST /small-group/save // POST /small-group/save
let save : HttpHandler = requireAccess [ Admin ] >=> validateCsrf >=> fun next ctx -> task { let save : HttpHandler = requireAccess [ Admin ] >=> validateCsrf >=> fun next ctx -> task {
match! ctx.TryBindFormAsync<EditSmallGroup> () with match! ctx.TryBindFormAsync<EditSmallGroup>() with
| Ok model -> | Ok model ->
let! tryGroup = let! tryGroup =
if model.IsNew then Task.FromResult (Some { SmallGroup.empty with Id = (Guid.NewGuid >> SmallGroupId) () }) if model.IsNew then Task.FromResult(Some { SmallGroup.empty with Id = (Guid.NewGuid >> SmallGroupId) () })
else SmallGroups.tryById (idFromShort SmallGroupId model.SmallGroupId) ctx.Conn else SmallGroups.tryById (idFromShort SmallGroupId model.SmallGroupId)
match tryGroup with match tryGroup with
| Some group -> | Some group ->
do! SmallGroups.save (model.populateGroup group) model.IsNew ctx.Conn do! SmallGroups.save (model.populateGroup group) model.IsNew
let act = ctx.Strings[if model.IsNew then "Added" else "Updated"].Value.ToLower () let act = ctx.Strings[if model.IsNew then "Added" else "Updated"].Value.ToLower()
addHtmlInfo ctx ctx.Strings["Successfully {0} group “{1}”", act, model.Name] addHtmlInfo ctx ctx.Strings["Successfully {0} group “{1}”", act, model.Name]
return! redirectTo false "/small-groups" next ctx return! redirectTo false "/small-groups" next ctx
| None -> return! fourOhFour ctx | None -> return! fourOhFour ctx
| Result.Error e -> return! bindError e next ctx | Result.Error e -> return! bindError e next ctx
} }
/// POST /small-group/member/save // POST /small-group/member/save
let saveMember : HttpHandler = requireAccess [ User ] >=> validateCsrf >=> fun next ctx -> task { let saveMember : HttpHandler = requireAccess [ User ] >=> validateCsrf >=> fun next ctx -> task {
match! ctx.TryBindFormAsync<EditMember> () with match! ctx.TryBindFormAsync<EditMember>() with
| Ok model -> | Ok model ->
let group = ctx.Session.CurrentGroup.Value let group = ctx.Session.CurrentGroup.Value
let! tryMbr = let! tryMbr =
if model.IsNew then if model.IsNew then
Task.FromResult (Some { Member.empty with Id = (Guid.NewGuid >> MemberId) (); SmallGroupId = group.Id }) Task.FromResult(Some { Member.empty with Id = (Guid.NewGuid >> MemberId) (); SmallGroupId = group.Id })
else Members.tryById (idFromShort MemberId model.MemberId) ctx.Conn else Members.tryById (idFromShort MemberId model.MemberId)
match tryMbr with match tryMbr with
| Some mbr when mbr.SmallGroupId = group.Id -> | Some mbr when mbr.SmallGroupId = group.Id ->
do! Members.save do! Members.save
{ mbr with { mbr with
Name = model.Name Name = model.Name
Email = model.Email Email = model.Email
Format = String.noneIfBlank model.Format |> Option.map EmailFormat.fromCode Format = String.noneIfBlank model.Format |> Option.map EmailFormat.fromCode }
} ctx.Conn let act = ctx.Strings[if model.IsNew then "Added" else "Updated"].Value.ToLower()
let act = ctx.Strings[if model.IsNew then "Added" else "Updated"].Value.ToLower ()
addInfo ctx ctx.Strings["Successfully {0} group member", act] addInfo ctx ctx.Strings["Successfully {0} group member", act]
return! redirectTo false "/small-group/members" next ctx return! redirectTo false "/small-group/members" next ctx
| Some _ | Some _
@ -225,18 +219,18 @@ let saveMember : HttpHandler = requireAccess [ User ] >=> validateCsrf >=> fun n
| Result.Error e -> return! bindError e next ctx | Result.Error e -> return! bindError e next ctx
} }
/// POST /small-group/preferences/save // POST /small-group/preferences/save
let savePreferences : HttpHandler = requireAccess [ User ] >=> validateCsrf >=> fun next ctx -> task { let savePreferences : HttpHandler = requireAccess [ User ] >=> validateCsrf >=> fun next ctx -> task {
match! ctx.TryBindFormAsync<EditPreferences> () with match! ctx.TryBindFormAsync<EditPreferences>() with
| Ok model -> | Ok model ->
// Since the class is stored in the session, we'll use an intermediate instance to persist it; once that works, // Since the class is stored in the session, we'll use an intermediate instance to persist it; once that works,
// we can repopulate the session instance. That way, if the update fails, the page should still show the // we can repopulate the session instance. That way, if the update fails, the page should still show the
// database values, not the then out-of-sync session ones. // database values, not the then out-of-sync session ones.
let group = ctx.Session.CurrentGroup.Value let group = ctx.Session.CurrentGroup.Value
match! SmallGroups.tryByIdWithPreferences group.Id ctx.Conn with match! SmallGroups.tryByIdWithPreferences group.Id with
| Some group -> | Some group ->
let pref = model.PopulatePreferences group.Preferences let pref = model.PopulatePreferences group.Preferences
do! SmallGroups.savePreferences pref ctx.Conn do! SmallGroups.savePreferences pref
// Refresh session instance // Refresh session instance
ctx.Session.CurrentGroup <- Some { group with Preferences = pref } ctx.Session.CurrentGroup <- Some { group with Preferences = pref }
addInfo ctx ctx.Strings["Group preferences updated successfully"] addInfo ctx ctx.Strings["Group preferences updated successfully"]
@ -247,10 +241,11 @@ let savePreferences : HttpHandler = requireAccess [ User ] >=> validateCsrf >=>
open Giraffe.ViewEngine open Giraffe.ViewEngine
open PrayerTracker.Views.CommonFunctions open PrayerTracker.Views.CommonFunctions
open Microsoft.Extensions.Configuration
/// POST /small-group/announcement/send // POST /small-group/announcement/send
let sendAnnouncement : HttpHandler = requireAccess [ User ] >=> validateCsrf >=> fun next ctx -> task { let sendAnnouncement : HttpHandler = requireAccess [ User ] >=> validateCsrf >=> fun next ctx -> task {
match! ctx.TryBindFormAsync<Announcement> () with match! ctx.TryBindFormAsync<Announcement>() with
| Ok model -> | Ok model ->
let group = ctx.Session.CurrentGroup.Value let group = ctx.Session.CurrentGroup.Value
let pref = group.Preferences let pref = group.Preferences
@ -266,21 +261,21 @@ let sendAnnouncement : HttpHandler = requireAccess [ User ] >=> validateCsrf >=>
// Send the e-mails // Send the e-mails
let! recipients = task { let! recipients = task {
if model.SendToClass = "N" && usr.IsAdmin then if model.SendToClass = "N" && usr.IsAdmin then
let! users = Users.all ctx.Conn let! users = Users.all ()
return users |> List.map (fun u -> { Member.empty with Name = u.Name; Email = u.Email }) return users |> List.map (fun u -> { Member.empty with Name = u.Name; Email = u.Email })
else return! Members.forGroup group.Id ctx.Conn else return! Members.forGroup group.Id
} }
use! client = Email.getConnection () use! client = Email.getConnection ()
do! Email.sendEmails do! Email.sendEmails
{ Client = client { Client = client
Recipients = recipients Recipients = recipients
Group = group Group = group
Subject = s["Announcement for {0} - {1:MMMM d, yyyy} {2}", group.Name, now.Date, Subject = s["Announcement for {0} - {1:MMMM d, yyyy} {2}", group.Name, now.Date,
(now.ToString ("h:mm tt", null)).ToLower ()].Value now.ToString("h:mm tt", null).ToLower()].Value
HtmlBody = htmlText HtmlBody = htmlText
PlainTextBody = plainText PlainTextBody = plainText
Strings = s Strings = s }
} do! client.DisconnectAsync true
// Add to the request list if desired // Add to the request list if desired
match model.SendToClass, model.AddToRequestList with match model.SendToClass, model.AddToRequestList with
| "N", _ | "N", _
@ -296,12 +291,11 @@ let sendAnnouncement : HttpHandler = requireAccess [ User ] >=> validateCsrf >=>
RequestType = (Option.get >> PrayerRequestType.fromCode) model.RequestType RequestType = (Option.get >> PrayerRequestType.fromCode) model.RequestType
Text = requestText Text = requestText
EnteredDate = now.Date.AtStartOfDayInZone(zone).ToInstant() EnteredDate = now.Date.AtStartOfDayInZone(zone).ToInstant()
UpdatedDate = now.InZoneLeniently(zone).ToInstant() UpdatedDate = now.InZoneLeniently(zone).ToInstant() }
} ctx.Conn
// Tell 'em what they've won, Johnny! // Tell 'em what they've won, Johnny!
let toWhom = let toWhom =
if model.SendToClass = "N" then s["{0} users", s["PrayerTracker"]].Value if model.SendToClass = "N" then s["{0} users", s["PrayerTracker"]].Value
else s["Group Members"].Value.ToLower () else s["Group Members"].Value.ToLower()
let andAdded = match model.AddToRequestList with Some x when x -> "and added it to the request list" | _ -> "" 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]] addInfo ctx s["Successfully sent announcement to all {0} {1}", toWhom, s[andAdded]]
return! return!

View File

@ -9,6 +9,8 @@ open PrayerTracker.Data
open PrayerTracker.Entities open PrayerTracker.Entities
open PrayerTracker.ViewModels open PrayerTracker.ViewModels
#nowarn "44" // The default Rfc2898DeriveBytes is used to identify passwords to be upgraded
/// Password hashing implementation extending ASP.NET Core's identity implementation /// Password hashing implementation extending ASP.NET Core's identity implementation
[<AutoOpen>] [<AutoOpen>]
module Hashing = module Hashing =
@ -17,10 +19,10 @@ module Hashing =
open System.Text open System.Text
/// Custom password hasher used to verify and upgrade old password hashes /// Custom password hasher used to verify and upgrade old password hashes
type PrayerTrackerPasswordHasher () = type PrayerTrackerPasswordHasher() =
inherit PasswordHasher<User> () inherit PasswordHasher<User>()
override this.VerifyHashedPassword (user, hashedPassword, providedPassword) = override this.VerifyHashedPassword(user, hashedPassword, providedPassword) =
if isNull hashedPassword then nullArg (nameof hashedPassword) if isNull hashedPassword then nullArg (nameof hashedPassword)
if isNull providedPassword then nullArg (nameof providedPassword) if isNull providedPassword then nullArg (nameof providedPassword)
@ -41,7 +43,7 @@ module Hashing =
| 254uy -> | 254uy ->
// v1 hashes - SHA-1 // v1 hashes - SHA-1
let v1Hash = let v1Hash =
use alg = SHA1.Create () use alg = SHA1.Create()
alg.ComputeHash (Encoding.ASCII.GetBytes providedPassword) alg.ComputeHash (Encoding.ASCII.GetBytes providedPassword)
|> Seq.map (fun byt -> byt.ToString "x2") |> Seq.map (fun byt -> byt.ToString "x2")
|> String.concat "" |> String.concat ""
@ -49,19 +51,19 @@ module Hashing =
PasswordVerificationResult.SuccessRehashNeeded PasswordVerificationResult.SuccessRehashNeeded
else else
PasswordVerificationResult.Failed PasswordVerificationResult.Failed
| _ -> base.VerifyHashedPassword (user, hashedPassword, providedPassword) | _ -> base.VerifyHashedPassword(user, hashedPassword, providedPassword)
/// Retrieve a user from the database by password, upgrading password hashes if required /// Retrieve a user from the database by password, upgrading password hashes if required
let private findUserByPassword model conn = task { let private findUserByPassword model = task {
match! Users.tryByEmailAndGroup model.Email (idFromShort SmallGroupId model.SmallGroupId) conn with match! Users.tryByEmailAndGroup model.Email (idFromShort SmallGroupId model.SmallGroupId) with
| Some user -> | Some user ->
let hasher = PrayerTrackerPasswordHasher () let hasher = PrayerTrackerPasswordHasher()
match hasher.VerifyHashedPassword (user, user.PasswordHash, model.Password) with match hasher.VerifyHashedPassword(user, user.PasswordHash, model.Password) with
| PasswordVerificationResult.Success -> return Some user | PasswordVerificationResult.Success -> return Some user
| PasswordVerificationResult.SuccessRehashNeeded -> | PasswordVerificationResult.SuccessRehashNeeded ->
let upgraded = { user with PasswordHash = hasher.HashPassword (user, model.Password) } let upgraded = { user with PasswordHash = hasher.HashPassword(user, model.Password) }
do! Users.updatePassword upgraded conn do! Users.updatePassword upgraded
return Some upgraded return Some upgraded
| _ -> return None | _ -> return None
| None -> return None | None -> return None
@ -74,16 +76,16 @@ let sanitizeUrl providedUrl defaultUrl =
elif Seq.exists Char.IsControl url then defaultUrl elif Seq.exists Char.IsControl url then defaultUrl
else url else url
/// POST /user/password/change // POST /user/password/change
let changePassword : HttpHandler = requireAccess [ User ] >=> validateCsrf >=> fun next ctx -> task { let changePassword : HttpHandler = requireAccess [ User ] >=> validateCsrf >=> fun next ctx -> task {
match! ctx.TryBindFormAsync<ChangePassword> () with match! ctx.TryBindFormAsync<ChangePassword>() with
| Ok model -> | Ok model ->
let curUsr = ctx.Session.CurrentUser.Value let curUsr = ctx.Session.CurrentUser.Value
let hasher = PrayerTrackerPasswordHasher () let hasher = PrayerTrackerPasswordHasher()
let! user = task { let! user = task {
match! Users.tryById curUsr.Id ctx.Conn with match! Users.tryById curUsr.Id with
| Some usr -> | Some usr ->
if hasher.VerifyHashedPassword (usr, usr.PasswordHash, model.OldPassword) if hasher.VerifyHashedPassword(usr, usr.PasswordHash, model.OldPassword)
= PasswordVerificationResult.Success then = PasswordVerificationResult.Success then
return Some usr return Some usr
else return None else return None
@ -91,7 +93,7 @@ let changePassword : HttpHandler = requireAccess [ User ] >=> validateCsrf >=> f
} }
match user with match user with
| Some usr when model.NewPassword = model.NewPasswordConfirm -> | Some usr when model.NewPassword = model.NewPasswordConfirm ->
do! Users.updatePassword { usr with PasswordHash = hasher.HashPassword (usr, model.NewPassword) } ctx.Conn do! Users.updatePassword { usr with PasswordHash = hasher.HashPassword(usr, model.NewPassword) }
addInfo ctx ctx.Strings["Your password was changed successfully"] addInfo ctx ctx.Strings["Your password was changed successfully"]
return! redirectTo false "/" next ctx return! redirectTo false "/" next ctx
| Some _ -> | Some _ ->
@ -103,12 +105,12 @@ let changePassword : HttpHandler = requireAccess [ User ] >=> validateCsrf >=> f
| Result.Error e -> return! bindError e next ctx | Result.Error e -> return! bindError e next ctx
} }
/// POST /user/[user-id]/delete // POST /user/[user-id]/delete
let delete usrId : HttpHandler = requireAccess [ Admin ] >=> validateCsrf >=> fun next ctx -> task { let delete usrId : HttpHandler = requireAccess [ Admin ] >=> validateCsrf >=> fun next ctx -> task {
let userId = UserId usrId let userId = UserId usrId
match! Users.tryById userId ctx.Conn with match! Users.tryById userId with
| Some user -> | Some user ->
do! Users.deleteById userId ctx.Conn do! Users.deleteById userId
addInfo ctx ctx.Strings["Successfully deleted user {0}", user.Name] addInfo ctx ctx.Strings["Successfully deleted user {0}", user.Name]
return! redirectTo false "/users" next ctx return! redirectTo false "/users" next ctx
| _ -> return! fourOhFour ctx | _ -> return! fourOhFour ctx
@ -120,28 +122,28 @@ open Microsoft.AspNetCore.Authentication
open Microsoft.AspNetCore.Authentication.Cookies open Microsoft.AspNetCore.Authentication.Cookies
open Microsoft.AspNetCore.Html open Microsoft.AspNetCore.Html
/// POST /user/log-on // POST /user/log-on
let doLogOn : HttpHandler = requireAccess [ AccessLevel.Public ] >=> validateCsrf >=> fun next ctx -> task { let doLogOn : HttpHandler = requireAccess [ AccessLevel.Public ] >=> validateCsrf >=> fun next ctx -> task {
match! ctx.TryBindFormAsync<UserLogOn> () with match! ctx.TryBindFormAsync<UserLogOn>() with
| Ok model -> | Ok model ->
let s = ctx.Strings let s = ctx.Strings
match! findUserByPassword model ctx.Conn with match! findUserByPassword model with
| Some user -> | Some user ->
match! SmallGroups.tryByIdWithPreferences (idFromShort SmallGroupId model.SmallGroupId) ctx.Conn with match! SmallGroups.tryByIdWithPreferences (idFromShort SmallGroupId model.SmallGroupId) with
| Some group -> | Some group ->
ctx.Session.CurrentUser <- Some user ctx.Session.CurrentUser <- Some user
ctx.Session.CurrentGroup <- Some group ctx.Session.CurrentGroup <- Some group
let identity = ClaimsIdentity ( let identity = ClaimsIdentity(
seq { seq {
Claim (ClaimTypes.NameIdentifier, shortGuid user.Id.Value) Claim(ClaimTypes.NameIdentifier, shortGuid user.Id.Value)
Claim (ClaimTypes.GroupSid, shortGuid group.Id.Value) Claim(ClaimTypes.GroupSid, shortGuid group.Id.Value)
}, CookieAuthenticationDefaults.AuthenticationScheme) }, CookieAuthenticationDefaults.AuthenticationScheme)
do! ctx.SignInAsync ( do! ctx.SignInAsync(
identity.AuthenticationType, ClaimsPrincipal identity, identity.AuthenticationType, ClaimsPrincipal identity,
AuthenticationProperties ( AuthenticationProperties(
IssuedUtc = DateTimeOffset.UtcNow, IssuedUtc = DateTimeOffset.UtcNow,
IsPersistent = defaultArg model.RememberMe false)) IsPersistent = defaultArg model.RememberMe false))
do! Users.updateLastSeen user.Id ctx.Now ctx.Conn do! Users.updateLastSeen user.Id ctx.Now
addHtmlInfo ctx s["Log On Successful Welcome to {0}", s["PrayerTracker"]] addHtmlInfo ctx s["Log On Successful Welcome to {0}", s["PrayerTracker"]]
return! redirectTo false (sanitizeUrl model.RedirectUrl "/small-group") next ctx return! redirectTo false (sanitizeUrl model.RedirectUrl "/small-group") next ctx
| None -> return! fourOhFour ctx | None -> return! fourOhFour ctx
@ -150,20 +152,18 @@ let doLogOn : HttpHandler = requireAccess [ AccessLevel.Public ] >=> validateCsr
Text = htmlLocString s["Invalid credentials - log on unsuccessful"] Text = htmlLocString s["Invalid credentials - log on unsuccessful"]
Description = Description =
let detail = let detail =
[ "This is likely due to one of the following reasons:<ul>" [ "This is likely due to one of the following reasons:<ul>"
"<li>The e-mail address “{0}” is invalid.</li>" "<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>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>" "<li>You are not authorized to administer the selected group.</li></ul>" ]
]
|> String.concat "" |> String.concat ""
Some (HtmlString (s[detail, WebUtility.HtmlEncode model.Email].Value)) Some (HtmlString(s[detail, WebUtility.HtmlEncode model.Email].Value)) }
}
|> addUserMessage ctx |> addUserMessage ctx
return! redirectTo false "/user/log-on" next ctx return! redirectTo false "/user/log-on" next ctx
| Result.Error e -> return! bindError e next ctx | Result.Error e -> return! bindError e next ctx
} }
/// GET /user/[user-id]/edit // GET /user/[user-id]/edit
let edit usrId : HttpHandler = requireAccess [ Admin ] >=> fun next ctx -> task { let edit usrId : HttpHandler = requireAccess [ Admin ] >=> fun next ctx -> task {
let userId = UserId usrId let userId = UserId usrId
if userId.Value = Guid.Empty then if userId.Value = Guid.Empty then
@ -172,7 +172,7 @@ let edit usrId : HttpHandler = requireAccess [ Admin ] >=> fun next ctx -> task
|> Views.User.edit EditUser.empty ctx |> Views.User.edit EditUser.empty ctx
|> renderHtml next ctx |> renderHtml next ctx
else else
match! Users.tryById userId ctx.Conn with match! Users.tryById userId with
| Some user -> | Some user ->
return! return!
viewInfo ctx viewInfo ctx
@ -181,9 +181,9 @@ let edit usrId : HttpHandler = requireAccess [ Admin ] >=> fun next ctx -> task
| _ -> return! fourOhFour 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 = requireAccess [ AccessLevel.Public ] >=> fun next ctx -> task {
let! groups = SmallGroups.listAll ctx.Conn let! groups = SmallGroups.listAll ()
let url = Option.ofObj <| ctx.Session.GetString Key.Session.redirectUrl let url = Option.ofObj <| ctx.Session.GetString Key.Session.redirectUrl
match url with match url with
| Some _ -> | Some _ ->
@ -196,16 +196,16 @@ let logOn : HttpHandler = requireAccess [ AccessLevel.Public ] >=> fun next ctx
|> renderHtml next ctx |> renderHtml next ctx
} }
/// GET /users // GET /users
let maintain : HttpHandler = requireAccess [ Admin ] >=> fun next ctx -> task { let maintain : HttpHandler = requireAccess [ Admin ] >=> fun next ctx -> task {
let! users = Users.all ctx.Conn let! users = Users.all ()
return! return!
viewInfo ctx viewInfo ctx
|> 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 = requireAccess [ User ] >=> fun next ctx ->
{ viewInfo ctx with HelpLink = Some Help.changePassword } { viewInfo ctx with HelpLink = Some Help.changePassword }
|> Views.User.changePassword ctx |> Views.User.changePassword ctx
@ -213,18 +213,18 @@ let password : HttpHandler = requireAccess [ User ] >=> fun next ctx ->
open System.Threading.Tasks open System.Threading.Tasks
/// POST /user/save // POST /user/save
let save : HttpHandler = requireAccess [ Admin ] >=> validateCsrf >=> fun next ctx -> task { let save : HttpHandler = requireAccess [ Admin ] >=> validateCsrf >=> fun next ctx -> task {
match! ctx.TryBindFormAsync<EditUser> () with match! ctx.TryBindFormAsync<EditUser>() with
| Ok model -> | Ok model ->
let! user = let! user =
if model.IsNew then Task.FromResult (Some { User.empty with Id = (Guid.NewGuid >> UserId) () }) if model.IsNew then Task.FromResult(Some { User.empty with Id = (Guid.NewGuid >> UserId) () })
else Users.tryById (idFromShort UserId model.UserId) ctx.Conn else Users.tryById (idFromShort UserId model.UserId)
match user with match user with
| Some usr -> | Some usr ->
let hasher = PrayerTrackerPasswordHasher () let hasher = PrayerTrackerPasswordHasher()
let updatedUser = model.PopulateUser usr (fun pw -> hasher.HashPassword (usr, pw)) let updatedUser = model.PopulateUser usr (fun pw -> hasher.HashPassword(usr, pw))
do! Users.save updatedUser ctx.Conn do! Users.save updatedUser
let s = ctx.Strings let s = ctx.Strings
if model.IsNew then if model.IsNew then
let h = CommonFunctions.htmlString let h = CommonFunctions.htmlString
@ -233,8 +233,7 @@ let save : HttpHandler = requireAccess [ Admin ] >=> validateCsrf >=> fun next c
Description = Description =
h s["Please select at least one group for which this user ({0}) is authorized", h s["Please select at least one group for which this user ({0}) is authorized",
updatedUser.Name] updatedUser.Name]
|> Some |> Some }
}
|> addUserMessage ctx |> addUserMessage ctx
return! redirectTo false $"/user/{shortGuid usr.Id.Value}/small-groups" next ctx return! redirectTo false $"/user/{shortGuid usr.Id.Value}/small-groups" next ctx
else else
@ -244,9 +243,9 @@ let save : HttpHandler = requireAccess [ Admin ] >=> validateCsrf >=> fun next c
| Result.Error e -> return! bindError e next ctx | Result.Error e -> return! bindError e next ctx
} }
/// POST /user/small-groups/save // POST /user/small-groups/save
let saveGroups : HttpHandler = requireAccess [ Admin ] >=> validateCsrf >=> fun next ctx -> task { let saveGroups : HttpHandler = requireAccess [ Admin ] >=> validateCsrf >=> fun next ctx -> task {
match! ctx.TryBindFormAsync<AssignGroups> () with match! ctx.TryBindFormAsync<AssignGroups>() with
| Ok model -> | Ok model ->
match Seq.length model.SmallGroups with match Seq.length model.SmallGroups with
| 0 -> | 0 ->
@ -254,19 +253,19 @@ let saveGroups : HttpHandler = requireAccess [ Admin ] >=> validateCsrf >=> fun
return! redirectTo false $"/user/{model.UserId}/small-groups" next ctx return! redirectTo false $"/user/{model.UserId}/small-groups" next ctx
| _ -> | _ ->
do! Users.updateSmallGroups (idFromShort UserId model.UserId) do! Users.updateSmallGroups (idFromShort UserId model.UserId)
(model.SmallGroups.Split ',' |> Array.map (idFromShort SmallGroupId) |> List.ofArray) ctx.Conn (model.SmallGroups.Split ',' |> Array.map (idFromShort SmallGroupId) |> List.ofArray)
addInfo ctx ctx.Strings["Successfully updated group permissions for {0}", model.UserName] addInfo ctx ctx.Strings["Successfully updated group permissions for {0}", model.UserName]
return! redirectTo false "/users" next ctx return! redirectTo false "/users" next ctx
| Result.Error e -> return! bindError e next ctx | Result.Error e -> return! bindError e next ctx
} }
/// GET /user/[user-id]/small-groups // GET /user/[user-id]/small-groups
let smallGroups usrId : HttpHandler = requireAccess [ Admin ] >=> fun next ctx -> task { let smallGroups usrId : HttpHandler = requireAccess [ Admin ] >=> fun next ctx -> task {
let userId = UserId usrId let userId = UserId usrId
match! Users.tryById userId ctx.Conn with match! Users.tryById userId with
| Some user -> | Some user ->
let! groups = SmallGroups.listAll ctx.Conn let! groups = SmallGroups.listAll ()
let! groupIds = Users.groupIdsByUserId userId ctx.Conn let! groupIds = Users.groupIdsByUserId userId
let curGroups = groupIds |> List.map (fun g -> shortGuid g.Value) let curGroups = groupIds |> List.map (fun g -> shortGuid g.Value)
return! return!
viewInfo ctx viewInfo ctx

View File

@ -5,6 +5,9 @@
background-color: white; background-color: white;
padding: 0 .25em; padding: 0 .25em;
} }
.pt-title-bar-home {
height: 2rem;
}
.pt-title-bar-left { .pt-title-bar-left {
color: white; color: white;
font-size: 1.25rem; font-size: 1.25rem;
@ -17,9 +20,24 @@
font-size: 1.1rem; font-size: 1.1rem;
font-variant: small-caps; font-variant: small-caps;
margin-right: 1rem; margin-right: 1rem;
align-self: center;
} }
h2 { h2 {
margin-top: 0; margin-top: 0;
padding-left: .5rem; padding-left: .5rem;
border-bottom: solid 1px #444; border-bottom: solid 1px #444;
} }
.pt-close-window, .pt-help-index {
font-size: 1.25rem;
}
.pt-help-index {
display: none;
}
@media screen and (min-width:451px) {
.pt-close-window {
display: none;
}
.pt-help-index {
display: block;
}
}

View File

@ -1,3 +0,0 @@
Set-Location PrayerTracker
dotnet publish -c Release -r linux-x64 -p:PublishSingleFile=true --self-contained false
Set-Location bin\Release\net6.0\linux-x64\publish

View File

@ -1,110 +0,0 @@
-- Church
ALTER TABLE pt."Church" RENAME COLUMN "ChurchId" TO id;
ALTER TABLE pt."Church" RENAME COLUMN "Name" TO church_name;
ALTER TABLE pt."Church" RENAME COLUMN "City" TO city;
ALTER TABLE pt."Church" RENAME COLUMN "ST" TO state;
ALTER TABLE pt."Church" RENAME COLUMN "HasVirtualPrayerRoomInterface" TO has_vps_interface;
ALTER TABLE pt."Church" RENAME COLUMN "InterfaceAddress" TO interface_address;
ALTER TABLE pt."Church" RENAME CONSTRAINT "PK_Church" TO pk_church;
ALTER TABLE pt."Church" RENAME TO church;
-- List Preference
ALTER TABLE pt."ListPreference" RENAME COLUMN "SmallGroupId" TO small_group_id;
ALTER TABLE pt."ListPreference" RENAME COLUMN "DaysToExpire" TO days_to_expire;
ALTER TABLE pt."ListPreference" RENAME COLUMN "DaysToKeepNew" TO days_to_keep_new;
ALTER TABLE pt."ListPreference" RENAME COLUMN "LongTermUpdateWeeks" TO long_term_update_weeks;
ALTER TABLE pt."ListPreference" RENAME COLUMN "EmailFromName" TO email_from_name;
ALTER TABLE pt."ListPreference" RENAME COLUMN "EmailFromAddress" TO email_from_address;
ALTER TABLE pt."ListPreference" RENAME COLUMN "ListFonts" TO fonts;
ALTER TABLE pt."ListPreference" RENAME COLUMN "HeadingColor" TO heading_color;
ALTER TABLE pt."ListPreference" RENAME COLUMN "LineColor" TO line_color;
ALTER TABLE pt."ListPreference" RENAME COLUMN "HeadingFontSize" TO heading_font_size;
ALTER TABLE pt."ListPreference" RENAME COLUMN "TextFontSize" TO text_font_size;
ALTER TABLE pt."ListPreference" RENAME COLUMN "RequestSort" TO request_sort;
ALTER TABLE pt."ListPreference" RENAME COLUMN "GroupPassword" TO group_password;
ALTER TABLE pt."ListPreference" RENAME COLUMN "DefaultEmailType" TO default_email_type;
ALTER TABLE pt."ListPreference" RENAME COLUMN "IsPublic" TO is_public;
ALTER TABLE pt."ListPreference" RENAME COLUMN "TimeZoneId" TO time_zone_id;
ALTER TABLE pt."ListPreference" RENAME COLUMN "PageSize" TO page_size;
ALTER TABLE pt."ListPreference" RENAME COLUMN "AsOfDateDisplay" TO as_of_date_display;
ALTER TABLE pt."ListPreference" RENAME CONSTRAINT "PK_ListPreference" TO pk_list_preference;
ALTER TABLE pt."ListPreference" RENAME CONSTRAINT "FK_ListPreference_SmallGroup_SmallGroupId" TO fk_list_preference_small_group_id;
ALTER TABLE pt."ListPreference" DROP CONSTRAINT "FK_ListPreference_TimeZone_TimeZoneId";
ALTER TABLE pt."ListPreference" RENAME TO list_preference;
ALTER INDEX pt."IX_ListPreference_TimeZoneId" RENAME TO ix_list_preference_time_zone_id;
ALTER TABLE pt.list_preference ALTER COLUMN email_from_address SET DEFAULT 'prayer@bitbadger.solutions';
ALTER TABLE pt.list_preference ALTER COLUMN fonts SET DEFAULT 'native';
-- Small Group Member
ALTER TABLE pt."Member" RENAME COLUMN "MemberId" TO id;
ALTER TABLE pt."Member" RENAME COLUMN "SmallGroupId" TO small_group_id;
ALTER TABLE pt."Member" RENAME COLUMN "MemberName" TO member_name;
ALTER TABLE pt."Member" RENAME COLUMN "Email" TO email;
ALTER TABLE pt."Member" RENAME COLUMN "Format" TO email_format;
ALTER TABLE pt."Member" RENAME CONSTRAINT "PK_Member" TO pk_member;
ALTER TABLE pt."Member" RENAME CONSTRAINT "FK_Member_SmallGroup_SmallGroupId" TO fk_member_small_group_id;
ALTER TABLE pt."Member" RENAME TO member;
ALTER INDEX pt."IX_Member_SmallGroupId" RENAME TO ix_member_small_group_id;
-- Prayer Request
ALTER TABLE pt."PrayerRequest" RENAME COLUMN "PrayerRequestId" TO id;
ALTER TABLE pt."PrayerRequest" RENAME COLUMN "RequestType" TO request_type;
ALTER TABLE pt."PrayerRequest" RENAME COLUMN "UserId" TO user_id;
ALTER TABLE pt."PrayerRequest" RENAME COLUMN "SmallGroupId" TO small_group_id;
ALTER TABLE pt."PrayerRequest" RENAME COLUMN "EnteredDate" TO entered_date;
ALTER TABLE pt."PrayerRequest" RENAME COLUMN "UpdatedDate" TO updated_date;
ALTER TABLE pt."PrayerRequest" RENAME COLUMN "Requestor" TO requestor;
ALTER TABLE pt."PrayerRequest" RENAME COLUMN "Text" TO request_text;
ALTER TABLE pt."PrayerRequest" RENAME COLUMN "NotifyChaplain" TO notify_chaplain;
ALTER TABLE pt."PrayerRequest" RENAME COLUMN "Expiration" TO expiration;
ALTER TABLE pt."PrayerRequest" RENAME CONSTRAINT "PK_PrayerRequest" TO pk_prayer_request;
ALTER TABLE pt."PrayerRequest" RENAME CONSTRAINT "FK_PrayerRequest_User_UserId" TO fk_prayer_request_user_id;
ALTER TABLE pt."PrayerRequest" RENAME CONSTRAINT "FK_PrayerRequest_SmallGroup_SmallGroupId" TO fk_prayer_request_small_group_id;
ALTER TABLE pt."PrayerRequest" RENAME TO prayer_request;
ALTER INDEX pt."IX_PrayerRequest_UserId" RENAME TO ix_prayer_request_user_id;
ALTER INDEX pt."IX_PrayerRequest_SmallGroupId" RENAME TO ix_prayer_request_small_group_id;
ALTER INDEX pt."IX_PrayerRequest_Requestor_TRGM" RENAME TO ix_prayer_request_trgm_requestor;
ALTER INDEX pt."IX_PrayerRequest_Text_TRGM" RENAME TO ix_prayer_request_trgm_request_text;
-- Small Group
ALTER TABLE pt."SmallGroup" RENAME COLUMN "SmallGroupId" TO id;
ALTER TABLE pt."SmallGroup" RENAME COLUMN "ChurchId" TO church_id;
ALTER TABLE pt."SmallGroup" RENAME COLUMN "Name" TO group_name;
ALTER TABLE pt."SmallGroup" RENAME CONSTRAINT "PK_SmallGroup" TO pk_small_group;
ALTER TABLE pt."SmallGroup" RENAME CONSTRAINT "FK_SmallGroup_Church_ChurchId" TO fk_small_group_church_id;
ALTER TABLE pt."SmallGroup" RENAME TO small_group;
ALTER INDEX pt."IX_SmallGroup_ChurchId" RENAME TO ix_small_group_church_id;
-- Time Zone (goes away)
DROP TABLE pt."TimeZone";
-- User
ALTER TABLE pt."User" RENAME COLUMN "UserId" TO id;
ALTER TABLE pt."User" RENAME COLUMN "FirstName" TO first_name;
ALTER TABLE pt."User" RENAME COLUMN "LastName" TO last_name;
ALTER TABLE pt."User" RENAME COLUMN "EmailAddress" TO email;
ALTER TABLE pt."User" RENAME COLUMN "IsSystemAdmin" TO is_admin;
ALTER TABLE pt."User" RENAME COLUMN "PasswordHash" TO password_hash;
ALTER TABLE pt."User" RENAME COLUMN "Salt" TO salt;
ALTER TABLE pt."User" RENAME CONSTRAINT "PK_User" TO pk_pt_user;
ALTER TABLE pt."User" RENAME TO pt_user;
ALTER TABLE pt.pt_user ADD COLUMN last_seen timestamptz;
-- User / Small Group
ALTER TABLE pt."User_SmallGroup" RENAME COLUMN "UserId" TO user_id;
ALTER TABLE pt."User_SmallGroup" RENAME COLUMN "SmallGroupId" TO small_group_id;
ALTER TABLE pt."User_SmallGroup" RENAME CONSTRAINT "PK_User_SmallGroup" TO pk_user_small_group;
ALTER TABLE pt."User_SmallGroup" RENAME CONSTRAINT "FK_User_SmallGroup_User_UserId" TO fk_user_small_group_user_id;
ALTER TABLE pt."User_SmallGroup" RENAME CONSTRAINT "FK_User_SmallGroup_SmallGroup_SmallGroupId" TO fk_user_small_group_small_group_id;
ALTER TABLE pt."User_SmallGroup" RENAME TO user_small_group;
ALTER INDEX pt."IX_User_SmallGroup_SmallGroupId" RENAME TO ix_user_small_group_small_group_id;
-- #41 - change to timestamptz
SET TimeZone = 'UTC';
ALTER TABLE pt.prayer_request ALTER COLUMN entered_date TYPE timestamptz;
ALTER TABLE pt.prayer_request ALTER COLUMN updated_date TYPE timestamptz;

View File

@ -1,27 +0,0 @@
create extension pg_trgm;
set search_path=pt,public;
create index "IX_PrayerRequest_Requestor_TRGM" on "PrayerRequest" using GIN (COALESCE("Requestor", '') gin_trgm_ops);
create index "IX_PrayerRequest_Text_TRGM" on "PrayerRequest" using GIN ("Text" gin_trgm_ops);
alter table "ListPreference" add column "PageSize" int not null default 100;
alter table "ListPreference" add column "AsOfDateDisplay" varchar(1) not null default 'N';
/* RequestType to 1 character code */
update "PrayerRequest" set "RequestType" = 'C' where "RequestType" = 'Current';
update "PrayerRequest" set "RequestType" = 'L' where "RequestType" = 'Recurring';
update "PrayerRequest" set "RequestType" = 'P' where "RequestType" = 'Praise';
update "PrayerRequest" set "RequestType" = 'E' where "RequestType" = 'Expecting';
update "PrayerRequest" set "RequestType" = 'A' where "RequestType" = 'Announcement';
alter table "PrayerRequest" alter column "RequestType" set data type varchar(1);
/* Change expiration to a 1-character code field */
alter table "PrayerRequest" add column "Expiration" varchar(1);
update "PrayerRequest" set "Expiration" = case when "IsManuallyExpired" then 'F' when "DoNotExpire" then 'M' else 'A' end;
alter table "PrayerRequest" alter column "Expiration" set not null;
alter table "PrayerRequest" drop column "DoNotExpire";
alter table "PrayerRequest" drop column "IsManuallyExpired";
/* Change e-mail type to 1-character code field in list preferences and members */
update "ListPreference" set "DefaultEmailType" = 'H' where "DefaultEmailType" = 'Html';
update "ListPreference" set "DefaultEmailType" = 'P' where "DefaultEmailType" = 'Text';
alter table "ListPreference" alter column "DefaultEmailType" set default 'H';
alter table "ListPreference" alter column "DefaultEmailType" set data type varchar(1);
update "Member" set "Format" = 'H' where "Format" = 'Html';
update "Member" set "Format" = 'P' where "Format" = 'Text';
alter table "Member" alter column "Format" set data type varchar(1);