From e0815031db3c2ed5d1fe260098bcd29c2657ed01 Mon Sep 17 00:00:00 2001 From: Chad Whitacre Date: Wed, 16 Sep 2015 11:32:04 -0400 Subject: [PATCH 01/31] Reimplement CSS using a renderer Over on #3786 I want to make a dashboard.css that uses the same but separate SCSS wiring. --- gratipay/main.py | 4 +- gratipay/renderers/scss.py | 43 +++++++++++++++++++ scss/gratipay.scss | 66 ---------------------------- www/assets/gratipay.css.spt | 85 ++++++++++++++++++++++++++++--------- 4 files changed, 110 insertions(+), 88 deletions(-) create mode 100644 gratipay/renderers/scss.py delete mode 100644 scss/gratipay.scss diff --git a/gratipay/main.py b/gratipay/main.py index b04f3faaf2..bc63412e5a 100644 --- a/gratipay/main.py +++ b/gratipay/main.py @@ -10,7 +10,7 @@ from gratipay.security import authentication, csrf, security_headers from gratipay.utils import erase_cookie, http_caching, i18n, set_cookie, timer from gratipay.version import get_version -from gratipay.renderers import csv_dump, jinja2_htmlescaped, eval_ +from gratipay.renderers import csv_dump, jinja2_htmlescaped, eval_, scss import aspen from aspen.website import Website @@ -27,8 +27,10 @@ website.renderer_factories['csv_dump'] = csv_dump.Factory(website) website.renderer_factories['eval'] = eval_.Factory(website) website.renderer_factories['jinja2_htmlescaped'] = jinja2_htmlescaped.Factory(website) +website.renderer_factories['scss'] = scss.Factory(website) website.default_renderers_by_media_type['text/html'] = 'jinja2_htmlescaped' website.default_renderers_by_media_type['text/plain'] = 'jinja2' # unescaped is fine here +website.default_renderers_by_media_type['text/css'] = 'scss' website.default_renderers_by_media_type['image/*'] = 'eval' website.renderer_factories['jinja2'].Renderer.global_context = { diff --git a/gratipay/renderers/scss.py b/gratipay/renderers/scss.py new file mode 100644 index 0000000000..50008d396d --- /dev/null +++ b/gratipay/renderers/scss.py @@ -0,0 +1,43 @@ +from __future__ import absolute_import, division, print_function, unicode_literals + +import re +from urlparse import urlsplit + +import sass +from aspen import renderers + + +class Renderer(renderers.Renderer): + + def __init__(self, *a, **kw): + renderers.Renderer.__init__(self, *a, **kw) + self.website = self._factory._configuration + + url_re = re.compile(r"""\burl\((['"])(.+?)['"]\)""") + + def url_sub(self, m): + url = urlsplit(m.group(2)) + if url.scheme or url.netloc: + # We need both tests because "//example.com" has no scheme and "data:" + # has no netloc. In either case, we want to leave the URL untouched. + return m.group(0) + repl = self.website.asset(url.path) \ + + (url.query and '&'+url.query) \ + + (url.fragment and '#'+url.fragment) + return 'url({0}{1}{0})'.format(m.group(1), repl) + + def replace_urls(self, css): + return self.url_re.sub(self.url_sub, css) + + def render_content(self, context): + output_style = 'compressed' if self.website.compress_assets else 'nested' + kw = dict(output_style=output_style, string=self.compiled) + if self.website.project_root is not None: + kw['include_paths'] = self.website.project_root + css = sass.compile(**kw) + if self.website.cache_static: + css = self.replace_urls(css) + return css + +class Factory(renderers.Factory): + Renderer = Renderer diff --git a/scss/gratipay.scss b/scss/gratipay.scss deleted file mode 100644 index 57cef0c59a..0000000000 --- a/scss/gratipay.scss +++ /dev/null @@ -1,66 +0,0 @@ -/* - This is the top of the Gratipay CSS tree. - - Our code organization here was inspired by Brad Frost's Atomic Web Design: - - http://bradfrost.com/blog/post/atomic-web-design/ - - We dropped the "atomic" metaphor and tried to use nomenclature consistent - with how the W3C talks about HTML. - -*/ - -@import "mixins/layout"; -@import "mixins/icons"; -@import "mixins/borders-backgrounds-shadows"; -@import "mixins/animation"; -@import "mixins/transform"; -@import "utils"; -@import "variables"; - -@import "elements/reset"; -@import "elements/buttons-knobs"; -@import "elements/elements"; - -@import "components/banner"; -@import "components/chart"; -@import "components/chosen"; -@import "components/communities"; -@import "components/cta"; -@import "components/dropdown"; -@import "components/emails"; -@import "components/js-edit"; -@import "components/linear_gradient"; -@import "components/loading-indicators"; -@import "components/memberships"; -@import "components/nav"; -@import "components/payments-by"; -@import "components/profile-statement"; -@import "components/sidebar"; -@import "components/sign_in"; -@import "components/status-icon"; -@import "components/support_gratipay"; -@import "components/table"; -@import "components/tip-distribution"; -@import "components/tipr"; -@import "components/upgrade"; - -@import "fragments/accounts"; -@import "fragments/members"; -@import "fragments/mini-user"; -@import "fragments/notifications"; -@import "fragments/pagination"; - -@import "layouts/layout"; -@import "layouts/responsiveness"; - -@import "pages/homepage"; -@import "pages/history"; -@import "pages/team"; -@import "pages/profile-edit"; -@import "pages/giving"; -@import "pages/settings"; -@import "pages/cc-ba"; -@import "pages/on-confirm"; -@import "pages/search"; -@import "pages/hall-of-fame"; diff --git a/www/assets/gratipay.css.spt b/www/assets/gratipay.css.spt index 9ed384eaa2..4838bc5b00 100644 --- a/www/assets/gratipay.css.spt +++ b/www/assets/gratipay.css.spt @@ -1,25 +1,68 @@ -import os -import re -from urlparse import urlsplit +[---] +[---] text/css via scss +/* + This is the top of the Gratipay CSS tree. -import sass + Our code organization here was inspired by Brad Frost's Atomic Web Design: -filename = os.path.join(website.project_root, 'scss', 'gratipay.scss') -output_style = 'compressed' if website.compress_assets else 'nested' + http://bradfrost.com/blog/post/atomic-web-design/ -def url_sub(m): - url = urlsplit(m.group(2)) - if url.scheme or url.netloc: - # We need both tests because "//example.com" has no scheme and "data:" - # has no netloc. In either case, we want to leave the URL untouched. - return m.group(0) - repl = website.asset(url.path) + (url.query and '&'+url.query) + (url.fragment and '#'+url.fragment) - return 'url({0}{1}{0})'.format(m.group(1), repl) + We dropped the "atomic" metaphor and tried to use nomenclature consistent + with how the W3C talks about HTML. -url_re = re.compile(r"""\burl\((['"])(.+?)['"]\)""") -[---] -css = sass.compile(output_style=str(output_style),filename=str(filename)) -if website.cache_static: - css = url_re.sub(url_sub, css) -[---] via stdlib_format -{css} +*/ + +@import "scss/mixins/layout"; +@import "scss/mixins/icons"; +@import "scss/mixins/borders-backgrounds-shadows"; +@import "scss/mixins/animation"; +@import "scss/mixins/transform"; +@import "scss/utils"; +@import "scss/variables"; + +@import "scss/elements/reset"; +@import "scss/elements/buttons-knobs"; +@import "scss/elements/elements"; + +@import "scss/components/banner"; +@import "scss/components/chart"; +@import "scss/components/chosen"; +@import "scss/components/communities"; +@import "scss/components/cta"; +@import "scss/components/dropdown"; +@import "scss/components/emails"; +@import "scss/components/js-edit"; +@import "scss/components/linear_gradient"; +@import "scss/components/loading-indicators"; +@import "scss/components/memberships"; +@import "scss/components/nav"; +@import "scss/components/payments-by"; +@import "scss/components/profile-statement"; +@import "scss/components/sidebar"; +@import "scss/components/sign_in"; +@import "scss/components/status-icon"; +@import "scss/components/support_gratipay"; +@import "scss/components/table"; +@import "scss/components/tip-distribution"; +@import "scss/components/tipr"; +@import "scss/components/upgrade"; + +@import "scss/fragments/accounts"; +@import "scss/fragments/members"; +@import "scss/fragments/mini-user"; +@import "scss/fragments/notifications"; +@import "scss/fragments/pagination"; + +@import "scss/layouts/layout"; +@import "scss/layouts/responsiveness"; + +@import "scss/pages/homepage"; +@import "scss/pages/history"; +@import "scss/pages/team"; +@import "scss/pages/profile-edit"; +@import "scss/pages/giving"; +@import "scss/pages/settings"; +@import "scss/pages/cc-ba"; +@import "scss/pages/on-confirm"; +@import "scss/pages/search"; +@import "scss/pages/hall-of-fame"; From c96df4e0099754cc24456424d4b9af42cd853a3f Mon Sep 17 00:00:00 2001 From: Chad Whitacre Date: Wed, 16 Sep 2015 09:05:45 -0400 Subject: [PATCH 02/31] Backbone app barely working --- sql/branch.sql | 7 +++ www/assets/backbone-min.js | 2 + www/assets/dashboard.js | 49 ++++++++++++++++ www/assets/underscore-min.js | 6 ++ www/dashboard/accounts/index.spt | 38 +++++++++++++ www/dashboard/index.spt | 96 +++----------------------------- www/dashboard/ledger.spt | 21 +++++++ www/dashboard/user-review.spt | 95 +++++++++++++++++++++++++++++++ 8 files changed, 226 insertions(+), 88 deletions(-) create mode 100644 sql/branch.sql create mode 100644 www/assets/backbone-min.js create mode 100644 www/assets/dashboard.js create mode 100644 www/assets/underscore-min.js create mode 100644 www/dashboard/accounts/index.spt create mode 100644 www/dashboard/ledger.spt create mode 100644 www/dashboard/user-review.spt diff --git a/sql/branch.sql b/sql/branch.sql new file mode 100644 index 0000000000..a0f7520a2e --- /dev/null +++ b/sql/branch.sql @@ -0,0 +1,7 @@ +BEGIN; + + CREATE TABLE accounts + ( + ); + +END; diff --git a/www/assets/backbone-min.js b/www/assets/backbone-min.js new file mode 100644 index 0000000000..1a1f708dad --- /dev/null +++ b/www/assets/backbone-min.js @@ -0,0 +1,2 @@ +(function(t){var e=typeof self=="object"&&self.self==self&&self||typeof global=="object"&&global.global==global&&global;if(typeof define==="function"&&define.amd){define(["underscore","jquery","exports"],function(i,r,n){e.Backbone=t(e,n,i,r)})}else if(typeof exports!=="undefined"){var i=require("underscore"),r;try{r=require("jquery")}catch(n){}t(e,exports,i,r)}else{e.Backbone=t(e,{},e._,e.jQuery||e.Zepto||e.ender||e.$)}})(function(t,e,i,r){var n=t.Backbone;var s=Array.prototype.slice;e.VERSION="1.2.3";e.$=r;e.noConflict=function(){t.Backbone=n;return this};e.emulateHTTP=false;e.emulateJSON=false;var a=function(t,e,r){switch(t){case 1:return function(){return i[e](this[r])};case 2:return function(t){return i[e](this[r],t)};case 3:return function(t,n){return i[e](this[r],h(t,this),n)};case 4:return function(t,n,s){return i[e](this[r],h(t,this),n,s)};default:return function(){var t=s.call(arguments);t.unshift(this[r]);return i[e].apply(i,t)}}};var o=function(t,e,r){i.each(e,function(e,n){if(i[n])t.prototype[n]=a(e,n,r)})};var h=function(t,e){if(i.isFunction(t))return t;if(i.isObject(t)&&!e._isModel(t))return u(t);if(i.isString(t))return function(e){return e.get(t)};return t};var u=function(t){var e=i.matches(t);return function(t){return e(t.attributes)}};var l=e.Events={};var c=/\s+/;var f=function(t,e,r,n,s){var a=0,o;if(r&&typeof r==="object"){if(n!==void 0&&"context"in s&&s.context===void 0)s.context=n;for(o=i.keys(r);a7);this._useHashChange=this._wantsHashChange&&this._hasHashChange;this._wantsPushState=!!this.options.pushState;this._hasPushState=!!(this.history&&this.history.pushState);this._usePushState=this._wantsPushState&&this._hasPushState;this.fragment=this.getFragment();this.root=("/"+this.root+"/").replace(O,"/");if(this._wantsHashChange&&this._wantsPushState){if(!this._hasPushState&&!this.atRoot()){var e=this.root.slice(0,-1)||"/";this.location.replace(e+"#"+this.getPath());return true}else if(this._hasPushState&&this.atRoot()){this.navigate(this.getHash(),{replace:true})}}if(!this._hasHashChange&&this._wantsHashChange&&!this._usePushState){this.iframe=document.createElement("iframe");this.iframe.src="javascript:0";this.iframe.style.display="none";this.iframe.tabIndex=-1;var r=document.body;var n=r.insertBefore(this.iframe,r.firstChild).contentWindow;n.document.open();n.document.close();n.location.hash="#"+this.fragment}var s=window.addEventListener||function(t,e){return attachEvent("on"+t,e)};if(this._usePushState){s("popstate",this.checkUrl,false)}else if(this._useHashChange&&!this.iframe){s("hashchange",this.checkUrl,false)}else if(this._wantsHashChange){this._checkUrlInterval=setInterval(this.checkUrl,this.interval)}if(!this.options.silent)return this.loadUrl()},stop:function(){var t=window.removeEventListener||function(t,e){return detachEvent("on"+t,e)};if(this._usePushState){t("popstate",this.checkUrl,false)}else if(this._useHashChange&&!this.iframe){t("hashchange",this.checkUrl,false)}if(this.iframe){document.body.removeChild(this.iframe);this.iframe=null}if(this._checkUrlInterval)clearInterval(this._checkUrlInterval);M.started=false},route:function(t,e){this.handlers.unshift({route:t,callback:e})},checkUrl:function(t){var e=this.getFragment();if(e===this.fragment&&this.iframe){e=this.getHash(this.iframe.contentWindow)}if(e===this.fragment)return false;if(this.iframe)this.navigate(e);this.loadUrl()},loadUrl:function(t){if(!this.matchRoot())return false;t=this.fragment=this.getFragment(t);return i.some(this.handlers,function(e){if(e.route.test(t)){e.callback(t);return true}})},navigate:function(t,e){if(!M.started)return false;if(!e||e===true)e={trigger:!!e};t=this.getFragment(t||"");var i=this.root;if(t===""||t.charAt(0)==="?"){i=i.slice(0,-1)||"/"}var r=i+t;t=this.decodeFragment(t.replace(U,""));if(this.fragment===t)return;this.fragment=t;if(this._usePushState){this.history[e.replace?"replaceState":"pushState"]({},document.title,r)}else if(this._wantsHashChange){this._updateHash(this.location,t,e.replace);if(this.iframe&&t!==this.getHash(this.iframe.contentWindow)){var n=this.iframe.contentWindow;if(!e.replace){n.document.open();n.document.close()}this._updateHash(n.location,t,e.replace)}}else{return this.location.assign(r)}if(e.trigger)return this.loadUrl(t)},_updateHash:function(t,e,i){if(i){var r=t.href.replace(/(javascript:|#).*$/,"");t.replace(r+"#"+e)}else{t.hash="#"+e}}});e.history=new M;var q=function(t,e){var r=this;var n;if(t&&i.has(t,"constructor")){n=t.constructor}else{n=function(){return r.apply(this,arguments)}}i.extend(n,r,e);var s=function(){this.constructor=n};s.prototype=r.prototype;n.prototype=new s;if(t)i.extend(n.prototype,t);n.__super__=r.prototype;return n};y.extend=x.extend=$.extend=I.extend=M.extend=q;var F=function(){throw new Error('A "url" property or function must be specified')};var z=function(t,e){var i=e.error;e.error=function(r){if(i)i.call(e.context,t,r,e);t.trigger("error",t,r,e)}};return e}); +//# sourceMappingURL=backbone-min.map \ No newline at end of file diff --git a/www/assets/dashboard.js b/www/assets/dashboard.js new file mode 100644 index 0000000000..25e0b01f01 --- /dev/null +++ b/www/assets/dashboard.js @@ -0,0 +1,49 @@ +Dashboard = {}; + +Dashboard.accounts = Backbone.View.extend({ + el: '.foo', + initialize: function() { + this.$table = this.$('table'); + this.data = new Dashboard.accounts.Accounts(); + this.data.fetch({reset:true}); + this.listenTo(this.data, 'reset', this.addAll); + }, + addOne: function (account) { + var view = new Dashboard.accounts.Row({model: account}); + var el = view.render().el; + this.$table.append(el); + }, + addAll: function () { + this.$table.html(''); + this.data.each(this.addOne, this); + } +}); + +Dashboard.accounts.Row = Backbone.View.extend({ + template: _.template('<%= number %><%= name %><%= kind %>'), + render: function() { + console.log(this); + this.$el.html(this.template(this.model.toJSON())); + return this; + } +}); + +Dashboard.accounts.Account = Backbone.Model.extend({ + defaults: { + number: null, + name: null, + kind: null + } +}); + +Dashboard.accounts.Accounts = Backbone.Collection.extend({ + url: '/dashboard/accounts/', + model: Dashboard.accounts.Account, + parse: function(data) { + return data.accounts; + } +}); + +Dashboard.init = function() { + new Dashboard.accounts(); +}; diff --git a/www/assets/underscore-min.js b/www/assets/underscore-min.js new file mode 100644 index 0000000000..f01025b7bc --- /dev/null +++ b/www/assets/underscore-min.js @@ -0,0 +1,6 @@ +// Underscore.js 1.8.3 +// http://underscorejs.org +// (c) 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors +// Underscore may be freely distributed under the MIT license. +(function(){function n(n){function t(t,r,e,u,i,o){for(;i>=0&&o>i;i+=n){var a=u?u[i]:i;e=r(e,t[a],a,t)}return e}return function(r,e,u,i){e=b(e,i,4);var o=!k(r)&&m.keys(r),a=(o||r).length,c=n>0?0:a-1;return arguments.length<3&&(u=r[o?o[c]:c],c+=n),t(r,e,u,o,c,a)}}function t(n){return function(t,r,e){r=x(r,e);for(var u=O(t),i=n>0?0:u-1;i>=0&&u>i;i+=n)if(r(t[i],i,t))return i;return-1}}function r(n,t,r){return function(e,u,i){var o=0,a=O(e);if("number"==typeof i)n>0?o=i>=0?i:Math.max(i+a,o):a=i>=0?Math.min(i+1,a):i+a+1;else if(r&&i&&a)return i=r(e,u),e[i]===u?i:-1;if(u!==u)return i=t(l.call(e,o,a),m.isNaN),i>=0?i+o:-1;for(i=n>0?o:a-1;i>=0&&a>i;i+=n)if(e[i]===u)return i;return-1}}function e(n,t){var r=I.length,e=n.constructor,u=m.isFunction(e)&&e.prototype||a,i="constructor";for(m.has(n,i)&&!m.contains(t,i)&&t.push(i);r--;)i=I[r],i in n&&n[i]!==u[i]&&!m.contains(t,i)&&t.push(i)}var u=this,i=u._,o=Array.prototype,a=Object.prototype,c=Function.prototype,f=o.push,l=o.slice,s=a.toString,p=a.hasOwnProperty,h=Array.isArray,v=Object.keys,g=c.bind,y=Object.create,d=function(){},m=function(n){return n instanceof m?n:this instanceof m?void(this._wrapped=n):new m(n)};"undefined"!=typeof exports?("undefined"!=typeof module&&module.exports&&(exports=module.exports=m),exports._=m):u._=m,m.VERSION="1.8.3";var b=function(n,t,r){if(t===void 0)return n;switch(null==r?3:r){case 1:return function(r){return n.call(t,r)};case 2:return function(r,e){return n.call(t,r,e)};case 3:return function(r,e,u){return n.call(t,r,e,u)};case 4:return function(r,e,u,i){return n.call(t,r,e,u,i)}}return function(){return n.apply(t,arguments)}},x=function(n,t,r){return null==n?m.identity:m.isFunction(n)?b(n,t,r):m.isObject(n)?m.matcher(n):m.property(n)};m.iteratee=function(n,t){return x(n,t,1/0)};var _=function(n,t){return function(r){var e=arguments.length;if(2>e||null==r)return r;for(var u=1;e>u;u++)for(var i=arguments[u],o=n(i),a=o.length,c=0;a>c;c++){var f=o[c];t&&r[f]!==void 0||(r[f]=i[f])}return r}},j=function(n){if(!m.isObject(n))return{};if(y)return y(n);d.prototype=n;var t=new d;return d.prototype=null,t},w=function(n){return function(t){return null==t?void 0:t[n]}},A=Math.pow(2,53)-1,O=w("length"),k=function(n){var t=O(n);return"number"==typeof t&&t>=0&&A>=t};m.each=m.forEach=function(n,t,r){t=b(t,r);var e,u;if(k(n))for(e=0,u=n.length;u>e;e++)t(n[e],e,n);else{var i=m.keys(n);for(e=0,u=i.length;u>e;e++)t(n[i[e]],i[e],n)}return n},m.map=m.collect=function(n,t,r){t=x(t,r);for(var e=!k(n)&&m.keys(n),u=(e||n).length,i=Array(u),o=0;u>o;o++){var a=e?e[o]:o;i[o]=t(n[a],a,n)}return i},m.reduce=m.foldl=m.inject=n(1),m.reduceRight=m.foldr=n(-1),m.find=m.detect=function(n,t,r){var e;return e=k(n)?m.findIndex(n,t,r):m.findKey(n,t,r),e!==void 0&&e!==-1?n[e]:void 0},m.filter=m.select=function(n,t,r){var e=[];return t=x(t,r),m.each(n,function(n,r,u){t(n,r,u)&&e.push(n)}),e},m.reject=function(n,t,r){return m.filter(n,m.negate(x(t)),r)},m.every=m.all=function(n,t,r){t=x(t,r);for(var e=!k(n)&&m.keys(n),u=(e||n).length,i=0;u>i;i++){var o=e?e[i]:i;if(!t(n[o],o,n))return!1}return!0},m.some=m.any=function(n,t,r){t=x(t,r);for(var e=!k(n)&&m.keys(n),u=(e||n).length,i=0;u>i;i++){var o=e?e[i]:i;if(t(n[o],o,n))return!0}return!1},m.contains=m.includes=m.include=function(n,t,r,e){return k(n)||(n=m.values(n)),("number"!=typeof r||e)&&(r=0),m.indexOf(n,t,r)>=0},m.invoke=function(n,t){var r=l.call(arguments,2),e=m.isFunction(t);return m.map(n,function(n){var u=e?t:n[t];return null==u?u:u.apply(n,r)})},m.pluck=function(n,t){return m.map(n,m.property(t))},m.where=function(n,t){return m.filter(n,m.matcher(t))},m.findWhere=function(n,t){return m.find(n,m.matcher(t))},m.max=function(n,t,r){var e,u,i=-1/0,o=-1/0;if(null==t&&null!=n){n=k(n)?n:m.values(n);for(var a=0,c=n.length;c>a;a++)e=n[a],e>i&&(i=e)}else t=x(t,r),m.each(n,function(n,r,e){u=t(n,r,e),(u>o||u===-1/0&&i===-1/0)&&(i=n,o=u)});return i},m.min=function(n,t,r){var e,u,i=1/0,o=1/0;if(null==t&&null!=n){n=k(n)?n:m.values(n);for(var a=0,c=n.length;c>a;a++)e=n[a],i>e&&(i=e)}else t=x(t,r),m.each(n,function(n,r,e){u=t(n,r,e),(o>u||1/0===u&&1/0===i)&&(i=n,o=u)});return i},m.shuffle=function(n){for(var t,r=k(n)?n:m.values(n),e=r.length,u=Array(e),i=0;e>i;i++)t=m.random(0,i),t!==i&&(u[i]=u[t]),u[t]=r[i];return u},m.sample=function(n,t,r){return null==t||r?(k(n)||(n=m.values(n)),n[m.random(n.length-1)]):m.shuffle(n).slice(0,Math.max(0,t))},m.sortBy=function(n,t,r){return t=x(t,r),m.pluck(m.map(n,function(n,r,e){return{value:n,index:r,criteria:t(n,r,e)}}).sort(function(n,t){var r=n.criteria,e=t.criteria;if(r!==e){if(r>e||r===void 0)return 1;if(e>r||e===void 0)return-1}return n.index-t.index}),"value")};var F=function(n){return function(t,r,e){var u={};return r=x(r,e),m.each(t,function(e,i){var o=r(e,i,t);n(u,e,o)}),u}};m.groupBy=F(function(n,t,r){m.has(n,r)?n[r].push(t):n[r]=[t]}),m.indexBy=F(function(n,t,r){n[r]=t}),m.countBy=F(function(n,t,r){m.has(n,r)?n[r]++:n[r]=1}),m.toArray=function(n){return n?m.isArray(n)?l.call(n):k(n)?m.map(n,m.identity):m.values(n):[]},m.size=function(n){return null==n?0:k(n)?n.length:m.keys(n).length},m.partition=function(n,t,r){t=x(t,r);var e=[],u=[];return m.each(n,function(n,r,i){(t(n,r,i)?e:u).push(n)}),[e,u]},m.first=m.head=m.take=function(n,t,r){return null==n?void 0:null==t||r?n[0]:m.initial(n,n.length-t)},m.initial=function(n,t,r){return l.call(n,0,Math.max(0,n.length-(null==t||r?1:t)))},m.last=function(n,t,r){return null==n?void 0:null==t||r?n[n.length-1]:m.rest(n,Math.max(0,n.length-t))},m.rest=m.tail=m.drop=function(n,t,r){return l.call(n,null==t||r?1:t)},m.compact=function(n){return m.filter(n,m.identity)};var S=function(n,t,r,e){for(var u=[],i=0,o=e||0,a=O(n);a>o;o++){var c=n[o];if(k(c)&&(m.isArray(c)||m.isArguments(c))){t||(c=S(c,t,r));var f=0,l=c.length;for(u.length+=l;l>f;)u[i++]=c[f++]}else r||(u[i++]=c)}return u};m.flatten=function(n,t){return S(n,t,!1)},m.without=function(n){return m.difference(n,l.call(arguments,1))},m.uniq=m.unique=function(n,t,r,e){m.isBoolean(t)||(e=r,r=t,t=!1),null!=r&&(r=x(r,e));for(var u=[],i=[],o=0,a=O(n);a>o;o++){var c=n[o],f=r?r(c,o,n):c;t?(o&&i===f||u.push(c),i=f):r?m.contains(i,f)||(i.push(f),u.push(c)):m.contains(u,c)||u.push(c)}return u},m.union=function(){return m.uniq(S(arguments,!0,!0))},m.intersection=function(n){for(var t=[],r=arguments.length,e=0,u=O(n);u>e;e++){var i=n[e];if(!m.contains(t,i)){for(var o=1;r>o&&m.contains(arguments[o],i);o++);o===r&&t.push(i)}}return t},m.difference=function(n){var t=S(arguments,!0,!0,1);return m.filter(n,function(n){return!m.contains(t,n)})},m.zip=function(){return m.unzip(arguments)},m.unzip=function(n){for(var t=n&&m.max(n,O).length||0,r=Array(t),e=0;t>e;e++)r[e]=m.pluck(n,e);return r},m.object=function(n,t){for(var r={},e=0,u=O(n);u>e;e++)t?r[n[e]]=t[e]:r[n[e][0]]=n[e][1];return r},m.findIndex=t(1),m.findLastIndex=t(-1),m.sortedIndex=function(n,t,r,e){r=x(r,e,1);for(var u=r(t),i=0,o=O(n);o>i;){var a=Math.floor((i+o)/2);r(n[a])i;i++,n+=r)u[i]=n;return u};var E=function(n,t,r,e,u){if(!(e instanceof t))return n.apply(r,u);var i=j(n.prototype),o=n.apply(i,u);return m.isObject(o)?o:i};m.bind=function(n,t){if(g&&n.bind===g)return g.apply(n,l.call(arguments,1));if(!m.isFunction(n))throw new TypeError("Bind must be called on a function");var r=l.call(arguments,2),e=function(){return E(n,e,t,this,r.concat(l.call(arguments)))};return e},m.partial=function(n){var t=l.call(arguments,1),r=function(){for(var e=0,u=t.length,i=Array(u),o=0;u>o;o++)i[o]=t[o]===m?arguments[e++]:t[o];for(;e=e)throw new Error("bindAll must be passed function names");for(t=1;e>t;t++)r=arguments[t],n[r]=m.bind(n[r],n);return n},m.memoize=function(n,t){var r=function(e){var u=r.cache,i=""+(t?t.apply(this,arguments):e);return m.has(u,i)||(u[i]=n.apply(this,arguments)),u[i]};return r.cache={},r},m.delay=function(n,t){var r=l.call(arguments,2);return setTimeout(function(){return n.apply(null,r)},t)},m.defer=m.partial(m.delay,m,1),m.throttle=function(n,t,r){var e,u,i,o=null,a=0;r||(r={});var c=function(){a=r.leading===!1?0:m.now(),o=null,i=n.apply(e,u),o||(e=u=null)};return function(){var f=m.now();a||r.leading!==!1||(a=f);var l=t-(f-a);return e=this,u=arguments,0>=l||l>t?(o&&(clearTimeout(o),o=null),a=f,i=n.apply(e,u),o||(e=u=null)):o||r.trailing===!1||(o=setTimeout(c,l)),i}},m.debounce=function(n,t,r){var e,u,i,o,a,c=function(){var f=m.now()-o;t>f&&f>=0?e=setTimeout(c,t-f):(e=null,r||(a=n.apply(i,u),e||(i=u=null)))};return function(){i=this,u=arguments,o=m.now();var f=r&&!e;return e||(e=setTimeout(c,t)),f&&(a=n.apply(i,u),i=u=null),a}},m.wrap=function(n,t){return m.partial(t,n)},m.negate=function(n){return function(){return!n.apply(this,arguments)}},m.compose=function(){var n=arguments,t=n.length-1;return function(){for(var r=t,e=n[t].apply(this,arguments);r--;)e=n[r].call(this,e);return e}},m.after=function(n,t){return function(){return--n<1?t.apply(this,arguments):void 0}},m.before=function(n,t){var r;return function(){return--n>0&&(r=t.apply(this,arguments)),1>=n&&(t=null),r}},m.once=m.partial(m.before,2);var M=!{toString:null}.propertyIsEnumerable("toString"),I=["valueOf","isPrototypeOf","toString","propertyIsEnumerable","hasOwnProperty","toLocaleString"];m.keys=function(n){if(!m.isObject(n))return[];if(v)return v(n);var t=[];for(var r in n)m.has(n,r)&&t.push(r);return M&&e(n,t),t},m.allKeys=function(n){if(!m.isObject(n))return[];var t=[];for(var r in n)t.push(r);return M&&e(n,t),t},m.values=function(n){for(var t=m.keys(n),r=t.length,e=Array(r),u=0;r>u;u++)e[u]=n[t[u]];return e},m.mapObject=function(n,t,r){t=x(t,r);for(var e,u=m.keys(n),i=u.length,o={},a=0;i>a;a++)e=u[a],o[e]=t(n[e],e,n);return o},m.pairs=function(n){for(var t=m.keys(n),r=t.length,e=Array(r),u=0;r>u;u++)e[u]=[t[u],n[t[u]]];return e},m.invert=function(n){for(var t={},r=m.keys(n),e=0,u=r.length;u>e;e++)t[n[r[e]]]=r[e];return t},m.functions=m.methods=function(n){var t=[];for(var r in n)m.isFunction(n[r])&&t.push(r);return t.sort()},m.extend=_(m.allKeys),m.extendOwn=m.assign=_(m.keys),m.findKey=function(n,t,r){t=x(t,r);for(var e,u=m.keys(n),i=0,o=u.length;o>i;i++)if(e=u[i],t(n[e],e,n))return e},m.pick=function(n,t,r){var e,u,i={},o=n;if(null==o)return i;m.isFunction(t)?(u=m.allKeys(o),e=b(t,r)):(u=S(arguments,!1,!1,1),e=function(n,t,r){return t in r},o=Object(o));for(var a=0,c=u.length;c>a;a++){var f=u[a],l=o[f];e(l,f,o)&&(i[f]=l)}return i},m.omit=function(n,t,r){if(m.isFunction(t))t=m.negate(t);else{var e=m.map(S(arguments,!1,!1,1),String);t=function(n,t){return!m.contains(e,t)}}return m.pick(n,t,r)},m.defaults=_(m.allKeys,!0),m.create=function(n,t){var r=j(n);return t&&m.extendOwn(r,t),r},m.clone=function(n){return m.isObject(n)?m.isArray(n)?n.slice():m.extend({},n):n},m.tap=function(n,t){return t(n),n},m.isMatch=function(n,t){var r=m.keys(t),e=r.length;if(null==n)return!e;for(var u=Object(n),i=0;e>i;i++){var o=r[i];if(t[o]!==u[o]||!(o in u))return!1}return!0};var N=function(n,t,r,e){if(n===t)return 0!==n||1/n===1/t;if(null==n||null==t)return n===t;n instanceof m&&(n=n._wrapped),t instanceof m&&(t=t._wrapped);var u=s.call(n);if(u!==s.call(t))return!1;switch(u){case"[object RegExp]":case"[object String]":return""+n==""+t;case"[object Number]":return+n!==+n?+t!==+t:0===+n?1/+n===1/t:+n===+t;case"[object Date]":case"[object Boolean]":return+n===+t}var i="[object Array]"===u;if(!i){if("object"!=typeof n||"object"!=typeof t)return!1;var o=n.constructor,a=t.constructor;if(o!==a&&!(m.isFunction(o)&&o instanceof o&&m.isFunction(a)&&a instanceof a)&&"constructor"in n&&"constructor"in t)return!1}r=r||[],e=e||[];for(var c=r.length;c--;)if(r[c]===n)return e[c]===t;if(r.push(n),e.push(t),i){if(c=n.length,c!==t.length)return!1;for(;c--;)if(!N(n[c],t[c],r,e))return!1}else{var f,l=m.keys(n);if(c=l.length,m.keys(t).length!==c)return!1;for(;c--;)if(f=l[c],!m.has(t,f)||!N(n[f],t[f],r,e))return!1}return r.pop(),e.pop(),!0};m.isEqual=function(n,t){return N(n,t)},m.isEmpty=function(n){return null==n?!0:k(n)&&(m.isArray(n)||m.isString(n)||m.isArguments(n))?0===n.length:0===m.keys(n).length},m.isElement=function(n){return!(!n||1!==n.nodeType)},m.isArray=h||function(n){return"[object Array]"===s.call(n)},m.isObject=function(n){var t=typeof n;return"function"===t||"object"===t&&!!n},m.each(["Arguments","Function","String","Number","Date","RegExp","Error"],function(n){m["is"+n]=function(t){return s.call(t)==="[object "+n+"]"}}),m.isArguments(arguments)||(m.isArguments=function(n){return m.has(n,"callee")}),"function"!=typeof/./&&"object"!=typeof Int8Array&&(m.isFunction=function(n){return"function"==typeof n||!1}),m.isFinite=function(n){return isFinite(n)&&!isNaN(parseFloat(n))},m.isNaN=function(n){return m.isNumber(n)&&n!==+n},m.isBoolean=function(n){return n===!0||n===!1||"[object Boolean]"===s.call(n)},m.isNull=function(n){return null===n},m.isUndefined=function(n){return n===void 0},m.has=function(n,t){return null!=n&&p.call(n,t)},m.noConflict=function(){return u._=i,this},m.identity=function(n){return n},m.constant=function(n){return function(){return n}},m.noop=function(){},m.property=w,m.propertyOf=function(n){return null==n?function(){}:function(t){return n[t]}},m.matcher=m.matches=function(n){return n=m.extendOwn({},n),function(t){return m.isMatch(t,n)}},m.times=function(n,t,r){var e=Array(Math.max(0,n));t=b(t,r,1);for(var u=0;n>u;u++)e[u]=t(u);return e},m.random=function(n,t){return null==t&&(t=n,n=0),n+Math.floor(Math.random()*(t-n+1))},m.now=Date.now||function(){return(new Date).getTime()};var B={"&":"&","<":"<",">":">",'"':""","'":"'","`":"`"},T=m.invert(B),R=function(n){var t=function(t){return n[t]},r="(?:"+m.keys(n).join("|")+")",e=RegExp(r),u=RegExp(r,"g");return function(n){return n=null==n?"":""+n,e.test(n)?n.replace(u,t):n}};m.escape=R(B),m.unescape=R(T),m.result=function(n,t,r){var e=null==n?void 0:n[t];return e===void 0&&(e=r),m.isFunction(e)?e.call(n):e};var q=0;m.uniqueId=function(n){var t=++q+"";return n?n+t:t},m.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g};var K=/(.)^/,z={"'":"'","\\":"\\","\r":"r","\n":"n","\u2028":"u2028","\u2029":"u2029"},D=/\\|'|\r|\n|\u2028|\u2029/g,L=function(n){return"\\"+z[n]};m.template=function(n,t,r){!t&&r&&(t=r),t=m.defaults({},t,m.templateSettings);var e=RegExp([(t.escape||K).source,(t.interpolate||K).source,(t.evaluate||K).source].join("|")+"|$","g"),u=0,i="__p+='";n.replace(e,function(t,r,e,o,a){return i+=n.slice(u,a).replace(D,L),u=a+t.length,r?i+="'+\n((__t=("+r+"))==null?'':_.escape(__t))+\n'":e?i+="'+\n((__t=("+e+"))==null?'':__t)+\n'":o&&(i+="';\n"+o+"\n__p+='"),t}),i+="';\n",t.variable||(i="with(obj||{}){\n"+i+"}\n"),i="var __t,__p='',__j=Array.prototype.join,"+"print=function(){__p+=__j.call(arguments,'');};\n"+i+"return __p;\n";try{var o=new Function(t.variable||"obj","_",i)}catch(a){throw a.source=i,a}var c=function(n){return o.call(this,n,m)},f=t.variable||"obj";return c.source="function("+f+"){\n"+i+"}",c},m.chain=function(n){var t=m(n);return t._chain=!0,t};var P=function(n,t){return n._chain?m(t).chain():t};m.mixin=function(n){m.each(m.functions(n),function(t){var r=m[t]=n[t];m.prototype[t]=function(){var n=[this._wrapped];return f.apply(n,arguments),P(this,r.apply(m,n))}})},m.mixin(m),m.each(["pop","push","reverse","shift","sort","splice","unshift"],function(n){var t=o[n];m.prototype[n]=function(){var r=this._wrapped;return t.apply(r,arguments),"shift"!==n&&"splice"!==n||0!==r.length||delete r[0],P(this,r)}}),m.each(["concat","join","slice"],function(n){var t=o[n];m.prototype[n]=function(){return P(this,t.apply(this._wrapped,arguments))}}),m.prototype.value=function(){return this._wrapped},m.prototype.valueOf=m.prototype.toJSON=m.prototype.value,m.prototype.toString=function(){return""+this._wrapped},"function"==typeof define&&define.amd&&define("underscore",[],function(){return m})}).call(this); +//# sourceMappingURL=underscore-min.map \ No newline at end of file diff --git a/www/dashboard/accounts/index.spt b/www/dashboard/accounts/index.spt new file mode 100644 index 0000000000..b36940b303 --- /dev/null +++ b/www/dashboard/accounts/index.spt @@ -0,0 +1,38 @@ +from aspen import Response +[---] +if user.ANON: + raise Response(401) +if not user.ADMIN: + raise Response(403) + +out = {"accounts": [ {"number": "100", "name": "accounts receivable", "kind": "asset"} + , {"number": "200", "name": "accounts payable", "kind": "liability"} + ]} +[---] application/json via json_dump +out +[---] text/html + + + + Chart of Accounts + + + + + + + +

