Compare commits

..

62 Commits

Author SHA1 Message Date
69ae5fe2ff fix syntax & unused code warnings 2023-07-10 19:19:53 -06:00
0b7a35c9b8 list the gives to a plan and gives to which this plan contributed 2023-07-09 20:37:08 -06:00
0257901c5b allow viewing of a project without an ID (and other refactors) 2023-07-09 09:38:28 -06:00
d9d6096275 consolidate the "gave" actions on a projecct 2023-07-09 08:31:11 -06:00
81dd6eb595 Merge pull request 'Updates to contacts UI. Sweep for buildIdentity and buildHeaders' (#35) from contacts-identity into master
Reviewed-on: trent_larson/kick-starter-for-time-pwa#35
2023-07-08 22:58:51 -04:00
Matthew Raymer
c61bb88788 More cleanup from project task list 2023-07-08 18:42:53 +08:00
Matthew Raymer
3bd55f3ad2 More cleanup and application of new db loading 2023-07-08 18:31:12 +08:00
Matthew Raymer
3471afdf25 Cleaned up messages and improved the accountsDB lookups 2023-07-08 17:39:20 +08:00
Matthew Raymer
e25a83ff1b Move account counter to mounted event 2023-07-08 17:19:52 +08:00
Matthew Raymer
0fbdb45d3e Project Task update 2023-07-07 20:33:43 +08:00
Matthew Raymer
dc23ba1375 Fix a bug in HomeView and clean up recordGive method 2023-07-07 18:43:16 +08:00
Matthew Raymer
08137eb000 Updates to contacts UI. Sweep for buildIdentity and buildHeaders 2023-07-07 18:28:06 +08:00
Matthew Raymer
5d49965166 Simple fix. Missing reference to QuickNav 2023-07-07 16:22:53 +08:00
8e8aa4356d Update 'project.task.yaml' 2023-07-06 22:20:43 -04:00
59a354027e Update 'src/views/StatisticsView.vue'
Clean up spurious comment.
2023-07-06 21:36:10 -04:00
Matthew Raymer
5dc80ce12a A bit more cleanup. Problem in Contacts to resolve. 2023-07-06 18:33:13 +08:00
Matthew Raymer
754bced2a9 Considerable cleanup. I think I also found the issue from the other day with values not loading from settings. 2023-07-06 18:12:21 +08:00
Matthew Raymer
e3f58bd593 Purge all vue-class-component with vue-facing-decorator.
Make some strike-throughs for project-task
Update package.json
2023-07-06 17:28:08 +08:00
Matthew Raymer
3b41014083 Considerable cleanup and merge 2023-07-06 16:59:50 +08:00
f568149745 Merge pull request 'allow choice of no identity (for testing)' (#32) from choose-no-id into master
Reviewed-on: trent_larson/kick-starter-for-time-pwa#32
2023-07-06 02:40:11 -04:00
a27d035e9b Merge branch 'master' into choose-no-id 2023-07-06 02:40:00 -04:00
16d0be681c Merge pull request 'quicknav-component' (#34) from quicknav-component into master
Reviewed-on: trent_larson/kick-starter-for-time-pwa#34
2023-07-06 02:38:19 -04:00
Matthew Raymer
5be67fd4c9 Rolled out to all views that had HTML quicknav 2023-07-05 17:59:31 +08:00
Matthew Raymer
dda3ad057d This is the QuickNav component 2023-07-05 17:58:18 +08:00
Matthew Raymer
cf54096326 Looks like GiftedDialog works? A little cleanup. 2023-07-05 16:27:21 +08:00
49c3971cf2 Merge pull request 'First draft of Vue3 version. WIll finish after error-logging merge' (#31) from gifted-dialog-conversion into master
Reviewed-on: trent_larson/kick-starter-for-time-pwa#31
2023-07-05 03:07:35 -04:00
Matthew Raymer
80a1185faa Fix for missing scene-container 2023-07-05 15:59:58 +08:00
cd8bc73bac Merge branch 'master' into gifted-dialog-conversion 2023-07-05 03:07:09 -04:00
e42b3ff11d allow choice of no identity (for testing) 2023-07-04 13:15:52 -06:00
d98e95915b Merge pull request 'error-logging' (#29) from error-logging into master
Reviewed-on: trent_larson/kick-starter-for-time-pwa#29
2023-07-04 12:15:24 -04:00
Matthew Raymer
4758a740de First draft of Vue3 version. WIll finish after error-logging merge 2023-07-04 20:03:36 +08:00
Matthew Raymer
0a020a4069 Clean up vestigle old alert code 2023-07-04 19:29:12 +08:00
Matthew Raymer
c859778832 Add AlertMessage component 2023-07-04 19:27:57 +08:00
Matthew Raymer
c24022c41c Make the visibility of the Alert indirect 2023-07-04 19:26:05 +08:00
Matthew Raymer
0fd4b86a84 A bit of linting 2023-07-03 21:06:24 +08:00
Matthew Raymer
c31445865e Straggler 2023-07-03 21:05:45 +08:00
Matthew Raymer
0af03227a6 Propagated AlertMessage component 2023-07-03 21:04:53 +08:00
Matthew Raymer
3c977a1f28 First roll out of an AlertMessage control 2023-07-03 20:24:23 +08:00
Matthew Raymer
8d8635a3e6 Added try...catch and linted 2023-07-03 19:44:41 +08:00
Matthew Raymer
bcc6de6fc0 New AlertMessage component 2023-07-03 19:40:53 +08:00
Matthew Raymer
99ea161da0 Removed created() and relocated to mounted() could not replicate issue 2023-07-03 18:48:01 +08:00
Matthew Raymer
3f6dbdebef Moved checkLimits inside try...catch since it has an identity check 2023-07-03 18:46:23 +08:00
Matthew Raymer
b139957e3e Added identity check 2023-07-03 18:44:42 +08:00
6e4f6d090a Merge pull request 'add project search (which just goes to console for now)' (#28) from search-projects into master
Reviewed-on: trent_larson/kick-starter-for-time-pwa#28
2023-07-02 20:21:35 -04:00
48227e8cf2 Merge branch 'master' into search-projects 2023-07-02 20:21:19 -04:00
09f02ca4b2 Merge pull request 'Quick links to record a gift, to this person or to a project' (#27) from give-to-project into master
Reviewed-on: trent_larson/kick-starter-for-time-pwa#27
2023-07-02 20:20:51 -04:00
9b3823ef0e Merge branch 'master' into give-to-project 2023-07-02 20:06:11 -04:00
cdeece1795 add project search (which just goes to console for now) 2023-07-02 07:55:45 -06:00
c2ebaa0a76 mark the give-to-project task as complete 2023-07-02 06:46:31 -06:00
3f60051599 Merge branch 'master' into give-to-project 2023-07-01 22:33:23 -06:00
a8f1e25986 add error messages for gives 2023-07-01 22:20:10 -06:00
964248e895 Update 'project.task.yaml' 2023-07-01 21:04:06 -04:00
a2b3cebdb3 finish contact selection for gives 2023-07-01 15:45:30 -06:00
bc6e52774c update tasks 2023-07-01 07:13:39 -06:00
643f777d10 start linking gives to projects 2023-07-01 07:07:46 -06:00
ec1d8404ca Merge pull request 'start a walk-through of the test' (#26) from scenarios into master
Reviewed-on: trent_larson/kick-starter-for-time-pwa#26
2023-07-01 08:12:55 -04:00
Jose Olarte III
1d6241abbb Various changes
- Loading animation in Projects view
- Per item icon + spacing fixes in Home view
2023-07-01 16:04:32 +08:00
c40b690878 fix load-project function 2023-06-28 20:28:14 -06:00
c9c81f1e5c fix wording in list of contacts, remove console.log 2023-06-28 20:20:06 -06:00
a94069e70a update tasks from previous conversation, marking milestone:2 done 2023-06-27 20:54:07 -06:00
Matthew Raymer
53f42e1ad3 Updates to fix merge and remove console.log 2023-06-27 20:07:38 +08:00
d9e9a7b740 start a walk-through 2023-06-26 20:00:23 -06:00
37 changed files with 2226 additions and 1739 deletions

View File

@@ -20,11 +20,6 @@ npm run build
npm run lint npm run lint
``` ```
### Clear data & restart
Clear cache for localhost, then go to http://localhost:8080/start
(because it'll generate a new one automatically if you start on the `/account` page).
### Test key contents ### Test key contents
See [this page](openssl_signing_console.rst) See [this page](openssl_signing_console.rst)
@@ -59,17 +54,35 @@ playing one of two ways:
### Create multiple identifiers ### Create multiple identifiers
Go to /import-account and import a new one. Then switch identifiers on the Go to /start and create or import a new one. Then switch identifiers on the bottom of the Your Identity page.
bottom of the Your Identity page.
### Create keys with alternate tools ### Create keys with alternate tools
See [this page](openssl_signing_console.rst) See [this page](openssl_signing_console.rst)
### Customize configuration ### Customize Vue configuration
See [Configuration Reference](https://cli.vuejs.org/config/). See [Configuration Reference](https://cli.vuejs.org/config/).
## Scenarios
- Create a new identity as prompted. Go to "Your Identity" screen and copy the ID to the clipboard.
- Go back to /start and import test User `did:ethr:0x000Ee5654b9742f6Fe18ea970e32b97ee2247B51` with this this seed phrase:
`seminar accuse mystery assist delay law thing deal image undo guard initial shallow wrestle list fragile borrow velvet tomorrow awake explain test offer control`
(Other test users are found [here](https://github.com/trentlarson/endorser-ch/blob/master/test/util.js).)
- Go to "Your Contacts" screen and add the ID you copied to the clipboard, and hit "+" to add them.
- Click on the "Registration Unknown" button and register that person to be able to make claims as them.
### Clear data & restart
Clear cache for localhost, then go to http://localhost:8080/start
(because it'll generate a new one automatically if you start on the `/account` page).
## Dependencies ## Dependencies
See https://tea.xyz See https://tea.xyz

950
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -21,15 +21,15 @@
"@veramo/did-provider-ethr": "^5.1.2", "@veramo/did-provider-ethr": "^5.1.2",
"@veramo/did-resolver": "^5.2.0", "@veramo/did-resolver": "^5.2.0",
"@veramo/key-manager": "^5.1.2", "@veramo/key-manager": "^5.1.2",
"@vueuse/core": "^10.2.0", "@vueuse/core": "^10.2.1",
"@zxing/text-encoding": "^0.9.0", "@zxing/text-encoding": "^0.9.0",
"axios": "^1.4.0", "axios": "^1.4.0",
"buffer": "^6.0.3", "buffer": "^6.0.3",
"class-transformer": "^0.5.1", "class-transformer": "^0.5.1",
"core-js": "^3.31.0", "core-js": "^3.31.1",
"dexie": "^3.2.4", "dexie": "^3.2.4",
"dexie-export-import": "^4.0.7", "dexie-export-import": "^4.0.7",
"did-jwt": "^7.2.2", "did-jwt": "^7.2.4",
"ethereum-cryptography": "^2.0.0", "ethereum-cryptography": "^2.0.0",
"ethereumjs-util": "^7.1.5", "ethereumjs-util": "^7.1.5",
"ethr-did-resolver": "^8.0.0", "ethr-did-resolver": "^8.0.0",
@@ -43,23 +43,22 @@
"pinia-plugin-persistedstate": "^3.1.0", "pinia-plugin-persistedstate": "^3.1.0",
"qr-code-generator-vue3": "^1.4.21", "qr-code-generator-vue3": "^1.4.21",
"ramda": "^0.29.0", "ramda": "^0.29.0",
"readable-stream": "^4.4.0", "readable-stream": "^4.4.2",
"reflect-metadata": "^0.1.13", "reflect-metadata": "^0.1.13",
"register-service-worker": "^1.7.2", "register-service-worker": "^1.7.2",
"three": "^0.153.0", "three": "^0.154.0",
"vue": "^3.3.4", "vue": "^3.3.4",
"vue-axios": "^3.5.2", "vue-axios": "^3.5.2",
"vue-class-component": "^8.0.0-0",
"vue-facing-decorator": "^2.1.20", "vue-facing-decorator": "^2.1.20",
"vue-property-decorator": "^9.1.2", "vue-property-decorator": "^9.1.2",
"vue-router": "^4.2.2", "vue-router": "^4.2.3",
"web-did-resolver": "^2.0.24" "web-did-resolver": "^2.0.27"
}, },
"devDependencies": { "devDependencies": {
"@types/ramda": "^0.29.2", "@types/ramda": "^0.29.3",
"@types/three": "^0.152.1", "@types/three": "^0.152.1",
"@typescript-eslint/eslint-plugin": "^5.60.0", "@typescript-eslint/eslint-plugin": "^5.61.0",
"@typescript-eslint/parser": "^5.60.0", "@typescript-eslint/parser": "^5.61.0",
"@vue/cli-plugin-babel": "~5.0.8", "@vue/cli-plugin-babel": "~5.0.8",
"@vue/cli-plugin-eslint": "~5.0.8", "@vue/cli-plugin-eslint": "~5.0.8",
"@vue/cli-plugin-pwa": "~5.0.8", "@vue/cli-plugin-pwa": "~5.0.8",
@@ -69,13 +68,13 @@
"@vue/cli-service": "~5.0.8", "@vue/cli-service": "~5.0.8",
"@vue/eslint-config-typescript": "^11.0.3", "@vue/eslint-config-typescript": "^11.0.3",
"autoprefixer": "^10.4.14", "autoprefixer": "^10.4.14",
"eslint": "^8.43.0", "eslint": "^8.44.0",
"eslint-config-prettier": "^8.8.0", "eslint-config-prettier": "^8.8.0",
"eslint-plugin-prettier": "^4.2.1", "eslint-plugin-prettier": "^5.0.0-alpha.1",
"eslint-plugin-vue": "^9.15.0", "eslint-plugin-vue": "^9.15.1",
"postcss": "^8.4.24", "postcss": "^8.4.24",
"prettier": "^2.8.8", "prettier": "^3.0.0",
"tailwindcss": "^3.3.2", "tailwindcss": "^3.3.2",
"typescript": "~5.1.3" "typescript": "~5.1.6"
} }
} }

View File

@@ -1,33 +1,29 @@
- top screens from img/screens.pdf milestone:2 : tasks:
- view all : - .5 audit all console.log calls
- add infinite scroll assignee:matthew - 01 design ideas for simple gives on the Home page
blocks: ref:https://raw.githubusercontent.com/trentlarson/lives-of-gifts/master/project.yaml#kickstarter%20for%20time - 01 add list of 'give' records for a project on ProjectView UI
- 02 Discover page - display results (currently in console.log) & link, spin when searching
- 08 search by location, endpoint, etc assignee:trent
- 01 add a location for a project via map pin (see API by clicking on "Nearby")
- 01 remove all the "form" fields (or at least investigate to see if that page refresh is desired)
- .2 change "errorMessage" to "alertMessage" on ProjectViewView.vue
- allow type annotations in World.js & landmarks.js (since we get this error - "Types are not supported by current JavaScript version") - 08 Scan QR code to import into contacts.
- replace user-affecting console.log & console.error with error messages (eg. catches)
- if there's no identity, handle it on pages which expect an identity (eg. project -- look for JSON.parse identity calls)
- 8 Move to vue-facing-decorator
- stats v1 :
- 01 show numeric stats
- 01 link to world for specific stats
- contacts v1 : - contacts v1 :
- 01 Import contact info a la QR code. - 01 Import contact info a la QR code.
- 01 Import all the non-sensitive data (ie. contacts & settings). - 01 Import all the non-sensitive data (ie. contacts & settings).
- .2 move all "identity" references to temporary account access - .2 move all "identity" references to temporary account access assignee:trent
- contacts v+ : - contacts v+ :
- .2 show error to user when adding a duplicate contact - .2 show error to user when adding a duplicate contact
- parse input more robustly (with CSV lib and not commas) - 01 parse input more robustly (with CSV lib and not commas)
- refactor UI : - refactor UI :
- .5 Alerts show at the top and can be missed, eg. account data download - .5 Alerts show at the top and can be missed, eg. account data download
- 01 Change alerts into a component (to cut down duplicate code)
- 01 Change "nav" tabs across the bottom into a component (eliminating duplicate code).
- .5 Fix how icons show on top of bottom bar on ContactAmounts page - .5 Fix how icons show on top of bottom bar on ContactAmounts page
- .2 Hide "Advanced" section in Account page by default
- show pop-up confirming that settings & contacts have been downloaded - show pop-up confirming that settings & contacts have been downloaded
@@ -38,7 +34,6 @@
- 01 quick action - send action, maybe choose via canvas tool https://github.com/konvajs/vue-konva - 01 quick action - send action, maybe choose via canvas tool https://github.com/konvajs/vue-konva
- .5 customize favicon - .5 customize favicon
- .5 make advanced features harder to access; advanced build?
- 04 allow user to download claims, mine + ones I can see about me from others - 04 allow user to download claims, mine + ones I can see about me from others
- 24 Move to Vite - 24 Move to Vite
@@ -46,15 +41,22 @@
- 40 notifications : - 40 notifications :
- push - push
- Discuss whether the remaining tasks are worthwhile before MVP release.
- 01 fix images on project page, on discovery page
- .2 fix "Rotary" and static icon to the right on project page
- stats v1 : - stats v1 :
- 01 show numeric stats - 01 show numeric stats
- 01 link to world for specific stats - 01 link to world for specific stats
- .5 don't load another instance of a bush if it already exists - .5 don't load another instance of a bush if it already exists
- maybe - allow type annotations in World.js & landmarks.js (since we get this error - "Types are not supported by current JavaScript version")
- 08 convert to cleaner implementation (maybe Drie -- https://github.com/janvorisek/drie)
- Do we want split first name & last name? - Do we want split first name & last name?
- remove 'about' page
- Release Minimum Viable Product : - Release Minimum Viable Product :
- 08 thorough testing for errors & edge cases
- Turn off stats-world or ensure it's usable (eg. cannot zoom out too far and lose world, cannot screenshot). - Turn off stats-world or ensure it's usable (eg. cannot zoom out too far and lose world, cannot screenshot).
- Add disclaimers. - Add disclaimers.
- Rename DB to TimeSafari. - Rename DB to TimeSafari.
@@ -62,10 +64,17 @@
- Deploy to a server. - Deploy to a server.
- Ensure public server has limits that work for group adoption. - Ensure public server has limits that work for group adoption.
- Test PWA features on Android and iOS. - Test PWA features on Android and iOS.
blocks: ref:https://raw.githubusercontent.com/trentlarson/lives-of-gifts/master/project.yaml#kickstarter%20for%20time
- 40 notifications v+ : - 40 notifications v+ :
- pull, w/ scheduled runs - pull, w/ scheduled runs
- linking between projects or plans :
- show total time given to & from a project
- terminology:
- for subtasks: fulfills (is it really the same?), feeds, contributes to, supplies, boosts, advances
- for blocking: blocks, precedes, comes before, is sought by -- vs follows, seeks, builds on ("contributes to" isn't specific enough, "succeeds" has different, possibly confusing meaning)
- Stats : - Stats :
- 01 point out user's location on the world - 01 point out user's location on the world
- 01 present a credential selected from the stats - 01 present a credential selected from the stats
@@ -74,11 +83,6 @@
- badge for amount given/offered to your project - badge for amount given/offered to your project
- set a goal of given/offers - set a goal of given/offers
- linking between projects or plans :
- terminology:
- Fulfills, Feeds, contributes to, supplies, boosts, advances
- Precedes, comes before, is sought by -- vs follows, seeks, builds on ("contributes to" isn't specific enough, "succeeds" has different, possibly confusing meaning)
- automated tests, eg. cypress - automated tests, eg. cypress
- Notifications (wake on the phone, push notifications) - Notifications (wake on the phone, push notifications)
@@ -89,10 +93,11 @@
- Peer DID - Peer DID
- DIDComm - DIDComm
- Write to or read from a different ledger (eg. private ACDC, attest.sh) - Write to or read from a different ledger (eg. private ACDC, attest.sh)
- v video for multiple identities https://youtu.be/p8L87AeD76w
- v video for adding time to contacts https://youtu.be/7Yylczevp10 log:
- videos for multiple identities https://youtu.be/p8L87AeD76w and for adding time to contacts https://youtu.be/7Yylczevp10 done:2023-03-29
- project lists, contact totals & actions, multiple identifiers, stats-world, activity feed, rename of this project file (use "--follow --") milestone:2 done:2023-06-27

View File

@@ -0,0 +1,47 @@
<template>
<div v-bind:class="computedAlertClassNames()">
<button
class="close-button bg-slate-200 w-8 leading-loose rounded-full absolute top-2 right-2"
@click="onClickClose()"
>
<fa icon="xmark"></fa>
</button>
<h4 class="font-bold pr-5">{{ alertTitle }}</h4>
<p>{{ alertMessage }}</p>
</div>
</template>
<script lang="ts">
import { Component, Prop, Vue } from "vue-facing-decorator";
@Component
export default class AlertMessage extends Vue {
@Prop alertTitle = "";
@Prop alertMessage = "";
isAlertVisible = this.alertMessage;
public onClickClose() {
this.isAlertVisible = false;
}
public computedAlertClassNames() {
return {
hidden: !this.isAlertVisible,
"dismissable-alert": true,
"bg-slate-100": true,
"p-5": true,
rounded: true,
"drop-shadow-lg": true,
fixed: true,
"top-3": true,
"inset-x-3": true,
"transition-transform": true,
"ease-in": true,
"duration-300": true,
};
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped></style>

View File

@@ -2,13 +2,12 @@
<div v-if="visible" class="dialog-overlay"> <div v-if="visible" class="dialog-overlay">
<div class="dialog"> <div class="dialog">
<h1 class="text-lg text-center"> <h1 class="text-lg text-center">
Received from {{ contact?.name || "nobody in particular" }} {{ message }} {{ giver?.name || "somebody not specified" }}
</h1> </h1>
<p class="py-2">{{ message }}</p>
<input <input
type="text" type="text"
class="block w-full rounded border border-slate-400 mb-4 px-3 py-2" class="block w-full rounded border border-slate-400 mb-4 px-3 py-2"
placeholder="What you received" placeholder="What was received"
v-model="description" v-model="description"
/> />
<div class="flex flex-row"> <div class="flex flex-row">
@@ -27,9 +26,10 @@
</div> </div>
</div> </div>
</div> </div>
<p class="text-right">Sign & Send to publish to the world</p>
<div class="text-right"> <div class="text-right">
<button class="rounded border border-slate-400" @click="confirm"> <button class="rounded border border-slate-400" @click="confirm">
<span class="m-2">Confirm</span> <span class="m-2">Sign & Send</span>
</button> </button>
&nbsp; &nbsp;
<button class="rounded border border-slate-400" @click="cancel"> <button class="rounded border border-slate-400" @click="cancel">
@@ -40,46 +40,59 @@
</div> </div>
</template> </template>
<script> <script lang="ts">
export default { import { Vue, Component, Prop, Emit } from "vue-facing-decorator";
props: ["message"],
data() { @Component
return { export default class GiftedDialog extends Vue {
contact: null, @Prop message = "";
description: "",
hours: "0", giver = null;
visible: false, description = "";
hours = "0";
visible = false;
open(giver) {
// giver: GiverInputInfo
this.giver = giver;
this.visible = true;
}
close() {
this.visible = false;
}
increment() {
this.hours = `${(parseFloat(this.hours) || 0) + 1}`;
}
decrement() {
this.hours = `${Math.max(0, (parseFloat(this.hours) || 1) - 1)}`;
}
@Emit("dialog-result")
confirm() {
const result = {
action: "confirm",
giver: this.giver,
hours: parseFloat(this.hours),
description: this.description,
}; };
}, this.close();
methods: { this.description = "";
open(contact) { this.giver = null;
this.contact = contact; this.hours = "0";
this.visible = true;
}, return result;
close() { }
this.visible = false;
}, @Emit("dialog-result")
increment() { cancel() {
this.hours = `${(parseFloat(this.hours) || 0) + 1}`; const result = { action: "cancel" };
}, this.close();
decrement() { return result;
this.hours = `${Math.max(0, (parseFloat(this.hours) || 1) - 1)}`; }
}, }
confirm() {
this.close();
this.$emit("dialog-result", {
action: "confirm",
contact: this.contact,
hours: parseFloat(this.hours),
description: this.description,
});
},
cancel() {
this.close();
this.$emit("dialog-result", { action: "cancel" });
},
},
};
</script> </script>
<style> <style>

View File

@@ -119,15 +119,11 @@
</template> </template>
<script lang="ts"> <script lang="ts">
import { Options, Vue } from "vue-class-component"; import { Component, Prop, Vue } from "vue-facing-decorator";
@Options({ @Component
props: {
msg: String,
},
})
export default class HelloWorld extends Vue { export default class HelloWorld extends Vue {
msg!: string; @Prop msg!: string;
} }
</script> </script>

View File

@@ -16,7 +16,6 @@ export default class InfiniteScroll extends Vue {
private isInitialRender = true; private isInitialRender = true;
updated() { updated() {
console.log("updated()");
if (!this.observer) { if (!this.observer) {
const options = { const options = {
root: null, root: null,
@@ -25,7 +24,7 @@ export default class InfiniteScroll extends Vue {
}; };
this.observer = new IntersectionObserver( this.observer = new IntersectionObserver(
this.handleIntersection, this.handleIntersection,
options options,
); );
this.observer.observe(this.$refs.sentinel as HTMLElement); this.observer.observe(this.$refs.sentinel as HTMLElement);
} }
@@ -40,23 +39,8 @@ export default class InfiniteScroll extends Vue {
@Emit("reached-bottom") @Emit("reached-bottom")
handleIntersection(entries: IntersectionObserverEntry[]) { handleIntersection(entries: IntersectionObserverEntry[]) {
console.log("handleIntersection");
const entry = entries[0]; const entry = entries[0];
if (entry.isIntersecting) { if (entry.isIntersecting) {
const distance = entry.boundingClientRect.top - entry.rootBounds.top;
console.log("distance: ", distance);
console.log("intersectionRatio", entry.intersectionRatio);
const sentinelPosition = (
this.$refs.sentinel as HTMLElement
).getBoundingClientRect();
// Access sentinel element's position properties
const sentinelTop = sentinelPosition.top;
console.log("sentinelTop", sentinelTop);
const scrollContainer = (
this.$refs.scrollContainer as HTMLElement
).getBoundingClientRect();
// Access scrollContainer properties or perform any necessary actions
console.log("scrollContainerTop", scrollContainer);
return true; return true;
} }
return false; return false;

View File

@@ -0,0 +1,93 @@
<template>
<!-- QUICK NAV -->
<nav id="QuickNav" class="fixed bottom-0 left-0 right-0 bg-slate-200 z-50">
<ul class="flex text-2xl p-2 gap-2">
<!-- Home Feed -->
<li
:class="{
'basis-1/5': true,
'rounded-md': true,
'bg-slate-400 text-white': selected === 'Home',
'text-slate-500': selected !== 'Home',
}"
>
<router-link :to="{ name: 'home' }" class="block text-center py-3 px-1">
<fa icon="house-chimney" class="fa-fw"></fa>
</router-link>
</li>
<!-- Search -->
<li
:class="{
'basis-1/5': true,
'rounded-md': true,
'bg-slate-400 text-white': selected === 'Discover',
'text-slate-500': selected !== 'Discover',
}"
>
<router-link
:to="{ name: 'discover' }"
class="block text-center py-3 px-1"
>
<fa icon="magnifying-glass" class="fa-fw"></fa>
</router-link>
</li>
<!-- Projects -->
<li
:class="{
'basis-1/5': true,
'rounded-md': true,
'bg-slate-400 text-white': selected === 'Projects',
'text-slate-500': selected !== 'Projects',
}"
>
<router-link
:to="{ name: 'projects' }"
class="block text-center py-3 px-1"
>
<fa icon="folder-open" class="fa-fw"></fa>
</router-link>
</li>
<!-- Contacts -->
<li
:class="{
'basis-1/5': true,
'rounded-md': true,
'bg-slate-400 text-white': selected === 'Contacts',
'text-slate-500': selected !== 'Contacts',
}"
>
<router-link
:to="{ name: 'contacts' }"
class="block text-center py-3 px-1"
>
<fa icon="users" class="fa-fw"></fa>
</router-link>
</li>
<!-- Profile -->
<li
:class="{
'basis-1/5': true,
'rounded-md': true,
'bg-slate-400 text-white': selected === 'Profile',
'text-slate-500': selected !== 'Profile',
}"
>
<router-link
:to="{ name: 'account' }"
class="block text-center py-3 px-1"
>
<fa icon="circle-user" class="fa-fw"></fa>
</router-link>
</li>
</ul>
</nav>
</template>
<script lang="ts">
import { Component, Vue, Prop } from "vue-facing-decorator";
@Component
export default class QuickNav extends Vue {
@Prop selected = "";
}
</script>

View File

@@ -5,7 +5,7 @@ function createCamera() {
35, // fov = Field Of View 35, // fov = Field Of View
1, // aspect ratio (dummy value) 1, // aspect ratio (dummy value)
0.1, // near clipping plane 0.1, // near clipping plane
350 // far clipping plane 350, // far clipping plane
); );
// move the camera back so we can view the scene // move the camera back so we can view the scene

View File

@@ -22,14 +22,16 @@ export async function loadLandmarks(vue, world, scene, loop) {
await accountsDB.open(); await accountsDB.open();
const accounts = await accountsDB.accounts.toArray(); const accounts = await accountsDB.accounts.toArray();
const account = R.find((acc) => acc.did === activeDid, accounts); const account = R.find((acc) => acc.did === activeDid, accounts);
const identity = JSON.parse(account?.identity || "undefined");
const token = await accessToken(identity);
const url = apiServer + "/api/v2/report/claims?claimType=GiveAction";
const headers = { const headers = {
"Content-Type": "application/json", "Content-Type": "application/json",
Authorization: "Bearer " + token,
}; };
const identity = JSON.parse(account?.identity || "null");
if (identity) {
const token = await accessToken(identity);
headers["Authorization"] = "Bearer " + token;
}
const url = apiServer + "/api/v2/report/claims?claimType=GiveAction";
const resp = await axios.get(url, { headers: headers }); const resp = await axios.get(url, { headers: headers });
if (resp.status === 200) { if (resp.status === 200) {
const landmarks = resp.data.data; const landmarks = resp.data.data;
@@ -60,7 +62,11 @@ export async function loadLandmarks(vue, world, scene, loop) {
// calculate positions for each claim, especially because some are random // calculate positions for each claim, especially because some are random
const locations = landmarks.map((claim) => const locations = landmarks.map((claim) =>
locForGive(claim, world.PLATFORM_SIZE, world.PLATFORM_EDGE_FOR_UNKNOWNS) locForGive(
claim,
world.PLATFORM_SIZE,
world.PLATFORM_EDGE_FOR_UNKNOWNS,
),
); );
// eslint-disable-next-line @typescript-eslint/no-this-alias // eslint-disable-next-line @typescript-eslint/no-this-alias
@@ -90,7 +96,7 @@ export async function loadLandmarks(vue, world, scene, loop) {
undefined, undefined,
function (error) { function (error) {
console.error(error); console.error(error);
} },
); );
// calculate when lights shine on appearing claim area // calculate when lights shine on appearing claim area
@@ -118,7 +124,7 @@ export async function loadLandmarks(vue, world, scene, loop) {
.onComplete(() => { .onComplete(() => {
scene.remove(light); scene.remove(light);
light.dispose(); light.dispose();
}) }),
) )
.start(); .start();
world.lights = [...world.lights, light]; world.lights = [...world.lights, light];
@@ -127,18 +133,18 @@ export async function loadLandmarks(vue, world, scene, loop) {
console.error( console.error(
"Got bad server response status & data of", "Got bad server response status & data of",
resp.status, resp.status,
resp.data resp.data,
); );
vue.setAlert( vue.setAlert(
"Error With Server", "Error With Server",
"There was an error retrieving your claims from the server." "There was an error retrieving your claims from the server.",
); );
} }
} catch (error) { } catch (error) {
console.error("Got exception contacting server:", error); console.error("Got exception contacting server:", error);
vue.setAlert( vue.setAlert(
"Error With Server", "Error With Server",
"There was a problem retrieving your claims from the server." "There was a problem retrieving your claims from the server.",
); );
} }
} }

View File

@@ -20,7 +20,7 @@ export const newIdentifier = (
address: string, address: string,
publicHex: string, publicHex: string,
privateHex: string, privateHex: string,
derivationPath: string derivationPath: string,
): Omit<IIdentifier, keyof "provider"> => { ): Omit<IIdentifier, keyof "provider"> => {
return { return {
did: DEFAULT_DID_PROVIDER_NAME + ":" + address, did: DEFAULT_DID_PROVIDER_NAME + ":" + address,
@@ -46,7 +46,7 @@ export const newIdentifier = (
* @return {*} {[string, string, string, string]} * @return {*} {[string, string, string, string]}
*/ */
export const deriveAddress = ( export const deriveAddress = (
mnemonic: string mnemonic: string,
): [string, string, string, string] => { ): [string, string, string, string] => {
const UPORT_ROOT_DERIVATION_PATH = "m/7696500'/0'/0'/0'"; const UPORT_ROOT_DERIVATION_PATH = "m/7696500'/0'/0'/0'";
mnemonic = mnemonic.trim().toLowerCase(); mnemonic = mnemonic.trim().toLowerCase();
@@ -134,7 +134,7 @@ export function fromJose(signature: string): {
const signatureBytes: Uint8Array = didJwt.base64ToBytes(signature); const signatureBytes: Uint8Array = didJwt.base64ToBytes(signature);
if (signatureBytes.length < 64 || signatureBytes.length > 65) { if (signatureBytes.length < 64 || signatureBytes.length > 65) {
throw new TypeError( throw new TypeError(
`Wrong size for signature. Expected 64 or 65 bytes, but got ${signatureBytes.length}` `Wrong size for signature. Expected 64 or 65 bytes, but got ${signatureBytes.length}`,
); );
} }
const r = bytesToHex(signatureBytes.slice(0, 32)); const r = bytesToHex(signatureBytes.slice(0, 32));

View File

@@ -3,6 +3,7 @@ import { IIdentifier } from "@veramo/core";
import { accessToken, SimpleSigner } from "@/libs/crypto"; import { accessToken, SimpleSigner } from "@/libs/crypto";
import * as didJwt from "did-jwt"; import * as didJwt from "did-jwt";
import { Axios, AxiosResponse } from "axios"; import { Axios, AxiosResponse } from "axios";
import { Contact } from "@/db/tables/contacts";
export const SCHEMA_ORG_CONTEXT = "https://schema.org"; export const SCHEMA_ORG_CONTEXT = "https://schema.org";
export const SERVICE_ID = "endorser.ch"; export const SERVICE_ID = "endorser.ch";
@@ -15,6 +16,11 @@ export interface AgreeVerifiableCredential {
object: Record<any, any>; object: Record<any, any>;
} }
export interface GiverInputInfo {
did?: string;
name?: string;
}
export interface ClaimResult { export interface ClaimResult {
success: { claimId: string; handleId: string }; success: { claimId: string; handleId: string };
error: { code: string; message: string }; error: { code: string; message: string };
@@ -46,6 +52,7 @@ export interface GiveVerifiableCredential {
"@type": string; "@type": string;
agent?: { identifier: string }; agent?: { identifier: string };
description?: string; description?: string;
fulfills?: { "@type": string; identifier: string };
identifier?: string; identifier?: string;
object?: { amountOfThisGood: number; unitCode: string }; object?: { amountOfThisGood: number; unitCode: string };
recipient: { identifier: string }; recipient: { identifier: string };
@@ -75,16 +82,19 @@ export function isHiddenDid(did) {
/** /**
always returns text, maybe UNNAMED_VISIBLE or UNKNOWN_ENTITY always returns text, maybe UNNAMED_VISIBLE or UNKNOWN_ENTITY
**/ **/
export function didInfo(did, identifiers, contacts) { export function didInfo(did, activeDid, identifiers, contacts) {
const myId = R.find((i) => i.did === did, identifiers); const myId: IIdentifier | undefined = R.find(
(i) => i.did === did,
identifiers,
);
if (myId) { if (myId) {
return "You"; return "You" + (myId.did !== activeDid ? " (Alt ID)" : "");
} else { } else {
const contact = R.find((c) => c.did === did, contacts); const contact: Contact | undefined = R.find((c) => c.did === did, contacts);
if (contact) { if (contact) {
return contact.name || "Someone Unnamed in Contacts"; return contact.name || "Someone Unnamed in Contacts";
} else if (!did) { } else if (!did) {
return "Unpecified Person"; return "Unspecified Person";
} else if (isHiddenDid(did)) { } else if (isHiddenDid(did)) {
return "Someone Not In Network"; return "Someone Not In Network";
} else { } else {
@@ -95,7 +105,7 @@ export function didInfo(did, identifiers, contacts) {
/** /**
* For result, see https://endorser.ch:3000/api-docs/#/claims/post_api_v2_claim * For result, see https://endorser.ch:3000/api-docs/#/claims/post_api_v2_claim
*
* @param identity * @param identity
* @param fromDid may be null * @param fromDid may be null
* @param toDid * @param toDid
@@ -109,7 +119,8 @@ export async function createAndSubmitGive(
fromDid: string, fromDid: string,
toDid: string, toDid: string,
description: string, description: string,
hours: number hours: number,
fulfillsProjectHandleId?: string,
): Promise<AxiosResponse<ClaimResult> | InternalError> { ): Promise<AxiosResponse<ClaimResult> | InternalError> {
// Make a claim // Make a claim
const vcClaim: GiveVerifiableCredential = { const vcClaim: GiveVerifiableCredential = {
@@ -126,6 +137,12 @@ export async function createAndSubmitGive(
if (hours) { if (hours) {
vcClaim.object = { amountOfThisGood: hours, unitCode: "HUR" }; vcClaim.object = { amountOfThisGood: hours, unitCode: "HUR" };
} }
if (fulfillsProjectHandleId) {
vcClaim.fulfills = {
"@type": "PlanAction",
identifier: fulfillsProjectHandleId,
};
}
// Make a payload for the claim // Make a payload for the claim
const vcPayload = { const vcPayload = {
vc: { vc: {

View File

@@ -81,7 +81,7 @@ function didProviderName(netName: string) {
const DEFAULT_DID_PROVIDER_NETWORK_NAME = "mainnet"; const DEFAULT_DID_PROVIDER_NETWORK_NAME = "mainnet";
export const DEFAULT_DID_PROVIDER_NAME = didProviderName( export const DEFAULT_DID_PROVIDER_NAME = didProviderName(
DEFAULT_DID_PROVIDER_NETWORK_NAME DEFAULT_DID_PROVIDER_NETWORK_NAME,
); );
export const HANDY_APP = false; export const HANDY_APP = false;

View File

@@ -17,6 +17,9 @@ import {
faCircleCheck, faCircleCheck,
faCircleQuestion, faCircleQuestion,
faCircleUser, faCircleUser,
faClock,
faCoins,
faComment,
faCopy, faCopy,
faEllipsisVertical, faEllipsisVertical,
faEye, faEye,
@@ -24,6 +27,7 @@ import {
faFileLines, faFileLines,
faFloppyDisk, faFloppyDisk,
faFolderOpen, faFolderOpen,
faGift,
faHand, faHand,
faHouseChimney, faHouseChimney,
faLongArrowAltLeft, faLongArrowAltLeft,
@@ -53,6 +57,9 @@ library.add(
faCircleCheck, faCircleCheck,
faCircleQuestion, faCircleQuestion,
faCircleUser, faCircleUser,
faClock,
faCoins,
faComment,
faCopy, faCopy,
faEllipsisVertical, faEllipsisVertical,
faEye, faEye,
@@ -60,6 +67,7 @@ library.add(
faFileLines, faFileLines,
faFloppyDisk, faFloppyDisk,
faFolderOpen, faFolderOpen,
faGift,
faHand, faHand,
faHouseChimney, faHouseChimney,
faLongArrowAltLeft, faLongArrowAltLeft,
@@ -78,7 +86,7 @@ library.add(
faTrashCan, faTrashCan,
faUser, faUser,
faUsers, faUsers,
faXmark faXmark,
); );
import { FontAwesomeIcon } from "@fortawesome/vue-fontawesome"; import { FontAwesomeIcon } from "@fortawesome/vue-fontawesome";

View File

@@ -7,7 +7,7 @@ if (process.env.NODE_ENV === "production") {
ready() { ready() {
console.log( console.log(
"App is being served from cache by a service worker.\n" + "App is being served from cache by a service worker.\n" +
"For more details, visit https://goo.gl/AFskqB" "For more details, visit https://goo.gl/AFskqB",
); );
}, },
registered() { registered() {
@@ -24,7 +24,7 @@ if (process.env.NODE_ENV === "production") {
}, },
offline() { offline() {
console.log( console.log(
"No internet connection found. App is running in offline mode." "No internet connection found. App is running in offline mode.",
); );
}, },
error(error) { error(error) {

View File

@@ -25,12 +25,6 @@ const routes: Array<RouteRecordRaw> = [
import(/* webpackChunkName: "home" */ "../views/HomeView.vue"), import(/* webpackChunkName: "home" */ "../views/HomeView.vue"),
beforeEnter: enterOrStart, beforeEnter: enterOrStart,
}, },
{
path: "/about",
name: "about",
component: () =>
import(/* webpackChunkName: "about" */ "../views/AboutView.vue"),
},
{ {
path: "/account", path: "/account",
name: "account", name: "account",

View File

@@ -1,14 +0,0 @@
<template>
<div class="about">
<h1>This is an about page</h1>
</div>
</template>
<script lang="ts">
import { Options, Vue } from "vue-class-component";
@Options({
components: {},
})
export default class AboutView extends Vue {}
</script>

View File

@@ -1,52 +1,5 @@
<template> <template>
<!-- QUICK NAV --> <QuickNav selected="Profile"></QuickNav>
<nav id="QuickNav" class="fixed bottom-0 left-0 right-0 bg-slate-200 z-50">
<ul class="flex text-2xl p-2 gap-2">
<!-- Home Feed -->
<li class="basis-1/5 rounded-md text-slate-500">
<router-link :to="{ name: 'home' }" class="block text-center py-3 px-1">
<fa icon="house-chimney" class="fa-fw"></fa>
</router-link>
</li>
<!-- Search -->
<li class="basis-1/5 rounded-md text-slate-500">
<router-link
:to="{ name: 'discover' }"
class="block text-center py-3 px-1"
>
<fa icon="magnifying-glass" class="fa-fw"></fa>
</router-link>
</li>
<!-- Projects -->
<li class="basis-1/5 rounded-md text-slate-500">
<router-link
:to="{ name: 'projects' }"
class="block text-center py-3 px-1"
>
<fa icon="folder-open" class="fa-fw"></fa>
</router-link>
</li>
<!-- Contacts -->
<li class="basis-1/5 rounded-md text-slate-500">
<router-link
:to="{ name: 'contacts' }"
class="block text-center py-3 px-1"
>
<fa icon="users" class="fa-fw"></fa>
</router-link>
</li>
<!-- Profile -->
<li class="basis-1/5 rounded-md bg-slate-400 text-white">
<router-link
:to="{ name: 'account' }"
class="block text-center py-3 px-1"
>
<fa icon="circle-user" class="fa-fw"></fa>
</router-link>
</li>
</ul>
</nav>
<!-- CONTENT --> <!-- CONTENT -->
<section id="Content" class="p-6 pb-24"> <section id="Content" class="p-6 pb-24">
<!-- Heading --> <!-- Heading -->
@@ -290,6 +243,11 @@
<div v-if="numAccounts > 0" class="flex py-2"> <div v-if="numAccounts > 0" class="flex py-2">
Switch Identifier Switch Identifier
<span>
<button class="text-blue-500 px-2" @click="switchAccount(0)">
None
</button>
</span>
<span v-for="accountNum in numAccounts" :key="accountNum"> <span v-for="accountNum in numAccounts" :key="accountNum">
<button class="text-blue-500 px-2" @click="switchAccount(accountNum)"> <button class="text-blue-500 px-2" @click="switchAccount(accountNum)">
#{{ accountNum }} #{{ accountNum }}
@@ -307,33 +265,26 @@
</router-link> </router-link>
</button> </button>
</div> </div>
<AlertMessage
<!-- This same popup code is in many files. --> :alertTitle="alertTitle"
<div v-bind:class="computedAlertClassNames()"> :alertMessage="alertMessage"
<button ></AlertMessage>
class="close-button bg-slate-200 w-8 leading-loose rounded-full absolute top-2 right-2"
@click="onClickClose()"
>
<fa icon="xmark"></fa>
</button>
<h4 class="font-bold pr-5">{{ alertTitle }}</h4>
<p>{{ alertMessage }}</p>
</div>
</section> </section>
</template> </template>
<script lang="ts"> <script lang="ts">
import "dexie-export-import"; import "dexie-export-import";
import * as R from "ramda";
import { Component, Vue } from "vue-facing-decorator"; import { Component, Vue } from "vue-facing-decorator";
import { useClipboard } from "@vueuse/core"; import { useClipboard } from "@vueuse/core";
import { AppString } from "@/constants/app"; import { AppString } from "@/constants/app";
import { db, accountsDB } from "@/db"; import { db, accountsDB } from "@/db";
import { AccountsSchema } from "@/db/tables/accounts";
import { MASTER_SETTINGS_KEY } from "@/db/tables/settings"; import { MASTER_SETTINGS_KEY } from "@/db/tables/settings";
import { accessToken } from "@/libs/crypto"; import { accessToken } from "@/libs/crypto";
import { AxiosError } from "axios/index"; import { AxiosError } from "axios/index";
import AlertMessage from "@/components/AlertMessage";
import QuickNav from "@/components/QuickNav";
// eslint-disable-next-line @typescript-eslint/no-var-requires // eslint-disable-next-line @typescript-eslint/no-var-requires
const Buffer = require("buffer/").Buffer; const Buffer = require("buffer/").Buffer;
@@ -347,7 +298,7 @@ interface RateLimits {
nextWeekBeginDateTime: string; nextWeekBeginDateTime: string;
} }
@Component @Component({ components: { AlertMessage, QuickNav } })
export default class AccountViewView extends Vue { export default class AccountViewView extends Vue {
Constants = AppString; Constants = AppString;
@@ -364,12 +315,38 @@ export default class AccountViewView extends Vue {
limitsMessage = ""; limitsMessage = "";
loadingLimits = true; // might as well now that we do it on mount, to avoid flashing the registration message loadingLimits = true; // might as well now that we do it on mount, to avoid flashing the registration message
showContactGives = false; showContactGives = false;
private accounts: AccountsSchema;
showDidCopy = false; showDidCopy = false;
showDerCopy = false; showDerCopy = false;
showB64Copy = false; showB64Copy = false;
showPubCopy = false; showPubCopy = false;
public async getIdentity(activeDid) {
await accountsDB.open();
const account = await accountsDB.accounts
.where("did")
.equals(activeDid)
.first();
const identity = JSON.parse(account?.identity || "null");
if (!identity) {
throw new Error(
"Attempted to load Give records with no identity available.",
);
}
return identity;
}
public async getHeaders(identity) {
const token = await accessToken(identity);
const headers = {
"Content-Type": "application/json",
Authorization: "Bearer " + token,
};
return headers;
}
// call fn, copy text to the clipboard, then redo fn after 2 seconds // call fn, copy text to the clipboard, then redo fn after 2 seconds
doCopyTwoSecRedo(text, fn) { doCopyTwoSecRedo(text, fn) {
fn(); fn();
@@ -387,7 +364,12 @@ export default class AccountViewView extends Vue {
return timeStr.substring(0, timeStr.indexOf("T")); return timeStr.substring(0, timeStr.indexOf("T"));
} }
// 'created' hook runs when the Vue instance is first created async beforeCreate() {
accountsDB.open();
this.accounts = accountsDB.accounts;
this.numAccounts = await this.accounts.count();
}
async created() { async created() {
// Uncomment this to register this user on the test server. // Uncomment this to register this user on the test server.
// To manage within the vue devtools browser extension https://devtools.vuejs.org/ // To manage within the vue devtools browser extension https://devtools.vuejs.org/
@@ -405,14 +387,8 @@ export default class AccountViewView extends Vue {
this.lastName = settings?.lastName || ""; this.lastName = settings?.lastName || "";
this.showContactGives = !!settings?.showContactGivesInline; this.showContactGives = !!settings?.showContactGivesInline;
await accountsDB.open(); const identity = await this.getIdentity(this.activeDid);
const accounts = await accountsDB.accounts.toArray();
this.numAccounts = accounts.length;
const account = R.find((acc) => acc.did === this.activeDid, accounts);
const identity = JSON.parse(account?.identity || "null");
if (!identity) {
throw new Error("No identity found.");
}
this.publicHex = identity.keys[0].publicKeyHex; this.publicHex = identity.keys[0].publicKeyHex;
this.publicBase64 = Buffer.from(this.publicHex, "hex").toString("base64"); this.publicBase64 = Buffer.from(this.publicHex, "hex").toString("base64");
this.derivationPath = identity.keys[0].meta.derivationPath; this.derivationPath = identity.keys[0].meta.derivationPath;
@@ -420,15 +396,24 @@ export default class AccountViewView extends Vue {
db.settings.update(MASTER_SETTINGS_KEY, { db.settings.update(MASTER_SETTINGS_KEY, {
activeDid: identity.did, activeDid: identity.did,
}); });
this.checkLimits();
} catch (err) { } catch (err) {
this.alertMessage = if (
"Clear your cache and start over (after data backup)."; err.message ===
console.error("Telling user to clear cache at page create because:", err); "Attempted to load account records with no identity available."
this.alertTitle = "Error Creating Account"; ) {
this.isAlertVisible = true; this.limitsMessage = "No identity.";
this.loadingLimits = false;
} else {
this.alertMessage =
"Clear your cache and start over (after data backup).";
console.error(
"Telling user to clear cache at page create because:",
err,
);
this.alertTitle = "Error Creating Account";
}
} }
this.checkLimits();
} }
public async updateShowContactAmounts() { public async updateShowContactAmounts() {
@@ -442,10 +427,9 @@ export default class AccountViewView extends Vue {
"Clear your cache and start over (after data backup)."; "Clear your cache and start over (after data backup).";
console.error( console.error(
"Telling user to clear cache after contact setting update because:", "Telling user to clear cache after contact setting update because:",
err err,
); );
this.alertTitle = "Error Updating Contact Setting"; this.alertTitle = "Error Updating Contact Setting";
this.isAlertVisible = true;
} }
} }
@@ -463,11 +447,9 @@ export default class AccountViewView extends Vue {
this.alertTitle = "Download Started"; this.alertTitle = "Download Started";
this.alertMessage = "See your downloads directory for the backup."; this.alertMessage = "See your downloads directory for the backup.";
this.isAlertVisible = true;
} catch (error) { } catch (error) {
this.alertTitle = "Export Error"; this.alertTitle = "Export Error";
this.alertMessage = "See console logs for more info."; this.alertMessage = "See console logs for more info.";
this.isAlertVisible = true;
console.error("Export Error:", error); console.error("Export Error:", error);
} }
} }
@@ -476,53 +458,62 @@ export default class AccountViewView extends Vue {
this.loadingLimits = true; this.loadingLimits = true;
this.limitsMessage = ""; this.limitsMessage = "";
const url = this.apiServer + "/api/report/rateLimits";
await accountsDB.open();
const accounts = await accountsDB.accounts.toArray();
const account = R.find((acc) => acc.did === this.activeDid, accounts);
const identity = JSON.parse(account?.identity || "null");
if (!identity) {
throw new Error("No identity found.");
}
const token = await accessToken(identity);
const headers = {
"Content-Type": "application/json",
Authorization: "Bearer " + token,
};
try { try {
const url = this.apiServer + "/api/report/rateLimits";
const identity = await this.getIdentity(this.activeDid);
const headers = await this.getHeaders(identity);
const resp = await this.axios.get(url, { headers }); const resp = await this.axios.get(url, { headers });
// axios throws an exception on a 400 // axios throws an exception on a 400
if (resp.status === 200) { if (resp.status === 200) {
this.limits = resp.data; this.limits = resp.data;
} }
} catch (error: unknown) { } catch (error: unknown) {
const serverError = error as AxiosError; if (
error.message ===
console.error("Bad response retrieving limits: ", serverError); "Attempted to load Give records with no identity available."
// Anybody know how to access items inside "response.data" without this? ) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any this.limitsMessage = "No identity.";
const data: any = serverError.response?.data; this.loadingLimits = false;
this.limitsMessage = data?.error?.message || "Bad server response."; } else {
const serverError = error as AxiosError;
console.error("Bad response retrieving limits: ", serverError);
// Anybody know how to access items inside "response.data" without this?
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const data: any = serverError.response?.data;
this.limitsMessage = data?.error?.message || "Bad server response.";
}
} }
this.loadingLimits = false; this.loadingLimits = false;
} }
async switchAccount(accountNum: number) { async switchAccount(accountNum: number) {
await accountsDB.open(); // 0 means none
const accounts = await accountsDB.accounts.toArray(); if (accountNum === 0) {
const account = accounts[accountNum - 1]; await db.open();
db.settings.update(MASTER_SETTINGS_KEY, {
activeDid: undefined,
});
this.activeDid = "";
this.derivationPath = "";
this.publicHex = "";
this.publicBase64 = "";
} else {
await accountsDB.open();
const accounts = await accountsDB.accounts.toArray();
const account = accounts[accountNum - 1];
await db.open(); await db.open();
db.settings.update(MASTER_SETTINGS_KEY, { db.settings.update(MASTER_SETTINGS_KEY, {
activeDid: account.did, activeDid: account.did,
}); });
this.activeDid = account.did; this.activeDid = account.did;
this.derivationPath = account.derivationPath; this.derivationPath = account.derivationPath;
this.publicHex = account.publicKeyHex; this.publicHex = account.publicKeyHex;
this.publicBase64 = Buffer.from(this.publicHex, "hex").toString("base64"); this.publicBase64 = Buffer.from(this.publicHex, "hex").toString("base64");
}
} }
public showContactGivesClassNames() { public showContactGivesClassNames() {
@@ -547,27 +538,5 @@ export default class AccountViewView extends Vue {
// This same popup code is in many files. // This same popup code is in many files.
alertMessage = ""; alertMessage = "";
alertTitle = ""; alertTitle = "";
isAlertVisible = false;
public onClickClose() {
this.isAlertVisible = false;
this.alertTitle = "";
this.alertMessage = "";
}
public computedAlertClassNames() {
return {
hidden: !this.isAlertVisible,
"dismissable-alert": true,
"bg-slate-100": true,
"p-5": true,
rounded: true,
"drop-shadow-lg": true,
fixed: true,
"top-3": true,
"inset-x-3": true,
"transition-transform": true,
"ease-in": true,
"duration-300": true,
};
}
} }
</script> </script>

View File

@@ -48,9 +48,9 @@
</template> </template>
<script lang="ts"> <script lang="ts">
import { Options, Vue } from "vue-class-component"; import { Component, Vue } from "vue-facing-decorator";
@Options({ @Component({
components: {}, components: {},
}) })
export default class ConfirmContactView extends Vue {} export default class ConfirmContactView extends Vue {}

View File

@@ -109,26 +109,19 @@
</div> </div>
</div> </div>
</div> </div>
<AlertMessage
<!-- This same popup code is in many files. --> :alertTitle="alertTitle"
<div v-bind:class="computedAlertClassNames()"> :alertMessage="alertMessage"
<button ></AlertMessage>
class="close-button bg-slate-200 w-8 leading-loose rounded-full absolute top-2 right-2"
@click="onClickClose()"
>
<fa icon="xmark"></fa>
</button>
<h4 class="font-bold pr-5">{{ alertTitle }}</h4>
<p>{{ alertMessage }}</p>
</div>
</section> </section>
</template> </template>
<script lang="ts"> <script lang="ts">
import * as R from "ramda"; import * as R from "ramda";
import { Options, Vue } from "vue-class-component";
import { Component, Vue } from "vue-facing-decorator";
import { accountsDB, db } from "@/db"; import { accountsDB, db } from "@/db";
import { AccountsSchema } from "@/db/tables/accounts";
import { Contact } from "@/db/tables/contacts"; import { Contact } from "@/db/tables/contacts";
import { MASTER_SETTINGS_KEY } from "@/db/tables/settings"; import { MASTER_SETTINGS_KEY } from "@/db/tables/settings";
import { accessToken, SimpleSigner } from "@/libs/crypto"; import { accessToken, SimpleSigner } from "@/libs/crypto";
@@ -140,43 +133,75 @@ import {
} from "@/libs/endorserServer"; } from "@/libs/endorserServer";
import * as didJwt from "did-jwt"; import * as didJwt from "did-jwt";
import { AxiosError } from "axios"; import { AxiosError } from "axios";
import AlertMessage from "@/components/AlertMessage";
@Options({}) @Component({ components: { AlertMessage } })
export default class ContactsView extends Vue { export default class ContactsView extends Vue {
activeDid = ""; activeDid = "";
apiServer = ""; apiServer = "";
contact: Contact | null = null; contact: Contact | null = null;
giveRecords: Array<GiveServerRecord> = []; giveRecords: Array<GiveServerRecord> = [];
alertTitle = "";
alertMessage = "";
accounts: AccountsSchema;
numAccounts = 0;
async beforeCreate() {
accountsDB.open();
this.accounts = accountsDB.accounts;
this.numAccounts = await this.accounts.count();
}
public async getIdentity(activeDid) {
await accountsDB.open();
const account = await accountsDB.accounts
.where("did")
.equals(activeDid)
.first();
const identity = JSON.parse(account?.identity || "null");
if (!identity) {
throw new Error(
"Attempted to load Give records with no identity available.",
);
}
return identity;
}
public async getHeaders(identity) {
const token = await accessToken(identity);
const headers = {
"Content-Type": "application/json",
Authorization: "Bearer " + token,
};
return headers;
}
// 'created' hook runs when the Vue instance is first created
async created() { async created() {
await db.open(); try {
const contactDid = this.$route.query.contactDid as string; await db.open();
this.contact = (await db.contacts.get(contactDid)) || null; const contactDid = this.$route.query.contactDid as string;
this.contact = (await db.contacts.get(contactDid)) || null;
const settings = await db.settings.get(MASTER_SETTINGS_KEY); const settings = await db.settings.get(MASTER_SETTINGS_KEY);
this.activeDid = settings?.activeDid || ""; this.activeDid = settings?.activeDid || "";
this.apiServer = settings?.apiServer || ""; this.apiServer = settings?.apiServer || "";
if (this.activeDid && this.contact) { if (this.activeDid && this.contact) {
this.loadGives(this.activeDid, this.contact); this.loadGives(this.activeDid, this.contact);
}
} catch (err) {
this.alertTitle = "Error";
this.alertMessage =
err.userMessage ||
"There was an error retrieving the latest sweet, sweet action.";
} }
} }
async loadGives(activeDid: string, contact: Contact) { async loadGives(activeDid: string, contact: Contact) {
// only load the private keys temporarily when needed
await accountsDB.open();
const accounts = await accountsDB.accounts.toArray();
const account = R.find((acc) => acc.did === activeDid, accounts);
const identity = JSON.parse(account?.identity || "null");
if (!identity) {
throw new Error("No identity found.");
}
// load all the time I have given to them
try { try {
const identity = await this.getIdentity(this.activeDid);
let result = []; let result = [];
const url = const url =
this.apiServer + this.apiServer +
"/api/v2/report/gives?agentDid=" + "/api/v2/report/gives?agentDid=" +
@@ -195,12 +220,11 @@ export default class ContactsView extends Vue {
console.error( console.error(
"Got bad response status & data of", "Got bad response status & data of",
resp.status, resp.status,
resp.data resp.data,
); );
this.alertTitle = "Error With Server"; this.alertTitle = "Error With Server";
this.alertMessage = this.alertMessage =
"Got an error retrieving your given time from the server."; "Got an error retrieving your given time from the server.";
this.isAlertVisible = true;
} }
const url2 = const url2 =
@@ -221,24 +245,22 @@ export default class ContactsView extends Vue {
console.error( console.error(
"Got bad response status & data of", "Got bad response status & data of",
resp2.status, resp2.status,
resp2.data resp2.data,
); );
this.alertTitle = "Error With Server"; this.alertTitle = "Error With Server";
this.alertMessage = this.alertMessage =
"Got an error retrieving your given time from the server."; "Got an error retrieving your given time from the server.";
this.isAlertVisible = true;
} }
const sortedResult: Array<GiveServerRecord> = R.sort( const sortedResult: Array<GiveServerRecord> = R.sort(
(a, b) => (a, b) =>
new Date(b.issuedAt).getTime() - new Date(a.issuedAt).getTime(), new Date(b.issuedAt).getTime() - new Date(a.issuedAt).getTime(),
result result,
); );
this.giveRecords = sortedResult; this.giveRecords = sortedResult;
} catch (error) { } catch (error) {
this.alertTitle = "Error With Server"; this.alertTitle = "Error With Server";
this.alertMessage = error as string; this.alertMessage = error as string;
this.isAlertVisible = true;
} }
} }
@@ -267,13 +289,7 @@ export default class ContactsView extends Vue {
}; };
// Create a signature using private key of identity // Create a signature using private key of identity
await accountsDB.open(); const identity = await this.getIdentity(this.activeDid);
const accounts = await accountsDB.accounts.toArray();
const account = R.find((acc) => acc.did === this.activeDid, accounts);
const identity = JSON.parse(account?.identity || "null");
if (!identity) {
throw new Error("No identity found.");
}
if (identity.keys[0].privateKeyHex !== null) { if (identity.keys[0].privateKeyHex !== null) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const privateKeyHex: string = identity.keys[0].privateKeyHex!; const privateKeyHex: string = identity.keys[0].privateKeyHex!;
@@ -316,7 +332,6 @@ export default class ContactsView extends Vue {
// Now set that error for the user to see. // Now set that error for the user to see.
this.alertTitle = "Error With Server"; this.alertTitle = "Error With Server";
this.alertMessage = userMessage; this.alertMessage = userMessage;
this.isAlertVisible = true;
} }
} }
} }
@@ -324,33 +339,6 @@ export default class ContactsView extends Vue {
cannotConfirmMessage() { cannotConfirmMessage() {
this.alertTitle = "Not Allowed"; this.alertTitle = "Not Allowed";
this.alertMessage = "Only the recipient can confirm final receipt."; this.alertMessage = "Only the recipient can confirm final receipt.";
this.isAlertVisible = true;
}
// This same popup code is in many files.
alertTitle = "";
alertMessage = "";
isAlertVisible = false;
public onClickClose() {
this.isAlertVisible = false;
this.alertTitle = "";
this.alertMessage = "";
}
public computedAlertClassNames() {
return {
hidden: !this.isAlertVisible,
"dismissable-alert": true,
"bg-slate-100": true,
"p-5": true,
rounded: true,
"drop-shadow-lg": true,
fixed: true,
"top-3": true,
"inset-x-3": true,
"transition-transform": true,
"ease-in": true,
"duration-300": true,
};
} }
} }
</script> </script>

View File

@@ -1,52 +1,5 @@
<template> <template>
<!-- QUICK NAV --> <QuickNav selected="Profile"></QuickNav>
<nav id="QuickNav" class="fixed bottom-0 left-0 right-0 bg-slate-200 z-50">
<ul class="flex text-2xl p-2 gap-2">
<!-- Home Feed -->
<li class="basis-1/5 rounded-md text-slate-500">
<router-link :to="{ name: 'home' }" class="block text-center py-3 px-1">
<fa icon="house-chimney" class="fa-fw"></fa>
</router-link>
</li>
<!-- Search -->
<li class="basis-1/5 rounded-md text-slate-500">
<router-link
:to="{ name: 'discover' }"
class="block text-center py-3 px-1"
>
<fa icon="magnifying-glass" class="fa-fw"></fa>
</router-link>
</li>
<!-- Projects -->
<li class="basis-1/5 rounded-md text-slate-500">
<router-link
:to="{ name: 'projects' }"
class="block text-center py-3 px-1"
>
<fa icon="folder-open" class="fa-fw"></fa>
</router-link>
</li>
<!-- Contacts -->
<li class="basis-1/5 rounded-md text-slate-500">
<router-link
:to="{ name: 'contacts' }"
class="block text-center py-3 px-1"
>
<fa icon="users" class="fa-fw"></fa>
</router-link>
</li>
<!-- Profile -->
<li class="basis-1/5 rounded-md bg-slate-400 text-white">
<router-link
:to="{ name: 'account' }"
class="block text-center py-3 px-1"
>
<fa icon="circle-user" class="fa-fw"></fa>
</router-link>
</li>
</ul>
</nav>
<!-- CONTENT --> <!-- CONTENT -->
<section id="Content" class="p-6 pb-24"> <section id="Content" class="p-6 pb-24">
<!-- Heading --> <!-- Heading -->
@@ -64,17 +17,10 @@
:dotsOptions="{ type: 'square' }" :dotsOptions="{ type: 'square' }"
class="flex justify-center" class="flex justify-center"
/> />
<AlertMessage
<!-- This same popup code is in many files. --> :alertTitle="alertTitle"
<div v-bind:class="computedAlertClassNames()"> :alertMessage="alertMessage"
<button ></AlertMessage>
class="close-button bg-slate-200 w-8 leading-loose rounded-full absolute top-2 right-2"
@click="onClickClose()"
>
<fa icon="xmark"></fa>
</button>
<p>{{ alertMessage }}</p>
</div>
</section> </section>
</template> </template>
@@ -86,6 +32,8 @@ import { MASTER_SETTINGS_KEY } from "@/db/tables/settings";
import * as R from "ramda"; import * as R from "ramda";
import { SimpleSigner } from "@/libs/crypto"; import { SimpleSigner } from "@/libs/crypto";
import * as didJwt from "did-jwt"; import * as didJwt from "did-jwt";
import AlertMessage from "@/components/AlertMessage";
import QuickNav from "@/components/QuickNav";
// eslint-disable-next-line @typescript-eslint/no-var-requires // eslint-disable-next-line @typescript-eslint/no-var-requires
const Buffer = require("buffer/").Buffer; const Buffer = require("buffer/").Buffer;
@@ -93,6 +41,8 @@ const Buffer = require("buffer/").Buffer;
@Component({ @Component({
components: { components: {
QRCodeVue3, QRCodeVue3,
AlertMessage,
QuickNav,
}, },
}) })
export default class ContactQRScanShow extends Vue { export default class ContactQRScanShow extends Vue {
@@ -100,7 +50,29 @@ export default class ContactQRScanShow extends Vue {
apiServer = ""; apiServer = "";
qrValue = ""; qrValue = "";
// 'created' hook runs when the Vue instance is first created public async getIdentity(activeDid) {
await accountsDB.open();
const accounts = await accountsDB.accounts.toArray();
const account = R.find((acc) => acc.did === activeDid, accounts);
const identity = JSON.parse(account?.identity || "null");
if (!identity) {
throw new Error(
"Attempted to load Give records with no identity available.",
);
}
return identity;
}
public async getHeaders(identity) {
const token = await accessToken(identity);
const headers = {
"Content-Type": "application/json",
Authorization: "Bearer " + token,
};
return headers;
}
async created() { async created() {
await db.open(); await db.open();
const settings = await db.settings.get(MASTER_SETTINGS_KEY); const settings = await db.settings.get(MASTER_SETTINGS_KEY);
@@ -113,11 +85,7 @@ export default class ContactQRScanShow extends Vue {
if (!account) { if (!account) {
this.alertMessage = "You have no identity yet."; this.alertMessage = "You have no identity yet.";
} else { } else {
const identity = JSON.parse(account?.identity || "null"); const identity = await this.getIdentity(this.activeDid);
if (!identity) {
throw new Error("No identity found.");
}
const publicKeyHex = identity.keys[0].publicKeyHex; const publicKeyHex = identity.keys[0].publicKeyHex;
const publicEncKey = Buffer.from(publicKeyHex, "hex").toString("base64"); const publicEncKey = Buffer.from(publicKeyHex, "hex").toString("base64");
const contactInfo = { const contactInfo = {
@@ -144,25 +112,7 @@ export default class ContactQRScanShow extends Vue {
} }
// This same popup code is in many files. // This same popup code is in many files.
alertTitle = "";
alertMessage = ""; alertMessage = "";
public onClickClose() {
this.alertMessage = "";
}
public computedAlertClassNames() {
return {
hidden: !this.alertMessage,
"dismissable-alert": true,
"bg-slate-100": true,
"p-5": true,
rounded: true,
"drop-shadow-lg": true,
fixed: true,
"top-3": true,
"inset-x-3": true,
"transition-transform": true,
"ease-in": true,
"duration-300": true,
};
}
} }
</script> </script>

View File

@@ -87,9 +87,9 @@
</template> </template>
<script lang="ts"> <script lang="ts">
import { Options, Vue } from "vue-class-component"; import { Component, Vue } from "vue-facing-decorator";
@Options({ @Component({
components: {}, components: {},
}) })
export default class ContactScanView extends Vue {} export default class ContactScanView extends Vue {}

View File

@@ -1,48 +1,5 @@
<template> <template>
<!-- QUICK NAV --> <QuickNav selected="Contacts"></QuickNav>
<nav id="QuickNav" class="fixed bottom-0 left-0 right-0 bg-slate-200 z-50">
<ul class="flex text-2xl p-2 gap-2">
<!-- Home Feed -->
<li class="basis-1/5 rounded-md text-slate-500">
<router-link :to="{ name: 'home' }" class="block text-center py-3 px-1"
><fa icon="house-chimney" class="fa-fw"></fa
></router-link>
</li>
<!-- Search -->
<li class="basis-1/5 rounded-md text-slate-500">
<router-link
:to="{ name: 'discover' }"
class="block text-center py-3 px-1"
><fa icon="magnifying-glass" class="fa-fw"></fa
></router-link>
</li>
<!-- Contacts -->
<li class="basis-1/5 rounded-md text-slate-500">
<router-link
:to="{ name: 'projects' }"
class="block text-center py-3 px-1"
><fa icon="folder-open" class="fa-fw"></fa
></router-link>
</li>
<!-- Contacts -->
<li class="basis-1/5 rounded-md bg-slate-400 text-white">
<router-link
:to="{ name: 'contacts' }"
class="block text-center py-3 px-1"
><fa icon="users" class="fa-fw"></fa
></router-link>
</li>
<!-- Profile -->
<li class="basis-1/5 rounded-md text-slate-500">
<router-link
:to="{ name: 'account' }"
class="block text-center py-3 px-1"
><fa icon="circle-user" class="fa-fw"></fa
></router-link>
</li>
</ul>
</nav>
<section id="Content" class="p-6 pb-24"> <section id="Content" class="p-6 pb-24">
<!-- Heading --> <!-- Heading -->
<h1 id="ViewHeading" class="text-4xl text-center font-light pt-4 mb-8"> <h1 id="ViewHeading" class="text-4xl text-center font-light pt-4 mb-8">
@@ -113,7 +70,7 @@
</div> </div>
<!-- Results List --> <!-- Results List -->
<ul class=""> <ul v-if="contacts.length > 0">
<li <li
class="border-b border-slate-300" class="border-b border-slate-300"
v-for="contact in contacts" v-for="contact in contacts"
@@ -230,19 +187,12 @@
</div> </div>
</li> </li>
</ul> </ul>
<p v-else>This identity has no contacts.</p>
<AlertMessage
:alertTitle="alertTitle"
:alertMessage="alertMessage"
></AlertMessage>
</section> </section>
<!-- This same popup code is in many files. -->
<div v-bind:class="computedAlertClassNames()">
<button
class="close-button bg-slate-200 w-8 leading-loose rounded-full absolute top-2 right-2"
@click="onClickClose()"
>
<fa icon="xmark"></fa>
</button>
<h4 class="font-bold pr-5">{{ alertTitle }}</h4>
<p>{{ alertMessage }}</p>
</div>
</template> </template>
<script lang="ts"> <script lang="ts">
@@ -250,24 +200,24 @@ import { AxiosError } from "axios";
import * as didJwt from "did-jwt"; import * as didJwt from "did-jwt";
import * as R from "ramda"; import * as R from "ramda";
import { IIdentifier } from "@veramo/core"; import { IIdentifier } from "@veramo/core";
import { Options, Vue } from "vue-class-component";
import { accountsDB, db } from "@/db"; import { accountsDB, db } from "@/db";
import { Contact } from "@/db/tables/contacts"; import { Contact } from "@/db/tables/contacts";
import { MASTER_SETTINGS_KEY } from "@/db/tables/settings"; import { MASTER_SETTINGS_KEY } from "@/db/tables/settings";
import { accessToken, SimpleSigner } from "@/libs/crypto"; import { accessToken, SimpleSigner } from "@/libs/crypto";
import { import {
GiveServerRecord,
GiveVerifiableCredential, GiveVerifiableCredential,
RegisterVerifiableCredential, RegisterVerifiableCredential,
SERVICE_ID, SERVICE_ID,
} from "@/libs/endorserServer"; } from "@/libs/endorserServer";
import { Component, Vue } from "vue-facing-decorator";
import AlertMessage from "@/components/AlertMessage";
import QuickNav from "@/components/QuickNav";
// eslint-disable-next-line @typescript-eslint/no-var-requires // eslint-disable-next-line @typescript-eslint/no-var-requires
const Buffer = require("buffer/").Buffer; const Buffer = require("buffer/").Buffer;
@Options({ @Component({
components: {}, components: { AlertMessage, QuickNav },
}) })
export default class ContactsView extends Vue { export default class ContactsView extends Vue {
activeDid = ""; activeDid = "";
@@ -291,8 +241,9 @@ export default class ContactsView extends Vue {
showGiveNumbers = false; showGiveNumbers = false;
showGiveTotals = true; showGiveTotals = true;
showGiveConfirmed = true; showGiveConfirmed = true;
alertTitle = "";
alertMessage = "";
// 'created' hook runs when the Vue instance is first created
async created() { async created() {
await db.open(); await db.open();
const settings = await db.settings.get(MASTER_SETTINGS_KEY); const settings = await db.settings.get(MASTER_SETTINGS_KEY);
@@ -306,130 +257,119 @@ export default class ContactsView extends Vue {
const allContacts = await db.contacts.toArray(); const allContacts = await db.contacts.toArray();
this.contacts = R.sort( this.contacts = R.sort(
(a: Contact, b) => (a.name || "").localeCompare(b.name || ""), (a: Contact, b) => (a.name || "").localeCompare(b.name || ""),
allContacts allContacts,
); );
} }
async loadGives() { public async getIdentity(activeDid) {
await accountsDB.open(); await accountsDB.open();
const accounts = await accountsDB.accounts.toArray(); const accounts = await accountsDB.accounts.toArray();
const account = R.find((acc) => acc.did === this.activeDid, accounts); const account = R.find((acc) => acc.did === activeDid, accounts);
const identity = JSON.parse(account?.identity || "null"); const identity = JSON.parse(account?.identity || "null");
if (!identity) { if (!identity) {
console.error( throw new Error(
"Attempted to load Give records with no identity available." "Attempted to load Give records with no identity available.",
); );
return;
} }
return identity;
}
public async getHeaders(identity) {
const token = await accessToken(identity);
const headers = {
"Content-Type": "application/json",
Authorization: "Bearer " + token,
};
return headers;
}
public async getHeadersAndIdentity(activeDid) {
const identity = await this.getIdentity(activeDid);
const headers = await this.getHeaders(identity);
return { headers, identity };
}
async loadGives() {
const handleResponse = (resp, descriptions, confirmed, unconfirmed) => {
if (resp.status === 200) {
const allData = resp.data.data;
for (const give of allData) {
if (give.unit === "HUR") {
if (give.amountConfirmed) {
const prevAmount = confirmed[give.agentDid] || 0;
confirmed[give.agentDid] = prevAmount + give.amount;
} else {
const prevAmount = unconfirmed[give.agentDid] || 0;
unconfirmed[give.agentDid] = prevAmount + give.amount;
}
if (!descriptions[give.agentDid] && give.description) {
descriptions[give.agentDid] = give.description;
}
}
}
} else {
console.error(
"Got bad response status & data of",
resp.status,
resp.data,
);
this.alertTitle = "Error With Server";
this.alertMessage =
"Got an error retrieving your " +
resp.config.url.includes("recipientDid")
? "received"
: "given" + " time from the server.";
}
};
// load all the time I have given
try { try {
const url = const { headers, identity } = await this.getHeadersAndIdentity(
this.activeDid,
);
const givenByUrl =
this.apiServer + this.apiServer +
"/api/v2/report/gives?agentDid=" + "/api/v2/report/gives?agentDid=" +
encodeURIComponent(identity.did); encodeURIComponent(identity.did);
const token = await accessToken(identity); const givenToUrl =
const headers = {
"Content-Type": "application/json",
Authorization: "Bearer " + token,
};
const resp = await this.axios.get(url, { headers });
//console.log("All gifts you've given:", resp.data);
if (resp.status === 200) {
const contactDescriptions: Record<string, string> = {};
const contactConfirmed: Record<string, number> = {};
const contactUnconfirmed: Record<string, number> = {};
const allData: Array<GiveServerRecord> = resp.data.data;
for (const give of allData) {
if (give.unit == "HUR") {
const recipDid: string = give.recipientDid;
if (give.amountConfirmed) {
const prevAmount = contactConfirmed[recipDid] || 0;
contactConfirmed[recipDid] = prevAmount + give.amount;
} else {
const prevAmount = contactUnconfirmed[recipDid] || 0;
contactUnconfirmed[recipDid] = prevAmount + give.amount;
}
if (!contactDescriptions[recipDid] && give.description) {
// Since many make the tooltip too big, we'll just use the latest.
contactDescriptions[recipDid] = give.description;
}
}
}
//console.log("Done retrieving gives", contactConfirmed);
this.givenByMeDescriptions = contactDescriptions;
this.givenByMeConfirmed = contactConfirmed;
this.givenByMeUnconfirmed = contactUnconfirmed;
} else {
console.error(
"Got bad response status & data of",
resp.status,
resp.data
);
this.alertTitle = "Error With Server";
this.alertMessage =
"Got an error retrieving your given time from the server.";
this.isAlertVisible = true;
}
} catch (error) {
this.alertTitle = "Error With Server";
this.alertMessage = error as string;
this.isAlertVisible = true;
}
// load all the time I have received
try {
const url =
this.apiServer + this.apiServer +
"/api/v2/report/gives?recipientDid=" + "/api/v2/report/gives?recipientDid=" +
encodeURIComponent(identity.did); encodeURIComponent(identity.did);
const token = await accessToken(identity);
const headers = { const [givenByMeResp, givenToMeResp] = await Promise.all([
"Content-Type": "application/json", this.axios.get(givenByUrl, { headers }),
Authorization: "Bearer " + token, this.axios.get(givenToUrl, { headers }),
}; ]);
const resp = await this.axios.get(url, { headers });
//console.log("All gifts you've recieved:", resp.data); const givenByMeDescriptions = {};
if (resp.status === 200) { const givenByMeConfirmed = {};
const contactDescriptions: Record<string, string> = {}; const givenByMeUnconfirmed = {};
const contactConfirmed: Record<string, number> = {}; handleResponse(
const contactUnconfirmed: Record<string, number> = {}; givenByMeResp,
const allData: Array<GiveServerRecord> = resp.data.data; givenByMeDescriptions,
for (const give of allData) { givenByMeConfirmed,
if (give.unit == "HUR") { givenByMeUnconfirmed,
if (give.amountConfirmed) { );
const prevAmount = contactConfirmed[give.agentDid] || 0; this.givenByMeDescriptions = givenByMeDescriptions;
contactConfirmed[give.agentDid] = prevAmount + give.amount; this.givenByMeConfirmed = givenByMeConfirmed;
} else { this.givenByMeUnconfirmed = givenByMeUnconfirmed;
const prevAmount = contactUnconfirmed[give.agentDid] || 0;
contactUnconfirmed[give.agentDid] = prevAmount + give.amount; const givenToMeDescriptions = {};
} const givenToMeConfirmed = {};
if (!contactDescriptions[give.agentDid] && give.description) { const givenToMeUnconfirmed = {};
// Since many make the tooltip too big, we'll just use the latest. handleResponse(
contactDescriptions[give.agentDid] = give.description; givenToMeResp,
} givenToMeDescriptions,
} givenToMeConfirmed,
} givenToMeUnconfirmed,
//console.log("Done retrieving receipts", contactConfirmed); );
this.givenToMeDescriptions = contactDescriptions; this.givenToMeDescriptions = givenToMeDescriptions;
this.givenToMeConfirmed = contactConfirmed; this.givenToMeConfirmed = givenToMeConfirmed;
this.givenToMeUnconfirmed = contactUnconfirmed; this.givenToMeUnconfirmed = givenToMeUnconfirmed;
} else {
console.error(
"Got bad response status & data of",
resp.status,
resp.data
);
this.alertTitle = "Error With Server";
this.alertMessage =
"Got an error retrieving your received time from the server.";
this.isAlertVisible = true;
}
} catch (error) { } catch (error) {
this.alertTitle = "Error With Server"; this.alertTitle = "Error With Server";
this.alertMessage = error as string; this.alertMessage = error as string;
this.isAlertVisible = true;
} }
} }
@@ -456,7 +396,7 @@ export default class ContactsView extends Vue {
const allContacts = this.contacts.concat([newContact]); const allContacts = this.contacts.concat([newContact]);
this.contacts = R.sort( this.contacts = R.sort(
(a: Contact, b) => (a.name || "").localeCompare(b.name || ""), (a: Contact, b) => (a.name || "").localeCompare(b.name || ""),
allContacts allContacts,
); );
} }
@@ -467,7 +407,7 @@ export default class ContactsView extends Vue {
this.nameForDid(this.contacts, contact.did) + this.nameForDid(this.contacts, contact.did) +
" with DID " + " with DID " +
contact.did + contact.did +
" ?" " ?",
) )
) { ) {
await db.open(); await db.open();
@@ -481,18 +421,11 @@ export default class ContactsView extends Vue {
confirm( confirm(
"Are you sure you want to use one of your registrations for " + "Are you sure you want to use one of your registrations for " +
this.nameForDid(this.contacts, contact.did) + this.nameForDid(this.contacts, contact.did) +
"?" "?",
) )
) { ) {
await accountsDB.open(); const identity = await this.getIdentity(this.activeDid);
const accounts = await accountsDB.accounts.toArray();
const account = R.find((acc) => acc.did === this.activeDid, accounts);
const identity = JSON.parse(account?.identity || "null");
if (!identity) {
throw new Error("No identity found.");
}
// Make a claim
const vcClaim: RegisterVerifiableCredential = { const vcClaim: RegisterVerifiableCredential = {
"@context": "https://schema.org", "@context": "https://schema.org",
"@type": "RegisterAction", "@type": "RegisterAction",
@@ -540,14 +473,12 @@ export default class ContactsView extends Vue {
message += " " + resp.data.success.embeddedRecordError; message += " " + resp.data.success.embeddedRecordError;
} }
this.alertMessage = message; this.alertMessage = message;
this.isAlertVisible = true;
} else if (resp.data?.success?.handleId) { } else if (resp.data?.success?.handleId) {
contact.registered = true; contact.registered = true;
db.contacts.update(contact.did, { registered: true }); db.contacts.update(contact.did, { registered: true });
this.alertTitle = "Registration Success"; this.alertTitle = "Registration Success";
this.alertMessage = contact.name + " has been registered."; this.alertMessage = contact.name + " has been registered.";
this.isAlertVisible = true;
} }
} catch (error) { } catch (error) {
let userMessage = "There was an error. See logs for more info."; let userMessage = "There was an error. See logs for more info.";
@@ -564,7 +495,6 @@ export default class ContactsView extends Vue {
// Now set that error for the user to see. // Now set that error for the user to see.
this.alertTitle = "Error With Server"; this.alertTitle = "Error With Server";
this.alertMessage = userMessage; this.alertMessage = userMessage;
this.isAlertVisible = true;
} }
} }
} }
@@ -575,19 +505,8 @@ export default class ContactsView extends Vue {
this.apiServer + this.apiServer +
"/api/report/" + "/api/report/" +
(visibility ? "canSeeMe" : "cannotSeeMe"); (visibility ? "canSeeMe" : "cannotSeeMe");
await accountsDB.open(); const identity = await this.getIdentity(this.activeDid);
const accounts = await accountsDB.accounts.toArray(); const headers = await this.getHeaders(identity);
const account = R.find((acc) => acc.did === this.activeDid, accounts);
const identity = JSON.parse(account?.identity || "null");
if (!identity) {
throw new Error("No identity found.");
}
const token = await accessToken(identity);
const headers = {
"Content-Type": "application/json",
Authorization: "Bearer " + token,
};
const payload = JSON.stringify({ did: contact.did }); const payload = JSON.stringify({ did: contact.did });
try { try {
@@ -603,12 +522,10 @@ export default class ContactsView extends Vue {
} else { } else {
this.alertMessage = "Bad server response of " + resp.status; this.alertMessage = "Bad server response of " + resp.status;
} }
this.isAlertVisible = true;
} }
} catch (err) { } catch (err) {
this.alertTitle = "Error With Server"; this.alertTitle = "Error With Server";
this.alertMessage = err as string; this.alertMessage = err as string;
this.isAlertVisible = true;
} }
} }
@@ -617,19 +534,6 @@ export default class ContactsView extends Vue {
this.apiServer + this.apiServer +
"/api/report/canDidExplicitlySeeMe?did=" + "/api/report/canDidExplicitlySeeMe?did=" +
encodeURIComponent(contact.did); encodeURIComponent(contact.did);
await accountsDB.open();
const accounts = await accountsDB.accounts.toArray();
const account = R.find((acc) => acc.did === this.activeDid, accounts);
const identity = JSON.parse(account?.identity || "null");
if (!identity) {
throw new Error("No identity found.");
}
const token = await accessToken(identity);
const headers = {
"Content-Type": "application/json",
Authorization: "Bearer " + token,
};
try { try {
const resp = await this.axios.get(url, { headers }); const resp = await this.axios.get(url, { headers });
@@ -644,7 +548,6 @@ export default class ContactsView extends Vue {
" can " + " can " +
(visibility ? "" : "not ") + (visibility ? "" : "not ") +
"see your activity."; "see your activity.";
this.isAlertVisible = true;
} else { } else {
this.alertTitle = "Error With Server"; this.alertTitle = "Error With Server";
if (resp.data.error?.message) { if (resp.data.error?.message) {
@@ -652,12 +555,10 @@ export default class ContactsView extends Vue {
} else { } else {
this.alertMessage = "Bad server response of " + resp.status; this.alertMessage = "Bad server response of " + resp.status;
} }
this.isAlertVisible = true;
} }
} catch (err) { } catch (err) {
this.alertTitle = "Error With Server"; this.alertTitle = "Error With Server";
this.alertMessage = err as string; this.alertMessage = err as string;
this.isAlertVisible = true;
} }
} }
@@ -677,13 +578,7 @@ export default class ContactsView extends Vue {
} }
async onClickAddGive(fromDid: string, toDid: string): Promise<void> { async onClickAddGive(fromDid: string, toDid: string): Promise<void> {
await accountsDB.open(); const identity = await this.getIdentity(this.activeDid);
const accounts = await accountsDB.accounts.toArray();
const account = R.find((acc) => acc.did === this.activeDid, accounts);
const identity = JSON.parse(account?.identity || "null");
if (!identity) {
throw new Error("No identity found.");
}
// if they have unconfirmed amounts, ask to confirm those first // if they have unconfirmed amounts, ask to confirm those first
if (toDid == identity?.did && this.givenToMeUnconfirmed[fromDid] > 0) { if (toDid == identity?.did && this.givenToMeUnconfirmed[fromDid] > 0) {
@@ -692,7 +587,7 @@ export default class ContactsView extends Vue {
"There are " + "There are " +
this.givenToMeUnconfirmed[fromDid] + this.givenToMeUnconfirmed[fromDid] +
" unconfirmed hours from them." + " unconfirmed hours from them." +
" Would you like to confirm some of those hours?" " Would you like to confirm some of those hours?",
) )
) { ) {
this.$router.push({ this.$router.push({
@@ -705,15 +600,12 @@ export default class ContactsView extends Vue {
this.alertTitle = "Input Error"; this.alertTitle = "Input Error";
this.alertMessage = this.alertMessage =
"This is not a valid number of hours: " + this.hourInput; "This is not a valid number of hours: " + this.hourInput;
this.isAlertVisible = true;
} else if (!parseFloat(this.hourInput)) { } else if (!parseFloat(this.hourInput)) {
this.alertTitle = "Input Error"; this.alertTitle = "Input Error";
this.alertMessage = "Giving 0 hours does nothing."; this.alertMessage = "Giving 0 hours does nothing.";
this.isAlertVisible = true;
} else if (!identity) { } else if (!identity) {
this.alertTitle = "Status Error"; this.alertTitle = "Status Error";
this.alertMessage = "No identity is available."; this.alertMessage = "No identity is available.";
this.isAlertVisible = true;
} else { } else {
// ask to confirm amount // ask to confirm amount
let toFrom; let toFrom;
@@ -735,7 +627,7 @@ export default class ContactsView extends Vue {
" hours " + " hours " +
toFrom + toFrom +
description + description +
"?" "?",
) )
) { ) {
this.createAndSubmitGive( this.createAndSubmitGive(
@@ -743,7 +635,7 @@ export default class ContactsView extends Vue {
fromDid, fromDid,
toDid, toDid,
parseFloat(this.hourInput), parseFloat(this.hourInput),
this.hourDescriptionInput this.hourDescriptionInput,
); );
} }
} }
@@ -754,7 +646,7 @@ export default class ContactsView extends Vue {
fromDid: string, fromDid: string,
toDid: string, toDid: string,
amount: number, amount: number,
description: string description: string,
): Promise<void> { ): Promise<void> {
// Make a claim // Make a claim
const vcClaim: GiveVerifiableCredential = { const vcClaim: GiveVerifiableCredential = {
@@ -804,7 +696,7 @@ export default class ContactsView extends Vue {
if (resp.data?.success?.handleId) { if (resp.data?.success?.handleId) {
this.alertTitle = "Done"; this.alertTitle = "Done";
this.alertMessage = "Successfully logged time to the server."; this.alertMessage = "Successfully logged time to the server.";
this.isAlertVisible = true;
if (fromDid === identity.did) { if (fromDid === identity.did) {
const newList = R.clone(this.givenByMeUnconfirmed); const newList = R.clone(this.givenByMeUnconfirmed);
newList[toDid] = (newList[toDid] || 0) + amount; newList[toDid] = (newList[toDid] || 0) + amount;
@@ -830,7 +722,6 @@ export default class ContactsView extends Vue {
// Now set that error for the user to see. // Now set that error for the user to see.
this.alertTitle = "Error With Server"; this.alertTitle = "Error With Server";
this.alertMessage = userMessage; this.alertMessage = userMessage;
this.isAlertVisible = true;
} }
} }
} }
@@ -848,32 +739,6 @@ export default class ContactsView extends Vue {
} }
} }
// This same popup code is in many files.
alertTitle = "";
alertMessage = "";
isAlertVisible = false;
public onClickClose() {
this.isAlertVisible = false;
this.alertTitle = "";
this.alertMessage = "";
}
public computedAlertClassNames() {
return {
hidden: !this.isAlertVisible,
"dismissable-alert": true,
"bg-slate-100": true,
"p-5": true,
rounded: true,
"drop-shadow-lg": true,
fixed: true,
"top-3": true,
"inset-x-3": true,
"transition-transform": true,
"ease-in": true,
"duration-300": true,
};
}
public showGiveAmountsClassNames() { public showGiveAmountsClassNames() {
return { return {
"bg-slate-500": this.showGiveTotals, "bg-slate-500": this.showGiveTotals,

View File

@@ -1,47 +1,5 @@
<template> <template>
<!-- QUICK NAV --> <QuickNav selected="Discover"></QuickNav>
<nav id="QuickNav" class="fixed bottom-0 left-0 right-0 bg-slate-200 z-50">
<ul class="flex text-2xl p-2 gap-2">
<!-- Home Feed -->
<li class="basis-1/5 rounded-md text-slate-500">
<router-link :to="{ name: 'home' }" class="block text-center py-3 px-1"
><fa icon="house-chimney" class="fa-fw"></fa
></router-link>
</li>
<!-- Search -->
<li class="basis-1/5 rounded-md bg-slate-400 text-white">
<router-link
:to="{ name: 'discover' }"
class="block text-center py-3 px-1"
><fa icon="magnifying-glass" class="fa-fw"></fa
></router-link>
</li>
<!-- Projects -->
<li class="basis-1/5 rounded-md text-slate-500">
<router-link
:to="{ name: 'projects' }"
class="block text-center py-3 px-1"
><fa icon="folder-open" class="fa-fw"></fa
></router-link>
</li>
<!-- Contacts -->
<li class="basis-1/5 rounded-md text-slate-500">
<router-link
:to="{ name: 'contacts' }"
class="block text-center py-3 px-1"
><fa icon="users" class="fa-fw"></fa
></router-link>
</li>
<!-- Profile -->
<li class="basis-1/5 rounded-md text-slate-500">
<router-link
:to="{ name: 'account' }"
class="block text-center py-3 px-1"
><fa icon="circle-user" class="fa-fw"></fa
></router-link>
</li>
</ul>
</nav>
<!-- CONTENT --> <!-- CONTENT -->
<section id="Content" class="p-6 pb-24"> <section id="Content" class="p-6 pb-24">
@@ -51,18 +9,20 @@
</h1> </h1>
<!-- Quick Search --> <!-- Quick Search -->
<form id="QuickSearch" class="mb-4 flex"> <div id="QuickSearch" class="mb-4 flex" v-on:keyup.enter="search()">
<input <input
type="text" type="text"
v-model="searchTerms"
placeholder="Search…" placeholder="Search…"
class="block w-full rounded-l border border-r-0 border-slate-400 px-3 py-2" class="block w-full rounded-l border border-r-0 border-slate-400 px-3 py-2"
/> />
<button <button
@click="search()"
class="px-4 rounded-r bg-slate-200 border border-l-0 border-slate-400" class="px-4 rounded-r bg-slate-200 border border-l-0 border-slate-400"
> >
<fa icon="magnifying-glass" class="fa-fw"></fa> <fa icon="magnifying-glass" class="fa-fw"></fa>
</button> </button>
</form> </div>
<!-- Result Tabs --> <!-- Result Tabs -->
<div class="text-center text-slate-500 border-b border-slate-300"> <div class="text-center text-slate-500 border-b border-slate-300">
@@ -70,6 +30,7 @@
<li> <li>
<a <a
href="#" href="#"
@click="searchLocal()"
class="inline-block py-3 rounded-t-lg border-b-2 active text-blue-600 border-blue-600 font-semibold" class="inline-block py-3 rounded-t-lg border-b-2 active text-blue-600 border-blue-600 font-semibold"
> >
Nearby Nearby
@@ -97,7 +58,14 @@
<!-- Results List --> <!-- Results List -->
<ul class=""> <ul class="">
<li class="border-b border-slate-300"> <li class="border-b border-slate-300">
<a href="project-view.html" class="block py-4 flex gap-4"> <a
@click="
onClickLoadProject(
'https://endorser.ch/entity/01H3HER4DTNCR6ZC4VXA3VPWVQ',
)
"
class="block py-4 flex gap-4"
>
<div class="w-12"> <div class="w-12">
<img <img
src="https://picsum.photos/200/200?random=1" src="https://picsum.photos/200/200?random=1"
@@ -115,7 +83,14 @@
</li> </li>
<li class="border-b border-slate-300"> <li class="border-b border-slate-300">
<a href="project-view.html" class="block py-4 flex gap-4"> <a
@click="
onClickLoadProject(
'https://endorser.ch/entity/01H3HER4DTNCR6ZC4VXA3VPWVQ',
)
"
class="block py-4 flex gap-4"
>
<div class="w-12"> <div class="w-12">
<img <img
src="https://picsum.photos/200/200?random=2" src="https://picsum.photos/200/200?random=2"
@@ -133,7 +108,14 @@
</li> </li>
<li class="border-b border-slate-300"> <li class="border-b border-slate-300">
<a href="project-view.html" class="block py-4 flex gap-4"> <a
@click="
onClickLoadProject(
'https://endorser.ch/entity/01H3HER4DTNCR6ZC4VXA3VPWVQ',
)
"
class="block py-4 flex gap-4"
>
<div class="w-12"> <div class="w-12">
<img <img
src="https://picsum.photos/200/200?random=3" src="https://picsum.photos/200/200?random=3"
@@ -151,14 +133,145 @@
</a> </a>
</li> </li>
</ul> </ul>
<AlertMessage
:alertTitle="alertTitle"
:alertMessage="alertMessage"
></AlertMessage>
</section> </section>
</template> </template>
<script lang="ts"> <script lang="ts">
import { Options, Vue } from "vue-class-component"; import { Component, Vue } from "vue-facing-decorator";
@Options({ import { accountsDB, db } from "@/db";
components: {}, import { MASTER_SETTINGS_KEY } from "@/db/tables/settings";
import { accessToken } from "@/libs/crypto";
import AlertMessage from "@/components/AlertMessage";
import QuickNav from "@/components/QuickNav";
@Component({
components: { AlertMessage, QuickNav },
}) })
export default class DiscoverView extends Vue {} export default class DiscoverView extends Vue {
activeDid = "";
apiServer = "";
searchTerms = "";
alertMessage = "";
alertTitle = "";
async mounted() {
await db.open();
const settings = await db.settings.get(MASTER_SETTINGS_KEY);
this.activeDid = settings?.activeDid || "";
this.apiServer = settings?.apiServer || "";
}
public async buildHeaders() {
const headers = { "Content-Type": "application/json" };
if (this.activeDid) {
await accountsDB.open();
const allAccounts = await accountsDB.accounts.toArray();
const account = allAccounts.find((acc) => acc.did === this.activeDid);
const identity = JSON.parse(account?.identity || "null");
if (!identity) {
throw new Error(
"An ID is chosen but there are no keys for it so it cannot be used to talk with the service.",
);
}
headers["Authorization"] = "Bearer " + (await accessToken(identity));
} else {
// it's OK without auth... we just won't get any identifiers
}
return headers;
}
public async search() {
const claimContents =
"claimContents=" + encodeURIComponent(this.searchTerms);
const claimType = "claimType=PlanAction";
const queryParams = [claimContents, claimType].join("&");
try {
const response = await fetch(
this.apiServer + "/api/v2/report/claims?" + queryParams,
{
method: "GET",
headers: await this.buildHeaders(),
},
);
if (response.status !== 200) {
const details = await response.text();
throw details;
}
const results = await response.json();
if (results.data) {
console.log("Plans found in that search:", results.data);
} else {
throw JSON.stringify(results);
}
} catch (e) {
console.log("Error with feed load:", e);
this.alertMessage =
e.userMessage || "There was an error retrieving projects.";
this.alertTitle = "Error";
}
}
public async searchLocal() {
const claimContents =
"claimContents=" + encodeURIComponent(this.searchTerms);
const queryParams = [
claimContents,
"minLocLat=40.901000",
"maxLocLat=40.904000",
"westLocLon=-111.914000",
"eastLocLon=-111.909000",
].join("&");
try {
const response = await fetch(
this.apiServer + "/api/v2/report/plansByLocation?" + queryParams,
{
method: "GET",
headers: await this.buildHeaders(),
},
);
if (response.status !== 200) {
throw await response.text();
}
const results = await response.json();
if (results.data) {
console.log("Plans found in that location:", results.data);
} else {
throw JSON.stringify(results);
}
} catch (e) {
console.log("Error with feed load:", e);
this.alertMessage =
e.userMessage || "There was an error retrieving projects.";
this.alertTitle = "Error";
}
}
/**
* Handle clicking on a project entry found in the list
* @param id of the project
**/
onClickLoadProject(id: string) {
localStorage.setItem("projectId", id);
const route = {
name: "project",
};
this.$router.push(route);
}
}
</script> </script>

View File

@@ -1,52 +1,5 @@
<template> <template>
<!-- QUICK NAV --> <QuickNav selected="Profile"></QuickNav>
<nav id="QuickNav" class="fixed bottom-0 left-0 right-0 bg-slate-200 z-50">
<ul class="flex text-2xl p-2 gap-2">
<!-- Home Feed -->
<li class="basis-1/5 rounded-md text-slate-500">
<router-link :to="{ name: 'home' }" class="block text-center py-3 px-1">
<fa icon="house-chimney" class="fa-fw"></fa>
</router-link>
</li>
<!-- Search -->
<li class="basis-1/5 rounded-md text-slate-500">
<router-link
:to="{ name: 'discover' }"
class="block text-center py-3 px-1"
>
<fa icon="magnifying-glass" class="fa-fw"></fa>
</router-link>
</li>
<!-- Projects -->
<li class="basis-1/5 rounded-md text-slate-500">
<router-link
:to="{ name: 'projects' }"
class="block text-center py-3 px-1"
>
<fa icon="folder-open" class="fa-fw"></fa>
</router-link>
</li>
<!-- Contacts -->
<li class="basis-1/5 rounded-md text-slate-500">
<router-link
:to="{ name: 'contacts' }"
class="block text-center py-3 px-1"
>
<fa icon="users" class="fa-fw"></fa>
</router-link>
</li>
<!-- Profile -->
<li class="basis-1/5 rounded-md text-slate-400">
<router-link
:to="{ name: 'account' }"
class="block text-center py-3 px-1"
>
<fa icon="circle-user" class="fa-fw"></fa>
</router-link>
</li>
</ul>
</nav>
<!-- CONTENT --> <!-- CONTENT -->
<section id="Content" class="p-6 pb-24"> <section id="Content" class="p-6 pb-24">
<!-- Heading --> <!-- Heading -->
@@ -228,8 +181,9 @@
<script lang="ts"> <script lang="ts">
import * as Package from "../../package.json"; import * as Package from "../../package.json";
import { Component, Vue } from "vue-facing-decorator"; import { Component, Vue } from "vue-facing-decorator";
import QuickNav from "@/components/QuickNav";
@Component @Component({ components: { QuickNav } })
export default class Help extends Vue { export default class Help extends Vue {
package = Package; package = Package;
} }

View File

@@ -1,69 +1,27 @@
<template> <template>
<!-- QUICK NAV --> <QuickNav selected="Home"></QuickNav>
<nav id="QuickNav" class="fixed bottom-0 left-0 right-0 bg-slate-200 z-50">
<ul class="flex text-2xl p-2 gap-2">
<!-- Home Feed -->
<li class="basis-1/5 rounded-md bg-slate-400 text-white">
<router-link :to="{ name: 'home' }" class="block text-center py-3 px-1"
><fa icon="house-chimney" class="fa-fw"></fa
></router-link>
</li>
<!-- Search -->
<li class="basis-1/5 rounded-md text-slate-500">
<router-link
:to="{ name: 'discover' }"
class="block text-center py-3 px-1"
><fa icon="magnifying-glass" class="fa-fw"></fa
></router-link>
</li>
<!-- Projects -->
<li class="basis-1/5 rounded-md text-slate-500">
<router-link
:to="{ name: 'projects' }"
class="block text-center py-3 px-1"
><fa icon="folder-open" class="fa-fw"></fa
></router-link>
</li>
<!-- Contacts -->
<li class="basis-1/5 rounded-md text-slate-500">
<router-link
:to="{ name: 'contacts' }"
class="block text-center py-3 px-1"
><fa icon="users" class="fa-fw"></fa
></router-link>
</li>
<!-- Profile -->
<li class="basis-1/5 rounded-md text-slate-500">
<router-link
:to="{ name: 'account' }"
class="block text-center py-3 px-1"
><fa icon="circle-user" class="fa-fw"></fa
></router-link>
</li>
</ul>
</nav>
<!-- CONTENT --> <!-- CONTENT -->
<section id="Content" class="p-6 pb-24"> <section id="Content" class="p-6 pb-24">
<h1 id="ViewHeading" class="text-4xl text-center font-light pt-4 mb-8"> <h1 id="ViewHeading" class="text-4xl text-center font-light pt-4 mb-8">
Time Safari Time Safari
</h1> </h1>
<div> <div class="mb-8">
<h1 class="text-2xl">Quick Action</h1> <h1 class="text-2xl">Quick Action</h1>
<p>Choose a contact to whom to show appreciation:</p> <p>Choose a contact to whom to show appreciation:</p>
<!-- similar contact selection code is in multiple places -->
<div class="px-4"> <div class="px-4">
<button <button
v-for="contact in allContacts" v-for="contact in allContacts"
:key="contact.did" :key="contact.did"
@click="openDialog(contact)" @click="openDialog(contact)"
class="text-blue-500" class="block w-full text-center text-md uppercase bg-slate-500 text-white px-1.5 py-2 rounded-md mb-2"
> >
&nbsp;{{ contact.name }}, {{ contact.name || "(no name)" }}
</button> </button>
or <span v-if="allContacts.length > 0">&nbsp;or&nbsp;</span>
<button @click="openDialog()" class="text-blue-500"> <button @click="openDialog()" class="text-blue-500">
nobody in particular someone not specified
</button> </button>
</div> </div>
</div> </div>
@@ -71,61 +29,61 @@
<GiftedDialog <GiftedDialog
ref="customDialog" ref="customDialog"
@dialog-result="handleDialogResult" @dialog-result="handleDialogResult"
message="Confirm to publish to the world." message="Received from"
> >
</GiftedDialog> </GiftedDialog>
<div class="py-4"> <div>
<h1 class="text-2xl">Latest Activity</h1> <h1 class="text-2xl">Latest Activity</h1>
<span :class="{ hidden: isHiddenSpinner }"> <span :class="{ hidden: isHiddenSpinner }">
<fa icon="spinner" class="fa-fw"></fa> <fa icon="spinner" class="fa-spin-pulse"></fa>
Loading&hellip; Loading&hellip;
</span> </span>
<ul class=""> <ul>
<li <li
class="border-b border-slate-300" class="border-b border-slate-300 py-2"
v-for="record in feedData" v-for="record in feedData"
:key="record.jwtId" :key="record.jwtId"
> >
<div <div
class="border-b text-orange-400 px-8 py-4" class="border-b border-dashed border-slate-400 text-orange-400 py-2 mb-2 font-bold uppercase text-sm"
v-if="record.jwtId == feedLastViewedId" v-if="record.jwtId == feedLastViewedId"
> >
You've seen all claims below. You've seen all claims below:
</div>
<div class="flex">
<fa
icon="gift"
class="fa-fw flex-none pt-1 pr-2 text-slate-500"
></fa>
<!-- icon values: "coins" = money; "clock" = time; "gift" = others -->
<span class="">{{ this.giveDescription(record) }}</span>
</div> </div>
{{ this.giveDescription(record) }}
</li> </li>
</ul> </ul>
</div> </div>
<AlertMessage
:alertTitle="alertTitle"
:alertMessage="alertMessage"
></AlertMessage>
</section> </section>
<!-- This same popup code is in many files. -->
<div v-bind:class="computedAlertClassNames()">
<button
class="close-button bg-slate-200 w-8 leading-loose rounded-full absolute top-2 right-2"
@click="onClickClose()"
>
<fa icon="xmark"></fa>
</button>
<h4 class="font-bold pr-5">{{ alertTitle }}</h4>
<p>{{ alertMessage }}</p>
</div>
</template> </template>
<script lang="ts"> <script lang="ts">
import * as R from "ramda"; import { Component, Vue } from "vue-facing-decorator";
import { Options, Vue } from "vue-class-component";
import GiftedDialog from "@/components/GiftedDialog.vue"; import GiftedDialog from "@/components/GiftedDialog.vue";
import { db, accountsDB } from "@/db"; import { db, accountsDB } from "@/db";
import { AccountsSchema } from "@/db/tables/accounts";
import { MASTER_SETTINGS_KEY } from "@/db/tables/settings"; import { MASTER_SETTINGS_KEY } from "@/db/tables/settings";
import { accessToken } from "@/libs/crypto"; import { accessToken } from "@/libs/crypto";
import { createAndSubmitGive, didInfo } from "@/libs/endorserServer"; import { createAndSubmitGive, didInfo } from "@/libs/endorserServer";
import { Account } from "@/db/tables/accounts"; import { Account } from "@/db/tables/accounts";
import { Contact } from "@/db/tables/contacts"; import { Contact } from "@/db/tables/contacts";
import AlertMessage from "@/components/AlertMessage";
import QuickNav from "@/components/QuickNav";
@Options({ @Component({
components: { GiftedDialog }, components: { GiftedDialog, AlertMessage, QuickNav },
}) })
export default class HomeView extends Vue { export default class HomeView extends Vue {
activeDid = ""; activeDid = "";
@@ -137,28 +95,54 @@ export default class HomeView extends Vue {
feedPreviousOldestId = null; feedPreviousOldestId = null;
feedLastViewedId = null; feedLastViewedId = null;
isHiddenSpinner = true; isHiddenSpinner = true;
alertTitle = "";
alertMessage = "";
accounts: AccountsSchema;
numAccounts = 0;
// 'created' hook runs when the Vue instance is first created async beforeCreate() {
async created() { accountsDB.open();
await accountsDB.open(); this.accounts = accountsDB.accounts;
this.allAccounts = await accountsDB.accounts.toArray(); this.numAccounts = await this.accounts.count();
await db.open();
const settings = await db.settings.get(MASTER_SETTINGS_KEY);
this.activeDid = settings?.activeDid || "";
this.allContacts = await db.contacts.toArray();
this.feedLastViewedId = settings?.lastViewedClaimId;
} }
// 'mounted' hook runs after initial render public async getIdentity(activeDid) {
async mounted() { await accountsDB.open();
const account = await accountsDB.accounts
.where("did")
.equals(activeDid)
.first();
const identity = JSON.parse(account?.identity || "null");
if (!identity) {
throw new Error(
"Attempted to load Give records with no identity available.",
);
}
return identity;
}
public async getHeaders(identity) {
const token = await accessToken(identity);
const headers = {
"Content-Type": "application/json",
Authorization: "Bearer " + token,
};
return headers;
}
async created() {
try { try {
await accountsDB.open();
this.allAccounts = await accountsDB.accounts.toArray();
await db.open(); await db.open();
const settings = await db.settings.get(MASTER_SETTINGS_KEY); const settings = await db.settings.get(MASTER_SETTINGS_KEY);
this.apiServer = settings?.apiServer || ""; this.apiServer = settings?.apiServer || "";
this.activeDid = settings?.activeDid || "";
this.allContacts = await db.contacts.toArray();
this.feedLastViewedId = settings?.lastViewedClaimId;
this.updateAllFeed(); this.updateAllFeed();
} catch (err) { } catch (err) {
console.log("Error in mounted():", err);
this.alertTitle = "Error"; this.alertTitle = "Error";
this.alertMessage = this.alertMessage =
err.userMessage || err.userMessage ||
@@ -166,14 +150,34 @@ export default class HomeView extends Vue {
} }
} }
updateAllFeed = async () => { public async buildHeaders() {
this.isHiddenSpinner = false; const headers = { "Content-Type": "application/json" };
if (this.activeDid) {
await accountsDB.open();
const allAccounts = await accountsDB.accounts.toArray();
const account = allAccounts.find((acc) => acc.did === this.activeDid);
const identity = JSON.parse(account?.identity || "null");
if (!identity) {
throw new Error(
"An ID is chosen but there are no keys for it so it cannot be used to talk with the service.",
);
}
headers["Authorization"] = "Bearer " + (await accessToken(identity));
} else {
// it's OK without auth... we just won't get any identifiers
}
return headers;
}
public async updateAllFeed() {
this.isHiddenSpinner = false;
await this.retrieveClaims(this.apiServer, null, this.feedPreviousOldestId) await this.retrieveClaims(this.apiServer, null, this.feedPreviousOldestId)
.then(async (results) => { .then(async (results) => {
if (results.data.length > 0) { if (results.data.length > 0) {
this.feedData = this.feedData.concat(results.data); this.feedData = this.feedData.concat(results.data);
//console.log("Feed data:", this.feedData);
this.feedAllLoaded = results.hitLimit; this.feedAllLoaded = results.hitLimit;
this.feedPreviousOldestId = this.feedPreviousOldestId =
results.data[results.data.length - 1].jwtId; results.data[results.data.length - 1].jwtId;
@@ -181,7 +185,6 @@ export default class HomeView extends Vue {
this.feedLastViewedId == null || this.feedLastViewedId == null ||
this.feedLastViewedId < results.data[0].jwtId this.feedLastViewedId < results.data[0].jwtId
) { ) {
// save it to storage
await db.open(); await db.open();
db.settings.update(MASTER_SETTINGS_KEY, { db.settings.update(MASTER_SETTINGS_KEY, {
lastViewedClaimId: results.data[0].jwtId, lastViewedClaimId: results.data[0].jwtId,
@@ -194,68 +197,63 @@ export default class HomeView extends Vue {
console.log("Error with feed load:", e); console.log("Error with feed load:", e);
this.alertMessage = this.alertMessage =
e.userMessage || "There was an error retrieving feed data."; e.userMessage || "There was an error retrieving feed data.";
this.alertTitle = "Error";
}); });
this.isHiddenSpinner = true; this.isHiddenSpinner = true;
}; }
retrieveClaims = async (endorserApiServer, identifier, beforeId) => { public async retrieveClaims(endorserApiServer, identifier, beforeId) {
//const afterQuery = afterId == null ? "" : "&afterId=" + afterId;
const beforeQuery = beforeId == null ? "" : "&beforeId=" + beforeId; const beforeQuery = beforeId == null ? "" : "&beforeId=" + beforeId;
const headers = { "Content-Type": "application/json" }; const response = await fetch(
if (this.activeDid) { endorserApiServer + "/api/v2/report/gives?" + beforeQuery,
const account = R.find( {
(acc) => acc.did === this.activeDid, method: "GET",
this.allAccounts headers: await this.buildHeaders(),
); },
//console.log("about to parse from", this.activeDid, account?.identity); );
const identity = JSON.parse(account?.identity || "null");
if (!identity) { if (response.status !== 200) {
throw new Error("No identity found."); throw await response.text();
}
const token = await accessToken(identity);
headers["Authorization"] = "Bearer " + token;
} else {
// it's OK without auth... we just won't get any identifiers
} }
return fetch(this.apiServer + "/api/v2/report/gives?" + beforeQuery, {
method: "GET", const results = await response.json();
headers: headers,
}) if (results.data) {
.then(async (response) => { return results;
if (response.status !== 200) { } else {
const details = await response.text(); throw JSON.stringify(results);
throw details; }
} }
return response.json();
})
.then((results) => {
if (results.data) {
return results;
} else {
throw JSON.stringify(results);
}
});
};
giveDescription(giveRecord) { giveDescription(giveRecord) {
let claim = giveRecord.fullClaim; let claim = giveRecord.fullClaim;
if (claim.claim) { if (claim.claim) {
// it's probably a Verified Credential
claim = claim.claim; claim = claim.claim;
} }
// agent.did is for legacy data, before March 2023 // agent.did is for legacy data, before March 2023
const giver = const giverDid =
claim.agent?.identifier || claim.agent?.did || giveRecord.issuer; claim.agent?.identifier || claim.agent?.did || giveRecord.issuer;
const giverInfo = didInfo(giver, this.allAccounts, this.allContacts); const giverInfo = didInfo(
giverDid,
this.activeDid,
this.allAccounts,
this.allContacts,
);
const gaveAmount = claim.object?.amountOfThisGood const gaveAmount = claim.object?.amountOfThisGood
? this.displayAmount(claim.object.unitCode, claim.object.amountOfThisGood) ? this.displayAmount(claim.object.unitCode, claim.object.amountOfThisGood)
: claim.description || "something unknown"; : claim.description || "something unknown";
// recipient.did is for legacy data, before March 2023 // recipient.did is for legacy data, before March 2023
const gaveRecipientId = claim.recipient?.identifier || claim.recipient?.did; const gaveRecipientId = claim.recipient?.identifier || claim.recipient?.did;
const gaveRecipientInfo = gaveRecipientId const gaveRecipientInfo = gaveRecipientId
? " to " + didInfo(gaveRecipientId, this.allAccounts, this.allContacts) ? " to " +
didInfo(
gaveRecipientId,
this.activeDid,
this.allAccounts,
this.allContacts,
)
: ""; : "";
return giverInfo + " gave " + gaveAmount + gaveRecipientInfo; return giverInfo + " gave " + gaveAmount + gaveRecipientInfo;
} }
@@ -268,13 +266,14 @@ export default class HomeView extends Vue {
return unitCode === "HUR" ? (single ? "hour" : "hours") : unitCode; return unitCode === "HUR" ? (single ? "hour" : "hours") : unitCode;
} }
openDialog(contact) { openDialog(giver) {
this.$refs.customDialog.open(contact); this.$refs.customDialog.open(giver);
} }
handleDialogResult(result) { handleDialogResult(result) {
if (result.action === "confirm") { if (result.action === "confirm") {
return new Promise((resolve) => { return new Promise((resolve) => {
this.recordGive(result.contact, result.description, result.hours); this.recordGive(result.contact?.did, result.description, result.hours);
resolve(); resolve();
}); });
} else { } else {
@@ -284,77 +283,75 @@ export default class HomeView extends Vue {
/** /**
* *
* @param contact may be null * @param giverDid may be null
* @param description may be an empty string * @param description may be an empty string
* @param hours may be 0 * @param hours may be 0
*/ */
recordGive(contact, description, hours) { public async recordGive(giverDid, description, hours) {
if (this.activeDid == null) { if (!this.activeDid) {
this.alertTitle = "Error"; this.setAlert(
this.alertMessage = "Error",
"You must select an identity before you can record a give."; "You must select an identity before you can record a give.",
);
return; return;
} }
const account = R.find(
(acc) => acc.did === this.activeDid, if (!description && !hours) {
this.allAccounts this.setAlert(
); "Error",
//console.log("about to parse from", this.activeDid, account?.identity); "You must enter a description or some number of hours.",
const identity = JSON.parse(account?.identity || "null"); );
if (!identity) { return;
throw new Error("No identity found."); }
try {
const identity = await this.getIdentity(this.activeDid);
const result = await createAndSubmitGive(
this.axios,
this.apiServer,
identity,
giverDid,
this.activeDid,
description,
hours,
);
if (isGiveCreationError(result)) {
const errorMessage = getGiveCreationErrorMessage(result);
console.log("Error with give result:", result);
this.setAlert(
"Error",
errorMessage || "There was an error recording the give.",
);
} else {
this.setAlert("Success", "That gift was recorded.");
}
} catch (error) {
console.log("Error with give caught:", error);
this.setAlert(
"Error",
getGiveErrorMessage(error) || "There was an error recording the give.",
);
} }
createAndSubmitGive(
this.axios,
this.apiServer,
identity,
contact?.did,
this.activeDid,
description,
hours
)
.then((result) => {
if (result.status != 201 || result.data?.error) {
console.log("Error with give result:", result);
this.alertTitle = "Error";
this.alertMessage =
result.data?.message || "There was an error recording the give.";
} else {
this.alertTitle = "Success";
this.alertMessage = "That gift was recorded.";
//this.updateAllFeed(); // full update is overkill but we should show something
}
})
.catch((e) => {
console.log("Error with give caught:", e);
this.alertTitle = "Error";
this.alertMessage =
e.userMessage || "There was an error recording the give.";
});
} }
// This same popup code is in many files. private setAlert(title, message) {
alertMessage = ""; this.alertTitle = title;
alertTitle = ""; this.alertMessage = message;
public onClickClose() {
this.alertTitle = "";
this.alertMessage = "";
} }
public computedAlertClassNames() {
return { // Helper functions for readability
hidden: !this.alertMessage,
"dismissable-alert": true, isGiveCreationError(result) {
"bg-slate-100": true, return result.status !== 201 || result.data?.error;
"p-5": true, }
rounded: true,
"drop-shadow-lg": true, getGiveCreationErrorMessage(result) {
fixed: true, return result.data?.error?.message;
"top-3": true, }
"inset-x-3": true,
"transition-transform": true, getGiveErrorMessage(error) {
"ease-in": true, return error.userMessage || error.response?.data?.error?.message;
"duration-300": true,
};
} }
} }
</script> </script>

View File

@@ -43,12 +43,12 @@
</template> </template>
<script lang="ts"> <script lang="ts">
import { Options, Vue } from "vue-class-component"; import { Component, Vue } from "vue-facing-decorator";
import { deriveAddress, newIdentifier } from "../libs/crypto"; import { deriveAddress, newIdentifier } from "../libs/crypto";
import { accountsDB, db } from "@/db"; import { accountsDB, db } from "@/db";
import { MASTER_SETTINGS_KEY } from "@/db/tables/settings"; import { MASTER_SETTINGS_KEY } from "@/db/tables/settings";
@Options({ @Component({
components: {}, components: {},
}) })
export default class ImportAccountView extends Vue { export default class ImportAccountView extends Vue {
@@ -72,7 +72,7 @@ export default class ImportAccountView extends Vue {
this.address, this.address,
this.publicHex, this.publicHex,
this.privateHex, this.privateHex,
this.derivationPath this.derivationPath,
); );
try { try {

View File

@@ -49,11 +49,11 @@
</template> </template>
<script lang="ts"> <script lang="ts">
import { Options, Vue } from "vue-class-component"; import { Component, Vue } from "vue-facing-decorator";
import { db } from "@/db"; import { db } from "@/db";
import { MASTER_SETTINGS_KEY } from "@/db/tables/settings"; import { MASTER_SETTINGS_KEY } from "@/db/tables/settings";
@Options({ @Component({
components: {}, components: {},
}) })
export default class NewEditAccountView extends Vue { export default class NewEditAccountView extends Vue {

View File

@@ -61,9 +61,9 @@
</template> </template>
<script lang="ts"> <script lang="ts">
import { Options, Vue } from "vue-class-component"; import { Component, Vue } from "vue-facing-decorator";
@Options({ @Component({
components: {}, components: {},
}) })
export default class NewEditCommitmentView extends Vue {} export default class NewEditCommitmentView extends Vue {}

View File

@@ -63,32 +63,25 @@
Cancel Cancel
</button> </button>
</div> </div>
<AlertMessage
:alertTitle="alertTitle"
:alertMessage="alertMessage"
></AlertMessage>
</section> </section>
<!-- This same popup code is in many files. -->
<div v-bind:class="computedAlertClassNames()">
<button
class="close-button bg-slate-200 w-8 leading-loose rounded-full absolute top-2 right-2"
@click="onClickClose()"
>
<fa icon="xmark"></fa>
</button>
<h4 class="font-bold pr-5">{{ alertTitle }}</h4>
<p>{{ alertMessage }}</p>
</div>
</template> </template>
<script lang="ts"> <script lang="ts">
import { AxiosError } from "axios"; import { AxiosError } from "axios";
import * as didJwt from "did-jwt"; import * as didJwt from "did-jwt";
import * as R from "ramda"; import { Component, Vue } from "vue-facing-decorator";
import { Options, Vue } from "vue-class-component";
import { accountsDB, db } from "@/db"; import { accountsDB, db } from "@/db";
import { AccountsSchema } from "@/db/tables/accounts";
import { MASTER_SETTINGS_KEY } from "@/db/tables/settings"; import { MASTER_SETTINGS_KEY } from "@/db/tables/settings";
import { accessToken, SimpleSigner } from "@/libs/crypto"; import { accessToken, SimpleSigner } from "@/libs/crypto";
import { useAppStore } from "@/store/app"; import { useAppStore } from "@/store/app";
import { IIdentifier } from "@veramo/core"; import { IIdentifier } from "@veramo/core";
import AlertMessage from "@/components/AlertMessage";
interface VerifiableCredential { interface VerifiableCredential {
"@context": string; "@context": string;
@@ -98,8 +91,8 @@ interface VerifiableCredential {
identifier?: string; identifier?: string;
} }
@Options({ @Component({
components: {}, components: { AlertMessage },
}) })
export default class NewEditProjectView extends Vue { export default class NewEditProjectView extends Vue {
activeDid = ""; activeDid = "";
@@ -107,12 +100,44 @@ export default class NewEditProjectView extends Vue {
projectName = ""; projectName = "";
description = ""; description = "";
errorMessage = ""; errorMessage = "";
accounts: AccountsSchema;
numAccounts = 0;
async beforeCreate() {
accountsDB.open();
this.accounts = accountsDB.accounts;
this.numAccounts = await this.accounts.count();
}
public async getIdentity(activeDid) {
await accountsDB.open();
const account = await accountsDB.accounts
.where("did")
.equals(activeDid)
.first();
const identity = JSON.parse(account?.identity || "null");
if (!identity) {
throw new Error(
"Attempted to load project records with no identity available.",
);
}
return identity;
}
public async getHeaders(identity) {
const token = await accessToken(identity);
const headers = {
"Content-Type": "application/json",
Authorization: "Bearer " + token,
};
return headers;
}
projectId = localStorage.getItem("projectId") || ""; projectId = localStorage.getItem("projectId") || "";
isHiddenSave = false; isHiddenSave = false;
isHiddenSpinner = true; isHiddenSpinner = true;
// 'created' hook runs when the Vue instance is first created
async created() { async created() {
await db.open(); await db.open();
const settings = await db.settings.get(MASTER_SETTINGS_KEY); const settings = await db.settings.get(MASTER_SETTINGS_KEY);
@@ -120,16 +145,14 @@ export default class NewEditProjectView extends Vue {
this.apiServer = settings?.apiServer || ""; this.apiServer = settings?.apiServer || "";
if (this.projectId) { if (this.projectId) {
await accountsDB.open(); if (this.numAccounts === 0) {
const num_accounts = await accountsDB.accounts.count();
if (num_accounts === 0) {
console.error("Error: no account was found."); console.error("Error: no account was found.");
} else { } else {
const accounts = await accountsDB.accounts.toArray(); const identity = await this.getIdentity(this.activeDid);
const account = R.find((acc) => acc.did === this.activeDid, accounts);
const identity = JSON.parse(account?.identity || "null");
if (!identity) { if (!identity) {
throw new Error("No identity found."); throw new Error(
"An ID is chosen but there are no keys for it so it cannot be used to talk with the service.",
);
} }
this.LoadProject(identity); this.LoadProject(identity);
} }
@@ -212,7 +235,7 @@ export default class NewEditProjectView extends Vue {
// handleId is new in server v release-1.6.0; remove fullIri when that // handleId is new in server v release-1.6.0; remove fullIri when that
// version shows up here: https://endorser.ch:3000/api-docs/ // version shows up here: https://endorser.ch:3000/api-docs/
useAppStore().setProjectId( useAppStore().setProjectId(
resp.data.success.handleId || resp.data.success.fullIri resp.data.success.handleId || resp.data.success.fullIri,
); );
setTimeout( setTimeout(
function (that: Vue) { function (that: Vue) {
@@ -222,14 +245,13 @@ export default class NewEditProjectView extends Vue {
that.$router.push(route); that.$router.push(route);
}, },
2000, 2000,
this this,
); );
} }
} catch (error) { } catch (error) {
let userMessage = "There was an error saving the project."; let userMessage = "There was an error saving the project.";
const serverError = error as AxiosError; const serverError = error as AxiosError;
if (serverError) { if (serverError) {
this.isAlertVisible = true;
if (Object.prototype.hasOwnProperty.call(serverError, "message")) { if (Object.prototype.hasOwnProperty.call(serverError, "message")) {
console.log(serverError); console.log(serverError);
this.alertTitle = "User Message"; this.alertTitle = "User Message";
@@ -242,7 +264,7 @@ export default class NewEditProjectView extends Vue {
} else { } else {
console.error( console.error(
"Here's the full error trying to save the claim:", "Here's the full error trying to save the claim:",
error error,
); );
this.alertTitle = "Claim Error"; this.alertTitle = "Claim Error";
this.alertMessage = error as string; this.alertMessage = error as string;
@@ -256,17 +278,11 @@ export default class NewEditProjectView extends Vue {
public async onSaveProjectClick() { public async onSaveProjectClick() {
this.isHiddenSave = true; this.isHiddenSave = true;
this.isHiddenSpinner = false; this.isHiddenSpinner = false;
await accountsDB.open();
const num_accounts = await accountsDB.accounts.count(); if (this.numAccounts === 0) {
if (num_accounts === 0) {
console.error("Error: there is no account."); console.error("Error: there is no account.");
} else { } else {
const accounts = await accountsDB.accounts.toArray(); const identity = await this.getIdentity(this.activeDid);
const account = R.find((acc) => acc.did === this.activeDid, accounts);
const identity = JSON.parse(account?.identity || "null");
if (!identity) {
throw new Error("No identity found.");
}
this.SaveProject(identity); this.SaveProject(identity);
} }
} }
@@ -278,27 +294,5 @@ export default class NewEditProjectView extends Vue {
// This same popup code is in many files. // This same popup code is in many files.
alertTitle = ""; alertTitle = "";
alertMessage = ""; alertMessage = "";
isAlertVisible = false;
public onClickClose() {
this.isAlertVisible = false;
this.alertTitle = "";
this.alertMessage = "";
}
public computedAlertClassNames() {
return {
hidden: !this.isAlertVisible,
"dismissable-alert": true,
"bg-slate-100": true,
"p-5": true,
rounded: true,
"drop-shadow-lg": true,
fixed: true,
"top-3": true,
"inset-x-3": true,
"transition-transform": true,
"ease-in": true,
"duration-300": true,
};
}
} }
</script> </script>

View File

@@ -1,52 +1,5 @@
<template> <template>
<!-- QUICK NAV --> <QuickNav selected="Profile"></QuickNav>
<nav id="QuickNav" class="fixed bottom-0 left-0 right-0 bg-slate-200 z-50">
<ul class="flex text-2xl p-2 gap-2">
<!-- Home Feed -->
<li class="basis-1/5 rounded-md text-slate-500">
<router-link :to="{ name: 'home' }" class="block text-center py-3 px-1">
<fa icon="house-chimney" class="fa-fw"></fa>
</router-link>
</li>
<!-- Search -->
<li class="basis-1/5 rounded-md text-slate-500">
<router-link
:to="{ name: 'discover' }"
class="block text-center py-3 px-1"
>
<fa icon="magnifying-glass" class="fa-fw"></fa>
</router-link>
</li>
<!-- Projects -->
<li class="basis-1/5 rounded-md text-slate-500">
<router-link
:to="{ name: 'projects' }"
class="block text-center py-3 px-1"
>
<fa icon="folder-open" class="fa-fw"></fa>
</router-link>
</li>
<!-- Contacts -->
<li class="basis-1/5 rounded-md text-slate-500">
<router-link
:to="{ name: 'contacts' }"
class="block text-center py-3 px-1"
>
<fa icon="users" class="fa-fw"></fa>
</router-link>
</li>
<!-- Profile -->
<li class="basis-1/5 rounded-md bg-slate-400 text-white">
<router-link
:to="{ name: 'account' }"
class="block text-center py-3 px-1"
>
<fa icon="circle-user" class="fa-fw"></fa>
</router-link>
</li>
</ul>
</nav>
<!-- CONTENT --> <!-- CONTENT -->
<section id="Content" class="p-6 pb-24"> <section id="Content" class="p-6 pb-24">
<!-- Heading --> <!-- Heading -->
@@ -90,8 +43,9 @@ import { Component, Vue } from "vue-facing-decorator";
import { accountsDB, db } from "@/db"; import { accountsDB, db } from "@/db";
import { deriveAddress, generateSeed, newIdentifier } from "@/libs/crypto"; import { deriveAddress, generateSeed, newIdentifier } from "@/libs/crypto";
import { MASTER_SETTINGS_KEY } from "@/db/tables/settings"; import { MASTER_SETTINGS_KEY } from "@/db/tables/settings";
import QuickNav from "@/components/QuickNav";
@Component @Component({ components: { QuickNav } })
export default class AccountViewView extends Vue { export default class AccountViewView extends Vue {
loading = true; loading = true;

View File

@@ -1,48 +1,5 @@
<template> <template>
<!-- QUICK NAV --> <QuickNav selected="Projects"></QuickNav>
<nav id="QuickNav" class="fixed bottom-0 left-0 right-0 bg-slate-200 z-50">
<ul class="flex text-2xl p-2 gap-2">
<!-- Home Feed -->
<li class="basis-1/5 rounded-md text-slate-500">
<router-link :to="{ name: 'home' }" class="block text-center py-3 px-1"
><fa icon="house-chimney" class="fa-fw"></fa
></router-link>
</li>
<!-- Search -->
<li class="basis-1/5 rounded-md bg-slate-400 text-white">
<router-link
:to="{ name: 'discover' }"
class="block text-center py-3 px-1"
><fa icon="magnifying-glass" class="fa-fw"></fa
></router-link>
</li>
<!-- Projects -->
<li class="basis-1/5 rounded-md text-slate-500">
<router-link
:to="{ name: 'projects' }"
class="block text-center py-3 px-1"
><fa icon="folder-open" class="fa-fw"></fa
></router-link>
</li>
<!-- Contacts -->
<li class="basis-1/5 rounded-md text-slate-500">
<router-link
:to="{ name: 'contacts' }"
class="block text-center py-3 px-1"
><fa icon="hand" class="fa-fw"></fa
></router-link>
</li>
<!-- Profile -->
<li class="basis-1/5 rounded-md text-slate-500">
<router-link
:to="{ name: 'account' }"
class="block text-center py-3 px-1"
><fa icon="circle-user" class="fa-fw"></fa
></router-link>
</li>
</ul>
</nav>
<!-- CONTENT --> <!-- CONTENT -->
<section id="Content" class="p-6 pb-24"> <section id="Content" class="p-6 pb-24">
<!-- Breadcrumb --> <!-- Breadcrumb -->
@@ -66,7 +23,7 @@
</h1> </h1>
</div> </div>
<div> <div class="text-red-500">
{{ errorMessage }} {{ errorMessage }}
</div> </div>
@@ -108,67 +65,183 @@
</button> </button>
</div> </div>
<!-- Commit --> <div>
<router-link <div v-if="activeDid">
:to="{ name: 'new-edit-commitment' }" <button
class="block text-center text-lg font-bold uppercase bg-blue-600 text-white px-2 py-3 rounded-md mb-8" @click="openDialog({ name: 'you', did: activeDid })"
>Make Commitment</router-link class="text-center text-lg font-bold uppercase bg-blue-600 text-white px-2 py-3 rounded-md"
> >
I gave...
<!-- Commitments --> </button>
<div class="bg-slate-100 px-4 py-3 rounded-md"> &horbar; or:
<h3 class="text-sm uppercase font-semibold mb-3">Commitments</h3> </div>
<!-- similar contact selection code is in multiple places -->
<ul class="text-sm border-t border-slate-300"> Record a gift from
<li class="flex justify-between gap-4 py-1.5 border-b border-slate-300"> <span v-for="contact in allContacts" :key="contact.did">
<span>[Username]</span> <button @click="openDialog(contact)" class="text-blue-500">
<span &nbsp;{{ contact.name }}</button
>5 hours <fa icon="spinner" class="fa-fw text-slate-400"></fa >,
></span> </span>
</li> <span v-if="allContacts.length > 0">&nbsp;or&nbsp;</span>
<button @click="openDialog()" class="text-blue-500">
<li class="flex justify-between gap-4 py-1.5 border-b border-slate-300"> someone not specified
<span>[Username]</span> </button>
<span
>US$ 20.00 <fa icon="circle-check" class="fa-fw text-lime-500"></fa
></span>
</li>
<li class="flex justify-between gap-4 py-1.5 border-b border-slate-300">
<span>[Username]</span>
<span
>0.1 BTC <fa icon="spinner" class="fa-fw text-slate-400"></fa
></span>
</li>
</ul>
</div> </div>
<!-- Gifts to & from this -->
<div class="mt-8 flex justify-around">
<div>
<h1 class="text-xl">Given to this Project</h1>
</div>
<div>
<h1 class="text-xl">... and from this Project</h1>
</div>
</div>
<div class="flex justify-around">
<div class="w-1/2">
<div v-for="give in givesToThis" :key="give.id">
<div class="flex justify-between">
<div class="flex gap-3">
<div class="flex gap-2">
<fa icon="user" class="fa-fw text-slate-400"></fa>
<span>{{
didInfo(give.agentDid, activeDid, accounts, allContacts)
}}</span>
</div>
<div class="flex gap-2" v-if="give.amount">
<fa icon="coins" class="fa-fw text-slate-400"></fa>
<span>{{ give.amount }}</span>
</div>
<div class="flex gap-2" v-if="give.description">
<fa icon="comment" class="fa-fw text-slate-400"></fa>
<span>{{ give.description }}</span>
</div>
</div>
</div>
</div>
</div>
<div class="w-1/2">
<div v-for="give in givesByThis" :key="give.id">
<div class="flex justify-between">
<div class="flex gap-3">
<div class="flex gap-2">
<fa icon="user" class="fa-fw text-slate-400"></fa>
<span>{{
didInfo(give.agentDid, activeDid, accounts, allContacts)
}}</span>
</div>
<div class="flex gap-2" v-if="give.amount">
<fa icon="coins" class="fa-fw text-slate-400"></fa>
<span>{{ give.amount }}</span>
</div>
<div class="flex gap-2">
<fa icon="comment" class="fa-fw text-slate-400"></fa>
<span>{{ give.description }}</span>
</div>
</div>
</div>
</div>
</div>
</div>
<GiftedDialog
ref="customDialog"
@dialog-result="handleDialogResult"
message="Received from"
>
</GiftedDialog>
<AlertMessage
:alertTitle="alertTitle"
:alertMessage="alertMessage"
></AlertMessage>
</section> </section>
</template> </template>
<script lang="ts"> <script lang="ts">
import { AxiosError } from "axios"; import { AxiosError } from "axios";
import * as moment from "moment"; import * as moment from "moment";
import * as R from "ramda"; import { IIdentifier } from "@veramo/core";
import { Options, Vue } from "vue-class-component"; import { Component, Vue } from "vue-facing-decorator";
import GiftedDialog from "@/components/GiftedDialog.vue";
import { accountsDB, db } from "@/db"; import { accountsDB, db } from "@/db";
import { AccountsSchema } from "@/db/tables/accounts";
import { Contact } from "@/db/tables/contacts";
import { MASTER_SETTINGS_KEY } from "@/db/tables/settings"; import { MASTER_SETTINGS_KEY } from "@/db/tables/settings";
import { accessToken } from "@/libs/crypto"; import { accessToken } from "@/libs/crypto";
import { IIdentifier } from "@veramo/core"; import {
createAndSubmitGive,
didInfo,
GiveServerRecord,
} from "@/libs/endorserServer";
import AlertMessage from "@/components/AlertMessage";
import QuickNav from "@/components/QuickNav";
@Options({ @Component({
components: {}, components: { GiftedDialog, AlertMessage, QuickNav },
}) })
export default class ProjectViewView extends Vue { export default class ProjectViewView extends Vue {
accounts: AccountsSchema;
activeDid = "";
alertMessage = "";
alertTitle = "";
allContacts: Array<Contact> = [];
apiServer = ""; apiServer = "";
expanded = false;
name = "";
description = ""; description = "";
errorMessage = "";
expanded = false;
givesToThis: Array<GiveServerRecord> = [];
givesByThis: Array<GiveServerRecord> = [];
name = "";
numAccounts = 0;
projectId = localStorage.getItem("projectId") || ""; // handle ID
timeSince = "";
truncatedDesc = ""; truncatedDesc = "";
truncateLength = 40; truncateLength = 40;
timeSince = "";
projectId = localStorage.getItem("projectId") || ""; async beforeCreate() {
errorMessage = ""; accountsDB.open();
this.accounts = accountsDB.accounts;
this.numAccounts = (await this.accounts?.count()) || 0;
}
async created() {
await db.open();
const settings = await db.settings.get(MASTER_SETTINGS_KEY);
this.activeDid = settings?.activeDid || "";
this.apiServer = settings?.apiServer || "";
this.allContacts = await db.contacts.toArray();
this.accounts = accountsDB.accounts;
const accountsArr = await this.accounts?.toArray();
const account = accountsArr.find((acc) => acc.did === this.activeDid);
const identity = JSON.parse(account?.identity || "null");
this.LoadProject(identity);
}
public async getIdentity(activeDid) {
await accountsDB.open();
const account = await accountsDB.accounts
.where("did")
.equals(activeDid)
.first();
const identity = JSON.parse(account?.identity || "null");
if (!identity) {
throw new Error(
"Attempted to load project records with no identity available.",
);
}
return identity;
}
public async getHeaders(identity) {
const token = await accessToken(identity);
const headers = {
"Content-Type": "application/json",
Authorization: "Bearer " + token,
};
return headers;
}
onEditClick() { onEditClick() {
localStorage.setItem("projectId", this.projectId as string); localStorage.setItem("projectId", this.projectId as string);
@@ -178,6 +251,11 @@ export default class ProjectViewView extends Vue {
this.$router.push(route); this.$router.push(route);
} }
// Isn't there a better way to make this available to the template?
didInfo(did, activeDid, identities, contacts) {
return didInfo(did, activeDid, identities, contacts);
}
expandText() { expandText() {
this.expanded = true; this.expanded = true;
} }
@@ -191,15 +269,19 @@ export default class ProjectViewView extends Vue {
this.apiServer + this.apiServer +
"/api/claim/byHandle/" + "/api/claim/byHandle/" +
encodeURIComponent(this.projectId); encodeURIComponent(this.projectId);
const token = await accessToken(identity);
const headers = { const headers = {
"Content-Type": "application/json", "Content-Type": "application/json",
Authorization: "Bearer " + token,
}; };
if (identity) {
const token = await accessToken(identity);
headers["Authorization"] = "Bearer " + token;
}
try { try {
const resp = await this.axios.get(url, { headers }); const resp = await this.axios.get(url, { headers });
if (resp.status === 200) { if (resp.status === 200) {
// feel free to remove this; I haven't yet because it's helpful
console.log("Loaded project: ", resp.data);
const startTime = resp.data.startTime; const startTime = resp.data.startTime;
if (startTime != null) { if (startTime != null) {
const eventDate = new Date(startTime); const eventDate = new Date(startTime);
@@ -224,27 +306,107 @@ export default class ProjectViewView extends Vue {
console.error("Error retrieving project:", error); console.error("Error retrieving project:", error);
} }
} }
const givesInUrl =
this.apiServer +
"/api/v2/report/givesForPlans?planIds=" +
encodeURIComponent(JSON.stringify([this.projectId]));
try {
const resp = await this.axios.get(givesInUrl, { headers });
if (resp.status === 200 && resp.data.data) {
this.givesToThis = resp.data.data;
} else {
this.errorMessage = "Failed to retrieve gives to this project.";
}
} catch (error: unknown) {
console.error("Error retrieving gives to this project:", error);
this.errorMessage =
"Something went wrong retrieving gives to this project.";
}
const givesOutUrl =
this.apiServer +
"/api/v2/report/givesProvidedBy?providerId=" +
encodeURIComponent(this.projectId);
try {
const resp = await this.axios.get(givesOutUrl, { headers });
if (resp.status === 200 && resp.data.data) {
this.givesByThis = resp.data.data;
} else {
this.errorMessage = "Failed to retrieve gives by this project.";
}
} catch (error: unknown) {
console.error("Error retrieving gives by this project:", error);
this.errorMessage = "Something went wrong retrieving gives by project.";
}
} }
// 'created' hook runs when the Vue instance is first created openDialog(contact) {
async created() { this.$refs.customDialog.open(contact);
await db.open(); }
const settings = await db.settings.get(MASTER_SETTINGS_KEY);
const activeDid = settings?.activeDid || "";
this.apiServer = settings?.apiServer || "";
await accountsDB.open(); handleDialogResult(result) {
const num_accounts = await accountsDB.accounts.count(); if (result.action === "confirm") {
if (num_accounts === 0) { return new Promise((resolve) => {
console.error("Problem! Should have a profile!"); this.recordGive(result.contact?.did, result.description, result.hours);
resolve();
});
} else { } else {
const accounts = await accountsDB.accounts.toArray(); // action was not "confirm" so do nothing
const account = R.find((acc) => acc.did === activeDid, accounts); }
const identity = JSON.parse(account?.identity || "null"); }
if (!identity) {
throw new Error("No identity found."); /**
*
* @param giverDid may be null
* @param description may be an empty string
* @param hours may be 0
*/
async recordGive(giverDid, description, hours) {
if (!this.activeDid) {
this.alertTitle = "Error";
this.alertMessage =
"You must select an identity before you can record a give.";
return;
}
if (!description && !hours) {
this.alertTitle = "Error";
this.alertMessage =
"You must enter a description or some number of hours.";
return;
}
try {
const identity = await this.getIdentity(this.activeDid);
const result = await createAndSubmitGive(
this.axios,
this.apiServer,
identity,
giverDid,
this.activeDid,
description,
hours,
this.projectId,
);
if (result.status !== 201 || result.data?.error) {
console.log("Error with give result:", result);
this.alertTitle = "Error";
this.alertMessage =
result.data?.error?.message ||
"There was an error recording the give.";
} else {
this.alertTitle = "Success";
this.alertMessage = "That gift was recorded.";
} }
this.LoadProject(identity); } catch (e) {
console.log("Error with give caught:", e);
this.alertTitle = "Error";
this.alertMessage =
e.userMessage ||
e.response?.data?.error?.message ||
"There was an error recording the give.";
} }
} }
} }

View File

@@ -1,47 +1,5 @@
<template> <template>
<!-- QUICK NAV --> <QuickNav selected="Projects"></QuickNav>
<nav id="QuickNav" class="fixed bottom-0 left-0 right-0 bg-slate-200 z-50">
<ul class="flex text-2xl p-2 gap-2">
<!-- Home Feed -->
<li class="basis-1/5 rounded-md text-slate-500">
<router-link :to="{ name: 'home' }" class="block text-center py-3 px-1"
><fa icon="house-chimney" class="fa-fw"></fa
></router-link>
</li>
<!-- Search -->
<li class="basis-1/5 rounded-md text-slate-500">
<router-link
:to="{ name: 'discover' }"
class="block text-center py-3 px-1"
><fa icon="magnifying-glass" class="fa-fw"></fa
></router-link>
</li>
<!-- Projects -->
<li class="basis-1/5 rounded-md bg-slate-400 text-white">
<router-link
:to="{ name: 'projects' }"
class="block text-center py-3 px-1"
><fa icon="folder-open" class="fa-fw"></fa
></router-link>
</li>
<!-- Contacts -->
<li class="basis-1/5 rounded-md text-slate-500">
<router-link
:to="{ name: 'contacts' }"
class="block text-center py-3 px-1"
><fa icon="users" class="fa-fw"></fa
></router-link>
</li>
<!-- Profile -->
<li class="basis-1/5 rounded-md text-slate-500">
<router-link
:to="{ name: 'account' }"
class="block text-center py-3 px-1"
><fa icon="circle-user" class="fa-fw"></fa
></router-link>
</li>
</ul>
</nav>
<section id="Content" class="p-6 pb-24"> <section id="Content" class="p-6 pb-24">
<!-- Heading --> <!-- Heading -->
<h1 id="ViewHeading" class="text-4xl text-center font-light pt-4 mb-8"> <h1 id="ViewHeading" class="text-4xl text-center font-light pt-4 mb-8">
@@ -70,6 +28,14 @@
<fa icon="plus" class="fa-fw"></fa> <fa icon="plus" class="fa-fw"></fa>
</button> </button>
<!-- Loading Animation -->
<div
class="fixed left-6 bottom-24 text-center text-4xl leading-none bg-slate-400 text-white w-14 py-2.5 rounded-full"
v-if="isLoading"
>
<fa icon="spinner" class="fa-spin-pulse"></fa>
</div>
<!-- Results List --> <!-- Results List -->
<InfiniteScroll @reached-bottom="loadMoreData"> <InfiniteScroll @reached-bottom="loadMoreData">
<ul> <ul>
@@ -99,18 +65,23 @@
</li> </li>
</ul> </ul>
</InfiniteScroll> </InfiniteScroll>
<AlertMessage
:alertTitle="alertTitle"
:alertMessage="alertMessage"
></AlertMessage>
</section> </section>
</template> </template>
<script lang="ts"> <script lang="ts">
import * as R from "ramda";
import { Component, Vue } from "vue-facing-decorator"; import { Component, Vue } from "vue-facing-decorator";
import { accountsDB, db } from "@/db"; import { accountsDB, db } from "@/db";
import { AccountsSchema } from "@/db/tables/accounts";
import { MASTER_SETTINGS_KEY } from "@/db/tables/settings"; import { MASTER_SETTINGS_KEY } from "@/db/tables/settings";
import { accessToken } from "@/libs/crypto"; import { accessToken } from "@/libs/crypto";
import { IIdentifier } from "@veramo/core"; import { IIdentifier } from "@veramo/core";
import InfiniteScroll from "@/components/InfiniteScroll"; import InfiniteScroll from "@/components/InfiniteScroll";
import AlertMessage from "@/components/AlertMessage";
import QuickNav from "@/components/QuickNav";
/** /**
* Represents data about a project * Represents data about a project
@@ -135,13 +106,23 @@ interface ProjectData {
} }
@Component({ @Component({
components: { InfiniteScroll }, components: { InfiniteScroll, AlertMessage, QuickNav },
}) })
export default class ProjectsView extends Vue { export default class ProjectsView extends Vue {
apiServer = ""; apiServer = "";
projects: ProjectData[] = []; projects: ProjectData[] = [];
current: IIdentifier; current: IIdentifier;
isLoading = false; isLoading = false;
alertTitle = "";
alertMessage = "";
accounts: AccountsSchema;
numAccounts = 0;
async beforeCreate() {
accountsDB.open();
this.accounts = accountsDB.accounts;
this.numAccounts = await this.accounts.count();
}
/** /**
* Core project data loader * Core project data loader
@@ -157,15 +138,20 @@ export default class ProjectsView extends Vue {
try { try {
this.isLoading = true; this.isLoading = true;
const resp = await this.axios.get(url, { headers }); const resp = await this.axios.get(url, { headers });
if (resp.status === 200) { if (resp.status === 200 || !resp.data.data) {
const plans: ProjectData[] = resp.data.data; const plans: ProjectData[] = resp.data.data;
for (const plan of plans) { for (const plan of plans) {
const { name, description, handleId = plan.fullIri, rowid } = plan; const { name, description, handleId = plan.fullIri, rowid } = plan;
this.projects.push({ name, description, handleId, rowid }); this.projects.push({ name, description, handleId, rowid });
} }
} else {
console.log("Bad server response & data:", resp.status, resp.data);
throw Error("Failed to get projects from the server.");
} }
} catch (error) { } catch (error) {
console.error("Got error loading projects:", error); console.error("Got error loading projects:", error.message);
this.alertTitle = "Error";
this.alertMessage = "Got an error loading projects:" + error.message;
} finally { } finally {
this.isLoading = false; this.isLoading = false;
} }
@@ -176,8 +162,7 @@ export default class ProjectsView extends Vue {
* @param payload is the flag from the InfiniteScroll indicating if it should load * @param payload is the flag from the InfiniteScroll indicating if it should load
**/ **/
async loadMoreData(payload: boolean) { async loadMoreData(payload: boolean) {
console.log(payload); if (this.projects.length > 0 && payload) {
if (this.projects.length > 0) {
const latestProject = this.projects[this.projects.length - 1]; const latestProject = this.projects[this.projects.length - 1];
const url = `${this.apiServer}/api/v2/report/plansByIssuer?beforeId=${latestProject.rowid}`; const url = `${this.apiServer}/api/v2/report/plansByIssuer?beforeId=${latestProject.rowid}`;
const token = await accessToken(this.current); const token = await accessToken(this.current);
@@ -186,9 +171,9 @@ export default class ProjectsView extends Vue {
} }
/** /**
* Handle clicking on a project entry found in the list * Handle clicking on a project entry found in the list
* @param id of the project * @param id of the project
**? **/
onClickLoadProject(id: string) { onClickLoadProject(id: string) {
localStorage.setItem("projectId", id); localStorage.setItem("projectId", id);
const route = { const route = {
@@ -198,37 +183,54 @@ export default class ProjectsView extends Vue {
} }
/** /**
* Load projects initially * Load projects initially
* @param identity of the user * @param identity of the user
**/ **/
async LoadProjects(identity: IIdentifier) { async LoadProjects(identity: IIdentifier) {
console.log("LoadProjects");
const url = `${this.apiServer}/api/v2/report/plansByIssuer`; const url = `${this.apiServer}/api/v2/report/plansByIssuer`;
const token: string = await accessToken(identity); const token: string = await accessToken(identity);
await this.dataLoader(url, token); await this.dataLoader(url, token);
} }
public async getIdentity(activeDid) {
await accountsDB.open();
const account = await accountsDB.accounts
.where("did")
.equals(activeDid)
.first();
const identity = JSON.parse(account?.identity || "null");
if (!identity) {
throw new Error(
"Attempted to load project records with no identity available.",
);
}
return identity;
}
/** /**
* 'created' hook runs when the Vue instance is first created * 'created' hook runs when the Vue instance is first created
**/ **/
async created() { async created() {
await db.open(); try {
const settings = await db.settings.get(MASTER_SETTINGS_KEY); await db.open();
const activeDid = settings?.activeDid || ""; const settings = await db.settings.get(MASTER_SETTINGS_KEY);
this.apiServer = settings?.apiServer || ""; const activeDid = settings?.activeDid || "";
this.apiServer = settings?.apiServer || "";
await accountsDB.open(); if (this.numAccounts === 0) {
const num_accounts = await accountsDB.accounts.count(); console.error("No accounts found.");
if (num_accounts === 0) { this.alertTitle = "Error";
console.error("Problem! Should have a profile!"); this.alertMessage = "You need an identity to load your projects.";
} else { } else {
const accounts = await accountsDB.accounts.toArray(); const identity = await this.getIdentity(activeDid);
const account = R.find((acc) => acc.did === activeDid, accounts); this.current = identity;
const identity = JSON.parse(account?.identity || "null"); this.LoadProjects(identity);
if (!identity) {
throw new Error("No identity found.");
} }
this.LoadProjects(identity); } catch (err) {
console.log("Error initializing:", err);
this.alertTitle = "Error";
this.alertMessage = "Something went wrong loading your projects.";
} }
} }

View File

@@ -1,52 +1,5 @@
<template> <template>
<!-- QUICK NAV --> <QuickNav selected="Profile"></QuickNav>
<nav id="QuickNav" class="fixed bottom-0 left-0 right-0 bg-slate-200 z-50">
<ul class="flex text-2xl p-2 gap-2">
<!-- Home Feed -->
<li class="basis-1/5 rounded-md text-slate-500">
<router-link :to="{ name: 'home' }" class="block text-center py-3 px-1">
<fa icon="house-chimney" class="fa-fw"></fa>
</router-link>
</li>
<!-- Search -->
<li class="basis-1/5 rounded-md text-slate-500">
<router-link
:to="{ name: 'discover' }"
class="block text-center py-3 px-1"
>
<fa icon="magnifying-glass" class="fa-fw"></fa>
</router-link>
</li>
<!-- Projects -->
<li class="basis-1/5 rounded-md text-slate-500">
<router-link
:to="{ name: 'projects' }"
class="block text-center py-3 px-1"
>
<fa icon="folder-open" class="fa-fw"></fa>
</router-link>
</li>
<!-- Contacts -->
<li class="basis-1/5 rounded-md text-slate-500">
<router-link
:to="{ name: 'contacts' }"
class="block text-center py-3 px-1"
>
<fa icon="users" class="fa-fw"></fa>
</router-link>
</li>
<!-- Profile -->
<li class="basis-1/5 rounded-md bg-slate-400 text-white">
<router-link
:to="{ name: 'account' }"
class="block text-center py-3 px-1"
>
<fa icon="circle-user" class="fa-fw"></fa>
</router-link>
</li>
</ul>
</nav>
<!-- CONTENT --> <!-- CONTENT -->
<section id="Content" class="p-6 pb-24"> <section id="Content" class="p-6 pb-24">
<!-- Heading --> <!-- Heading -->
@@ -85,18 +38,10 @@
<p v-if="showSeed">{{ activeAccount.mnemonic }}</p> <p v-if="showSeed">{{ activeAccount.mnemonic }}</p>
</div> </div>
<div v-else>You do not have an active identity.</div> <div v-else>You do not have an active identity.</div>
<AlertMessage
<!-- This same popup code is in many files. --> :alertTitle="alertTitle"
<div v-bind:class="computedAlertClassNames()"> :alertMessage="alertMessage"
<button ></AlertMessage>
class="close-button bg-slate-200 w-8 leading-loose rounded-full absolute top-2 right-2"
@click="onClickClose()"
>
<fa icon="xmark"></fa>
</button>
<h4 class="font-bold pr-5">{{ alertTitle }}</h4>
<p>{{ alertMessage }}</p>
</div>
</section> </section>
</template> </template>
@@ -105,11 +50,15 @@ import { Component, Vue } from "vue-facing-decorator";
import { accountsDB, db } from "@/db"; import { accountsDB, db } from "@/db";
import * as R from "ramda"; import * as R from "ramda";
import { MASTER_SETTINGS_KEY } from "@/db/tables/settings"; import { MASTER_SETTINGS_KEY } from "@/db/tables/settings";
import AlertMessage from "@/components/AlertMessage";
import QuickNav from "@/components/QuickNav";
@Component @Component({ components: { AlertMessage, QuickNav } })
export default class SeedBackupView extends Vue { export default class SeedBackupView extends Vue {
activeAccount = null; activeAccount = null;
showSeed = false; showSeed = false;
alertMessage = "";
alertTitle = "";
// 'created' hook runs when the Vue instance is first created // 'created' hook runs when the Vue instance is first created
async created() { async created() {
@@ -125,38 +74,11 @@ export default class SeedBackupView extends Vue {
console.error("Got an error loading an identity:", err); console.error("Got an error loading an identity:", err);
this.alertTitle = "Error Loading Account"; this.alertTitle = "Error Loading Account";
this.alertMessage = "Got an error loading your seed data."; this.alertMessage = "Got an error loading your seed data.";
this.isAlertVisible = true;
} }
} }
showSeedPhrase() { showSeedPhrase() {
this.showSeed = true; this.showSeed = true;
} }
// This same popup code is in many files.
alertMessage = "";
alertTitle = "";
isAlertVisible = false;
public onClickClose() {
this.isAlertVisible = false;
this.alertTitle = "";
this.alertMessage = "";
}
public computedAlertClassNames() {
return {
hidden: !this.isAlertVisible,
"dismissable-alert": true,
"bg-slate-100": true,
"p-5": true,
rounded: true,
"drop-shadow-lg": true,
fixed: true,
"top-3": true,
"inset-x-3": true,
"transition-transform": true,
"ease-in": true,
"duration-300": true,
};
}
} }
</script> </script>

View File

@@ -28,9 +28,9 @@
</template> </template>
<script lang="ts"> <script lang="ts">
import { Options, Vue } from "vue-class-component"; import { Component, Vue } from "vue-facing-decorator";
@Options({ @Component({
components: {}, components: {},
}) })
export default class StartView extends Vue { export default class StartView extends Vue {

View File

@@ -1,52 +1,5 @@
<template> <template>
<!-- QUICK NAV --> <QuickNav selected="Profile"></QuickNav>
<nav id="QuickNav" class="fixed bottom-0 left-0 right-0 bg-slate-200 z-50">
<ul class="flex text-2xl p-2 gap-2">
<!-- Home Feed -->
<li class="basis-1/5 rounded-md text-slate-500">
<router-link :to="{ name: 'home' }" class="block text-center py-3 px-1">
<fa icon="house-chimney" class="fa-fw"></fa>
</router-link>
</li>
<!-- Search -->
<li class="basis-1/5 rounded-md text-slate-500">
<router-link
:to="{ name: 'discover' }"
class="block text-center py-3 px-1"
>
<fa icon="magnifying-glass" class="fa-fw"></fa>
</router-link>
</li>
<!-- Projects -->
<li class="basis-1/5 rounded-md text-slate-500">
<router-link
:to="{ name: 'projects' }"
class="block text-center py-3 px-1"
>
<fa icon="folder-open" class="fa-fw"></fa>
</router-link>
</li>
<!-- Contacts -->
<li class="basis-1/5 rounded-md text-slate-500">
<router-link
:to="{ name: 'contacts' }"
class="block text-center py-3 px-1"
>
<fa icon="users" class="fa-fw"></fa>
</router-link>
</li>
<!-- Profile -->
<li class="basis-1/5 rounded-md bg-slate-400 text-white">
<router-link
:to="{ name: 'account' }"
class="block text-center py-3 px-1"
>
<fa icon="circle-user" class="fa-fw"></fa>
</router-link>
</li>
</ul>
</nav>
<!-- CONTENT --> <!-- CONTENT -->
<section id="Content" class="p-6 pb-24"> <section id="Content" class="p-6 pb-24">
<!-- Heading --> <!-- Heading -->
@@ -79,107 +32,48 @@
{{ worldProperties.animationDurationSeconds }} seconds {{ worldProperties.animationDurationSeconds }} seconds
</div> </div>
</div> </div>
<button class="float-right" @click="captureGraphics()">Screenshot</button> <button class="float-right" @click="captureGraphics()">Screenshot</button>
<!-- Another place to play with the sizing is in Resizer.setSize -->
<div id="scene-container" class="h-screen"></div> <div id="scene-container" class="h-screen"></div>
<AlertMessage
<div v-bind:class="computedAlertClassNames()"> :alertTitle="alertTitle"
<button :alertMessage="alertMessage"
class="close-button bg-slate-200 w-8 leading-loose rounded-full absolute top-2 right-2" ></AlertMessage>
@click="onClickClose()"
>
<fa icon="xmark"></fa>
</button>
<h4 class="font-bold pr-5">{{ alertTitle }}</h4>
<p>{{ alertMessage }}</p>
</div>
</section> </section>
</template> </template>
<script lang="ts"> <script lang="ts">
import { SVGRenderer } from "three/addons/renderers/SVGRenderer.js"; import { SVGRenderer } from "three/addons/renderers/SVGRenderer.js";
import { Component, Vue } from "vue-facing-decorator"; import { Component, Vue } from "vue-facing-decorator";
import { World } from "@/components/World/World.js"; import { World } from "@/components/World/World.js";
import AlertMessage from "@/components/AlertMessage";
import QuickNav from "@/components/QuickNav";
interface WorldProperties { interface WorldProperties {
startTime?: string; startTime?: string;
endTime?: string; endTime?: string;
} }
@Component @Component({ components: { AlertMessage, World, QuickNav } })
export default class StatisticsView extends Vue { export default class StatisticsView extends Vue {
world: World; world: World;
worldProperties: WorldProperties = {}; worldProperties: WorldProperties = {};
alertTitle = "";
alertMessage = "";
// 'mounted' hook runs after initial render
mounted() { mounted() {
const container = document.querySelector("#scene-container"); try {
const newWorld = new World(container, this); const container = document.querySelector("#scene-container");
newWorld.start(); console.log(container);
this.world = newWorld; const newWorld = new World(container, this);
newWorld.start();
this.world = newWorld;
} catch (err) {
console.log(err);
this.alertTitle = "Mounting error";
this.alertMessage = err.message;
}
} }
public captureGraphics() { public captureGraphics() {
/**
// from https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob#examples
// Adds a blank image
const dataBlob = document
.querySelector("#scene-container")
.firstChild.toBlob((blob) => {
const newImg = document.createElement("img");
const url = URL.createObjectURL(blob);
newImg.onload = () => {
// no longer need to read the blob so it's revoked
URL.revokeObjectURL(url);
};
newImg.src = url;
document.body.appendChild(newImg);
});
**/
/**
// Yields a blank page with the iframe below
const dataUrl = document
.querySelector("#scene-container")
.firstChild.toDataURL("image/png");
**/
/**
// Yields a blank page with the iframe below
const dataUrl = this.world.renderer.domElement.toDataURL("image/png");
**/
/**
// Show the image in a new tab
const iframe = `
<iframe
src="${dataUrl}"
frameborder="0"
style="border:0; top:0px; left:0px; bottom:0px; right:0px; width:100%; height:100%;"
allowfullscreen>
</iframe>`;
const win = window.open();
win.document.open();
win.document.write(iframe);
win.document.close();
**/
// from https://stackoverflow.com/a/17407392/845494
// This yields a file with funny formatting.
//const image = const dataUrl.replace("image/png", "image/octet-stream");
/**
// Yields a blank image at the bottom of the page
// from https://discourse.threejs.org/t/save-screenshot-on-server/39900/3
const img = new Image();
img.src = this.world.renderer.domElement.toDataURL();
document.body.appendChild(img);
**/
/** /**
* This yields an SVG that only shows white and black highlights * This yields an SVG that only shows white and black highlights
// from https://stackoverflow.com/questions/27632621/exporting-from-three-js-scene-to-svg-or-other-vector-format // from https://stackoverflow.com/questions/27632621/exporting-from-three-js-scene-to-svg-or-other-vector-format
@@ -187,46 +81,12 @@ export default class StatisticsView extends Vue {
const rendererSVG = new SVGRenderer(); const rendererSVG = new SVGRenderer();
rendererSVG.setSize(window.innerWidth, window.innerHeight); rendererSVG.setSize(window.innerWidth, window.innerHeight);
rendererSVG.render(this.world.scene, this.world.camera); rendererSVG.render(this.world.scene, this.world.camera);
//document.body.appendChild(rendererSVG.domElement);
ExportToSVG(rendererSVG, "test.svg"); ExportToSVG(rendererSVG, "test.svg");
} }
public setWorldProperty(propertyName, propertyValue) { public setWorldProperty(propertyName, propertyValue) {
this.worldProperties[propertyName] = propertyValue; this.worldProperties[propertyName] = propertyValue;
} }
alertTitle = "";
alertMessage = "";
isAlertVisible = false;
public setAlert(title, message) {
this.alertTitle = title;
this.alertMessage = message;
this.isAlertVisible = true;
}
public onClickClose() {
this.isAlertVisible = false;
this.alertTitle = "";
this.alertMessage = "";
}
public computedAlertClassNames() {
return {
hidden: !this.isAlertVisible,
"dismissable-alert": true,
"bg-slate-100": true,
"p-5": true,
rounded: true,
"drop-shadow-lg": true,
fixed: true,
"top-3": true,
"inset-x-3": true,
"transition-transform": true,
"ease-in": true,
"duration-300": true,
};
}
} }
function ExportToSVG(rendererSVG, filename) { function ExportToSVG(rendererSVG, filename) {