diff --git a/Jenkinsfile b/Jenkinsfile index ec6b860c..219d449c 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -25,7 +25,11 @@ def dockerreponame = "statusim/openbounty-app" } stage('Deploy') { - build job: 'status-openbounty/openbounty-cluster', parameters: [[$class: 'StringParameterValue', name: 'DEPLOY_ENVIRONMENT', value: "dev"], [$class: 'StringParameterValue', name: 'BRANCH', value: env.BRANCH_NAME]] + if ( currentBuild.rawBuild.getCauses()[0].toString().contains('UserIdCause') ){ + build job: 'status-openbounty/openbounty-cluster', parameters: [[$class: 'StringParameterValue', name: 'DEPLOY_ENVIRONMENT', value: "dev"], [$class: 'StringParameterValue', name: 'BRANCH', value: env.BRANCH_NAME]] + } else { + echo "No deployment on automatic trigger, go to Jenkins and push build button to deliver it." + } } } catch (e) { diff --git a/README.md b/README.md index 13295f14..de5fd301 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,15 @@ Live testnet (Ropsten) version: https://openbounty.status.im:444 The `develop` branch is automatically deployed here. +## Table of contents +- [Prerequisites](#prerequisites) +- [Application config](#application-config) +- [GitHub integration](#github-integration) +- [Running](#running) +- [Testing](#testing) +- [More info](#more-info) + + ## Prerequisites @@ -47,16 +56,6 @@ brew install https://raw.githubusercontent.com/web3j/homebrew-web3j/881cf369b551 brew pin web3j ``` -## Running - -Launch following commands each in its own shell: - -``` -lein run -lein figwheel -lein less auto -``` - ## Application config Make sure to create `/config-dev.edn` and populate it correctly, which is based on `env/dev/resources/config.edn`. Description of config fields is given below: @@ -92,20 +91,38 @@ Follow the steps [here](https://developer.github.com/apps/building-github-apps/c ## Running -Lauch a local geth node with the bot account unlocked: +### Geth +Launch a local geth node with the bot account unlocked: ``` #!/bin/bash geth --fast --testnet --cache=1024 --datadir=$HOME/.ropsten --verbosity 4 --port 50100 --ipcpath ~/.ropsten/geth.ipc --rpc --rpcaddr 127.0.0.1 --rpcport 8545 --rpcapi db,eth,net,web3,personal --rpccorsdomain "https://wallet.ethereum.org" --unlock "0xYOUR_ADDR" --password <(echo "YOUR_PASSPHRASE") ``` +### CSS auto-compilation Launch the following command in a separate shell: ``` lein less auto ``` -Next you want to start a REPL on the backend and the frontend. +### Solidity compilation +Invoke `build-contracts` Leiningen task to compile Solidity files into Java classes: +``` +lein build-contracts +``` + +### Clojure app without REPL +Launch following commands each in its own shell: + +``` +lein run +lein figwheel +``` + +### Clojure app with REPL + +You'll have to start a REPL on the backend and the frontend. ``` lein repl @@ -135,7 +152,10 @@ To create a standalone uberjar: lein uberjar ``` -This creates `target/uberjar/commiteth-.jar` +This creates `target/uberjar/commiteth.jar`. You can run it with the following command from within project root: +``` +java -Dconf= -jar target/uberjar/commiteth.jar +``` ## Testing @@ -174,8 +194,8 @@ Landing page is static and different CSS and JS due to time constraints. This copies over necessary artifacts to `resources` dir. -### Troubleshooting -See the [Cookbook](doc/cookbook.md). +## More info +Detailed information on code structure, troubleshooting, etc. can be found [here](doc/README.md). ## License diff --git a/doc/core_testing_workflow.md b/doc/core_testing_workflow.md new file mode 100644 index 00000000..55c54c9f --- /dev/null +++ b/doc/core_testing_workflow.md @@ -0,0 +1,27 @@ +# Testing pull requests in Open Bounty + +All new functionality and features both are being delivered by pull requests (hereinafter PRs). +How to test PR? Steps below could help a bit! + +### Prerequisites +Requirements for PRs to be tested: +* should be in `To test` column in `Pipeline For Pull Requests` project +* shouldn't have conflicts with `develop` branch +* should have a successful build in Jenkins [status-openbounty-app](https://jenkins.status.im/job/status-openbounty/job/status-openbounty-app/view/change-requests/) + + +### Deployment +In order to deploy feature to [testing env](https://testing.openbounty.status.im/) you should **rebuild** PR you are about to test. + +Only one PR can be deployed on [testing env](https://testing.openbounty.status.im/) + +Fresh develop branch with last changes is deployed automatically on [staging env](https://openbounty.status.im:444) + +### Testing +1) Move appropriate PR card to IN TESTING on the [Board](https://github.com/status-im/open-bounty/projects/3) and let people know you are on it - assign it to yourself! :) +2) Сheck the functionality current PR fixes / delivers (positive/negative tests related to the feature). In curtain cases it's worth to look in 'Files changed' tab in GitHub to check the list of what was changed to get understanding of the test coverage or "weak" places that have to be covered. Ask PR-author in #openbounty channel in slack what was changed if it's not clear from the notes in PR. +3) Check reasonable regression using [SOB-general test suite](https://ethstatus.testrail.net/index.php?/suites/view/27&group_by=cases:section_id&group_order=asc) +4) No issues? Perfect! Put appropriate label to the PR (`Tested - OK`), merge it to develop and move the PR instance to `Merged to develop`. +5) Found issues? Check for duplicates before adding one. Hint: make sure the issue is really introduced by current PR - check latest `develop` branch on [staging env](https://openbounty.status.im:444) . Issue exists in develop? Check existing issues list and make sure you are not adding duplicates before creating your own bug :) **All PR-specific issues should be added as comments to tested PR.** +Once all issues are logged put label `Tested-issues` to the PR and notify developer that there are several problems that are preventing the PR to merge. Move the PR to `Reviewing, waiting for contributor` on the board if PR is developed by external contributor, and to `Developing` - if it is presented by core contributor. + diff --git a/doc/decisions/0001-record-decisions.md b/doc/decisions/0001-record-decisions.md new file mode 100644 index 00000000..8d32aefb --- /dev/null +++ b/doc/decisions/0001-record-decisions.md @@ -0,0 +1,40 @@ +# 1. Record Decisions + +| Date | Tags | +|------------|---------| +| 2018-02-16 | process | + +## Status + +Proposed + +## Context + +We make a lot of decisions during the life of a project and +documenting those decisions would help new team members and outside +contributors follow our thinking. It also opens up an opportunity for +constructive criticism around those decisions which will result +in better decision making. + +We want to develop a product in the open. Opening up our decision making process for outside contributors is an important part in providing the opportunity to take ownership and impact the project in non-trivial ways. + +Recording decisions will also be a useful form of documentation in general as it does not get out of date. All that's documented is that a decision has been made at a certain point in time. + +## Decision + +We will adopt a format similar to [Architecture Decision +Records](http://thinkrelevance.com/blog/2011/11/15/documenting-architecture-decisions) (ADR) +to propose and document notable decisions. In contrast to ADRs we will try to embrace this tool for more than just architectural concerns. Decisions regarding development practices and product direction are just as important. + +What decisions are notable and which are not is left to common-sense and informal consensus among the team. + +Decisions may be proposed and discussed informally, should however eventually end up — with all relevant discussion summarized — in the `doc/decisions/` directory of this repository. + +Decisions are numbered to have a clear identifier. + +## Consequences + +- We need to document that we record decisions this way and where people can find those documents. +- We should probably provide some pointers around tooling to better work with decision records. [`adr-tools`](https://github.com/npryce/adr-tools) comes to mind. +- Since we deviate from ADRs a bit (we document more than architecture-related decisions) we might need to provide different templates than what comes with tools like `adr-tools` by default. + A template like this may also be useful to guide decision authors to provide appropriate context. \ No newline at end of file diff --git a/doc/decisions/0002-sign-commits-with-gpg.md b/doc/decisions/0002-sign-commits-with-gpg.md new file mode 100644 index 00000000..324ca3e3 --- /dev/null +++ b/doc/decisions/0002-sign-commits-with-gpg.md @@ -0,0 +1,52 @@ +# 2. Sign Commits With GPG + +| Date | Tags | +|------------|-------------------| +| 2018-02-16 | process, security | + + +## Status + +Proposed + +## Context + +OpenBounty is a system which has value flowing through it. +Naturally security is a concern that should be taken into consideration. + +Currently an attacker might get access to an account of a team member +and pose as that developer, merging PRs and pushing changes. + +Status.im as a company is also encouraging the use of GPG signing and +has a Pull Request check in place on Github. This check will mark PRs +as failing if the commits come from an organization member and have not +been GPG-signed. + +## Decision + +In order to verify that commits in the repository are actually authored by the specified +author we adopt [GPG signing of Git commits](https://git-scm.com/book/id/v2/Git-Tools-Signing-Your-Work). + +This will allow us to verify authenticity of the author information saved in +a Git commit and make workflows like deploying on push safer. + +It also introduces some complexity because contributors who want to sign +their commits need to set up the appropriate tooling. Due to that we will +not require outside contributors to sign their commits for now. + +Adopting GPG signing for contributors will also make our PR checks pass +allowing us to more easily discern actually broken and working PRs. + +## Consequences + +GPG signing is only making things safer if we have a trusted way of +exchanging public keys. In the scenario outlined above a user who got access +to GitHub could simply upload an additional key. + +This is currently a work-in-progress within the wider Status organization +and we'll have to wait to see what comes out of that. + +## Appendix + +- [GitHub's instructions for setting up GPG signing](https://help.github.com/articles/signing-commits-using-gpg/) +- More discussion around the usefulness of GPG signing in [issue #285](https://github.com/status-im/open-bounty/issues/285) diff --git a/doc/decisions/README.md b/doc/decisions/README.md new file mode 100644 index 00000000..0c501a75 --- /dev/null +++ b/doc/decisions/README.md @@ -0,0 +1,14 @@ +# Decisions + +We record decisions. More context on why and how we do that can be found in [DR-0001](doc/decisions/0001-record-decisions.md). + +The remainder of this document is intended to document tooling around this process. + +### Utilities to Write Decision Records + +- `doc/decisions/templates/template.md` - contains a template for a decision record. +- When recording a decision follow the established file name format + `XXXX-some-title.md` where XXXX is the ever increasing count of decisions + we've made. + +> More to come. Perhaps document how we can use [`adr-tools`](https://github.com/npryce/adr-tools) \ No newline at end of file diff --git a/doc/decisions/templates/template.md b/doc/decisions/templates/template.md new file mode 100644 index 00000000..01c4d407 --- /dev/null +++ b/doc/decisions/templates/template.md @@ -0,0 +1,31 @@ +# NUMBER. TITLE + +| Date | Tags | +|---|---| +| DATE | e.g: architecture, database | + + +## Status + +STATUS + +Common states: proposed, accepted, rejected, deprecated, superseded + +## Context + +Describe the context in which the decision has been made. +Some questions that should give some ideas what to write here: + +- What problems have you encountered that this decision impacts? +- What is the current state of things that are related to this decision? + +## Decision + +Describe your decision. + +- In what ways does it solve the aforementioned problems or improves something? +- What tradeoffs does this decision make? + +## Consequences + +Expand on tradeoffs and other side-effects of this decision. diff --git a/doc/development_workflow.md b/doc/development_workflow.md new file mode 100644 index 00000000..f9bdb883 --- /dev/null +++ b/doc/development_workflow.md @@ -0,0 +1,74 @@ +# Development process in Status Open Bounty + +We have a continuously deployed version tracking the `develop` branch live at [test environment](https://openbounty.status.im:444). It uses the [Ropsten](https://ropsten.io/) Ethereum testnet. Any one is welcome to use it and contribute to Open Bounty. + +Any help is greatly appreciated! +Currently we use two projects - `Pipeline For Issues` and `Pipeline For Pull Requests`, issues and pull requests in our repository are passing through all or several stages described below. +Whole team is responsible to keep the projects with accurate information. + +**If issue or pull request marked with `Blocked` label, it means that it is blocked on some stage, reason of blocking have to be in comment.** + +## Pipeline For Issues + +Team is working only on issues that included in this project. +Issues can be added to this project by any core team member. + +#### To define +This is backlog for all features/issues/enhancements which we want to include to development process. + +All issues here should be marked with: + +* **type** - `bug`, `tech-debt`,` enhancement` labels. Issues with `proposal` label should be converted to `bug`, `tech-debt`,` enhancement` before addidng to project. +* **priority** - `Prio: high`, `Prio: med`, `Prio: low` labels. On the board inside issues with same priority sorting from higher to lower priority is applied. + +#### Defining +The column is intended for issues not completely clear or for features, that should be splitted to smaller issues in order to go ahead. +After defining all issues that are intended to develop should have size label + +* `Size: XS` - 1-2 hours, +* `Size: S` - 2-4 hours, +* `Size: M` - 4-8 hours, +* `Size: L` - 8-20 hours, +* `Size: XL` - 20-40 hours, +* `Size: XXL` - 40-60 hours. + +#### To design +It is used for issues that are already defined and require designing process. +#### Designing +It shows up that issues are currently in designing process. +#### To develop +It stores issues which are ready for development. +They are explained, clear, designed and **small enough to create one pull request per issue.** +#### In Bounty +The store with issues which are open bounties. When we put funds to issue and it shows up in [status open bounty](https://openbounty.status.im), we move issue here. +#### Developing +This is for issues that are currently developing, so pull requests assosiated with issues have to be placed in `Pipeline for Pull Request` project. +#### Done +It stores issues with merged to `master` pull requests. +## Pipeline For Pull Requests + +#### Developing +Contains all open pull requests (hereinafter PRs) that already assosiated with issues. +#### Reviewing, waiting for contributor +It keeps all PRs from external contributors which should pass `Reviewing` stage. +#### Reviewing +The storage for all PRs that pass reviewing process. +Review process is discussed [here](https://github.com/status-im/open-bounty/issues/221) +The number of reviewers should be proportional to the complexity of the change and may vary from PR to PR. +Recommended: +* PR is trivial (from core contributor) - 1 approval from core contributor +* PR is normal (or from external contributor) - 2 or more approvals from core contributors +* PR need to be based on and opened against the `develop` branch. +* If a PR has undergone review and requires changes from author, move it back to `Contributor` column +#### To test +All PRs, that are already developed, reviewed, and haven't conflicts with `develop` branch, so ready to be tested. +In case if PR has conflict - it is moved to `Reviewing, waiting for contributor` for external contributors or to `Developing` for core contributors. +#### Testing +Contains all PRs that are currently should pass through testing process, which is described in `core_testing_workflow.md`. +After testing two scenarios possible: +* no issues assosiated with PR - `Tested: OK` label, merge to develop (using `Merge` button) to `Merged to develop` +* issues found - all of them are created as comments to current PR and PR is moved to `Developing` +#### Merged to develop +Keeps PRs that should be merged to `master` and deployed to [prod environment](https://openbounty.status.im/) +#### Done +Stores all merged and closed PRs. diff --git a/env/dev/clj/user.clj b/env/dev/clj/user.clj index b318a866..a70555af 100644 --- a/env/dev/clj/user.clj +++ b/env/dev/clj/user.clj @@ -1,15 +1,34 @@ (ns user (:require [mount.core :as mount] - [commiteth.figwheel :refer [start-fw stop-fw cljs]])) + [commiteth.figwheel :refer [start-fw stop-fw cljs]] + [clojure.tools.namespace.repl :as repl])) -(defn start [] +(repl/set-refresh-dirs "src" "dev" "test") + +(defn start + "Start all the application components" + [] (require 'commiteth.core) (mount/start-without (ns-resolve 'commiteth.core 'repl-server))) -(defn stop [] +(defn stop + "Stop all the application components" + [] (require 'commiteth.core) (mount/stop-except (ns-resolve 'commiteth.core 'repl-server))) +(defn refresh + "Reload the latest namespace definitions" + [] + (repl/refresh)) + +(defn reset + "Restart application after refreshing namespace definitions" + [] + (stop) + (repl/refresh :after 'user/start)) + (defn restart [] + "Restart without refreshing namespace definitions" (stop) (start)) diff --git a/project.clj b/project.clj index ccb500f6..094f2f98 100644 --- a/project.clj +++ b/project.clj @@ -42,7 +42,6 @@ [cheshire "5.8.0"] [mpg "1.3.0"] [pandect "0.6.1"] - [cljsjs/moment "2.17.1-1"] [org.clojure/tools.nrepl "0.2.13"] [com.cemerick/piggieback "0.2.2"] [jarohen/chime "0.2.2"] @@ -84,14 +83,13 @@ :uberjar-exclusions [#"public/README.md" #"public/cards.html"] :clean-targets ^{:protect false} - [:target-path [:cljsbuild :builds :app :compiler :output-dir] [:cljsbuild :builds :app :compiler :output-to]] + [:target-path :java-source-paths [:cljsbuild :builds :app :compiler :output-dir] [:cljsbuild :builds :app :compiler :output-to]] :figwheel {:http-server-root "public" :nrepl-port 7002 :css-dirs ["resources/public/css"] :nrepl-middleware [cemerick.piggieback/wrap-cljs-repl]} - :profiles {:uberjar {:jvm-opts ["-server" "-Dconf=config-prod.edn"] :omit-source true @@ -125,6 +123,7 @@ [binaryage/devtools "0.9.7"] [figwheel-sidecar "0.5.14"] [org.clojure/tools.nrepl "0.2.13"] + [org.clojure/tools.namespace "0.2.11"] [com.cemerick/piggieback "0.2.2"] [sablono "0.8.1"]] :plugins [[com.jakemccrary/lein-test-refresh "0.14.0"] @@ -143,7 +142,6 @@ :optimizations :none :pretty-print true}}]} - :prep-tasks ["build-contracts" "javac"] :doo {:build "test"} :source-paths ["env/dev/clj" "test/clj"] :resource-paths ["env/dev/resources"] diff --git a/resources/migrations/20171226182259-hide-user.down.sql b/resources/migrations/20171226182259-hide-user.down.sql new file mode 100644 index 00000000..1b3dcc81 --- /dev/null +++ b/resources/migrations/20171226182259-hide-user.down.sql @@ -0,0 +1,35 @@ +BEGIN; + +-- restore the previous version of the view +CREATE OR REPLACE VIEW "public"."claims_view" AS +SELECT + i.title AS issue_title, + i.issue_number, + r.repo AS repo_name, + r.owner AS repo_owner, + COALESCE(u.name, u.login) AS user_name, + u.avatar_url AS user_avatar_url, + i.payout_receipt, + p.updated, + i.updated AS issue_updated, + i.balance_eth, + i.tokens, + i.value_usd, + p.state AS pr_state, + i.is_open AS issue_open, + (case when u.address IS NULL THEN false ELSE true END) AS user_has_address + FROM issues i, + users u, + repositories r, + pull_requests p + WHERE r.repo_id = i.repo_id + AND p.issue_id = i.issue_id + AND p.user_id = u.id + AND i.contract_address IS NOT NULL + AND i.comment_id IS NOT NULL + ORDER BY p.updated; + +ALTER TABLE users + DROP COLUMN is_hidden_in_hunters; + +COMMIT; diff --git a/resources/migrations/20171226182259-hide-user.up.sql b/resources/migrations/20171226182259-hide-user.up.sql new file mode 100644 index 00000000..a1aa2338 --- /dev/null +++ b/resources/migrations/20171226182259-hide-user.up.sql @@ -0,0 +1,35 @@ +BEGIN; + +ALTER TABLE users + ADD COLUMN is_hidden_in_hunters BOOLEAN NOT NULL DEFAULT FALSE; + +CREATE OR REPLACE VIEW "public"."claims_view" AS +SELECT + i.title AS issue_title, + i.issue_number, + r.repo AS repo_name, + r.owner AS repo_owner, + COALESCE(u.name, u.login) AS user_name, + u.avatar_url AS user_avatar_url, + i.payout_receipt, + p.updated, + i.updated AS issue_updated, + i.balance_eth, + i.tokens, + i.value_usd, + p.state AS pr_state, + i.is_open AS issue_open, + (case when u.address IS NULL THEN false ELSE true END) AS user_has_address + FROM issues i, + users u, + repositories r, + pull_requests p + WHERE r.repo_id = i.repo_id + AND p.issue_id = i.issue_id + AND p.user_id = u.id + AND i.contract_address IS NOT NULL + AND i.comment_id IS NOT NULL + AND NOT u.is_hidden_in_hunters -- added + ORDER BY p.updated; + +COMMIT; diff --git a/resources/sql/queries.sql b/resources/sql/queries.sql index 4b13c440..8c80d96d 100644 --- a/resources/sql/queries.sql +++ b/resources/sql/queries.sql @@ -18,6 +18,12 @@ WHERE NOT exists(SELECT 1 WHERE id = :id) RETURNING id, login, name, email, avatar_url, address, created; +-- :name user-exists? :? :1 +-- :doc Checks where a user exists in the database. +select 1 +from users u +where u.id = :id; + -- :name update-user! :! :n -- :doc updates an existing user record UPDATE users @@ -589,6 +595,7 @@ WHERE pr.commit_sha = i.commit_sha AND u.id = pr.user_id AND i.payout_receipt IS NOT NULL +AND NOT u.is_hidden_in_hunters GROUP BY u.id ORDER BY total_usd DESC LIMIT 5; diff --git a/src/clj/commiteth/core.clj b/src/clj/commiteth/core.clj index d3c46a74..da45953d 100644 --- a/src/clj/commiteth/core.clj +++ b/src/clj/commiteth/core.clj @@ -54,10 +54,9 @@ repl-server (cond (some #{"migrate" "rollback"} args) (do - (mount/start - #'commiteth.config/env - #'commiteth.db.core/*db*) - (migrations/migrate args (select-keys env [:jdbc-database-url])) + (mount/start #'commiteth.config/env) + (migrations/migrate args {:database-url (:jdbc-database-url env)}) + (log/info "Successfully ran" (first args)) (System/exit 0)) :else (start-app args))) diff --git a/src/clj/commiteth/db/core.clj b/src/clj/commiteth/db/core.clj index a33f2e08..2ca5ff74 100644 --- a/src/clj/commiteth/db/core.clj +++ b/src/clj/commiteth/db/core.clj @@ -27,7 +27,6 @@ :migration-table-name "schema_migrations" :db db}] (migratus/migrate migratus-config) - (conman/bind-connection db "sql/queries.sql") (conman/connect! {:jdbc-url db}) db)) @@ -85,3 +84,11 @@ (sql-value [value] (to-pg-json value)) IPersistentVector (sql-value [value] (to-pg-json value))) + +(defmacro with-tx [& body] + "Performs a set of queries in transaction." + `(conman/with-transaction [*db*] + ~@body)) + +(defn update! [& args] + (apply jdbc/update! *db* args)) diff --git a/src/clj/commiteth/routes/services.clj b/src/clj/commiteth/routes/services.clj index 82c56334..d8139624 100644 --- a/src/clj/commiteth/routes/services.clj +++ b/src/clj/commiteth/routes/services.clj @@ -5,6 +5,7 @@ [compojure.api.meta :refer [restructure-param]] [buddy.auth.accessrules :refer [restrict]] [buddy.auth :refer [authenticated?]] + [commiteth.db.core :as db] [commiteth.db.users :as users] [commiteth.db.usage-metrics :as usage-metrics] [commiteth.db.repositories :as repositories] @@ -214,26 +215,35 @@ (do (log/debug "/usage-metrics" user) (ok (usage-metrics/usage-metrics-by-day)))) + (context "/user" [] + (GET "/" {:keys [params]} :auth-rules authenticated? :current-user user (ok (handle-get-user user (:token params)))) - (POST "/address" [] + + (POST "/" [] :auth-rules authenticated? - :body-params [user-id :- Long, address :- String] - :summary "Update user address" - (if-not (eth/valid-address? address) - (do - (log/debug "POST /address: invalid input" address) - {:status 400 - :body (str "Invalid Ethereum address '" address "'")}) - (let [result (users/update-user-address - user-id - address)] - (if (= 1 result) - (ok) - (internal-server-error))))) + :current-user user + :body [body {:address s/Str + :is_hidden_in_hunters s/Bool}] + :summary "Updates user's fields." + + (let [user-id (:id user) + {:keys [address]} body] + + (when-not (eth/valid-address? address) + (log/debugf "POST /user: Wrong address %s" address) + (bad-request! (format "Invalid Ethereum address: %s" address))) + + (db/with-tx + (when-not (db/user-exists? {:id user-id}) + (not-found! "No such a user.")) + (db/update! :users body ["id = ?" user-id])) + + (ok))) + (GET "/repositories" {:keys [params]} :auth-rules authenticated? :current-user user diff --git a/src/cljs/commiteth/activity.cljs b/src/cljs/commiteth/activity.cljs index 887b8c7c..ec991fa5 100644 --- a/src/cljs/commiteth/activity.cljs +++ b/src/cljs/commiteth/activity.cljs @@ -1,7 +1,7 @@ (ns commiteth.activity (:require [re-frame.core :as rf] [reagent.core :as r] - [commiteth.common :refer [moment-timestamp + [commiteth.common :refer [human-time items-per-page display-data-page issue-url]])) @@ -54,7 +54,7 @@ ^{:key (random-uuid)} [:div.balance-badge.token (str (subs (str tla) 1) " " balance)])]) - [:div.time (moment-timestamp updated)]]]]) + [:div.time (human-time updated)]]]]) (defn activity-list [{:keys [items item-count page-number total-count] :as activity-page-data} diff --git a/src/cljs/commiteth/bounties.cljs b/src/cljs/commiteth/bounties.cljs index bbdceec7..d4eaa8fb 100644 --- a/src/cljs/commiteth/bounties.cljs +++ b/src/cljs/commiteth/bounties.cljs @@ -1,7 +1,7 @@ (ns commiteth.bounties (:require [reagent.core :as r] [re-frame.core :as rf] - [commiteth.common :refer [moment-timestamp + [commiteth.common :refer [human-time display-data-page items-per-page issue-url]] @@ -33,7 +33,7 @@ [:div.open-bounty-item-content [:div.header issue-link] [:div.bounty-item-row - [:div.time (moment-timestamp updated)] + [:div.time (human-time updated)] [:span.bounty-repo-label repo-link]] [:div.footer-row diff --git a/src/cljs/commiteth/common.cljs b/src/cljs/commiteth/common.cljs index 1213395e..94fca42d 100644 --- a/src/cljs/commiteth/common.cljs +++ b/src/cljs/commiteth/common.cljs @@ -2,7 +2,9 @@ (:require [reagent.core :as r] [re-frame.core :as rf] [clojure.string :as str] - [cljsjs.moment])) + [goog.date.relative] + [goog.i18n.DateTimePatterns :as DateTimePatterns]) + (:import (goog.i18n DateTimeFormat))) (defn input [val-ratom props] (fn [] @@ -12,21 +14,32 @@ :on-change #(reset! val-ratom (-> % .-target .-value))})])) (defn dropdown [props title val-ratom items] + "If val-ratom is set, preselect it in the dropdown. + Otherwise, prepend title as a disabled option." (fn [] - (if (= 1 (count items)) - (reset! val-ratom (first items))) [:select.ui.basic.selection.dropdown (merge props {:on-change - #(reset! val-ratom (-> % .-target .-value))}) - (doall (for [item items] - ^{:key item} [:option - {:value item} - item]))])) + #(reset! val-ratom (-> % .-target .-value)) + :default-value (or @val-ratom title)}) + (for [item items] + ^{:key item} [:option {:value item + :disabled (= item title)} + item])])) -(defn moment-timestamp [time] - (let [now (.now js/Date.) - js-time (clj->js time)] - (.to (js/moment.utc) js-time))) +(def ^:private long-ago-fmt + (DateTimeFormat. DateTimePatterns/MONTH_DAY_FULL)) + +(defn human-time [date] + "Shows a given date in a human-friendly way. For dates less than + two weeks ago this means a relative '3 hours ago' kind of thing. + For dates longer ago we return 'January 01'." + (let [ms (.getTime date) + relative (goog.date.relative/format ms)] + ;; Dates older than 2 weeks will not be shown as relative + ;; https://github.com/google/closure-library/blob/99d7fa323f4c9e35ce7a97ea3cb08fc1d97d9e92/closure/goog/date/relative.js#L206 + (if-not (empty? relative) + relative + (goog.date.relative/formatDay ms #(.format long-ago-fmt %))))) (defn issue-url [owner repo number] (str "https://github.com/" owner "/" repo "/issues/" number)) diff --git a/src/cljs/commiteth/core.cljs b/src/cljs/commiteth/core.cljs index 20344492..7fdf6599 100644 --- a/src/cljs/commiteth/core.cljs +++ b/src/cljs/commiteth/core.cljs @@ -217,8 +217,8 @@ [:div.ui.container.top-hunters [:h3.top-hunters-header "Top 5 hunters"] [:div.top-hunters-subheader "All time"] - [top-hunters]]])]] - [footer]]]))) + [top-hunters]]])]]] + [footer]]))) (secretary/set-config! :prefix "#") diff --git a/src/cljs/commiteth/handlers.cljs b/src/cljs/commiteth/handlers.cljs index 20fdd74a..1bf471df 100644 --- a/src/cljs/commiteth/handlers.cljs +++ b/src/cljs/commiteth/handlers.cljs @@ -62,7 +62,6 @@ (fn [db [_ path value]] (assoc-in db path value))) - (reg-event-db :set-active-page (fn [db [_ page]] @@ -319,32 +318,38 @@ {:db db :dispatch [:set-active-page :update-address]})) +(reg-event-db + :update-user + (fn [db [_ fields]] + (update db :user merge fields))) (reg-event-fx - :save-user-address - (fn [{:keys [db]} [_ user-id address]] - (prn "save-user-address" user-id address) - {:db (assoc db :updating-address true) + :save-user-fields + (fn [{:keys [db]} [_ fields]] + {:dispatch [:set-updating-user] :http {:method POST - :url "/api/user/address" + :url "/api/user" :on-success #(do - (dispatch [:assoc-in [:user [:address] address]]) + (dispatch [:update-user fields]) (dispatch [:set-flash-message :success - "Address saved"])) - :on-error #(do - (println %) - (dispatch [:set-flash-message - :error - (:response %)])) - :finally #(dispatch [:clear-updating-address]) - :params {:user-id user-id :address address}}})) + "Settings saved"])) + :on-error #(dispatch [:set-flash-message + :error + (:response %)]) + :finally #(dispatch [:clear-updating-user]) + :params fields}})) + (reg-event-db - :clear-updating-address + :set-updating-user (fn [db _] - (dissoc db :updating-address))) + (assoc db :updating-user true))) +(reg-event-db + :clear-updating-user + (fn [db _] + (dissoc db :updating-user))) (reg-event-fx :save-payout-hash diff --git a/src/cljs/commiteth/manage_payouts.cljs b/src/cljs/commiteth/manage_payouts.cljs index 746b1a94..4c4368ab 100644 --- a/src/cljs/commiteth/manage_payouts.cljs +++ b/src/cljs/commiteth/manage_payouts.cljs @@ -1,6 +1,6 @@ (ns commiteth.manage-payouts (:require [re-frame.core :as rf] - [commiteth.common :refer [moment-timestamp]])) + [commiteth.common :refer [human-time]])) @@ -33,7 +33,7 @@ [:div.description (if paid? (str "(paid to " winner-login ")") (str "(" (if merged? "merged" "open") ")"))] - [:div.time (moment-timestamp updated)] + [:div.time (human-time updated)] [:button.ui.button (merge (if (and merged? (not paid?)) {} diff --git a/src/cljs/commiteth/ui_model.cljs b/src/cljs/commiteth/ui_model.cljs index 909828c1..d814a45e 100644 --- a/src/cljs/commiteth/ui_model.cljs +++ b/src/cljs/commiteth/ui_model.cljs @@ -87,8 +87,8 @@ ::bounty-filter-type.category ::bounty-filter-type-category|multiple-dynamic-options ::bounty-filter-type.re-frame-subs-key-for-options :commiteth.subscriptions/open-bounties-currencies ::bounty-filter-type.predicate (fn [filter-value bounty] - (or (and (contains? #{"ETH"} filter-value) - (< 0 (:balance-eth bounty))) + (or (and (contains? filter-value "ETH") + (< 0 (js/parseFloat (:balance-eth bounty)))) (not-empty (set/intersection (->> filter-value (remove #{"ETH"}) set) diff --git a/src/cljs/commiteth/update_address.cljs b/src/cljs/commiteth/update_address.cljs index b5eb0af4..870cec46 100644 --- a/src/cljs/commiteth/update_address.cljs +++ b/src/cljs/commiteth/update_address.cljs @@ -3,42 +3,71 @@ [commiteth.common :refer [input dropdown]] [reagent.core :as r] [reagent.crypt :as crypt] + [clojure.string :as str] [cljs-web3.eth :as web3-eth])) (defn update-address-page-contents [] (let [db (rf/subscribe [:db]) - user (rf/subscribe [:user]) - updating-address (rf/subscribe [:get-in [:updating-address]]) - address (r/atom @(rf/subscribe [:get-in [:user :address]]))] + updating-user (rf/subscribe [:get-in [:updating-user]]) + address (r/atom @(rf/subscribe [:get-in [:user :address]])) + hidden (r/atom @(rf/subscribe [:get-in [:user :is_hidden_in_hunters]]))] + (fn [] (let [web3 (:web3 @db) web3-accounts (when web3 (web3-eth/accounts web3))] - (println "web3-accounts" web3-accounts) [:div.ui.container.grid [:div.ui.form.sixteen.wide.column [:h3 "Update address"] [:p "Insert your Ethereum address in hex format."] [:div.field (if-not (empty? web3-accounts) - [dropdown {:class "address-input"} "Select address" - address - (vec - (for [acc web3-accounts] - acc))] + ; Add value of address if it's missing from items list. + ; If address is empty, add title + (let [accounts (map str/lower-case web3-accounts) + addr @address + title "Select address" + addr-not-in-web3? (and addr (as-> web3-accounts acc + (map str/lower-case acc) + (set acc) + (contains? acc addr) + (not acc))) + items (cond->> web3-accounts + addr-not-in-web3? (into [addr]) + (not addr) (into [title]))] + [dropdown {:class "address-input"} + title + address + items]) [:div.ui.input.address-input - [input address {:placeholder "0x0000000000000000000000000000000000000000" + [input address {:placeholder "0x0000000000000000000000000000000000000000" :auto-complete "off" :auto-correct "off" :spell-check "false" :max-length 42}]])] + + [:h3 "Settings"] + + [:div + [:input + {:type :checkbox + :disabled @updating-user + :id :input-hidden + :checked @hidden + :on-change + (fn [e] + (let [value (-> e .-target .-checked)] + (reset! hidden value)))}] + + [:label {:for :input-hidden} "Disguise myself from the top hunters and activity lists."]] + [:button (merge {:on-click - #(rf/dispatch [:save-user-address - (:id @user) - @address]) + #(rf/dispatch [:save-user-fields {:address @address + :is_hidden_in_hunters @hidden}]) + :disabled (str/blank? @address) :class (str "ui button small update-address-button" - (when @updating-address + (when @updating-user " busy loading"))}) "UPDATE"]]])))) diff --git a/src/less/style.less b/src/less/style.less index 8b90d73a..bef51baf 100644 --- a/src/less/style.less +++ b/src/less/style.less @@ -41,17 +41,26 @@ .update-address-button { background-color: #57a7ed!important; + margin-top: 10px !important; &:hover { background-color: #57a7ed!important; } } +label[for="input-hidden"] { + padding-left: 8px; +} + +#input-hidden { + vertical-align: bottom; + position: relative; + top: -4px; +} .login-button { background-color: rgba(255,255,255,0.2)!important; } - .commiteth-header { background-color: #57a7ed!important; border-radius: 0em; @@ -864,6 +873,8 @@ box-shadow: none; border-radius: 0.3em; + min-height: calc(~"100vh - 400px"); + h3 { color: #474951; } @@ -986,7 +997,6 @@ z-index: -1; display: flex; justify-content: center; - margin-top: 20px; } @@ -1285,5 +1295,3 @@ body { color: #8d99a4; padding-top: 20px; } - -