Chart of Accounts

+
+ + + + diff --git a/www/dashboard/index.spt b/www/dashboard/index.spt index b370c7571e..a6629c5365 100644 --- a/www/dashboard/index.spt +++ b/www/dashboard/index.spt @@ -1,93 +1,13 @@ from aspen import Response - [---] +if user.ANON: + raise Response(401) if not user.ADMIN: raise Response(403) - - -unreviewed = website.db.all(""" - - SELECT username - , balance - , giving - , ngiving_to - FROM participants - WHERE is_suspicious IS NULL - AND braintree_customer_id IS NOT NULL - AND NOT is_closed - ORDER BY claimed_time - -""") - -title = _("Fraud Review Dashboard") [---] text/html - - - - -

Unreviewed Accounts (N = {{ len(unreviewed) }})

- -{% for account in unreviewed %} - - - - - - -{% endfor %} -
- - - - {{ account.username }} - ${{ account.giving }}{{ account.ngiving_to }}
- +

Dashboard

+ diff --git a/www/dashboard/ledger.spt b/www/dashboard/ledger.spt new file mode 100644 index 0000000000..5949017cd2 --- /dev/null +++ b/www/dashboard/ledger.spt @@ -0,0 +1,21 @@ +from aspen import Response +[---] +if user.ANON: + raise Response(401) +if not user.ADMIN: + raise Response(403) +[---] text/html + + + + + + +
+ + +
+

Hello {{yourName}}!

+
+ + diff --git a/www/dashboard/user-review.spt b/www/dashboard/user-review.spt new file mode 100644 index 0000000000..4150874f08 --- /dev/null +++ b/www/dashboard/user-review.spt @@ -0,0 +1,95 @@ +from aspen import Response + +[---] +if user.ANON: + raise Response(401) +if not user.ADMIN: + raise Response(403) + + +unreviewed = website.db.all(""" + + SELECT username + , balance + , giving + , ngiving_to + FROM participants + WHERE is_suspicious IS NULL + AND braintree_customer_id IS NOT NULL + AND NOT is_closed + ORDER BY claimed_time + +""") + +title = _("Fraud Review Dashboard") +[---] text/html + + + + +

Unreviewed Accounts (N = {{ len(unreviewed) }})

+ +{% for account in unreviewed %} + + + + + + +{% endfor %} +
+ + + + {{ account.username }} + ${{ account.giving }}{{ account.ngiving_to }}
+ From 6fb9b3d4d0bcfc3ab04a23c1ab18343d8787aadb Mon Sep 17 00:00:00 2001 From: Chad Whitacre Date: Wed, 16 Sep 2015 10:49:02 -0400 Subject: [PATCH 03/31] Refactor and get templating working --- www/assets/dashboard.js | 57 +++++++++++++++++--------------- www/dashboard/accounts/index.spt | 21 +++++++----- 2 files changed, 43 insertions(+), 35 deletions(-) diff --git a/www/assets/dashboard.js b/www/assets/dashboard.js index 25e0b01f01..378252522e 100644 --- a/www/assets/dashboard.js +++ b/www/assets/dashboard.js @@ -1,26 +1,45 @@ -Dashboard = {}; +Dashboard = {models: {}, views: {}, collections: {}}; -Dashboard.accounts = Backbone.View.extend({ - el: '.foo', +Dashboard.models.Account = Backbone.Model.extend({ + defaults: { + number: null, + name: null, + kind: null + } +}); + +Dashboard.collections.Accounts = Backbone.Collection.extend({ + url: '/dashboard/accounts/', + model: Dashboard.models.Account, + parse: function(data) { + return data.accounts; + } +}); + +Dashboard.views.ChartOfAccounts = Backbone.View.extend({ + el: '#chart-of-accounts', initialize: function() { - this.$table = this.$('table'); - this.data = new Dashboard.accounts.Accounts(); + this.$tbody= this.$('tbody'); + this.data = new Dashboard.collections.Accounts(); this.data.fetch({reset:true}); this.listenTo(this.data, 'reset', this.addAll); }, addOne: function (account) { - var view = new Dashboard.accounts.Row({model: account}); + var view = new Dashboard.views.AccountRow({model: account}); var el = view.render().el; - this.$table.append(el); + this.$tbody.append(el); }, addAll: function () { - this.$table.html(''); + this.$tbody.html(''); this.data.each(this.addOne, this); } }); -Dashboard.accounts.Row = Backbone.View.extend({ - template: _.template('<%= number %><%= name %><%= kind %>'), +Dashboard.views.AccountRow = Backbone.View.extend({ + tagName: 'tr', + initialize: function() { + this.template = _.template($('#AccountRow').html()); + }, render: function() { console.log(this); this.$el.html(this.template(this.model.toJSON())); @@ -28,22 +47,6 @@ Dashboard.accounts.Row = Backbone.View.extend({ } }); -Dashboard.accounts.Account = Backbone.Model.extend({ - defaults: { - number: null, - name: null, - kind: null - } -}); - -Dashboard.accounts.Accounts = Backbone.Collection.extend({ - url: '/dashboard/accounts/', - model: Dashboard.accounts.Account, - parse: function(data) { - return data.accounts; - } -}); - Dashboard.init = function() { - new Dashboard.accounts(); + new Dashboard.views.ChartOfAccounts(); }; diff --git a/www/dashboard/accounts/index.spt b/www/dashboard/accounts/index.spt index b36940b303..358af2eb21 100644 --- a/www/dashboard/accounts/index.spt +++ b/www/dashboard/accounts/index.spt @@ -23,16 +23,21 @@ out $(document).ready(Dashboard.init); - +

Chart of Accounts

-
+ + + + + + + +
NumberNameKind
- From fe93c11bb4b984b302c3d4ab7a65c930b45486e2 Mon Sep 17 00:00:00 2001 From: Chad Whitacre Date: Wed, 16 Sep 2015 10:55:47 -0400 Subject: [PATCH 04/31] Everyone seems to say "type" of account --- www/assets/dashboard.js | 3 +-- www/dashboard/accounts/index.spt | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/www/assets/dashboard.js b/www/assets/dashboard.js index 378252522e..d009f8184e 100644 --- a/www/assets/dashboard.js +++ b/www/assets/dashboard.js @@ -4,7 +4,7 @@ Dashboard.models.Account = Backbone.Model.extend({ defaults: { number: null, name: null, - kind: null + type: null } }); @@ -41,7 +41,6 @@ Dashboard.views.AccountRow = Backbone.View.extend({ this.template = _.template($('#AccountRow').html()); }, render: function() { - console.log(this); this.$el.html(this.template(this.model.toJSON())); return this; } diff --git a/www/dashboard/accounts/index.spt b/www/dashboard/accounts/index.spt index 358af2eb21..0c9c6fdad4 100644 --- a/www/dashboard/accounts/index.spt +++ b/www/dashboard/accounts/index.spt @@ -29,7 +29,7 @@ out Number Name - Kind + Type From d27510c0c5e7a0852b853a7d579b67c577b5961c Mon Sep 17 00:00:00 2001 From: Chad Whitacre Date: Wed, 16 Sep 2015 13:10:06 -0400 Subject: [PATCH 05/31] Implement routing We want a single Dashboard js app that includes both the general ledger and chart of accounts. --- www/assets/dashboard.css.spt | 7 ++++ www/assets/dashboard.js | 59 ++++++++++++++++++++++++++++++-- www/dashboard/%index.spt | 57 ++++++++++++++++++++++++++++++ www/dashboard/accounts/index.spt | 43 ----------------------- www/dashboard/index.spt | 13 ------- www/dashboard/ledger.spt | 21 ------------ www/v2/accounts/index.spt | 12 +++++++ 7 files changed, 132 insertions(+), 80 deletions(-) create mode 100644 www/assets/dashboard.css.spt create mode 100644 www/dashboard/%index.spt delete mode 100644 www/dashboard/accounts/index.spt delete mode 100644 www/dashboard/index.spt delete mode 100644 www/dashboard/ledger.spt create mode 100644 www/v2/accounts/index.spt diff --git a/www/assets/dashboard.css.spt b/www/assets/dashboard.css.spt new file mode 100644 index 0000000000..c9af77662a --- /dev/null +++ b/www/assets/dashboard.css.spt @@ -0,0 +1,7 @@ +[---] +[---] text/css via scss +#dashboard { + section { + display: none; + } +} diff --git a/www/assets/dashboard.js b/www/assets/dashboard.js index d009f8184e..96f500f912 100644 --- a/www/assets/dashboard.js +++ b/www/assets/dashboard.js @@ -1,5 +1,21 @@ Dashboard = {models: {}, views: {}, collections: {}}; +Dashboard.Router = Backbone.Router.extend({ + routes: {'ledger': 'ledger', 'accounts': 'accounts'}, + ledger: function() { + $('section').hide(); + $('#general-ledger').show(); + }, + accounts: function() { + $('section').hide(); + $('#chart-of-accounts').show(); + } +}); + + +// Models +// ====== + Dashboard.models.Account = Backbone.Model.extend({ defaults: { number: null, @@ -8,21 +24,54 @@ Dashboard.models.Account = Backbone.Model.extend({ } }); + +// Collections +// =========== + Dashboard.collections.Accounts = Backbone.Collection.extend({ - url: '/dashboard/accounts/', + url: '/v2/accounts/', model: Dashboard.models.Account, parse: function(data) { return data.accounts; } }); + +// Views +// ===== + +Dashboard.views.Main = Backbone.View.extend({ + el: 'body', + initialize: function() { + new Dashboard.views.GeneralLedger; + new Dashboard.views.ChartOfAccounts; + + this.router = new Dashboard.Router; + Backbone.history.start({pushState: true, root: "/dashboard/"}); + }, + events: { + 'click #navigation a': 'loadSection' + }, + loadSection: function(e) { + this.router.navigate($(e.currentTarget).attr('href'), {trigger: true}); + e.preventDefault(); + }, +}); + +Dashboard.views.GeneralLedger = Backbone.View.extend({ + el: '#general-ledger', + initialize: function() { + this.$tbody= this.$('tbody'); + }, +}); + Dashboard.views.ChartOfAccounts = Backbone.View.extend({ el: '#chart-of-accounts', initialize: function() { this.$tbody= this.$('tbody'); this.data = new Dashboard.collections.Accounts(); - this.data.fetch({reset:true}); this.listenTo(this.data, 'reset', this.addAll); + this.data.fetch({reset:true}); }, addOne: function (account) { var view = new Dashboard.views.AccountRow({model: account}); @@ -46,6 +95,10 @@ Dashboard.views.AccountRow = Backbone.View.extend({ } }); + +// Entrypoint +// ========== + Dashboard.init = function() { - new Dashboard.views.ChartOfAccounts(); + new Dashboard.views.Main(); }; diff --git a/www/dashboard/%index.spt b/www/dashboard/%index.spt new file mode 100644 index 0000000000..d88759e774 --- /dev/null +++ b/www/dashboard/%index.spt @@ -0,0 +1,57 @@ +from aspen import Response +[---] +if user.ANON: + raise Response(401) +if not user.ADMIN: + raise Response(403) +[---] text/html + + + Dashboard + + + + + + + + +

Dashboard

+ + +
+

General Ledger

+ + + + + + + +
AccountDebitsCredits
+
+ +
+

Chart of Accounts

+ + + + + + + +
NumberNameType
+
+ + + + diff --git a/www/dashboard/accounts/index.spt b/www/dashboard/accounts/index.spt deleted file mode 100644 index 0c9c6fdad4..0000000000 --- a/www/dashboard/accounts/index.spt +++ /dev/null @@ -1,43 +0,0 @@ -from aspen import Response -[---] -if user.ANON: - raise Response(401) -if not user.ADMIN: - raise Response(403) - -out = {"accounts": [ {"number": "100", "name": "accounts receivable", "kind": "asset"} - , {"number": "200", "name": "accounts payable", "kind": "liability"} - ]} -[---] application/json via json_dump -out -[---] text/html - - - - Chart of Accounts - - - - - - - -

Chart of Accounts

- - - - - - - -
NumberNameType
- - - - diff --git a/www/dashboard/index.spt b/www/dashboard/index.spt deleted file mode 100644 index a6629c5365..0000000000 --- a/www/dashboard/index.spt +++ /dev/null @@ -1,13 +0,0 @@ -from aspen import Response -[---] -if user.ANON: - raise Response(401) -if not user.ADMIN: - raise Response(403) -[---] text/html -

Dashboard

- diff --git a/www/dashboard/ledger.spt b/www/dashboard/ledger.spt deleted file mode 100644 index 5949017cd2..0000000000 --- a/www/dashboard/ledger.spt +++ /dev/null @@ -1,21 +0,0 @@ -from aspen import Response -[---] -if user.ANON: - raise Response(401) -if not user.ADMIN: - raise Response(403) -[---] text/html - - - - - - -
- - -
-

Hello {{yourName}}!

-
- - diff --git a/www/v2/accounts/index.spt b/www/v2/accounts/index.spt new file mode 100644 index 0000000000..c7eb8d2f1e --- /dev/null +++ b/www/v2/accounts/index.spt @@ -0,0 +1,12 @@ +from aspen import Response +[---] +if user.ANON: + raise Response(401) +if not user.ADMIN: + raise Response(403) + +out = {"accounts": [ {"number": "100", "name": "accounts receivable", "type": "asset"} + , {"number": "200", "name": "accounts payable", "type": "liability"} + ]} +[---] application/json via json_dump +out From e211fda03fbf5e9cbde0ccb96210d23260a259c0 Mon Sep 17 00:00:00 2001 From: Chad Whitacre Date: Wed, 16 Sep 2015 13:35:41 -0400 Subject: [PATCH 06/31] Start styling the Dashboard --- www/assets/dashboard.css.spt | 71 ++++++++++++++++++++++++++++++++++++ www/assets/dashboard.js | 4 ++ www/dashboard/%index.spt | 1 + 3 files changed, 76 insertions(+) diff --git a/www/assets/dashboard.css.spt b/www/assets/dashboard.css.spt index c9af77662a..d3a33c711a 100644 --- a/www/assets/dashboard.css.spt +++ b/www/assets/dashboard.css.spt @@ -1,7 +1,78 @@ [---] [---] text/css via scss +@import "scss/elements/reset"; +@import 'scss/variables'; + #dashboard { + font-family: $Ideal; + + h1 { + display: none; + } + h2 { + display: none; + } + + #navigation { + margin: 10px 0 0; + padding: 0 0 0 36px; + border-bottom: 2px solid $green; + li { + display: inline-block; + list-style: none; + margin: 0 6px 0 0; + padding: 0; + a { + display: block; + padding: 10px; + position: relative; + top: 2px; + text-decoration: none; + color: $medium-gray; + border: 2px solid $medium-gray; + border-radius: 5px 5px 0 0; + border-bottom-color: $green; + &:hover { + background: $green; + color: white; + border-color: $green; + } + &.selected { + color: $black; + border-color: $green; + border-bottom-color: $white; + cursor: default; + &:hover { + background: $white; + } + } + } + } + } + section { display: none; + padding: 36px; + } + + table { + border-collapse: collapse; + th { + font: bold 16px/18px $Ideal; + font-weight: bold; + border-bottom: 1px solid $light-brown; + } + td { + font: normal 14px/16px $Mono; + } + + th, td { + text-align: left; + margin: 0; + padding: 6px 18px 3px 0; + &:last-child { + padding-right: 0; + } + } } } diff --git a/www/assets/dashboard.js b/www/assets/dashboard.js index 96f500f912..d804aa76c4 100644 --- a/www/assets/dashboard.js +++ b/www/assets/dashboard.js @@ -4,10 +4,14 @@ Dashboard.Router = Backbone.Router.extend({ routes: {'ledger': 'ledger', 'accounts': 'accounts'}, ledger: function() { $('section').hide(); + $('#navigation a.selected').removeClass('selected'); + $('#navigation a[href=ledger]').addClass('selected'); $('#general-ledger').show(); }, accounts: function() { $('section').hide(); + $('#navigation a.selected').removeClass('selected'); + $('#navigation a[href=accounts]').addClass('selected'); $('#chart-of-accounts').show(); } }); diff --git a/www/dashboard/%index.spt b/www/dashboard/%index.spt index d88759e774..cb275fa940 100644 --- a/www/dashboard/%index.spt +++ b/www/dashboard/%index.spt @@ -9,6 +9,7 @@ if not user.ADMIN: Dashboard + From f632d21cbe0bd98696adb795e1bb6083f80f9e58 Mon Sep 17 00:00:00 2001 From: Chad Whitacre Date: Wed, 16 Sep 2015 13:42:18 -0400 Subject: [PATCH 07/31] Fix tests --- tests/py/test_pages.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/py/test_pages.py b/tests/py/test_pages.py index ce83ebc1d8..89e4f3345b 100644 --- a/tests/py/test_pages.py +++ b/tests/py/test_pages.py @@ -33,7 +33,8 @@ def browse(self, setup=None, **kw): .replace('/%exchange_id.int', '/%s' % exchange_id) \ .replace('/%redirect_to', '/giving') \ .replace('/%endpoint', '/public') \ - .replace('/about/me/%sub', '/about/me') + .replace('/about/me/%sub', '/about/me') \ + .replace('/dashboard/%index', '') assert '/%' not in url if 'index' in url.split('/')[-1]: url = url.rsplit('/', 1)[0] + '/' From 050fd206764fc333f3a1e4df01258c0f3db4a4a9 Mon Sep 17 00:00:00 2001 From: Chad Whitacre Date: Wed, 16 Sep 2015 14:05:55 -0400 Subject: [PATCH 08/31] Center the dashboard --- www/assets/dashboard.css.spt | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/www/assets/dashboard.css.spt b/www/assets/dashboard.css.spt index d3a33c711a..392f7c9e37 100644 --- a/www/assets/dashboard.css.spt +++ b/www/assets/dashboard.css.spt @@ -14,9 +14,11 @@ } #navigation { - margin: 10px 0 0; - padding: 0 0 0 36px; + margin: 0; + padding: 10px 0 0; + text-align: center; border-bottom: 2px solid $green; + background: $lighter-gray; li { display: inline-block; list-style: none; @@ -38,6 +40,7 @@ border-color: $green; } &.selected { + background: $white; color: $black; border-color: $green; border-bottom-color: $white; @@ -52,11 +55,13 @@ section { display: none; - padding: 36px; + padding: 48px; + background: $white; } table { border-collapse: collapse; + margin: 0 auto; th { font: bold 16px/18px $Ideal; font-weight: bold; From 8c2679693ff9d732a1d6f868f9222058960d6ab0 Mon Sep 17 00:00:00 2001 From: Chad Whitacre Date: Wed, 16 Sep 2015 15:25:36 -0400 Subject: [PATCH 09/31] Markup and wiring to add account; API needed --- www/assets/dashboard.css.spt | 14 ++++++++++- www/assets/dashboard.js | 48 +++++++++++++++++++++++++++++++++++- www/dashboard/%index.spt | 25 +++++++++++++++++++ 3 files changed, 85 insertions(+), 2 deletions(-) diff --git a/www/assets/dashboard.css.spt b/www/assets/dashboard.css.spt index 392f7c9e37..4f33162663 100644 --- a/www/assets/dashboard.css.spt +++ b/www/assets/dashboard.css.spt @@ -1,7 +1,9 @@ [---] [---] text/css via scss -@import "scss/elements/reset"; +@import "scss/mixins/borders-backgrounds-shadows"; @import 'scss/variables'; +@import "scss/elements/buttons-knobs"; +@import "scss/elements/reset"; #dashboard { font-family: $Ideal; @@ -24,6 +26,9 @@ list-style: none; margin: 0 6px 0 0; padding: 0; + &:last-child { + margin-right: 0; + } a { display: block; padding: 10px; @@ -80,4 +85,11 @@ } } } + + .add-account { + border-top: 1px solid $light-brown; + tr:last-child td { + text-align: right; + } + } } diff --git a/www/assets/dashboard.js b/www/assets/dashboard.js index d804aa76c4..4172c38f95 100644 --- a/www/assets/dashboard.js +++ b/www/assets/dashboard.js @@ -72,10 +72,16 @@ Dashboard.views.GeneralLedger = Backbone.View.extend({ Dashboard.views.ChartOfAccounts = Backbone.View.extend({ el: '#chart-of-accounts', initialize: function() { - this.$tbody= this.$('tbody'); + this.$table = this.$('table'); + this.$tbody = this.$('tbody'); this.data = new Dashboard.collections.Accounts(); this.listenTo(this.data, 'reset', this.addAll); this.data.fetch({reset:true}); + + this.addAccountOff = new Dashboard.views.AddAccountOff; + this.addAccountOn = new Dashboard.views.AddAccountOn; + + this.turnAddAccountOff(); }, addOne: function (account) { var view = new Dashboard.views.AccountRow({model: account}); @@ -85,6 +91,22 @@ Dashboard.views.ChartOfAccounts = Backbone.View.extend({ addAll: function () { this.$tbody.html(''); this.data.each(this.addOne, this); + }, + events: { + 'click .add-account.off button': 'turnAddAccountOn', + 'click .add-account.on button[type=cancel]': 'turnAddAccountOff', + 'click .add-account.on button[type=submit]': 'addAccount' + }, + turnAddAccountOn: function() { + this.addAccountOff.remove(); + this.$table.append(this.addAccountOn.render().el); + }, + turnAddAccountOff: function() { + this.addAccountOn.remove(); + this.$table.append(this.addAccountOff.render().el); + }, + addAccount: function() { + console.log('adding account ...'); } }); @@ -99,6 +121,30 @@ Dashboard.views.AccountRow = Backbone.View.extend({ } }); +Dashboard.views.AddAccountOff = Backbone.View.extend({ + tagName: 'tfoot', + className: 'add-account off', + initialize: function() { + this.template = _.template($('#AddAccountOff').html()); + }, + render: function() { + this.$el.html(this.template()); + return this; + }, +}); + +Dashboard.views.AddAccountOn = Backbone.View.extend({ + tagName: 'tfoot', + className: 'add-account on', + initialize: function() { + this.template = _.template($('#AddAccountOn').html()); + }, + render: function() { + this.$el.html(this.template()); + return this; + } +}); + // Entrypoint // ========== diff --git a/www/dashboard/%index.spt b/www/dashboard/%index.spt index cb275fa940..94bd81d8f6 100644 --- a/www/dashboard/%index.spt +++ b/www/dashboard/%index.spt @@ -54,5 +54,30 @@ if not user.ADMIN: <%= name %> <%= type %> + + + + From d10ef7396ea4539580a7c65f435bd58d8b7d9091 Mon Sep 17 00:00:00 2001 From: Chad Whitacre Date: Wed, 16 Sep 2015 17:44:54 -0400 Subject: [PATCH 10/31] Update stub data --- www/v2/accounts/index.spt | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/www/v2/accounts/index.spt b/www/v2/accounts/index.spt index c7eb8d2f1e..3d4db10aff 100644 --- a/www/v2/accounts/index.spt +++ b/www/v2/accounts/index.spt @@ -5,8 +5,22 @@ if user.ANON: if not user.ADMIN: raise Response(403) -out = {"accounts": [ {"number": "100", "name": "accounts receivable", "type": "asset"} - , {"number": "200", "name": "accounts payable", "type": "liability"} +out = {"accounts": [ {"number": "100-00", "name": "Balanced"} + , {"number": "100-01", "name": "Balanced - Pending"} + , {"number": "101-00", "name": "Citizens"} + , {"number": "101-01", "name": "Citizens - Pending"} + , {"number": "102-00", "name": "Ally"} + , {"number": "102-01", "name": "Ally - Pending"} + , {"number": "103-00", "name": "New Alliance"} + , {"number": "103-01", "name": "New Alliance - Pending"} + , {"number": "104-00", "name": "PayPal"} + , {"number": "104-01", "name": "PayPal - Pending"} + , {"number": "105-00", "name": "Coinbase"} + , {"number": "105-01", "name": "Coinbase - Pending"} + , {"number": "200-111", "name": "~user 111"} + , {"number": "201-222", "name": "Team 222"} + , {"number": "300", "name": "Income"} + , {"number": "400", "name": "Expenses"} ]} [---] application/json via json_dump out From b5c833aab4e182cd55c5bb8c06a2bbb940c3408a Mon Sep 17 00:00:00 2001 From: Chad Whitacre Date: Wed, 16 Sep 2015 17:45:07 -0400 Subject: [PATCH 11/31] Refactor to push add widget down --- www/assets/dashboard.css.spt | 4 +- www/assets/dashboard.js | 93 +++++++++++++++++------------------- www/dashboard/%index.spt | 29 +++++------ 3 files changed, 58 insertions(+), 68 deletions(-) diff --git a/www/assets/dashboard.css.spt b/www/assets/dashboard.css.spt index 4f33162663..23f5e3bc8a 100644 --- a/www/assets/dashboard.css.spt +++ b/www/assets/dashboard.css.spt @@ -86,9 +86,9 @@ } } - .add-account { + tfoot { border-top: 1px solid $light-brown; - tr:last-child td { + tr.buttons td { text-align: right; } } diff --git a/www/assets/dashboard.js b/www/assets/dashboard.js index 4172c38f95..aa6c366296 100644 --- a/www/assets/dashboard.js +++ b/www/assets/dashboard.js @@ -1,3 +1,5 @@ +var ENTER_KEY = 13; + Dashboard = {models: {}, views: {}, collections: {}}; Dashboard.Router = Backbone.Router.extend({ @@ -65,49 +67,35 @@ Dashboard.views.Main = Backbone.View.extend({ Dashboard.views.GeneralLedger = Backbone.View.extend({ el: '#general-ledger', initialize: function() { - this.$tbody= this.$('tbody'); }, }); Dashboard.views.ChartOfAccounts = Backbone.View.extend({ el: '#chart-of-accounts', initialize: function() { - this.$table = this.$('table'); - this.$tbody = this.$('tbody'); - this.data = new Dashboard.collections.Accounts(); - this.listenTo(this.data, 'reset', this.addAll); - this.data.fetch({reset:true}); + new Dashboard.views.AccountsListing; + new Dashboard.views.AddAccountWidget; + }, +}); - this.addAccountOff = new Dashboard.views.AddAccountOff; - this.addAccountOn = new Dashboard.views.AddAccountOn; - this.turnAddAccountOff(); - }, - addOne: function (account) { - var view = new Dashboard.views.AccountRow({model: account}); - var el = view.render().el; - this.$tbody.append(el); +Dashboard.views.AccountsListing = Backbone.View.extend({ + el: '#chart-of-accounts tbody', + initialize: function() { + this.data = new Dashboard.collections.Accounts(); + this.listenTo(this.data, 'reset', this.render); + this.data.fetch({reset:true}); }, - addAll: function () { - this.$tbody.html(''); + render: function() { + this.$el.html(''); this.data.each(this.addOne, this); + return this; }, - events: { - 'click .add-account.off button': 'turnAddAccountOn', - 'click .add-account.on button[type=cancel]': 'turnAddAccountOff', - 'click .add-account.on button[type=submit]': 'addAccount' - }, - turnAddAccountOn: function() { - this.addAccountOff.remove(); - this.$table.append(this.addAccountOn.render().el); - }, - turnAddAccountOff: function() { - this.addAccountOn.remove(); - this.$table.append(this.addAccountOff.render().el); + addOne: function(account) { + var view = new Dashboard.views.AccountRow({model: account}); + var el = view.render().el; + this.$el.append(el); }, - addAccount: function() { - console.log('adding account ...'); - } }); Dashboard.views.AccountRow = Backbone.View.extend({ @@ -116,32 +104,39 @@ Dashboard.views.AccountRow = Backbone.View.extend({ this.template = _.template($('#AccountRow').html()); }, render: function() { - this.$el.html(this.template(this.model.toJSON())); + this.el = this.template(this.model.attributes); return this; } }); -Dashboard.views.AddAccountOff = Backbone.View.extend({ - tagName: 'tfoot', - className: 'add-account off', + +Dashboard.views.AddAccountWidget = Backbone.View.extend({ + el: '#chart-of-accounts tfoot', initialize: function() { - this.template = _.template($('#AddAccountOff').html()); + this.$el.html($('#AddAccountWidget').html()); + this.turnAddAccountOff(); }, - render: function() { - this.$el.html(this.template()); - return this; + events: { + 'click .off button': 'turnAddAccountOn', + 'click .on button[type=cancel]': 'turnAddAccountOff', + 'click button[type=submit]': 'addAccount', + 'keydown input' : 'keyAction' }, -}); - -Dashboard.views.AddAccountOn = Backbone.View.extend({ - tagName: 'tfoot', - className: 'add-account on', - initialize: function() { - this.template = _.template($('#AddAccountOn').html()); + turnAddAccountOn: function() { + this.$('.off').hide(); + this.$('.on').show(); + this.$('.on input').first().focus(); }, - render: function() { - this.$el.html(this.template()); - return this; + turnAddAccountOff: function() { + this.$('.on').hide(); + this.$('.off').show(); + }, + keyAction: function(e) { + if (e.which === ENTER_KEY) + this.addAccount(); + }, + addAccount: function() { + alert('clicked!'); } }); diff --git a/www/dashboard/%index.spt b/www/dashboard/%index.spt index 94bd81d8f6..5aa3e666a0 100644 --- a/www/dashboard/%index.spt +++ b/www/dashboard/%index.spt @@ -33,6 +33,7 @@ if not user.ADMIN: Debits Credits + @@ -43,36 +44,30 @@ if not user.ADMIN: Number Name - Type + - - - diff --git a/www/v2/accounts/%number.spt b/www/v2/accounts/%number.spt new file mode 100644 index 0000000000..b83ce0d925 --- /dev/null +++ b/www/v2/accounts/%number.spt @@ -0,0 +1,31 @@ +import re +from aspen import Response +from psycopg2 import IntegrityError + +number_re = re.compile(r'^[0-9-]{1,32}$') +name_re = re.compile(r'^[A-Za-z0-9 ~-]{1,32}$') +[---] +if user.ANON: raise Response(401) +if not user.ADMIN: raise Response(403) + +request.allow('GET', 'PUT') + +number = request.path['number'] +if not number_re.match(number): + raise Response(404) + +if request.method == 'PUT': + name = request.body.get('name') + if not name_re.match(name): + raise Response(400, 'Invalid name.') + with website.db.get_cursor() as c: + try: + website.db.run("INSERT INTO accounts (number, name) VALUES (%s, %s)", (number, name)) + except IntegrityError: + website.db.run("UPDATE accounts SET name=%s WHERE number=%s") + +out = website.db.one("SELECT * FROM accounts WHERE number=%s", (number,)) +if not out: + raise Response(404) +[---] application/json via json_dump +out From a985a724185e0e53e4e7a87079f28a43be61788f Mon Sep 17 00:00:00 2001 From: Chad Whitacre Date: Wed, 16 Sep 2015 21:22:48 -0400 Subject: [PATCH 13/31] Tighten up widths on the accounts table --- www/assets/dashboard.css.spt | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/www/assets/dashboard.css.spt b/www/assets/dashboard.css.spt index 23f5e3bc8a..412d25d8e1 100644 --- a/www/assets/dashboard.css.spt +++ b/www/assets/dashboard.css.spt @@ -74,6 +74,12 @@ } td { font: normal 14px/16px $Mono; + &.number { + min-width: 96px; + } + &.name { + min-width: 144px; + } } th, td { @@ -91,5 +97,9 @@ tr.buttons td { text-align: right; } + td { + &.number input { width: 92px; } + &.name input { width: 140px; } + } } } From 5a3aa457005872b7df5fdda8804a086494e295fa Mon Sep 17 00:00:00 2001 From: Chad Whitacre Date: Wed, 16 Sep 2015 21:26:23 -0400 Subject: [PATCH 14/31] Persistence! --- www/assets/dashboard.js | 14 +++++++++----- www/v2/accounts/%number.spt | 4 ++-- www/v2/accounts/index.spt | 18 +----------------- 3 files changed, 12 insertions(+), 24 deletions(-) diff --git a/www/assets/dashboard.js b/www/assets/dashboard.js index ca3fe7cdd0..bc266d9423 100644 --- a/www/assets/dashboard.js +++ b/www/assets/dashboard.js @@ -84,6 +84,7 @@ Dashboard.views.AccountsListing = Backbone.View.extend({ el: '#chart-of-accounts tbody', initialize: function() { this.listenTo(this.collection, 'reset', this.render); + this.listenTo(this.collection, 'sync', this.render); this.collection.fetch({reset:true}); }, render: function() { @@ -136,12 +137,15 @@ Dashboard.views.AddAccountWidget = Backbone.View.extend({ this.addAccount(); }, addAccount: function() { - - var data = { number: this.$('input[name=number]').val() - , name: this.$('input[name=name]').val() + var data = { number: $.trim(this.$('input[name=number]').val()) + , name: $.trim(this.$('input[name=name]').val()) }; - if (data.number && data.name) - this.collection.create(data); + if (data.number && data.name) { + function success() { + this.$('input').val('').first().focus(); + } + this.collection.create(data, {success: success, wait: true}); + } } }); diff --git a/www/v2/accounts/%number.spt b/www/v2/accounts/%number.spt index b83ce0d925..20f750717d 100644 --- a/www/v2/accounts/%number.spt +++ b/www/v2/accounts/%number.spt @@ -22,10 +22,10 @@ if request.method == 'PUT': try: website.db.run("INSERT INTO accounts (number, name) VALUES (%s, %s)", (number, name)) except IntegrityError: - website.db.run("UPDATE accounts SET name=%s WHERE number=%s") + website.db.run("UPDATE accounts SET name=%s WHERE number=%s", (name, number)) out = website.db.one("SELECT * FROM accounts WHERE number=%s", (number,)) -if not out: +if out is None: raise Response(404) [---] application/json via json_dump out diff --git a/www/v2/accounts/index.spt b/www/v2/accounts/index.spt index 3d4db10aff..ace9a273f3 100644 --- a/www/v2/accounts/index.spt +++ b/www/v2/accounts/index.spt @@ -5,22 +5,6 @@ if user.ANON: if not user.ADMIN: raise Response(403) -out = {"accounts": [ {"number": "100-00", "name": "Balanced"} - , {"number": "100-01", "name": "Balanced - Pending"} - , {"number": "101-00", "name": "Citizens"} - , {"number": "101-01", "name": "Citizens - Pending"} - , {"number": "102-00", "name": "Ally"} - , {"number": "102-01", "name": "Ally - Pending"} - , {"number": "103-00", "name": "New Alliance"} - , {"number": "103-01", "name": "New Alliance - Pending"} - , {"number": "104-00", "name": "PayPal"} - , {"number": "104-01", "name": "PayPal - Pending"} - , {"number": "105-00", "name": "Coinbase"} - , {"number": "105-01", "name": "Coinbase - Pending"} - , {"number": "200-111", "name": "~user 111"} - , {"number": "201-222", "name": "Team 222"} - , {"number": "300", "name": "Income"} - , {"number": "400", "name": "Expenses"} - ]} +out = {"accounts": website.db.all('SELECT * FROM accounts ORDER BY number ASC')} [---] application/json via json_dump out From 3d7cec998ca14bf6a29f712f3fa5addd7dbdc37c Mon Sep 17 00:00:00 2001 From: Chad Whitacre Date: Wed, 16 Sep 2015 21:28:54 -0400 Subject: [PATCH 15/31] Fix test_pages again --- tests/py/test_pages.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/py/test_pages.py b/tests/py/test_pages.py index 89e4f3345b..4bf0b70d80 100644 --- a/tests/py/test_pages.py +++ b/tests/py/test_pages.py @@ -34,7 +34,8 @@ def browse(self, setup=None, **kw): .replace('/%redirect_to', '/giving') \ .replace('/%endpoint', '/public') \ .replace('/about/me/%sub', '/about/me') \ - .replace('/dashboard/%index', '') + .replace('/dashboard/%index', '') \ + .replace('/v2/accounts/%number', '/v2/accounts/100') assert '/%' not in url if 'index' in url.split('/')[-1]: url = url.rsplit('/', 1)[0] + '/' From 81fa191182a1a079827b2317be97f06cbf8d8719 Mon Sep 17 00:00:00 2001 From: Chad Whitacre Date: Thu, 17 Sep 2015 09:01:59 -0400 Subject: [PATCH 16/31] Implement account editing Not pixel-perfect but fine for now. --- www/assets/dashboard.css.spt | 25 ++++++++++++++------ www/assets/dashboard.js | 45 ++++++++++++++++++++++++++++++++---- www/dashboard/%index.spt | 18 +++++++++------ www/v2/accounts/%number.spt | 5 +++- 4 files changed, 74 insertions(+), 19 deletions(-) diff --git a/www/assets/dashboard.css.spt b/www/assets/dashboard.css.spt index 412d25d8e1..6f3583a2cc 100644 --- a/www/assets/dashboard.css.spt +++ b/www/assets/dashboard.css.spt @@ -76,18 +76,33 @@ font: normal 14px/16px $Mono; &.number { min-width: 96px; + input { width: 92px; } } &.name { min-width: 144px; + input { width: 140px; } + } + .edit { + display: none; } } - th, td { text-align: left; margin: 0; - padding: 6px 18px 3px 0; + padding: 6px 18px 5px 3px; &:last-child { - padding-right: 0; + padding-right: 3px; + } + } + tr.editing { + td { + padding: 1px 0 1px 0; + input { + display: inline-block; + border: 1px solid $light-brown; + padding: 2px; + outline: none; + } } } } @@ -97,9 +112,5 @@ tr.buttons td { text-align: right; } - td { - &.number input { width: 92px; } - &.name input { width: 140px; } - } } } diff --git a/www/assets/dashboard.js b/www/assets/dashboard.js index bc266d9423..02efda460d 100644 --- a/www/assets/dashboard.js +++ b/www/assets/dashboard.js @@ -1,4 +1,5 @@ var ENTER_KEY = 13; +var ESCAPE_KEY = 27; Dashboard = {models: {}, views: {}, collections: {}}; @@ -75,7 +76,7 @@ Dashboard.views.ChartOfAccounts = Backbone.View.extend({ initialize: function() { this.collection = new Dashboard.collections.Accounts(); new Dashboard.views.AccountsListing({collection: this.collection}); - new Dashboard.views.AddAccountWidget({collection: this.collection}); + new Dashboard.views.AddAccount({collection: this.collection}); }, }); @@ -103,18 +104,54 @@ Dashboard.views.AccountRow = Backbone.View.extend({ tagName: 'tr', initialize: function() { this.template = _.template($('#AccountRow').html()); + this.listenTo(this.model, 'change', this.render); }, render: function() { - this.el = this.template(this.model.attributes); + this.$el.html(this.template(this.model.attributes)); return this; + }, + events: { + 'dblclick td': 'turnEditAccountOn', + 'keydown input' : 'keyAction' + }, + turnEditAccountOn: function(e) { + this.$el.addClass('editing'); + this.$('.view').hide(); + this.$('.edit').show(); + $('input', e.currentTarget).focus(); + }, + turnEditAccountOff: function() { + this.$el.removeClass('editing'); + this.$('.view').show(); + this.$('.edit').hide(); + }, + keyAction: function(e) { + switch (e.which) { + case (ENTER_KEY): + this.editAccount(); + break; + case (ESCAPE_KEY): + this.turnEditAccountOff(); + break; + } + }, + editAccount: function() { + var data = { number: $.trim(this.$('input[name=number]').val()) + , name: $.trim(this.$('input[name=name]').val()) + }; + if (data.number && data.name) { + this.model.save(data, {wait: true}); + } } }); -Dashboard.views.AddAccountWidget = Backbone.View.extend({ + + +Dashboard.views.AddAccount = Backbone.View.extend({ el: '#chart-of-accounts tfoot', initialize: function() { - this.$el.html($('#AddAccountWidget').html()); + this.$el.html($('#AddAccount').html()); this.turnAddAccountOff(); }, events: { diff --git a/www/dashboard/%index.spt b/www/dashboard/%index.spt index bde6a1bb9a..dc2a36307a 100644 --- a/www/dashboard/%index.spt +++ b/www/dashboard/%index.spt @@ -51,15 +51,19 @@ if not user.ADMIN: - + +{% endblock %} diff --git a/www/api/v2/accounts/%number.spt b/www/api/v2/accounts/%number.spt index ed46ed1a5e..135a888843 100644 --- a/www/api/v2/accounts/%number.spt +++ b/www/api/v2/accounts/%number.spt @@ -59,10 +59,10 @@ out Returns a single account. -``` -$ curl https://gratipay.com/api/v2/accounts/100 \ - -H \"Accept: application/json\" \ - -u $user_id:$api_key +```bash +$ curl \"https://gratipay.com/api/v2/accounts/100\" \\ + -H \"Accept: application/json\" \\ + -u \"$user_id:$api_key\" {\"number\": \"100\": \"name\": \"Cash\"} ``` @@ -71,12 +71,13 @@ $ curl https://gratipay.com/api/v2/accounts/100 \ Upserts a single account, returning the account. -``` -$ curl https://gratipay.com/api/v2/accounts/101 \ - -H \"Accept: application/json\" \ - -u $user_id:$api_key \ - -X PUT - -d \"\" +```bash +$ curl \"https://gratipay.com/api/v2/accounts/101\" \\ + -H \"Accept: application/json\" \\ + -u \"$user_id:$api_key\" \\ + -X \"PUT\" \\ + -H \"Content-Type: application/json\" \\ + -d '{\"number\": \"101\", \"name\": \"Accounts Receivable\"}' {\"number\": \"101\": \"name\": \"Accounts Receivable\"} ``` diff --git a/www/api/v2/accounts/index.spt b/www/api/v2/accounts/index.spt index f554cb589c..1f4f85f22f 100644 --- a/www/api/v2/accounts/index.spt +++ b/www/api/v2/accounts/index.spt @@ -40,8 +40,10 @@ ascending. Gotcha: account numbers are text and are sorted as such. Also, we only return 128 records. You'll have to wait for us to implement paging to receive more than that. -``` -$ curl -H \"Accept: application/json\" -u $user_id:$api_key https://gratipay.com/api/v2/accounts/ +```bash +$ curl \"https://gratipay.com/api/v2/accounts/\" \\ + -H \"Accept: application/json\" \\ + -u $user_id:$api_key [{\"number\": \"101\": \"name\": \"Accounts Receivable\"}, {\"number\": \"201\": \"name\": \"Accounts Payable\"}] ``` diff --git a/www/api/v2/index.spt b/www/api/v2/index.spt index 1cf56cda40..c470fe4431 100644 --- a/www/api/v2/index.spt +++ b/www/api/v2/index.spt @@ -15,8 +15,10 @@ Most of the HTTP resources under [`/api/v2/`](/api/v2/) that you're browsing right now as `text/html` also have JSON representations. Set the `Accept` header to `application/json` to request the JSON version: -``` -$ curl -H \"Accept: application/json\" https://gratipay.com/api/v2/foo/ +```bash +$ curl \"https://gratipay.com/api/v2/\" \\ + -H \"Accept: application/json\" +{\"you\": \"anon\"} ``` @@ -25,8 +27,11 @@ $ curl -H \"Accept: application/json\" https://gratipay.com/api/v2/foo/ Use the user id and API key from [your settings page](/about/me/settings) to authenticate your requests: -``` -$ curl -H \"Accept: application/json\" -u $user_id:$api_key https://gratipay.com/api/v2/foo/ +```bash +$ curl \"https://gratipay.com/api/v2/\" \\ + -H \"Accept: application/json\" \\ + -u $user_id:$api_key +{\"you\": \"your-username\"} ``` @@ -87,4 +92,14 @@ the [postgres.py](http://postgres-py.readthedocs.org/) client library. [PagerDuty](https://gratipay.pagerduty.com/) for monitoring, and we have some stats on [a Librato dashboard](https://metrics.librato.com/share/dashboards/42hmoj9j). + +## Resources + +Here are the resources currently exposed in this API: + + - [`accounts/`](/api/v2/accounts/)—our chart of accounts, requires the + `admin` role + """ )}}{% endblock %} +[---] application/json via json_dump +{"you": "anon" if user.ANON else user.participant.username} diff --git a/www/assets/hljs/agate.css b/www/assets/hljs/agate.css new file mode 100644 index 0000000000..f8bd0d8312 --- /dev/null +++ b/www/assets/hljs/agate.css @@ -0,0 +1,17 @@ +/*! + * Agate by Taufik Nurrohman + * ---------------------------------------------------- + * + * #ade5fc + * #a2fca2 + * #c6b4f0 + * #d36363 + * #fcc28c + * #fc9b9b + * #ffa + * #fff + * #333 + * #62c8f3 + * #888 + * + */.hljs{display:block;overflow-x:auto;padding:.5em;background:#333;color:white;-webkit-text-size-adjust:none}.asciidoc .hljs-title,.hljs-label,.hljs-tag .hljs-title,.hljs-prompt,.http .hljs-request{font-weight:bold}.hljs-change,.hljs-code{font-style:italic}.hljs-tag,.ini .hljs-title{color:#62c8f3}.hljs-id,.hljs-cbracket,.hljs-tag .hljs-value{color:#ade5fc}.hljs-string,.hljs-bullet{color:#a2fca2}.hljs-type,.hljs-variable,.hljs-name,.actionscript .hljs-title,.aspectj .hljs-annotation,.aspectj .hljs-title,.hljs-attribute,.hljs-change,.hljs-blockquote,.hljs-built_in{color:#ffa}.hljs-number,.hljs-hexcolor,.hljs-link_label,.hljs-link_reference{color:#d36363}.hljs-keyword,.hljs-literal,.hljs-constant,.css .hljs-tag,.hljs-typename,.hljs-winutils{color:#fcc28c}.hljs-comment,.hljs-cdata,.hljs-preprocessor,.hljs-annotation,.hljs-decorator,.hljs-doctype,.hljs-deletion,.hljs-shebang,.apache .hljs-sqbracket,.tex .hljs-formula,.hljs-header,.hljs-horizontal_rule,.hljs-code{color:#888}.hljs-regexp,.hljs-attr_selector{color:#c6b4f0}.hljs-important,.hljs-doctype,.hljs-pi,.hljs-chunk,.actionscript .hljs-type,.hljs-shebang,.hljs-pragma,.http .hljs-attribute{color:#fc9b9b}.hljs-deletion{background-color:#fc9b9b;color:#333}.hljs-addition{background-color:#a2fca2;color:#333}.hljs a,.hljs-tag .hljs-attribute{color:inherit}.hljs a:focus,.hljs a:hover{color:inherit;text-decoration:underline} \ No newline at end of file diff --git a/www/assets/hljs/highlight.js b/www/assets/hljs/highlight.js new file mode 100644 index 0000000000..89376fce2a --- /dev/null +++ b/www/assets/hljs/highlight.js @@ -0,0 +1 @@ +!function(e){"undefined"!=typeof exports?e(exports):(window.hljs=e({}),"function"==typeof define&&define.amd&&define("hljs",[],function(){return window.hljs}))}(function(e){function n(e){return e.replace(/&/gm,"&").replace(//gm,">")}function t(e){return e.nodeName.toLowerCase()}function r(e,n){var t=e&&e.exec(n);return t&&0==t.index}function a(e){return/^(no-?highlight|plain|text)$/i.test(e)}function i(e){var n,t,r,i=e.className+" ";if(i+=e.parentNode?e.parentNode.className:"",t=/\blang(?:uage)?-([\w-]+)\b/i.exec(i))return w(t[1])?t[1]:"no-highlight";for(i=i.split(/\s+/),n=0,r=i.length;r>n;n++)if(w(i[n])||a(i[n]))return i[n]}function o(e,n){var t,r={};for(t in e)r[t]=e[t];if(n)for(t in n)r[t]=n[t];return r}function u(e){var n=[];return function r(e,a){for(var i=e.firstChild;i;i=i.nextSibling)3==i.nodeType?a+=i.nodeValue.length:1==i.nodeType&&(n.push({event:"start",offset:a,node:i}),a=r(i,a),t(i).match(/br|hr|img|input/)||n.push({event:"stop",offset:a,node:i}));return a}(e,0),n}function c(e,r,a){function i(){return e.length&&r.length?e[0].offset!=r[0].offset?e[0].offset"}function u(e){f+=""}function c(e){("start"==e.event?o:u)(e.node)}for(var s=0,f="",l=[];e.length||r.length;){var g=i();if(f+=n(a.substr(s,g[0].offset-s)),s=g[0].offset,g==e){l.reverse().forEach(u);do c(g.splice(0,1)[0]),g=i();while(g==e&&g.length&&g[0].offset==s);l.reverse().forEach(o)}else"start"==g[0].event?l.push(g[0].node):l.pop(),c(g.splice(0,1)[0])}return f+n(a.substr(s))}function s(e){function n(e){return e&&e.source||e}function t(t,r){return new RegExp(n(t),"m"+(e.cI?"i":"")+(r?"g":""))}function r(a,i){if(!a.compiled){if(a.compiled=!0,a.k=a.k||a.bK,a.k){var u={},c=function(n,t){e.cI&&(t=t.toLowerCase()),t.split(" ").forEach(function(e){var t=e.split("|");u[t[0]]=[n,t[1]?Number(t[1]):1]})};"string"==typeof a.k?c("keyword",a.k):Object.keys(a.k).forEach(function(e){c(e,a.k[e])}),a.k=u}a.lR=t(a.l||/\b\w+\b/,!0),i&&(a.bK&&(a.b="\\b("+a.bK.split(" ").join("|")+")\\b"),a.b||(a.b=/\B|\b/),a.bR=t(a.b),a.e||a.eW||(a.e=/\B|\b/),a.e&&(a.eR=t(a.e)),a.tE=n(a.e)||"",a.eW&&i.tE&&(a.tE+=(a.e?"|":"")+i.tE)),a.i&&(a.iR=t(a.i)),void 0===a.r&&(a.r=1),a.c||(a.c=[]);var s=[];a.c.forEach(function(e){e.v?e.v.forEach(function(n){s.push(o(e,n))}):s.push("self"==e?a:e)}),a.c=s,a.c.forEach(function(e){r(e,a)}),a.starts&&r(a.starts,i);var f=a.c.map(function(e){return e.bK?"\\.?("+e.b+")\\.?":e.b}).concat([a.tE,a.i]).map(n).filter(Boolean);a.t=f.length?t(f.join("|"),!0):{exec:function(){return null}}}}r(e)}function f(e,t,a,i){function o(e,n){for(var t=0;t";return i+=e+'">',i+n+o}function p(){if(!L.k)return n(y);var e="",t=0;L.lR.lastIndex=0;for(var r=L.lR.exec(y);r;){e+=n(y.substr(t,r.index-t));var a=g(L,r);a?(B+=a[1],e+=h(a[0],n(r[0]))):e+=n(r[0]),t=L.lR.lastIndex,r=L.lR.exec(y)}return e+n(y.substr(t))}function d(){var e="string"==typeof L.sL;if(e&&!x[L.sL])return n(y);var t=e?f(L.sL,y,!0,M[L.sL]):l(y,L.sL.length?L.sL:void 0);return L.r>0&&(B+=t.r),e&&(M[L.sL]=t.top),h(t.language,t.value,!1,!0)}function b(){return void 0!==L.sL?d():p()}function v(e,t){var r=e.cN?h(e.cN,"",!0):"";e.rB?(k+=r,y=""):e.eB?(k+=n(t)+r,y=""):(k+=r,y=t),L=Object.create(e,{parent:{value:L}})}function m(e,t){if(y+=e,void 0===t)return k+=b(),0;var r=o(t,L);if(r)return k+=b(),v(r,t),r.rB?0:t.length;var a=u(L,t);if(a){var i=L;i.rE||i.eE||(y+=t),k+=b();do L.cN&&(k+=""),B+=L.r,L=L.parent;while(L!=a.parent);return i.eE&&(k+=n(t)),y="",a.starts&&v(a.starts,""),i.rE?0:t.length}if(c(t,L))throw new Error('Illegal lexeme "'+t+'" for mode "'+(L.cN||"")+'"');return y+=t,t.length||1}var N=w(e);if(!N)throw new Error('Unknown language: "'+e+'"');s(N);var R,L=i||N,M={},k="";for(R=L;R!=N;R=R.parent)R.cN&&(k=h(R.cN,"",!0)+k);var y="",B=0;try{for(var C,j,I=0;;){if(L.t.lastIndex=I,C=L.t.exec(t),!C)break;j=m(t.substr(I,C.index-I),C[0]),I=C.index+j}for(m(t.substr(I)),R=L;R.parent;R=R.parent)R.cN&&(k+="");return{r:B,value:k,language:e,top:L}}catch(O){if(-1!=O.message.indexOf("Illegal"))return{r:0,value:n(t)};throw O}}function l(e,t){t=t||E.languages||Object.keys(x);var r={r:0,value:n(e)},a=r;return t.forEach(function(n){if(w(n)){var t=f(n,e,!1);t.language=n,t.r>a.r&&(a=t),t.r>r.r&&(a=r,r=t)}}),a.language&&(r.second_best=a),r}function g(e){return E.tabReplace&&(e=e.replace(/^((<[^>]+>|\t)+)/gm,function(e,n){return n.replace(/\t/g,E.tabReplace)})),E.useBR&&(e=e.replace(/\n/g,"
")),e}function h(e,n,t){var r=n?R[n]:t,a=[e.trim()];return e.match(/\bhljs\b/)||a.push("hljs"),-1===e.indexOf(r)&&a.push(r),a.join(" ").trim()}function p(e){var n=i(e);if(!a(n)){var t;E.useBR?(t=document.createElementNS("http://www.w3.org/1999/xhtml","div"),t.innerHTML=e.innerHTML.replace(/\n/g,"").replace(//g,"\n")):t=e;var r=t.textContent,o=n?f(n,r,!0):l(r),s=u(t);if(s.length){var p=document.createElementNS("http://www.w3.org/1999/xhtml","div");p.innerHTML=o.value,o.value=c(s,u(p),r)}o.value=g(o.value),e.innerHTML=o.value,e.className=h(e.className,n,o.language),e.result={language:o.language,re:o.r},o.second_best&&(e.second_best={language:o.second_best.language,re:o.second_best.r})}}function d(e){E=o(E,e)}function b(){if(!b.called){b.called=!0;var e=document.querySelectorAll("pre code");Array.prototype.forEach.call(e,p)}}function v(){addEventListener("DOMContentLoaded",b,!1),addEventListener("load",b,!1)}function m(n,t){var r=x[n]=t(e);r.aliases&&r.aliases.forEach(function(e){R[e]=n})}function N(){return Object.keys(x)}function w(e){return e=e.toLowerCase(),x[e]||x[R[e]]}var E={classPrefix:"hljs-",tabReplace:null,useBR:!1,languages:void 0},x={},R={};return e.highlight=f,e.highlightAuto=l,e.fixMarkup=g,e.highlightBlock=p,e.configure=d,e.initHighlighting=b,e.initHighlightingOnLoad=v,e.registerLanguage=m,e.listLanguages=N,e.getLanguage=w,e.inherit=o,e.IR="[a-zA-Z]\\w*",e.UIR="[a-zA-Z_]\\w*",e.NR="\\b\\d+(\\.\\d+)?",e.CNR="(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)",e.BNR="\\b(0b[01]+)",e.RSR="!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~",e.BE={b:"\\\\[\\s\\S]",r:0},e.ASM={cN:"string",b:"'",e:"'",i:"\\n",c:[e.BE]},e.QSM={cN:"string",b:'"',e:'"',i:"\\n",c:[e.BE]},e.PWM={b:/\b(a|an|the|are|I|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such)\b/},e.C=function(n,t,r){var a=e.inherit({cN:"comment",b:n,e:t,c:[]},r||{});return a.c.push(e.PWM),a.c.push({cN:"doctag",b:"(?:TODO|FIXME|NOTE|BUG|XXX):",r:0}),a},e.CLCM=e.C("//","$"),e.CBCM=e.C("/\\*","\\*/"),e.HCM=e.C("#","$"),e.NM={cN:"number",b:e.NR,r:0},e.CNM={cN:"number",b:e.CNR,r:0},e.BNM={cN:"number",b:e.BNR,r:0},e.CSSNM={cN:"number",b:e.NR+"(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",r:0},e.RM={cN:"regexp",b:/\//,e:/\/[gimuy]*/,i:/\n/,c:[e.BE,{b:/\[/,e:/\]/,r:0,c:[e.BE]}]},e.TM={cN:"title",b:e.IR,r:0},e.UTM={cN:"title",b:e.UIR,r:0},e});hljs.registerLanguage("bash",function(e){var t={cN:"variable",v:[{b:/\$[\w\d#@][\w\d_]*/},{b:/\$\{(.*?)}/}]},s={cN:"string",b:/"/,e:/"/,c:[e.BE,t,{cN:"variable",b:/\$\(/,e:/\)/,c:[e.BE]}]},a={cN:"string",b:/'/,e:/'/};return{aliases:["sh","zsh"],l:/-?[a-z\.]+/,k:{keyword:"if then else elif fi for while in do done case esac function",literal:"true false",built_in:"break cd continue eval exec exit export getopts hash pwd readonly return shift test times trap umask unset alias bind builtin caller command declare echo enable help let local logout mapfile printf read readarray source type typeset ulimit unalias set shopt autoload bg bindkey bye cap chdir clone comparguments compcall compctl compdescribe compfiles compgroups compquote comptags comptry compvalues dirs disable disown echotc echoti emulate fc fg float functions getcap getln history integer jobs kill limit log noglob popd print pushd pushln rehash sched setcap setopt stat suspend ttyctl unfunction unhash unlimit unsetopt vared wait whence where which zcompile zformat zftp zle zmodload zparseopts zprof zpty zregexparse zsocket zstyle ztcp",operator:"-ne -eq -lt -gt -f -d -e -s -l -a"},c:[{cN:"shebang",b:/^#![^\n]+sh\s*$/,r:10},{cN:"function",b:/\w[\w\d_]*\s*\(\s*\)\s*\{/,rB:!0,c:[e.inherit(e.TM,{b:/\w[\w\d_]*/})],r:0},e.HCM,e.NM,s,a,t]}}); \ No newline at end of file From 0852582974d4e7a40b637f75518ef896a3e1fd58 Mon Sep 17 00:00:00 2001 From: Chad Whitacre Date: Thu, 17 Sep 2015 15:55:53 -0400 Subject: [PATCH 27/31] Exercise the {"you": "foo"} behavior on /api/v2/ --- tests/py/test_v2_api.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 tests/py/test_v2_api.py diff --git a/tests/py/test_v2_api.py b/tests/py/test_v2_api.py new file mode 100644 index 0000000000..2b7c7b61e8 --- /dev/null +++ b/tests/py/test_v2_api.py @@ -0,0 +1,21 @@ +from __future__ import absolute_import, division, print_function, unicode_literals + +from aspen import json +from gratipay.testing import Harness + + +class Tests(Harness): + + def load(self, auth_as=None): + response = self.client.GET( '/api/v2/' + , auth_as=auth_as + , **{b'HTTP_ACCEPT': b'application/json' + }) + return json.loads(response.body) + + def test_anon_gets_anon(self): + assert self.load() == {'you': 'anon'} + + def test_non_anon_gets_their_username(self): + self.make_participant('alice') + assert self.load('alice') == {'you': 'alice'} From bd8b346bfc30bd6e7c9b777d39f675df3e7d6c71 Mon Sep 17 00:00:00 2001 From: Chad Whitacre Date: Thu, 17 Sep 2015 15:57:04 -0400 Subject: [PATCH 28/31] Standardize curl calls --- www/api/v2/accounts/index.spt | 2 +- www/api/v2/index.spt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/www/api/v2/accounts/index.spt b/www/api/v2/accounts/index.spt index 1f4f85f22f..54d6087807 100644 --- a/www/api/v2/accounts/index.spt +++ b/www/api/v2/accounts/index.spt @@ -43,7 +43,7 @@ receive more than that. ```bash $ curl \"https://gratipay.com/api/v2/accounts/\" \\ -H \"Accept: application/json\" \\ - -u $user_id:$api_key + -u \"$user_id:$api_key\" [{\"number\": \"101\": \"name\": \"Accounts Receivable\"}, {\"number\": \"201\": \"name\": \"Accounts Payable\"}] ``` diff --git a/www/api/v2/index.spt b/www/api/v2/index.spt index c470fe4431..c3fb48293f 100644 --- a/www/api/v2/index.spt +++ b/www/api/v2/index.spt @@ -30,7 +30,7 @@ authenticate your requests: ```bash $ curl \"https://gratipay.com/api/v2/\" \\ -H \"Accept: application/json\" \\ - -u $user_id:$api_key + -u \"$user_id:$api_key\" {\"you\": \"your-username\"} ``` From d272878422434ffaa2542789940bbdfde5eb1a7f Mon Sep 17 00:00:00 2001 From: Chad Whitacre Date: Thu, 17 Sep 2015 16:07:23 -0400 Subject: [PATCH 29/31] Point people from accounts/detail to accounts/ --- www/api/v2/accounts/%number.spt | 3 +++ 1 file changed, 3 insertions(+) diff --git a/www/api/v2/accounts/%number.spt b/www/api/v2/accounts/%number.spt index 135a888843..d4c392ef31 100644 --- a/www/api/v2/accounts/%number.spt +++ b/www/api/v2/accounts/%number.spt @@ -51,6 +51,9 @@ out {% extends "templates/api-accounts.html" %} {% block content %}{{ markdown.render(""" +See the chart of [`accounts`](/api/v2/accounts/) documentation for a +description of the accounts format. + ## Role Required `admin` From f1b52568d3b326675854bcee23b80cfbbd95fed9 Mon Sep 17 00:00:00 2001 From: Chad Whitacre Date: Mon, 21 Sep 2015 19:41:44 -0400 Subject: [PATCH 30/31] Write up docs for new GL Accounts schema --- templates/api-database.html | 9 ++++++++ templates/api.html | 1 + www/api/v2/accounts/index.spt | 25 +++++++++++----------- www/api/v2/database/continuants.spt | 26 +++++++++++++++++++++++ www/api/v2/database/index.spt | 33 +++++++++++++++++++++++++++++ www/api/v2/index.spt | 2 +- www/assets/hljs/highlight.js | 2 +- www/dashboard/%index.spt | 10 +++++++-- 8 files changed, 91 insertions(+), 17 deletions(-) create mode 100644 templates/api-database.html create mode 100644 www/api/v2/database/continuants.spt create mode 100644 www/api/v2/database/index.spt diff --git a/templates/api-database.html b/templates/api-database.html new file mode 100644 index 0000000000..9a1e7d647b --- /dev/null +++ b/templates/api-database.html @@ -0,0 +1,9 @@ +{% extends "templates/api.html" %} +{% block subnav %} + {% set current_page = request.path.raw.split('/')[4] %} + {% set nav_base = '/api/v2/database' %} + {% set pages = [ ('/', _('Overview')) + , ('/continuants', _('Continuants')) + ] %} + {% include "templates/nav.html" %} +{% endblock %} diff --git a/templates/api.html b/templates/api.html index 35beec3263..edef484985 100644 --- a/templates/api.html +++ b/templates/api.html @@ -4,6 +4,7 @@ {% set nav_base = "/api/v2" %} {% set pages = [ ('/', _('Overview')) , ('/accounts/', _('Accounts')) + , ('/database/', _('Database')) ] %} {% include "templates/nav.html" %} {% endblock %} diff --git a/www/api/v2/accounts/index.spt b/www/api/v2/accounts/index.spt index 54d6087807..2e847a8014 100644 --- a/www/api/v2/accounts/index.spt +++ b/www/api/v2/accounts/index.spt @@ -6,7 +6,7 @@ if not user.ADMIN: raise Response(403) request.allow('GET') banner = _("API") -title = _("Chart of Accounts") +title = _("General Ledger Accounts") [---] application/json via json_dump website.db.all('SELECT * FROM accounts ORDER BY number ASC LIMIT 128') @@ -14,18 +14,17 @@ website.db.all('SELECT * FROM accounts ORDER BY number ASC LIMIT 128') {% extends "templates/api-accounts.html" %} {% block content %}{{ markdown.render(""" -Gratipay's chart of accounts is in the `accounts` database table. It's a simple -mapping of account `number` to `name`, and forms the basis for our general -ledger. Our convention is to encode the type of account in the account number -like so: +Gratipay's general ledger accounts are in the `general_ledger_accounts` +database table, which uses the [continuant + pattern](/api/v2/database/continuants). The essential property for GL +account continuants is `id`. Our convention is to encode the type of account in +the account number like so: - **1xx**—Assets - **2xx**—Liabilities - - **3xx**—Income - - **4xx**—Expenses - -Every ~user and Team on Gratipay has an account in the chart of accounts, as -well as every banking and payments partner that we've used. + - **3xx**—Equity + - **4xx**—Revenue + - **5xx**—Expenses ## Role Required @@ -35,10 +34,10 @@ well as every banking and payments partner that we've used. ## GET -Returns a listing of accounts from the chart of accounts, sorted by `number` +Returns a chart of accounts for Gratipay's general ledger, sorted by `number` ascending. Gotcha: account numbers are text and are sorted as such. Also, we -only return 128 records. You'll have to wait for us to implement paging to -receive more than that. +only return 128 records. You'll have to help or wait for us to implement paging +to receive more than that. ```bash $ curl \"https://gratipay.com/api/v2/accounts/\" \\ diff --git a/www/api/v2/database/continuants.spt b/www/api/v2/database/continuants.spt new file mode 100644 index 0000000000..e2697e7bda --- /dev/null +++ b/www/api/v2/database/continuants.spt @@ -0,0 +1,26 @@ +from gratipay.utils import markdown +[---] +banner = _("API") +title = _("Continuants") +[---] text/html +{% extends "templates/api-database.html" %} +{% block content %}{{ markdown.render(""" + +The continuant schema design pattern begins with the notion of a \"foo\" object +that persists through time (or \"continues,\" hence, \"continuant\") despite +changes to its accidental properties. We encode such an object as multiple +records in a `foo` table, which is effectively a log of all changes to all Foos +over time. A `current_foo` view exposes each Foo as it exists at present. + +The `foo` table will have `ctime` and `mtime` fields, timestamps at which the +notional continuant \"foo\" was created and modified (respectively). The +`ctime` field is carried forward on each `foo` record for convenience (using +[`COALESCE`](http://www.postgresql.org/docs/9.3/static/functions-conditional.html#FUNCTIONS-COALESCE-NVL-IFNULL)), +while the `mtime` field is unique for each record. Certain fields in `foo` are +essential to the identity of each Foo, and are carried forward along with the +`ctime`. + +Grep the codebase for `payment_instructions` for an instance of this pattern, +or check out [`accounts`](/api/v2/accounts). + +""") }}{% endblock %} diff --git a/www/api/v2/database/index.spt b/www/api/v2/database/index.spt new file mode 100644 index 0000000000..c4f62441c4 --- /dev/null +++ b/www/api/v2/database/index.spt @@ -0,0 +1,33 @@ +from gratipay.utils import markdown +[---] +banner = _("API") +title = _("Database") +[---] text/html +{% extends "templates/api-database.html" %} +{% block content %}{{ markdown.render(""" + +We store our data in [PostgreSQL +9.3](http://www.postgresql.org/docs/9.3/static/), and we write a fair amount of +the [Postgres dialect of +SQL](http://www.postgresql.org/docs/9.3/static/sql.html). We use and maintain +the [postgres.py](http://postgres-py.readthedocs.org/) client library. + +Our database schema is a mish-mash of different techniques and patterns. +Ideally we can standardize and be consistent, but that's gonna take some work. +Let's start with some documentation! Shall we? :-) + + +## Auditability Patterns + +One of the things we want our database schema to support is auditability: we +want both ~users and admins to be able to review the history of changes to data +over time. We have two competing patterns for this: + + - the [\"continuant\"](/api/v2/database/continuants) pattern, and + - an `events` table (not documented yet). + +The continuant pattern came first historically. We started replacing it with an +`events` table, but we never finished. See +[1549](https://github.com/gratipay/gratipay.com/issues/1549) for backstory. + +""") }}{% endblock %} diff --git a/www/api/v2/index.spt b/www/api/v2/index.spt index c3fb48293f..a171b9446f 100644 --- a/www/api/v2/index.spt +++ b/www/api/v2/index.spt @@ -50,7 +50,7 @@ process during a weekly event called `payday`. Here's a high-level technical overview of the software architecture by which we deliver our application: - - **Database**—We store our data in [PostgreSQL + - **[Database](/api/v2/database/)**—We store our data in [PostgreSQL 9.3](http://www.postgresql.org/docs/9.3/static/), and we write a fair amount of the [Postgres dialect of SQL](http://www.postgresql.org/docs/9.3/static/sql.html). We use and maintain diff --git a/www/assets/hljs/highlight.js b/www/assets/hljs/highlight.js index 89376fce2a..29fd189c60 100644 --- a/www/assets/hljs/highlight.js +++ b/www/assets/hljs/highlight.js @@ -1 +1 @@ -!function(e){"undefined"!=typeof exports?e(exports):(window.hljs=e({}),"function"==typeof define&&define.amd&&define("hljs",[],function(){return window.hljs}))}(function(e){function n(e){return e.replace(/&/gm,"&").replace(//gm,">")}function t(e){return e.nodeName.toLowerCase()}function r(e,n){var t=e&&e.exec(n);return t&&0==t.index}function a(e){return/^(no-?highlight|plain|text)$/i.test(e)}function i(e){var n,t,r,i=e.className+" ";if(i+=e.parentNode?e.parentNode.className:"",t=/\blang(?:uage)?-([\w-]+)\b/i.exec(i))return w(t[1])?t[1]:"no-highlight";for(i=i.split(/\s+/),n=0,r=i.length;r>n;n++)if(w(i[n])||a(i[n]))return i[n]}function o(e,n){var t,r={};for(t in e)r[t]=e[t];if(n)for(t in n)r[t]=n[t];return r}function u(e){var n=[];return function r(e,a){for(var i=e.firstChild;i;i=i.nextSibling)3==i.nodeType?a+=i.nodeValue.length:1==i.nodeType&&(n.push({event:"start",offset:a,node:i}),a=r(i,a),t(i).match(/br|hr|img|input/)||n.push({event:"stop",offset:a,node:i}));return a}(e,0),n}function c(e,r,a){function i(){return e.length&&r.length?e[0].offset!=r[0].offset?e[0].offset"}function u(e){f+=""}function c(e){("start"==e.event?o:u)(e.node)}for(var s=0,f="",l=[];e.length||r.length;){var g=i();if(f+=n(a.substr(s,g[0].offset-s)),s=g[0].offset,g==e){l.reverse().forEach(u);do c(g.splice(0,1)[0]),g=i();while(g==e&&g.length&&g[0].offset==s);l.reverse().forEach(o)}else"start"==g[0].event?l.push(g[0].node):l.pop(),c(g.splice(0,1)[0])}return f+n(a.substr(s))}function s(e){function n(e){return e&&e.source||e}function t(t,r){return new RegExp(n(t),"m"+(e.cI?"i":"")+(r?"g":""))}function r(a,i){if(!a.compiled){if(a.compiled=!0,a.k=a.k||a.bK,a.k){var u={},c=function(n,t){e.cI&&(t=t.toLowerCase()),t.split(" ").forEach(function(e){var t=e.split("|");u[t[0]]=[n,t[1]?Number(t[1]):1]})};"string"==typeof a.k?c("keyword",a.k):Object.keys(a.k).forEach(function(e){c(e,a.k[e])}),a.k=u}a.lR=t(a.l||/\b\w+\b/,!0),i&&(a.bK&&(a.b="\\b("+a.bK.split(" ").join("|")+")\\b"),a.b||(a.b=/\B|\b/),a.bR=t(a.b),a.e||a.eW||(a.e=/\B|\b/),a.e&&(a.eR=t(a.e)),a.tE=n(a.e)||"",a.eW&&i.tE&&(a.tE+=(a.e?"|":"")+i.tE)),a.i&&(a.iR=t(a.i)),void 0===a.r&&(a.r=1),a.c||(a.c=[]);var s=[];a.c.forEach(function(e){e.v?e.v.forEach(function(n){s.push(o(e,n))}):s.push("self"==e?a:e)}),a.c=s,a.c.forEach(function(e){r(e,a)}),a.starts&&r(a.starts,i);var f=a.c.map(function(e){return e.bK?"\\.?("+e.b+")\\.?":e.b}).concat([a.tE,a.i]).map(n).filter(Boolean);a.t=f.length?t(f.join("|"),!0):{exec:function(){return null}}}}r(e)}function f(e,t,a,i){function o(e,n){for(var t=0;t";return i+=e+'">',i+n+o}function p(){if(!L.k)return n(y);var e="",t=0;L.lR.lastIndex=0;for(var r=L.lR.exec(y);r;){e+=n(y.substr(t,r.index-t));var a=g(L,r);a?(B+=a[1],e+=h(a[0],n(r[0]))):e+=n(r[0]),t=L.lR.lastIndex,r=L.lR.exec(y)}return e+n(y.substr(t))}function d(){var e="string"==typeof L.sL;if(e&&!x[L.sL])return n(y);var t=e?f(L.sL,y,!0,M[L.sL]):l(y,L.sL.length?L.sL:void 0);return L.r>0&&(B+=t.r),e&&(M[L.sL]=t.top),h(t.language,t.value,!1,!0)}function b(){return void 0!==L.sL?d():p()}function v(e,t){var r=e.cN?h(e.cN,"",!0):"";e.rB?(k+=r,y=""):e.eB?(k+=n(t)+r,y=""):(k+=r,y=t),L=Object.create(e,{parent:{value:L}})}function m(e,t){if(y+=e,void 0===t)return k+=b(),0;var r=o(t,L);if(r)return k+=b(),v(r,t),r.rB?0:t.length;var a=u(L,t);if(a){var i=L;i.rE||i.eE||(y+=t),k+=b();do L.cN&&(k+=""),B+=L.r,L=L.parent;while(L!=a.parent);return i.eE&&(k+=n(t)),y="",a.starts&&v(a.starts,""),i.rE?0:t.length}if(c(t,L))throw new Error('Illegal lexeme "'+t+'" for mode "'+(L.cN||"")+'"');return y+=t,t.length||1}var N=w(e);if(!N)throw new Error('Unknown language: "'+e+'"');s(N);var R,L=i||N,M={},k="";for(R=L;R!=N;R=R.parent)R.cN&&(k=h(R.cN,"",!0)+k);var y="",B=0;try{for(var C,j,I=0;;){if(L.t.lastIndex=I,C=L.t.exec(t),!C)break;j=m(t.substr(I,C.index-I),C[0]),I=C.index+j}for(m(t.substr(I)),R=L;R.parent;R=R.parent)R.cN&&(k+="");return{r:B,value:k,language:e,top:L}}catch(O){if(-1!=O.message.indexOf("Illegal"))return{r:0,value:n(t)};throw O}}function l(e,t){t=t||E.languages||Object.keys(x);var r={r:0,value:n(e)},a=r;return t.forEach(function(n){if(w(n)){var t=f(n,e,!1);t.language=n,t.r>a.r&&(a=t),t.r>r.r&&(a=r,r=t)}}),a.language&&(r.second_best=a),r}function g(e){return E.tabReplace&&(e=e.replace(/^((<[^>]+>|\t)+)/gm,function(e,n){return n.replace(/\t/g,E.tabReplace)})),E.useBR&&(e=e.replace(/\n/g,"
")),e}function h(e,n,t){var r=n?R[n]:t,a=[e.trim()];return e.match(/\bhljs\b/)||a.push("hljs"),-1===e.indexOf(r)&&a.push(r),a.join(" ").trim()}function p(e){var n=i(e);if(!a(n)){var t;E.useBR?(t=document.createElementNS("http://www.w3.org/1999/xhtml","div"),t.innerHTML=e.innerHTML.replace(/\n/g,"").replace(//g,"\n")):t=e;var r=t.textContent,o=n?f(n,r,!0):l(r),s=u(t);if(s.length){var p=document.createElementNS("http://www.w3.org/1999/xhtml","div");p.innerHTML=o.value,o.value=c(s,u(p),r)}o.value=g(o.value),e.innerHTML=o.value,e.className=h(e.className,n,o.language),e.result={language:o.language,re:o.r},o.second_best&&(e.second_best={language:o.second_best.language,re:o.second_best.r})}}function d(e){E=o(E,e)}function b(){if(!b.called){b.called=!0;var e=document.querySelectorAll("pre code");Array.prototype.forEach.call(e,p)}}function v(){addEventListener("DOMContentLoaded",b,!1),addEventListener("load",b,!1)}function m(n,t){var r=x[n]=t(e);r.aliases&&r.aliases.forEach(function(e){R[e]=n})}function N(){return Object.keys(x)}function w(e){return e=e.toLowerCase(),x[e]||x[R[e]]}var E={classPrefix:"hljs-",tabReplace:null,useBR:!1,languages:void 0},x={},R={};return e.highlight=f,e.highlightAuto=l,e.fixMarkup=g,e.highlightBlock=p,e.configure=d,e.initHighlighting=b,e.initHighlightingOnLoad=v,e.registerLanguage=m,e.listLanguages=N,e.getLanguage=w,e.inherit=o,e.IR="[a-zA-Z]\\w*",e.UIR="[a-zA-Z_]\\w*",e.NR="\\b\\d+(\\.\\d+)?",e.CNR="(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)",e.BNR="\\b(0b[01]+)",e.RSR="!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~",e.BE={b:"\\\\[\\s\\S]",r:0},e.ASM={cN:"string",b:"'",e:"'",i:"\\n",c:[e.BE]},e.QSM={cN:"string",b:'"',e:'"',i:"\\n",c:[e.BE]},e.PWM={b:/\b(a|an|the|are|I|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such)\b/},e.C=function(n,t,r){var a=e.inherit({cN:"comment",b:n,e:t,c:[]},r||{});return a.c.push(e.PWM),a.c.push({cN:"doctag",b:"(?:TODO|FIXME|NOTE|BUG|XXX):",r:0}),a},e.CLCM=e.C("//","$"),e.CBCM=e.C("/\\*","\\*/"),e.HCM=e.C("#","$"),e.NM={cN:"number",b:e.NR,r:0},e.CNM={cN:"number",b:e.CNR,r:0},e.BNM={cN:"number",b:e.BNR,r:0},e.CSSNM={cN:"number",b:e.NR+"(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",r:0},e.RM={cN:"regexp",b:/\//,e:/\/[gimuy]*/,i:/\n/,c:[e.BE,{b:/\[/,e:/\]/,r:0,c:[e.BE]}]},e.TM={cN:"title",b:e.IR,r:0},e.UTM={cN:"title",b:e.UIR,r:0},e});hljs.registerLanguage("bash",function(e){var t={cN:"variable",v:[{b:/\$[\w\d#@][\w\d_]*/},{b:/\$\{(.*?)}/}]},s={cN:"string",b:/"/,e:/"/,c:[e.BE,t,{cN:"variable",b:/\$\(/,e:/\)/,c:[e.BE]}]},a={cN:"string",b:/'/,e:/'/};return{aliases:["sh","zsh"],l:/-?[a-z\.]+/,k:{keyword:"if then else elif fi for while in do done case esac function",literal:"true false",built_in:"break cd continue eval exec exit export getopts hash pwd readonly return shift test times trap umask unset alias bind builtin caller command declare echo enable help let local logout mapfile printf read readarray source type typeset ulimit unalias set shopt autoload bg bindkey bye cap chdir clone comparguments compcall compctl compdescribe compfiles compgroups compquote comptags comptry compvalues dirs disable disown echotc echoti emulate fc fg float functions getcap getln history integer jobs kill limit log noglob popd print pushd pushln rehash sched setcap setopt stat suspend ttyctl unfunction unhash unlimit unsetopt vared wait whence where which zcompile zformat zftp zle zmodload zparseopts zprof zpty zregexparse zsocket zstyle ztcp",operator:"-ne -eq -lt -gt -f -d -e -s -l -a"},c:[{cN:"shebang",b:/^#![^\n]+sh\s*$/,r:10},{cN:"function",b:/\w[\w\d_]*\s*\(\s*\)\s*\{/,rB:!0,c:[e.inherit(e.TM,{b:/\w[\w\d_]*/})],r:0},e.HCM,e.NM,s,a,t]}}); \ No newline at end of file +!function(e){"undefined"!=typeof exports?e(exports):(window.hljs=e({}),"function"==typeof define&&define.amd&&define("hljs",[],function(){return window.hljs}))}(function(e){function n(e){return e.replace(/&/gm,"&").replace(//gm,">")}function t(e){return e.nodeName.toLowerCase()}function r(e,n){var t=e&&e.exec(n);return t&&0==t.index}function a(e){return/^(no-?highlight|plain|text)$/i.test(e)}function i(e){var n,t,r,i=e.className+" ";if(i+=e.parentNode?e.parentNode.className:"",t=/\blang(?:uage)?-([\w-]+)\b/i.exec(i))return w(t[1])?t[1]:"no-highlight";for(i=i.split(/\s+/),n=0,r=i.length;r>n;n++)if(w(i[n])||a(i[n]))return i[n]}function o(e,n){var t,r={};for(t in e)r[t]=e[t];if(n)for(t in n)r[t]=n[t];return r}function u(e){var n=[];return function r(e,a){for(var i=e.firstChild;i;i=i.nextSibling)3==i.nodeType?a+=i.nodeValue.length:1==i.nodeType&&(n.push({event:"start",offset:a,node:i}),a=r(i,a),t(i).match(/br|hr|img|input/)||n.push({event:"stop",offset:a,node:i}));return a}(e,0),n}function c(e,r,a){function i(){return e.length&&r.length?e[0].offset!=r[0].offset?e[0].offset"}function u(e){f+=""}function c(e){("start"==e.event?o:u)(e.node)}for(var s=0,f="",l=[];e.length||r.length;){var g=i();if(f+=n(a.substr(s,g[0].offset-s)),s=g[0].offset,g==e){l.reverse().forEach(u);do c(g.splice(0,1)[0]),g=i();while(g==e&&g.length&&g[0].offset==s);l.reverse().forEach(o)}else"start"==g[0].event?l.push(g[0].node):l.pop(),c(g.splice(0,1)[0])}return f+n(a.substr(s))}function s(e){function n(e){return e&&e.source||e}function t(t,r){return new RegExp(n(t),"m"+(e.cI?"i":"")+(r?"g":""))}function r(a,i){if(!a.compiled){if(a.compiled=!0,a.k=a.k||a.bK,a.k){var u={},c=function(n,t){e.cI&&(t=t.toLowerCase()),t.split(" ").forEach(function(e){var t=e.split("|");u[t[0]]=[n,t[1]?Number(t[1]):1]})};"string"==typeof a.k?c("keyword",a.k):Object.keys(a.k).forEach(function(e){c(e,a.k[e])}),a.k=u}a.lR=t(a.l||/\b\w+\b/,!0),i&&(a.bK&&(a.b="\\b("+a.bK.split(" ").join("|")+")\\b"),a.b||(a.b=/\B|\b/),a.bR=t(a.b),a.e||a.eW||(a.e=/\B|\b/),a.e&&(a.eR=t(a.e)),a.tE=n(a.e)||"",a.eW&&i.tE&&(a.tE+=(a.e?"|":"")+i.tE)),a.i&&(a.iR=t(a.i)),void 0===a.r&&(a.r=1),a.c||(a.c=[]);var s=[];a.c.forEach(function(e){e.v?e.v.forEach(function(n){s.push(o(e,n))}):s.push("self"==e?a:e)}),a.c=s,a.c.forEach(function(e){r(e,a)}),a.starts&&r(a.starts,i);var f=a.c.map(function(e){return e.bK?"\\.?("+e.b+")\\.?":e.b}).concat([a.tE,a.i]).map(n).filter(Boolean);a.t=f.length?t(f.join("|"),!0):{exec:function(){return null}}}}r(e)}function f(e,t,a,i){function o(e,n){for(var t=0;t";return i+=e+'">',i+n+o}function p(){if(!L.k)return n(y);var e="",t=0;L.lR.lastIndex=0;for(var r=L.lR.exec(y);r;){e+=n(y.substr(t,r.index-t));var a=g(L,r);a?(B+=a[1],e+=h(a[0],n(r[0]))):e+=n(r[0]),t=L.lR.lastIndex,r=L.lR.exec(y)}return e+n(y.substr(t))}function d(){var e="string"==typeof L.sL;if(e&&!x[L.sL])return n(y);var t=e?f(L.sL,y,!0,M[L.sL]):l(y,L.sL.length?L.sL:void 0);return L.r>0&&(B+=t.r),e&&(M[L.sL]=t.top),h(t.language,t.value,!1,!0)}function b(){return void 0!==L.sL?d():p()}function v(e,t){var r=e.cN?h(e.cN,"",!0):"";e.rB?(k+=r,y=""):e.eB?(k+=n(t)+r,y=""):(k+=r,y=t),L=Object.create(e,{parent:{value:L}})}function m(e,t){if(y+=e,void 0===t)return k+=b(),0;var r=o(t,L);if(r)return k+=b(),v(r,t),r.rB?0:t.length;var a=u(L,t);if(a){var i=L;i.rE||i.eE||(y+=t),k+=b();do L.cN&&(k+=""),B+=L.r,L=L.parent;while(L!=a.parent);return i.eE&&(k+=n(t)),y="",a.starts&&v(a.starts,""),i.rE?0:t.length}if(c(t,L))throw new Error('Illegal lexeme "'+t+'" for mode "'+(L.cN||"")+'"');return y+=t,t.length||1}var N=w(e);if(!N)throw new Error('Unknown language: "'+e+'"');s(N);var R,L=i||N,M={},k="";for(R=L;R!=N;R=R.parent)R.cN&&(k=h(R.cN,"",!0)+k);var y="",B=0;try{for(var C,j,I=0;;){if(L.t.lastIndex=I,C=L.t.exec(t),!C)break;j=m(t.substr(I,C.index-I),C[0]),I=C.index+j}for(m(t.substr(I)),R=L;R.parent;R=R.parent)R.cN&&(k+="");return{r:B,value:k,language:e,top:L}}catch(O){if(-1!=O.message.indexOf("Illegal"))return{r:0,value:n(t)};throw O}}function l(e,t){t=t||E.languages||Object.keys(x);var r={r:0,value:n(e)},a=r;return t.forEach(function(n){if(w(n)){var t=f(n,e,!1);t.language=n,t.r>a.r&&(a=t),t.r>r.r&&(a=r,r=t)}}),a.language&&(r.second_best=a),r}function g(e){return E.tabReplace&&(e=e.replace(/^((<[^>]+>|\t)+)/gm,function(e,n){return n.replace(/\t/g,E.tabReplace)})),E.useBR&&(e=e.replace(/\n/g,"
")),e}function h(e,n,t){var r=n?R[n]:t,a=[e.trim()];return e.match(/\bhljs\b/)||a.push("hljs"),-1===e.indexOf(r)&&a.push(r),a.join(" ").trim()}function p(e){var n=i(e);if(!a(n)){var t;E.useBR?(t=document.createElementNS("http://www.w3.org/1999/xhtml","div"),t.innerHTML=e.innerHTML.replace(/\n/g,"").replace(//g,"\n")):t=e;var r=t.textContent,o=n?f(n,r,!0):l(r),s=u(t);if(s.length){var p=document.createElementNS("http://www.w3.org/1999/xhtml","div");p.innerHTML=o.value,o.value=c(s,u(p),r)}o.value=g(o.value),e.innerHTML=o.value,e.className=h(e.className,n,o.language),e.result={language:o.language,re:o.r},o.second_best&&(e.second_best={language:o.second_best.language,re:o.second_best.r})}}function d(e){E=o(E,e)}function b(){if(!b.called){b.called=!0;var e=document.querySelectorAll("pre code");Array.prototype.forEach.call(e,p)}}function v(){addEventListener("DOMContentLoaded",b,!1),addEventListener("load",b,!1)}function m(n,t){var r=x[n]=t(e);r.aliases&&r.aliases.forEach(function(e){R[e]=n})}function N(){return Object.keys(x)}function w(e){return e=e.toLowerCase(),x[e]||x[R[e]]}var E={classPrefix:"hljs-",tabReplace:null,useBR:!1,languages:void 0},x={},R={};return e.highlight=f,e.highlightAuto=l,e.fixMarkup=g,e.highlightBlock=p,e.configure=d,e.initHighlighting=b,e.initHighlightingOnLoad=v,e.registerLanguage=m,e.listLanguages=N,e.getLanguage=w,e.inherit=o,e.IR="[a-zA-Z]\\w*",e.UIR="[a-zA-Z_]\\w*",e.NR="\\b\\d+(\\.\\d+)?",e.CNR="(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)",e.BNR="\\b(0b[01]+)",e.RSR="!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~",e.BE={b:"\\\\[\\s\\S]",r:0},e.ASM={cN:"string",b:"'",e:"'",i:"\\n",c:[e.BE]},e.QSM={cN:"string",b:'"',e:'"',i:"\\n",c:[e.BE]},e.PWM={b:/\b(a|an|the|are|I|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such)\b/},e.C=function(n,t,r){var a=e.inherit({cN:"comment",b:n,e:t,c:[]},r||{});return a.c.push(e.PWM),a.c.push({cN:"doctag",b:"(?:TODO|FIXME|NOTE|BUG|XXX):",r:0}),a},e.CLCM=e.C("//","$"),e.CBCM=e.C("/\\*","\\*/"),e.HCM=e.C("#","$"),e.NM={cN:"number",b:e.NR,r:0},e.CNM={cN:"number",b:e.CNR,r:0},e.BNM={cN:"number",b:e.BNR,r:0},e.CSSNM={cN:"number",b:e.NR+"(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?",r:0},e.RM={cN:"regexp",b:/\//,e:/\/[gimuy]*/,i:/\n/,c:[e.BE,{b:/\[/,e:/\]/,r:0,c:[e.BE]}]},e.TM={cN:"title",b:e.IR,r:0},e.UTM={cN:"title",b:e.UIR,r:0},e});hljs.registerLanguage("bash",function(e){var t={cN:"variable",v:[{b:/\$[\w\d#@][\w\d_]*/},{b:/\$\{(.*?)}/}]},s={cN:"string",b:/"/,e:/"/,c:[e.BE,t,{cN:"variable",b:/\$\(/,e:/\)/,c:[e.BE]}]},a={cN:"string",b:/'/,e:/'/};return{aliases:["sh","zsh"],l:/-?[a-z\.]+/,k:{keyword:"if then else elif fi for while in do done case esac function",literal:"true false",built_in:"break cd continue eval exec exit export getopts hash pwd readonly return shift test times trap umask unset alias bind builtin caller command declare echo enable help let local logout mapfile printf read readarray source type typeset ulimit unalias set shopt autoload bg bindkey bye cap chdir clone comparguments compcall compctl compdescribe compfiles compgroups compquote comptags comptry compvalues dirs disable disown echotc echoti emulate fc fg float functions getcap getln history integer jobs kill limit log noglob popd print pushd pushln rehash sched setcap setopt stat suspend ttyctl unfunction unhash unlimit unsetopt vared wait whence where which zcompile zformat zftp zle zmodload zparseopts zprof zpty zregexparse zsocket zstyle ztcp",operator:"-ne -eq -lt -gt -f -d -e -s -l -a"},c:[{cN:"shebang",b:/^#![^\n]+sh\s*$/,r:10},{cN:"function",b:/\w[\w\d_]*\s*\(\s*\)\s*\{/,rB:!0,c:[e.inherit(e.TM,{b:/\w[\w\d_]*/})],r:0},e.HCM,e.NM,s,a,t]}});hljs.registerLanguage("css",function(e){var c="[a-zA-Z-][a-zA-Z0-9_-]*",a={cN:"function",b:c+"\\(",rB:!0,eE:!0,e:"\\("},r={cN:"rule",b:/[A-Z\_\.\-]+\s*:/,rB:!0,e:";",eW:!0,c:[{cN:"attribute",b:/\S/,e:":",eE:!0,starts:{cN:"value",eW:!0,eE:!0,c:[a,e.CSSNM,e.QSM,e.ASM,e.CBCM,{cN:"hexcolor",b:"#[0-9A-Fa-f]+"},{cN:"important",b:"!important"}]}}]};return{cI:!0,i:/[=\/|'\$]/,c:[e.CBCM,r,{cN:"id",b:/\#[A-Za-z0-9_-]+/},{cN:"class",b:/\.[A-Za-z0-9_-]+/},{cN:"attr_selector",b:/\[/,e:/\]/,i:"$"},{cN:"pseudo",b:/:(:)?[a-zA-Z0-9\_\-\+\(\)"']+/},{cN:"at_rule",b:"@(font-face|page)",l:"[a-z-]+",k:"font-face page"},{cN:"at_rule",b:"@",e:"[{;]",c:[{cN:"keyword",b:/\S+/},{b:/\s/,eW:!0,eE:!0,r:0,c:[a,e.ASM,e.QSM,e.CSSNM]}]},{cN:"tag",b:c,r:0},{cN:"rules",b:"{",e:"}",i:/\S/,c:[e.CBCM,r]}]}});hljs.registerLanguage("sql",function(e){var t=e.C("--","$");return{cI:!0,i:/[<>{}*]/,c:[{cN:"operator",bK:"begin end start commit rollback savepoint lock alter create drop rename call delete do handler insert load replace select truncate update set show pragma grant merge describe use explain help declare prepare execute deallocate release unlock purge reset change stop analyze cache flush optimize repair kill install uninstall checksum restore check backup revoke",e:/;/,eW:!0,k:{keyword:"abort abs absolute acc acce accep accept access accessed accessible account acos action activate add addtime admin administer advanced advise aes_decrypt aes_encrypt after agent aggregate ali alia alias allocate allow alter always analyze ancillary and any anydata anydataset anyschema anytype apply archive archived archivelog are as asc ascii asin assembly assertion associate asynchronous at atan atn2 attr attri attrib attribu attribut attribute attributes audit authenticated authentication authid authors auto autoallocate autodblink autoextend automatic availability avg backup badfile basicfile before begin beginning benchmark between bfile bfile_base big bigfile bin binary_double binary_float binlog bit_and bit_count bit_length bit_or bit_xor bitmap blob_base block blocksize body both bound buffer_cache buffer_pool build bulk by byte byteordermark bytes c cache caching call calling cancel capacity cascade cascaded case cast catalog category ceil ceiling chain change changed char_base char_length character_length characters characterset charindex charset charsetform charsetid check checksum checksum_agg child choose chr chunk class cleanup clear client clob clob_base clone close cluster_id cluster_probability cluster_set clustering coalesce coercibility col collate collation collect colu colum column column_value columns columns_updated comment commit compact compatibility compiled complete composite_limit compound compress compute concat concat_ws concurrent confirm conn connec connect connect_by_iscycle connect_by_isleaf connect_by_root connect_time connection consider consistent constant constraint constraints constructor container content contents context contributors controlfile conv convert convert_tz corr corr_k corr_s corresponding corruption cos cost count count_big counted covar_pop covar_samp cpu_per_call cpu_per_session crc32 create creation critical cross cube cume_dist curdate current current_date current_time current_timestamp current_user cursor curtime customdatum cycle d data database databases datafile datafiles datalength date_add date_cache date_format date_sub dateadd datediff datefromparts datename datepart datetime2fromparts day day_to_second dayname dayofmonth dayofweek dayofyear days db_role_change dbtimezone ddl deallocate declare decode decompose decrement decrypt deduplicate def defa defau defaul default defaults deferred defi defin define degrees delayed delegate delete delete_all delimited demand dense_rank depth dequeue des_decrypt des_encrypt des_key_file desc descr descri describ describe descriptor deterministic diagnostics difference dimension direct_load directory disable disable_all disallow disassociate discardfile disconnect diskgroup distinct distinctrow distribute distributed div do document domain dotnet double downgrade drop dumpfile duplicate duration e each edition editionable editions element ellipsis else elsif elt empty enable enable_all enclosed encode encoding encrypt end end-exec endian enforced engine engines enqueue enterprise entityescaping eomonth error errors escaped evalname evaluate event eventdata events except exception exceptions exchange exclude excluding execu execut execute exempt exists exit exp expire explain export export_set extended extent external external_1 external_2 externally extract f failed failed_login_attempts failover failure far fast feature_set feature_value fetch field fields file file_name_convert filesystem_like_logging final finish first first_value fixed flash_cache flashback floor flush following follows for forall force form forma format found found_rows freelist freelists freepools fresh from from_base64 from_days ftp full function g general generated get get_format get_lock getdate getutcdate global global_name globally go goto grant grants greatest group group_concat group_id grouping grouping_id groups gtid_subtract guarantee guard handler hash hashkeys having hea head headi headin heading heap help hex hierarchy high high_priority hosts hour http i id ident_current ident_incr ident_seed identified identity idle_time if ifnull ignore iif ilike ilm immediate import in include including increment index indexes indexing indextype indicator indices inet6_aton inet6_ntoa inet_aton inet_ntoa infile initial initialized initially initrans inmemory inner innodb input insert install instance instantiable instr interface interleaved intersect into invalidate invisible is is_free_lock is_ipv4 is_ipv4_compat is_not is_not_null is_used_lock isdate isnull isolation iterate java join json json_exists k keep keep_duplicates key keys kill l language large last last_day last_insert_id last_value lax lcase lead leading least leaves left len lenght length less level levels library like like2 like4 likec limit lines link list listagg little ln load load_file lob lobs local localtime localtimestamp locate locator lock locked log log10 log2 logfile logfiles logging logical logical_reads_per_call logoff logon logs long loop low low_priority lower lpad lrtrim ltrim m main make_set makedate maketime managed management manual map mapping mask master master_pos_wait match matched materialized max maxextents maximize maxinstances maxlen maxlogfiles maxloghistory maxlogmembers maxsize maxtrans md5 measures median medium member memcompress memory merge microsecond mid migration min minextents minimum mining minus minute minvalue missing mod mode model modification modify module monitoring month months mount move movement multiset mutex n name name_const names nan national native natural nav nchar nclob nested never new newline next nextval no no_write_to_binlog noarchivelog noaudit nobadfile nocheck nocompress nocopy nocycle nodelay nodiscardfile noentityescaping noguarantee nokeep nologfile nomapping nomaxvalue nominimize nominvalue nomonitoring none noneditionable nonschema noorder nopr nopro noprom nopromp noprompt norely noresetlogs noreverse normal norowdependencies noschemacheck noswitch not nothing notice notrim novalidate now nowait nth_value nullif nulls num numb numbe nvarchar nvarchar2 object ocicoll ocidate ocidatetime ociduration ociinterval ociloblocator ocinumber ociref ocirefcursor ocirowid ocistring ocitype oct octet_length of off offline offset oid oidindex old on online only opaque open operations operator optimal optimize option optionally or oracle oracle_date oradata ord ordaudio orddicom orddoc order ordimage ordinality ordvideo organization orlany orlvary out outer outfile outline output over overflow overriding p package pad parallel parallel_enable parameters parent parse partial partition partitions pascal passing password password_grace_time password_lock_time password_reuse_max password_reuse_time password_verify_function patch path patindex pctincrease pctthreshold pctused pctversion percent percent_rank percentile_cont percentile_disc performance period period_add period_diff permanent physical pi pipe pipelined pivot pluggable plugin policy position post_transaction pow power pragma prebuilt precedes preceding precision prediction prediction_cost prediction_details prediction_probability prediction_set prepare present preserve prior priority private private_sga privileges procedural procedure procedure_analyze processlist profiles project prompt protection public publishingservername purge quarter query quick quiesce quota quotename radians raise rand range rank raw read reads readsize rebuild record records recover recovery recursive recycle redo reduced ref reference referenced references referencing refresh regexp_like register regr_avgx regr_avgy regr_count regr_intercept regr_r2 regr_slope regr_sxx regr_sxy reject rekey relational relative relaylog release release_lock relies_on relocate rely rem remainder rename repair repeat replace replicate replication required reset resetlogs resize resource respect restore restricted result result_cache resumable resume retention return returning returns reuse reverse revoke right rlike role roles rollback rolling rollup round row row_count rowdependencies rowid rownum rows rtrim rules safe salt sample save savepoint sb1 sb2 sb4 scan schema schemacheck scn scope scroll sdo_georaster sdo_topo_geometry search sec_to_time second section securefile security seed segment select self sequence sequential serializable server servererror session session_user sessions_per_user set sets settings sha sha1 sha2 share shared shared_pool short show shrink shutdown si_averagecolor si_colorhistogram si_featurelist si_positionalcolor si_stillimage si_texture siblings sid sign sin size size_t sizes skip slave sleep smalldatetimefromparts smallfile snapshot some soname sort soundex source space sparse spfile split sql sql_big_result sql_buffer_result sql_cache sql_calc_found_rows sql_small_result sql_variant_property sqlcode sqldata sqlerror sqlname sqlstate sqrt square standalone standby start starting startup statement static statistics stats_binomial_test stats_crosstab stats_ks_test stats_mode stats_mw_test stats_one_way_anova stats_t_test_ stats_t_test_indep stats_t_test_one stats_t_test_paired stats_wsr_test status std stddev stddev_pop stddev_samp stdev stop storage store stored str str_to_date straight_join strcmp strict string struct stuff style subdate subpartition subpartitions substitutable substr substring subtime subtring_index subtype success sum suspend switch switchoffset switchover sync synchronous synonym sys sys_xmlagg sysasm sysaux sysdate sysdatetimeoffset sysdba sysoper system system_user sysutcdatetime t table tables tablespace tan tdo template temporary terminated tertiary_weights test than then thread through tier ties time time_format time_zone timediff timefromparts timeout timestamp timestampadd timestampdiff timezone_abbr timezone_minute timezone_region to to_base64 to_date to_days to_seconds todatetimeoffset trace tracking transaction transactional translate translation treat trigger trigger_nestlevel triggers trim truncate try_cast try_convert try_parse type ub1 ub2 ub4 ucase unarchived unbounded uncompress under undo unhex unicode uniform uninstall union unique unix_timestamp unknown unlimited unlock unpivot unrecoverable unsafe unsigned until untrusted unusable unused update updated upgrade upped upper upsert url urowid usable usage use use_stored_outlines user user_data user_resources users using utc_date utc_timestamp uuid uuid_short validate validate_password_strength validation valist value values var var_samp varcharc vari varia variab variabl variable variables variance varp varraw varrawc varray verify version versions view virtual visible void wait wallet warning warnings week weekday weekofyear wellformed when whene whenev wheneve whenever where while whitespace with within without work wrapped xdb xml xmlagg xmlattributes xmlcast xmlcolattval xmlelement xmlexists xmlforest xmlindex xmlnamespaces xmlpi xmlquery xmlroot xmlschema xmlserialize xmltable xmltype xor year year_to_month years yearweek",literal:"true false null",built_in:"array bigint binary bit blob boolean char character date dec decimal float int int8 integer interval number numeric real record serial serial8 smallint text varchar varying void"},c:[{cN:"string",b:"'",e:"'",c:[e.BE,{b:"''"}]},{cN:"string",b:'"',e:'"',c:[e.BE,{b:'""'}]},{cN:"string",b:"`",e:"`",c:[e.BE]},e.CNM,e.CBCM,t]},e.CBCM,t]}});hljs.registerLanguage("scss",function(e){var t="[a-zA-Z-][a-zA-Z0-9_-]*",i={cN:"variable",b:"(\\$"+t+")\\b"},r={cN:"function",b:t+"\\(",rB:!0,eE:!0,e:"\\("},o={cN:"hexcolor",b:"#[0-9A-Fa-f]+"};({cN:"attribute",b:"[A-Z\\_\\.\\-]+",e:":",eE:!0,i:"[^\\s]",starts:{cN:"value",eW:!0,eE:!0,c:[r,o,e.CSSNM,e.QSM,e.ASM,e.CBCM,{cN:"important",b:"!important"}]}});return{cI:!0,i:"[=/|']",c:[e.CLCM,e.CBCM,r,{cN:"id",b:"\\#[A-Za-z0-9_-]+",r:0},{cN:"class",b:"\\.[A-Za-z0-9_-]+",r:0},{cN:"attr_selector",b:"\\[",e:"\\]",i:"$"},{cN:"tag",b:"\\b(a|abbr|acronym|address|area|article|aside|audio|b|base|big|blockquote|body|br|button|canvas|caption|cite|code|col|colgroup|command|datalist|dd|del|details|dfn|div|dl|dt|em|embed|fieldset|figcaption|figure|footer|form|frame|frameset|(h[1-6])|head|header|hgroup|hr|html|i|iframe|img|input|ins|kbd|keygen|label|legend|li|link|map|mark|meta|meter|nav|noframes|noscript|object|ol|optgroup|option|output|p|param|pre|progress|q|rp|rt|ruby|samp|script|section|select|small|span|strike|strong|style|sub|sup|table|tbody|td|textarea|tfoot|th|thead|time|title|tr|tt|ul|var|video)\\b",r:0},{cN:"pseudo",b:":(visited|valid|root|right|required|read-write|read-only|out-range|optional|only-of-type|only-child|nth-of-type|nth-last-of-type|nth-last-child|nth-child|not|link|left|last-of-type|last-child|lang|invalid|indeterminate|in-range|hover|focus|first-of-type|first-line|first-letter|first-child|first|enabled|empty|disabled|default|checked|before|after|active)"},{cN:"pseudo",b:"::(after|before|choices|first-letter|first-line|repeat-index|repeat-item|selection|value)"},i,{cN:"attribute",b:"\\b(z-index|word-wrap|word-spacing|word-break|width|widows|white-space|visibility|vertical-align|unicode-bidi|transition-timing-function|transition-property|transition-duration|transition-delay|transition|transform-style|transform-origin|transform|top|text-underline-position|text-transform|text-shadow|text-rendering|text-overflow|text-indent|text-decoration-style|text-decoration-line|text-decoration-color|text-decoration|text-align-last|text-align|tab-size|table-layout|right|resize|quotes|position|pointer-events|perspective-origin|perspective|page-break-inside|page-break-before|page-break-after|padding-top|padding-right|padding-left|padding-bottom|padding|overflow-y|overflow-x|overflow-wrap|overflow|outline-width|outline-style|outline-offset|outline-color|outline|orphans|order|opacity|object-position|object-fit|normal|none|nav-up|nav-right|nav-left|nav-index|nav-down|min-width|min-height|max-width|max-height|mask|marks|margin-top|margin-right|margin-left|margin-bottom|margin|list-style-type|list-style-position|list-style-image|list-style|line-height|letter-spacing|left|justify-content|initial|inherit|ime-mode|image-orientation|image-resolution|image-rendering|icon|hyphens|height|font-weight|font-variant-ligatures|font-variant|font-style|font-stretch|font-size-adjust|font-size|font-language-override|font-kerning|font-feature-settings|font-family|font|float|flex-wrap|flex-shrink|flex-grow|flex-flow|flex-direction|flex-basis|flex|filter|empty-cells|display|direction|cursor|counter-reset|counter-increment|content|column-width|column-span|column-rule-width|column-rule-style|column-rule-color|column-rule|column-gap|column-fill|column-count|columns|color|clip-path|clip|clear|caption-side|break-inside|break-before|break-after|box-sizing|box-shadow|box-decoration-break|bottom|border-width|border-top-width|border-top-style|border-top-right-radius|border-top-left-radius|border-top-color|border-top|border-style|border-spacing|border-right-width|border-right-style|border-right-color|border-right|border-radius|border-left-width|border-left-style|border-left-color|border-left|border-image-width|border-image-source|border-image-slice|border-image-repeat|border-image-outset|border-image|border-color|border-collapse|border-bottom-width|border-bottom-style|border-bottom-right-radius|border-bottom-left-radius|border-bottom-color|border-bottom|border|background-size|background-repeat|background-position|background-origin|background-image|background-color|background-clip|background-attachment|background-blend-mode|background|backface-visibility|auto|animation-timing-function|animation-play-state|animation-name|animation-iteration-count|animation-fill-mode|animation-duration|animation-direction|animation-delay|animation|align-self|align-items|align-content)\\b",i:"[^\\s]"},{cN:"value",b:"\\b(whitespace|wait|w-resize|visible|vertical-text|vertical-ideographic|uppercase|upper-roman|upper-alpha|underline|transparent|top|thin|thick|text|text-top|text-bottom|tb-rl|table-header-group|table-footer-group|sw-resize|super|strict|static|square|solid|small-caps|separate|se-resize|scroll|s-resize|rtl|row-resize|ridge|right|repeat|repeat-y|repeat-x|relative|progress|pointer|overline|outside|outset|oblique|nowrap|not-allowed|normal|none|nw-resize|no-repeat|no-drop|newspaper|ne-resize|n-resize|move|middle|medium|ltr|lr-tb|lowercase|lower-roman|lower-alpha|loose|list-item|line|line-through|line-edge|lighter|left|keep-all|justify|italic|inter-word|inter-ideograph|inside|inset|inline|inline-block|inherit|inactive|ideograph-space|ideograph-parenthesis|ideograph-numeric|ideograph-alpha|horizontal|hidden|help|hand|groove|fixed|ellipsis|e-resize|double|dotted|distribute|distribute-space|distribute-letter|distribute-all-lines|disc|disabled|default|decimal|dashed|crosshair|collapse|col-resize|circle|char|center|capitalize|break-word|break-all|bottom|both|bolder|bold|block|bidi-override|below|baseline|auto|always|all-scroll|absolute|table|table-cell)\\b"},{cN:"value",b:":",e:";",c:[r,i,o,e.CSSNM,e.QSM,e.ASM,{cN:"important",b:"!important"}]},{cN:"at_rule",b:"@",e:"[{;]",k:"mixin include extend for if else each while charset import debug media page content font-face namespace warn",c:[r,i,e.QSM,e.ASM,o,e.CSSNM,{cN:"preprocessor",b:"\\s[A-Za-z0-9_.-]+",r:0}]}]}});hljs.registerLanguage("python",function(e){var r={cN:"prompt",b:/^(>>>|\.\.\.) /},b={cN:"string",c:[e.BE],v:[{b:/(u|b)?r?'''/,e:/'''/,c:[r],r:10},{b:/(u|b)?r?"""/,e:/"""/,c:[r],r:10},{b:/(u|r|ur)'/,e:/'/,r:10},{b:/(u|r|ur)"/,e:/"/,r:10},{b:/(b|br)'/,e:/'/},{b:/(b|br)"/,e:/"/},e.ASM,e.QSM]},a={cN:"number",r:0,v:[{b:e.BNR+"[lLjJ]?"},{b:"\\b(0o[0-7]+)[lLjJ]?"},{b:e.CNR+"[lLjJ]?"}]},l={cN:"params",b:/\(/,e:/\)/,c:["self",r,a,b]};return{aliases:["py","gyp"],k:{keyword:"and elif is global as in if from raise for except finally print import pass return exec else break not with class assert yield try while continue del or def lambda async await nonlocal|10 None True False",built_in:"Ellipsis NotImplemented"},i:/(<\/|->|\?)/,c:[r,a,b,e.HCM,{v:[{cN:"function",bK:"def",r:10},{cN:"class",bK:"class"}],e:/:/,i:/[${=;\n,]/,c:[e.UTM,l]},{cN:"decorator",b:/^[\t ]*@/,e:/$/},{b:/\b(print|exec)\(/}]}});hljs.registerLanguage("json",function(e){var t={literal:"true false null"},i=[e.QSM,e.CNM],l={cN:"value",e:",",eW:!0,eE:!0,c:i,k:t},c={b:"{",e:"}",c:[{cN:"attribute",b:'\\s*"',e:'"\\s*:\\s*',eB:!0,eE:!0,c:[e.BE],i:"\\n",starts:l}],i:"\\S"},n={b:"\\[",e:"\\]",c:[e.inherit(l,{cN:null})],i:"\\S"};return i.splice(i.length,0,c,n),{c:i,k:t,i:"\\S"}});hljs.registerLanguage("javascript",function(e){return{aliases:["js"],k:{keyword:"in of if for while finally var new function do return void else break catch instanceof with throw case default try this switch continue typeof delete let yield const export super debugger as async await",literal:"true false null undefined NaN Infinity",built_in:"eval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Error EvalError InternalError RangeError ReferenceError StopIteration SyntaxError TypeError URIError Number Math Date String RegExp Array Float32Array Float64Array Int16Array Int32Array Int8Array Uint16Array Uint32Array Uint8Array Uint8ClampedArray ArrayBuffer DataView JSON Intl arguments require module console window document Symbol Set Map WeakSet WeakMap Proxy Reflect Promise"},c:[{cN:"pi",r:10,b:/^\s*['"]use (strict|asm)['"]/},e.ASM,e.QSM,{cN:"string",b:"`",e:"`",c:[e.BE,{cN:"subst",b:"\\$\\{",e:"\\}"}]},e.CLCM,e.CBCM,{cN:"number",v:[{b:"\\b(0[bB][01]+)"},{b:"\\b(0[oO][0-7]+)"},{b:e.CNR}],r:0},{b:"("+e.RSR+"|\\b(case|return|throw)\\b)\\s*",k:"return throw case",c:[e.CLCM,e.CBCM,e.RM,{b:/\s*[);\]]/,r:0,sL:"xml"}],r:0},{cN:"function",bK:"function",e:/\{/,eE:!0,c:[e.inherit(e.TM,{b:/[A-Za-z$_][0-9A-Za-z$_]*/}),{cN:"params",b:/\(/,e:/\)/,eB:!0,eE:!0,c:[e.CLCM,e.CBCM]}],i:/\[|%/},{b:/\$[(.]/},{b:"\\."+e.IR,r:0},{bK:"import",e:"[;$]",k:"import from as",c:[e.ASM,e.QSM]},{cN:"class",bK:"class",e:/[{;=]/,eE:!0,i:/[:"\[\]]/,c:[{bK:"extends"},e.UTM]}],i:/#/}});hljs.registerLanguage("xml",function(t){var s="[A-Za-z0-9\\._:-]+",c={b:/<\?(php)?(?!\w)/,e:/\?>/,sL:"php"},e={eW:!0,i:/]+/}]}]}]};return{aliases:["html","xhtml","rss","atom","xsl","plist"],cI:!0,c:[{cN:"doctype",b:"",r:10,c:[{b:"\\[",e:"\\]"}]},t.C("",{r:10}),{cN:"cdata",b:"<\\!\\[CDATA\\[",e:"\\]\\]>",r:10},{cN:"tag",b:"|$)",e:">",k:{title:"style"},c:[e],starts:{e:"",rE:!0,sL:"css"}},{cN:"tag",b:"|$)",e:">",k:{title:"script"},c:[e],starts:{e:"",rE:!0,sL:["actionscript","javascript","handlebars"]}},c,{cN:"pi",b:/<\?\w+/,e:/\?>/,r:10},{cN:"tag",b:"",c:[{cN:"title",b:/[^ \/><\n\t]+/,r:0},e]}]}}); \ No newline at end of file diff --git a/www/dashboard/%index.spt b/www/dashboard/%index.spt index dc2a36307a..4becc4a9aa 100644 --- a/www/dashboard/%index.spt +++ b/www/dashboard/%index.spt @@ -21,12 +21,18 @@ if not user.ADMIN:

Dashboard

General Ledger

+ From 544429d73414a0230433ddfadc0cc4be3131729e Mon Sep 17 00:00:00 2001 From: Chad Whitacre Date: Mon, 21 Sep 2015 19:52:40 -0400 Subject: [PATCH 31/31] Rename accounts/ to general-ledger-accounts/ We're not worrying about subledgers yet. --- ....html => api-general-ledger-accounts.html} | 2 +- templates/api.html | 2 +- tests/py/test_pages.py | 2 +- ....py => test_v2_general-ledger-accounts.py} | 24 +++++++++---------- .../%number.spt | 16 ++++++------- .../index.spt | 6 ++--- www/api/v2/index.spt | 4 ++-- 7 files changed, 28 insertions(+), 28 deletions(-) rename templates/{api-accounts.html => api-general-ledger-accounts.html} (82%) rename tests/py/{test_v2_accounts.py => test_v2_general-ledger-accounts.py} (78%) rename www/api/v2/{accounts => general-ledger-accounts}/%number.spt (84%) rename www/api/v2/{accounts => general-ledger-accounts}/index.spt (85%) diff --git a/templates/api-accounts.html b/templates/api-general-ledger-accounts.html similarity index 82% rename from templates/api-accounts.html rename to templates/api-general-ledger-accounts.html index b91110def6..2619ef7f7b 100644 --- a/templates/api-accounts.html +++ b/templates/api-general-ledger-accounts.html @@ -1,7 +1,7 @@ {% extends "templates/api.html" %} {% block subnav %} {% set current_page = request.path.raw.split('/')[4] %} - {% set nav_base = '/api/v2/accounts' %} + {% set nav_base = '/api/v2/general-ledger-accounts' %} {% set pages = [ ('/', _('Listing')) , ('/number', _('Detail')) ] %} diff --git a/templates/api.html b/templates/api.html index edef484985..4c1de9d30b 100644 --- a/templates/api.html +++ b/templates/api.html @@ -3,7 +3,7 @@ {% set current_page = request.path.raw.split('/')[3] %} {% set nav_base = "/api/v2" %} {% set pages = [ ('/', _('Overview')) - , ('/accounts/', _('Accounts')) + , ('/general-ledger-accounts/', _('GL Accounts')) , ('/database/', _('Database')) ] %} {% include "templates/nav.html" %} diff --git a/tests/py/test_pages.py b/tests/py/test_pages.py index 4bf0b70d80..3910cb5c4f 100644 --- a/tests/py/test_pages.py +++ b/tests/py/test_pages.py @@ -35,7 +35,7 @@ def browse(self, setup=None, **kw): .replace('/%endpoint', '/public') \ .replace('/about/me/%sub', '/about/me') \ .replace('/dashboard/%index', '') \ - .replace('/v2/accounts/%number', '/v2/accounts/100') + .replace('/v2/general-ledger-accounts/%number', '/v2/accounts/100') assert '/%' not in url if 'index' in url.split('/')[-1]: url = url.rsplit('/', 1)[0] + '/' diff --git a/tests/py/test_v2_accounts.py b/tests/py/test_v2_general-ledger-accounts.py similarity index 78% rename from tests/py/test_v2_accounts.py rename to tests/py/test_v2_general-ledger-accounts.py index a5f6f524f5..af31368873 100644 --- a/tests/py/test_v2_accounts.py +++ b/tests/py/test_v2_general-ledger-accounts.py @@ -12,28 +12,28 @@ def setUp(self): self.db.run("INSERT INTO accounts VALUES ('100', 'Cash')") def load(self, number): - return json.loads(self.client.GET('/api/v2/accounts/'+number, auth_as='admin').body) + return json.loads(self.client.GET('/api/v2/general-ledger-accounts/'+number, auth_as='admin').body) def test_can_list_accounts(self): - actual = json.loads(self.client.GET('/api/v2/accounts/', auth_as='admin').body) + actual = json.loads(self.client.GET('/api/v2/general-ledger-accounts/', auth_as='admin').body) assert actual == [{"number": "100", "name": "Cash"}] def test_can_get_one_account(self): assert self.load('100') == {"number": "100", "name": "Cash"} def test_401_for_anon(self): - assert self.client.GxT('/api/v2/accounts/').code == 401 - assert self.client.GxT('/api/v2/accounts/100').code == 401 + assert self.client.GxT('/api/v2/general-ledger-accounts/').code == 401 + assert self.client.GxT('/api/v2/general-ledger-accounts/100').code == 401 def test_403_for_non_admin(self): self.make_participant('alice') - assert self.client.GxT('/api/v2/accounts/', auth_as='alice').code == 403 - assert self.client.GxT('/api/v2/accounts/100', auth_as='alice').code == 403 + assert self.client.GxT('/api/v2/general-ledger-accounts/', auth_as='alice').code == 403 + assert self.client.GxT('/api/v2/general-ledger-accounts/100', auth_as='alice').code == 403 def test_can_change_name(self): self.client.hit( 'PUT' - , '/api/v2/accounts/100' + , '/api/v2/general-ledger-accounts/100' , data={'number': '100', 'name': 'Cash'} , auth_as='admin' ) @@ -41,7 +41,7 @@ def test_can_change_name(self): def test_bad_name_is_400(self): response = self.client.hit( 'PUT' - , '/api/v2/accounts/100' + , '/api/v2/general-ledger-accounts/100' , data={'number': '100', 'name': 'Cash!'} , auth_as='admin' , raise_immediately=False @@ -54,7 +54,7 @@ def test_bad_name_is_400(self): def test_can_save_new_account(self): assert raises(Response, self.load, '101').value.code == 404 self.client.hit( 'PUT' - , '/api/v2/accounts/101' + , '/api/v2/general-ledger-accounts/101' , data={'number': '101', 'name': 'Accounts Receivable'} , auth_as='admin' ) @@ -62,7 +62,7 @@ def test_can_save_new_account(self): def test_inserting_a_duplicate_name_is_400(self): response = self.client.hit( 'PUT' - , '/api/v2/accounts/101' + , '/api/v2/general-ledger-accounts/101' , data={'number': '101', 'name': 'Cash'} , auth_as='admin' , raise_immediately=False @@ -76,12 +76,12 @@ def test_inserting_a_duplicate_name_is_400(self): def test_updating_a_duplicate_name_is_400(self): self.client.hit( 'PUT' - , '/api/v2/accounts/101' + , '/api/v2/general-ledger-accounts/101' , data={'number': '101', 'name': 'Accounts Receivable'} , auth_as='admin' ) response = self.client.hit( 'PUT' - , '/api/v2/accounts/101' + , '/api/v2/general-ledger-accounts/101' , data={'number': '101', 'name': 'Cash'} , auth_as='admin' , raise_immediately=False diff --git a/www/api/v2/accounts/%number.spt b/www/api/v2/general-ledger-accounts/%number.spt similarity index 84% rename from www/api/v2/accounts/%number.spt rename to www/api/v2/general-ledger-accounts/%number.spt index d4c392ef31..5abe577acd 100644 --- a/www/api/v2/accounts/%number.spt +++ b/www/api/v2/general-ledger-accounts/%number.spt @@ -44,15 +44,15 @@ if number: raise Response(404) banner = _("API") -title = _("Account Detail") +title = _("GL Account Detail") [---] application/json via json_dump out [---] text/html -{% extends "templates/api-accounts.html" %} +{% extends "templates/api-general-ledger-accounts.html" %} {% block content %}{{ markdown.render(""" -See the chart of [`accounts`](/api/v2/accounts/) documentation for a -description of the accounts format. +See the [GL accounts](/api/v2/general-ledger-accounts/) documentation for a +description of the account format. ## Role Required @@ -60,10 +60,10 @@ description of the accounts format. ## GET -Returns a single account. +Returns a single GL account. ```bash -$ curl \"https://gratipay.com/api/v2/accounts/100\" \\ +$ curl \"https://gratipay.com/api/v2/general-ledger-accounts/100\" \\ -H \"Accept: application/json\" \\ -u \"$user_id:$api_key\" {\"number\": \"100\": \"name\": \"Cash\"} @@ -72,10 +72,10 @@ $ curl \"https://gratipay.com/api/v2/accounts/100\" \\ ## PUT -Upserts a single account, returning the account. +Upserts a GL single account, returning the account. ```bash -$ curl \"https://gratipay.com/api/v2/accounts/101\" \\ +$ curl \"https://gratipay.com/api/v2/general-ledger-accounts/101\" \\ -H \"Accept: application/json\" \\ -u \"$user_id:$api_key\" \\ -X \"PUT\" \\ diff --git a/www/api/v2/accounts/index.spt b/www/api/v2/general-ledger-accounts/index.spt similarity index 85% rename from www/api/v2/accounts/index.spt rename to www/api/v2/general-ledger-accounts/index.spt index 2e847a8014..8d776cc8c6 100644 --- a/www/api/v2/accounts/index.spt +++ b/www/api/v2/general-ledger-accounts/index.spt @@ -11,10 +11,10 @@ title = _("General Ledger Accounts") [---] application/json via json_dump website.db.all('SELECT * FROM accounts ORDER BY number ASC LIMIT 128') [---] text/html -{% extends "templates/api-accounts.html" %} +{% extends "templates/api-general-ledger-accounts.html" %} {% block content %}{{ markdown.render(""" -Gratipay's general ledger accounts are in the `general_ledger_accounts` +Gratipay's general ledger (GL) accounts are in the `general_ledger_accounts` database table, which uses the [continuant pattern](/api/v2/database/continuants). The essential property for GL account continuants is `id`. Our convention is to encode the type of account in @@ -49,7 +49,7 @@ $ curl \"https://gratipay.com/api/v2/accounts/\" \\ ## Drill-Down -[`/api/v2/accounts/%number`](/api/v2/accounts/number) +[`/api/v2/general-ledger-accounts/%number`](/api/v2/general-ledger-accounts/number) """) }} {% endblock %} diff --git a/www/api/v2/index.spt b/www/api/v2/index.spt index a171b9446f..d42e652501 100644 --- a/www/api/v2/index.spt +++ b/www/api/v2/index.spt @@ -97,8 +97,8 @@ the [postgres.py](http://postgres-py.readthedocs.org/) client library. Here are the resources currently exposed in this API: - - [`accounts/`](/api/v2/accounts/)—our chart of accounts, requires the - `admin` role + - [`general-ledger-accounts/`](/api/v2/general-ledger-accounts/)—our + general ledger chart of accounts, requires the `admin` role """ )}}{% endblock %} [---] application/json via json_dump
Account