diff --git a/.buckconfig b/.buckconfig new file mode 100644 index 0000000000000000000000000000000000000000..934256cb29d4a3616c740861c6af35ff6a165917 --- /dev/null +++ b/.buckconfig @@ -0,0 +1,6 @@ + +[android] + target = Google Inc.:Google APIs:23 + +[maven_repositories] + central = https://repo1.maven.org/maven2 diff --git a/.flowconfig b/.flowconfig new file mode 100644 index 0000000000000000000000000000000000000000..466bb117d90833062b718469907c061ea7989313 --- /dev/null +++ b/.flowconfig @@ -0,0 +1,99 @@ +[ignore] + +# We fork some components by platform. +.*/*.web.js +.*/*.android.js + +# Some modules have their own node_modules with overlap +.*/node_modules/node-haste/.* + +# Ugh +.*/node_modules/babel.* +.*/node_modules/babylon.* +.*/node_modules/invariant.* + +# Ignore react and fbjs where there are overlaps, but don't ignore +# anything that react-native relies on +.*/node_modules/fbjs/lib/Map.js +.*/node_modules/fbjs/lib/ErrorUtils.js + +# Flow has a built-in definition for the 'react' module which we prefer to use +# over the currently-untyped source +.*/node_modules/react/react.js +.*/node_modules/react/lib/React.js +.*/node_modules/react/lib/ReactDOM.js + +.*/__mocks__/.* +.*/__tests__/.* + +.*/commoner/test/source/widget/share.js + +# Ignore commoner tests +.*/node_modules/commoner/test/.* + +# See https://github.com/facebook/flow/issues/442 +.*/react-tools/node_modules/commoner/lib/reader.js + +# Ignore jest +.*/node_modules/jest-cli/.* + +# Ignore Website +.*/website/.* + +# Ignore generators +.*/local-cli/generator.* + +# Ignore BUCK generated folders +.*\.buckd/ + +# Ignore RNPM +.*/local-cli/rnpm/.* + +.*/node_modules/is-my-json-valid/test/.*\.json +.*/node_modules/iconv-lite/encodings/tables/.*\.json +.*/node_modules/y18n/test/.*\.json +.*/node_modules/spdx-license-ids/spdx-license-ids.json +.*/node_modules/spdx-exceptions/index.json +.*/node_modules/resolve/test/subdirs/node_modules/a/b/c/x.json +.*/node_modules/resolve/lib/core.json +.*/node_modules/jsonparse/samplejson/.*\.json +.*/node_modules/json5/test/.*\.json +.*/node_modules/ua-parser-js/test/.*\.json +.*/node_modules/builtin-modules/builtin-modules.json +.*/node_modules/binary-extensions/binary-extensions.json +.*/node_modules/url-regex/tlds.json +.*/node_modules/joi/.*\.json +.*/node_modules/isemail/.*\.json +.*/node_modules/tr46/.*\.json + + +[include] + +[libs] +node_modules/react-native/Libraries/react-native/react-native-interface.js +node_modules/react-native/flow +flow/ + +[options] +module.system=haste + +esproposal.class_static_fields=enable +esproposal.class_instance_fields=enable + +experimental.strict_type_args=true + +munge_underscores=true + +module.name_mapper='^image![a-zA-Z0-9$_-]+$' -> 'GlobalImageStub' +module.name_mapper='^[./a-zA-Z0-9$_-]+\.\(bmp\|gif\|jpg\|jpeg\|png\|psd\|svg\|webp\|m4v\|mov\|mp4\|mpeg\|mpg\|webm\|aac\|aiff\|caf\|m4a\|mp3\|wav\|html\|pdf\)$' -> 'RelativeImageStub' + +suppress_type=$FlowIssue +suppress_type=$FlowFixMe +suppress_type=$FixMe + +suppress_comment=\\(.\\|\n\\)*\\$FlowFixMe\\($\\|[^(]\\|(\\(>=0\\.\\(2[0-6]\\|1[0-9]\\|[0-9]\\).[0-9]\\)? *\\(site=[a-z,_]*react_native[a-z,_]*\\)?)\\) +suppress_comment=\\(.\\|\n\\)*\\$FlowIssue\\((\\(>=0\\.\\(2[0-6]\\|1[0-9]\\|[0-9]\\).[0-9]\\)? *\\(site=[a-z,_]*react_native[a-z,_]*\\)?)\\)?:? #[0-9]+ +suppress_comment=\\(.\\|\n\\)*\\$FlowFixedInNextDeploy + +[version] +^0.26.0 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..bf4bf6a5d58e1537b31211c8e2f4db5199aea72b --- /dev/null +++ b/.gitignore @@ -0,0 +1,46 @@ +# OSX +# +.DS_Store + +# Xcode +# +build/ +*.pbxuser +!default.pbxuser +*.mode1v3 +!default.mode1v3 +*.mode2v3 +!default.mode2v3 +*.perspectivev3 +!default.perspectivev3 +xcuserdata +*.xccheckout +*.moved-aside +DerivedData +*.hmap +*.ipa +*.xcuserstate +project.xcworkspace + +# Android/IJ +# +*.iml +.idea +.gradle +local.properties + +# node.js +# +node_modules/ +npm-debug.log + +# BUCK +buck-out/ +\.buckd/ +android/app/libs +android/keystores/debug.keystore +test_card.sdcard +.vscode/ + +export_server/local +export_server/local/ diff --git a/.watchmanconfig b/.watchmanconfig new file mode 100644 index 0000000000000000000000000000000000000000..0967ef424bce6791893e9a57bb952f80fd536e93 --- /dev/null +++ b/.watchmanconfig @@ -0,0 +1 @@ +{} diff --git a/README.md b/README.md new file mode 100644 index 0000000000000000000000000000000000000000..887a22d5f953914212cdffd5c84ba0b40bf4298f --- /dev/null +++ b/README.md @@ -0,0 +1,137 @@ +# MobileAudit - BlocPower mobile audit prototype. + +##Setup and configuration + +Setting up the project starts with setting up [react native](https://facebook.github.io/react-native/docs/getting-started.html#content) for android. + +The next step is pulling donw the project from github. + +The project should be able to be started by running + +```dos +react-native run-android +``` +in the root of the project. NOTE: you have to have either the android emulator or a physical device hooked up for this to run without errors. + +The connection is managed through the Android Debug Bridge (adb) and I found the following commands very useful: + +1. adb devices - _This lists all the devices connected to the system. If multiple devices are connected, run-android will install the app on all of them_ +2. adb shell - _This gives you access to the shell on the device, and the app folder is at /data/data/com.blockpower.blockpoweraudit, with the database in the files folder_ +3. The instructions for developing on a live device are [here](https://facebook.github.io/react-native/docs/running-on-device-android.html) + +###Navigating the project +1. The project is setup like the projects generated by the react-native init command, even though it was build by hand. The core configuration is handled through the package.json and index.android.js in the root, and the android project is in the android folder. The bulk of the react native code is in the root app folder, and the pdf and csv export app is in the export_server folder. +2. The android project is setup like the project generated from the react native project init command. It is managed using gradle files, and I primarally used Android Studio to edit the project. The android folder contains the master files, and the app folder has the blocpower app files. The release build puts the release apk in the /android/app/build/outputs/apk folder. +3. The react native project is organized into several areas + 1. entities.js - _This file contains meta data for all the objects that are edited by the app including the base hierarchy and validation information_ + 2. routes.js - _This is the information required for each screen in the app and includes labels and the reference to the scene component to render the page_ + 3. /actions/ - _This folder contains all the action pools for the application_ + 4. /assets/ - _Contains the base styles and images for the application, This is an overview of styles in react native: [Style](https://facebook.github.io/react-native/docs/style.html)_ + 5. /components/ - _Components to be used by the scenes and navigator for the app._ + 6. /scenes/ - _The pages of the application._ + 7. /stores/ - _The data management part of the application. There are 3 types of stores, nav, data, and entity._ + 1. navStore - _This manages the navigation for the applciation and ties the navigation actions to the navigator events_ + 2. dataStore - _This store manages the setup of the couchbase lite database including database creation, setting up views, replicatoion, and change monitoring._ + 3. entityStores - _There is a template for each entity store and there is a store created for each entity in the entities file, these consist of 3 main sub stores, edit - editing a single record, list - for listing all the objects of an entity, and children - for accessing all the children of a single record._ + 8. /utils/ - _There are general purpose classes and functions here_ + +###Overall Design +The application is built using functional reactive design on top of kefir.js for application data management and navigation. Everything is accomplished by plugging events into action streams defined by the application, each stream is an object with a raw stream property and some helper functions documented after the list. The action streams are: +1. nav - _These actions control navigation for the application_ + 1. push - Putting a route object onto this stream will load that page in the navigation. + 2. pop - Putting any event on this stream will call the pop method on the navigator navigate back to the previous page. + 3. navigator - When the app starts, the navigator object is put onto the stream to connect it with the navigation store. + 4. homeback - Putting an object onto this action will put it on the pop stream except for the home screen, then it does nothing. + 5. hardwareback - This will also put an event onto pop, but will close the app if it is activated from the home screen. +2. data + 2. deleteDatabae - This is used for testing. +3. entity - _one of these is created for each entity defined in the entity object_ + 1. newObj - Putting an object on this stream will load the appropriate edit screen with the new object. The object can be empty, or any properties can be set to pre-populate the data for the edit screen. + 2. editObj - Putting an object on the stream will load the edit screen like the newObj action, but this object must already have it's _id, _rev and type fields set. + 3. saveEntity - Putting any value onto this stream will trigger validation for the currently edited object, and if it passes, the object will be saved. + 4. destroy - Putting an object on this stream will delete it from the database. + 5. editField - This stream accepts { key:'', value:''} objects which update the currently edited object. + 6. loadChildren - Putting a parent object on this stream will load all the child objects on the associated entityStore + 7. saveAttachment - Putting an object with the following fields will create an attachment + 1. obj - the parent object to attach the attachment to. + 2. name - the name for the object, it must be unique within the attachments for the parent object + 3. uri - the uri for the object, either a local file reference or an http url + 4. type - the mime type of the attachment + +Each action stream is an object with the following 4 properties +1. raw - This is the kefir [pool](https://rpominov.github.io/kefir/#pool) that can be hooked up to source streams like events. +2. handler - This is a helper function which is useful for hooking the action streams up to react actions. It puts the event into the raw stream as a value. +3. handlerConst - This is another helper function that returns an endpoint that puts a constant value into the stream every time the handler is called. +4. handlerKV - This helper function is similar to handler and handlerConst. It takes a single keyName parameter and returns a handler that puts { key: keyName, value: event} objects into the stream. It is useful for wiring edit controls up to the editField actions. + +The store objects are responsible for maintianing application state, storing changes in the database, responding to change events from the database, and providing update streams for the UI to hook into. + +The stores use a core pattern, they do updates to objects stored in a [scan](https://rpominov.github.io/kefir/#scan) stream node. The stores take data from the input action, convert it into a stream of functions that are applied to the the object held in the scan node. + +For objects, save actions will put the object in the scan node into a stream for validation and then into a stream to save the object in the couchbase store. + +For lists, all input comes from the initial application load, and the changes stream from the database. + + Like the actions, they are organized according to the features of the application. There are the following stores and their exports, and a few change streams: +1. nav - This store hooks the actions up to the navigator for the app and then emits actions from the navigation state. + 1. stack - This is the current full state of the navigation element. It includes the current screen and all the hidden parent screens. + 2. current - This is the current route object for the current screen. + 3. depth - This is the count of how many routes are on the current stack. + 4. pop - This is the pop action stream + 5. close - This stream gets an event when the hardware back action is called on the home screen. + 6. navigator - This is the current navigator that is set for the application. +2. changes - this is the raw change stream from the couchbase db, it includes local changes from the application as well as changes replicated from other instances of the application. +3. change_actions - this is a stream of single change events with actions attached, these are used to make changes to the in memory data stores for the applicaton. +4. entityStores - These are the core of the application they are responsible for editing,saving, loading and validating the data of the application. They each expose the following streams: + 1. all + 2. edit + 3. entitySaved + 4. deleteSaved - A stream to signal that an entity has been deleted. The value is the result from + 5. children + 6. attachmentSaved - A stream to signal that an attachement has been saved. + 7. errors - A stream of all the errors from this store used to pull results from the streams and to drive user alerts when there is an issue. + 8. getAttachmentUri - A local api call to get the uri for an attachment. + +##Release Build +The release build for the application is done by following the [instructions here](https://facebook.github.io/react-native/docs/signed-apk-android.html). I've generated a signing key just to test on devices. + +##Dependencies + +###Android +The android portion of this project depends on two outside projects: +1. [react-native-couchbase-lite](https://github.com/couchbaselabs/react-native-couchbase-lite) +2. [react-native-image-picker](https://github.com/marcshilling/react-native-image-picker) + +###React Native +1. [react-native-material-design](http://react-native-material-design.github.io/) +2. [react-native-datepicker](https://github.com/xgfe/react-native-datepicker) +3. [react-native-action-button](https://github.com/mastermoo/react-native-action-button) +4. [kefir](https://rpominov.github.io/kefir/) +5. [immutable](https://facebook.github.io/immutable-js/) +6. [lodash](https://lodash.com/) + +###Server +1. [couchbase](http://www.couchbase.com/nosql-databases/couchbase-mobile) +2. [sync gateway](http://developer.couchbase.com/documentation/mobile/1.2/develop/guides/sync-gateway/index.html) + +###Useful books - free ebooks +* [Learning React Native](http://it-ebooks.info/book/6616/) +* [Pro Couchbase Server](http://it-ebooks.info/book/6690/) +* [Gradle for Android](http://it-ebooks.info/book/6122/) +* [Learn Android Studio](http://it-ebooks.info/book/5818/) +* [Reactive Programming wiht RxJS](http://it-ebooks.info/book/5818/) +* [Functional Javascript](http://it-ebooks.info/book/2573/) + +###Useful articles +* [Javascript on MDN for the ES6 syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/New_in_JavaScript) +* [Getting Started with React Native Android and Couchbase Lite](http://blog.couchbase.com/2015/november/getting-started-with-react-native-android-and-couchbase-lite) +* [Couchbase server & Sync Gateway on AWS](https://aws.amazon.com/marketplace/pp/B00FA8DO50) + + +NOTES: +I ran into an issue with windows path lengths and had to move the project into the root C drive on my computer, if you see error messages during compilation about path lengths then this might be required. + +### Form Components + +[Components Documentation](components.md) + diff --git a/android/.gitignore b/android/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..c6cbe562a42726ab875d51cb513723b234787300 --- /dev/null +++ b/android/.gitignore @@ -0,0 +1,8 @@ +*.iml +.gradle +/local.properties +/.idea/workspace.xml +/.idea/libraries +.DS_Store +/build +/captures diff --git a/android/app/.gitignore b/android/app/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..796b96d1c402326528b4ba3c12ee9d92d0e212e9 --- /dev/null +++ b/android/app/.gitignore @@ -0,0 +1 @@ +/build diff --git a/android/app/BUCK b/android/app/BUCK new file mode 100644 index 0000000000000000000000000000000000000000..3d3e64bdd2d97e5f60073a62944d73685110e8f5 --- /dev/null +++ b/android/app/BUCK @@ -0,0 +1,66 @@ +import re + +# To learn about Buck see [Docs](https://buckbuild.com/). +# To run your application with Buck: +# - install Buck +# - `npm start` - to start the packager +# - `cd android` +# - `keytool -genkey -v -keystore keystores/debug.keystore -storepass android -alias androiddebugkey -keypass android -dname "CN=Android Debug,O=Android,C=US` +# - `./gradlew :app:copyDownloadableDepsToLibs` - make all Gradle compile dependencies available to Buck +# - `buck install -r android/app` - compile, install and run application +# + +lib_deps = [] +for jarfile in glob(['libs/*.jar']): + name = 'jars__' + re.sub(r'^.*/([^/]+)\.jar$', r'\1', jarfile) + lib_deps.append(':' + name) + prebuilt_jar( + name = name, + binary_jar = jarfile, + ) + +for aarfile in glob(['libs/*.aar']): + name = 'aars__' + re.sub(r'^.*/([^/]+)\.aar$', r'\1', aarfile) + lib_deps.append(':' + name) + android_prebuilt_aar( + name = name, + aar = aarfile, + ) + +android_library( + name = 'all-libs', + exported_deps = lib_deps +) + +android_library( + name = 'app-code', + srcs = glob([ + 'src/main/java/**/*.java', + ]), + deps = [ + ':all-libs', + ':build_config', + ':res', + ], +) + +android_build_config( + name = 'build_config', + package = 'com.blocpower.blocpoweraudit', +) + +android_resource( + name = 'res', + res = 'src/main/res', + package = 'com.blocpower.blocpoweraudit', +) + +android_binary( + name = 'app', + package_type = 'debug', + manifest = 'src/main/AndroidManifest.xml', + keystore = '//android/keystores:debug', + deps = [ + ':app-code', + ], +) diff --git a/android/app/build.gradle b/android/app/build.gradle new file mode 100644 index 0000000000000000000000000000000000000000..e4613ee9e9fb521e880cbcfdbd1deca4dac04ca3 --- /dev/null +++ b/android/app/build.gradle @@ -0,0 +1,161 @@ +apply plugin: 'com.android.application' + +import com.android.build.OutputFile + +/** + * The react.gradle file registers a task for each build variant (e.g. bundleDebugJsAndAssets + * and bundleReleaseJsAndAssets). + * These basically call `react-native bundle` with the correct arguments during the Android build + * cycle. By default, bundleDebugJsAndAssets is skipped, as in debug/dev mode we prefer to load the + * bundle directly from the development server. Below you can see all the possible configurations + * and their defaults. If you decide to add a configuration block, make sure to add it before the + * `apply from: "../../node_modules/react-native/react.gradle"` line. + * + * project.ext.react = [ + * // the name of the generated asset file containing your JS bundle + * bundleAssetName: "index.android.bundle", + * + * // the entry file for bundle generation + * entryFile: "index.android.js", + * + * // whether to bundle JS and assets in debug mode + * bundleInDebug: false, + * + * // whether to bundle JS and assets in release mode + * bundleInRelease: true, + * + * // whether to bundle JS and assets in another build variant (if configured). + * // See http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Build-Variants + * // The configuration property can be in the following formats + * // 'bundleIn${productFlavor}${buildType}' + * // 'bundleIn${buildType}' + * // bundleInFreeDebug: true, + * // bundleInPaidRelease: true, + * // bundleInBeta: true, + * + * // the root of your project, i.e. where "package.json" lives + * root: "../../", + * + * // where to put the JS bundle asset in debug mode + * jsBundleDirDebug: "$buildDir/intermediates/assets/debug", + * + * // where to put the JS bundle asset in release mode + * jsBundleDirRelease: "$buildDir/intermediates/assets/release", + * + * // where to put drawable resources / React Native assets, e.g. the ones you use via + * // require('./image.png')), in debug mode + * resourcesDirDebug: "$buildDir/intermediates/res/merged/debug", + * + * // where to put drawable resources / React Native assets, e.g. the ones you use via + * // require('./image.png')), in release mode + * resourcesDirRelease: "$buildDir/intermediates/res/merged/release", + * + * // by default the gradle tasks are skipped if none of the JS files or assets change; this means + * // that we don't look at files in android/ or ios/ to determine whether the tasks are up to + * // date; if you have any other folders that you want to ignore for performance reasons (gradle + * // indexes the entire tree), add them here. Alternatively, if you have JS files in android/ + * // for example, you might want to remove it from here. + * inputExcludes: ["android/**", "ios/**"] + * ] + */ + +apply from: "../../node_modules/react-native/react.gradle" + +/** + * Set this to true to create two separate APKs instead of one: + * - An APK that only works on ARM devices + * - An APK that only works on x86 devices + * The advantage is the size of the APK is reduced by about 4MB. + * Upload all the APKs to the Play Store and people will download + * the correct one based on the CPU architecture of their device. + */ +def enableSeparateBuildPerCPUArchitecture = false + +/** + * Run Proguard to shrink the Java bytecode in release builds. + */ +def enableProguardInReleaseBuilds = false + +android { + compileSdkVersion 23 + buildToolsVersion "23.0.2" + + defaultConfig { + applicationId "com.blocpower.blocpoweraudit" + minSdkVersion 16 + targetSdkVersion 22 + versionCode 1 + versionName "1.0" + ndk { + abiFilters "armeabi-v7a", "x86" + } + } + signingConfigs { + release { + storeFile file('my-release-key.keystore') + storePassword '123456' + keyAlias 'my-key-alias' + keyPassword '123456' + } + } + splits { + abi { + reset() + enable enableSeparateBuildPerCPUArchitecture + universalApk false // If true, also generate a universal APK + include "armeabi-v7a", "x86" + } + } + buildTypes { + release { + minifyEnabled enableProguardInReleaseBuilds + proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' + signingConfig signingConfigs.release + } + debug { + debuggable true + } + } + // applicationVariants are e.g. debug, release + applicationVariants.all { variant -> + variant.outputs.each { output -> + // For each separate APK per architecture, set a unique version code as described here: + // http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits + def versionCodes = ["armeabi-v7a":1, "x86":2] + def abi = output.getFilter(OutputFile.ABI) + if (abi != null) { // null for the universal-debug, universal-release variants + output.versionCodeOverride = + versionCodes.get(abi) * 1048576 + defaultConfig.versionCode + } + } + } +// workaround for "duplicate files during packaging of APK" issue +// see https://groups.google.com/d/msg/adt-dev/bl5Rc4Szpzg/wC8cylTWuIEJ + packagingOptions { + exclude 'META-INF/ASL2.0' + exclude 'META-INF/LICENSE' + exclude 'META-INF/NOTICE' + } +} + +dependencies { + compile fileTree(dir: 'libs', include: ['*.jar']) + testCompile 'junit:junit:4.12' + compile 'com.android.support:appcompat-v7:23.4.0' + + compile 'com.couchbase.lite:couchbase-lite-android:+' + compile 'com.couchbase.lite:couchbase-lite-java-listener:+' + compile 'com.couchbase.lite:couchbase-lite-java-javascript:+' + + compile "com.facebook.react:react-native:+" // From node_modules + compile project(':react-native-couchbase-lite') + + compile project(':react-native-image-picker') +} + +// Run this once to be able to run the application with BUCK +// puts all compile dependencies into folder libs for BUCK to use +task copyDownloadableDepsToLibs(type: Copy) { + from configurations.compile + into 'libs' +} diff --git a/android/app/my-release-key.keystore b/android/app/my-release-key.keystore new file mode 100644 index 0000000000000000000000000000000000000000..dfb5aff51eef088c47bda46f4b16d6119259f79a Binary files /dev/null and b/android/app/my-release-key.keystore differ diff --git a/android/app/proguard-rules.pro b/android/app/proguard-rules.pro new file mode 100644 index 0000000000000000000000000000000000000000..9852871bd0de3525d486ea65582595d10f49fbfa --- /dev/null +++ b/android/app/proguard-rules.pro @@ -0,0 +1,63 @@ +# Add project specific ProGuard rules here. +# By default, the flags in this file are appended to flags specified +# in /usr/local/Cellar/android-sdk/24.3.3/tools/proguard/proguard-android.txt +# You can edit the include path and order by changing the proguardFiles +# directive in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# Add any project specific keep options here: + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Disabling obfuscation is useful if you collect stack traces from production crashes +# (unless you are using a system that supports de-obfuscate the stack traces). +-dontobfuscate + +# React Native + +# Keep our interfaces so they can be used by other ProGuard rules. +# See http://sourceforge.net/p/proguard/bugs/466/ +-keep,allowobfuscation @interface com.facebook.proguard.annotations.DoNotStrip +-keep,allowobfuscation @interface com.facebook.proguard.annotations.KeepGettersAndSetters + +# Do not strip any method/class that is annotated with @DoNotStrip +-keep @com.facebook.proguard.annotations.DoNotStrip class * +-keepclassmembers class * { + @com.facebook.proguard.annotations.DoNotStrip *; +} + +-keepclassmembers @com.facebook.proguard.annotations.KeepGettersAndSetters class * { + void set*(***); + *** get*(); +} + +-keep class * extends com.facebook.react.bridge.JavaScriptModule { *; } +-keep class * extends com.facebook.react.bridge.NativeModule { *; } +-keepclassmembers,includedescriptorclasses class * { native ; } +-keepclassmembers class * { @com.facebook.react.uimanager.UIProp ; } +-keepclassmembers class * { @com.facebook.react.uimanager.annotations.ReactProp ; } +-keepclassmembers class * { @com.facebook.react.uimanager.annotations.ReactPropGroup ; } + +-dontwarn com.facebook.react.** + +# okhttp + +-keepattributes Signature +-keepattributes *Annotation* +-keep class okhttp3.** { *; } +-keep interface okhttp3.** { *; } +-dontwarn okhttp3.** + +# okio + +-keep class sun.misc.Unsafe { *; } +-dontwarn java.nio.file.* +-dontwarn org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement +-dontwarn okio.** diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000000000000000000000000000000000000..db5f6c6c07cf72727c59c21939362abd6800ead2 --- /dev/null +++ b/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,33 @@ + + + + + + + + + + + + + + + > + + + + + + + + + + diff --git a/android/app/src/main/assets/fonts/MaterialIcons.ttf b/android/app/src/main/assets/fonts/MaterialIcons.ttf new file mode 100644 index 0000000000000000000000000000000000000000..7015564ad166a3e9d88c82f17829f0cc01ebe29a Binary files /dev/null and b/android/app/src/main/assets/fonts/MaterialIcons.ttf differ diff --git a/android/app/src/main/java/com/blocpower/blocpoweraudit/MainActivity.java b/android/app/src/main/java/com/blocpower/blocpoweraudit/MainActivity.java new file mode 100644 index 0000000000000000000000000000000000000000..2c598de786823f0f9828e9cf134034ce076fe49c --- /dev/null +++ b/android/app/src/main/java/com/blocpower/blocpoweraudit/MainActivity.java @@ -0,0 +1,107 @@ +package com.blocpower.blocpoweraudit; + +import android.os.Bundle; + +import com.facebook.react.ReactActivity; +import com.facebook.react.ReactPackage; +import com.facebook.react.shell.MainReactPackage; + +import com.couchbase.lite.Manager; +import com.couchbase.lite.View; +import com.couchbase.lite.android.AndroidContext; +import com.couchbase.lite.javascript.JavaScriptViewCompiler; +import com.couchbase.lite.listener.Credentials; +import com.couchbase.lite.listener.LiteListener; +import com.couchbase.lite.util.Log; + +import java.util.Arrays; +import java.util.List; + +import me.fraserxu.rncouchbaselite.ReactCBLiteManager; +import com.imagepicker.ImagePickerPackage; + + +public class MainActivity extends ReactActivity { + private final String TAG = "Audit"; + private static final int DEFAULT_LISTEN_PORT = 5984; + private int listenPort; + private Credentials allowedCredentials; + + /** + * Returns the name of the main component registered from JavaScript. + * This is used to schedule rendering of the component. + */ + @Override + protected String getMainComponentName() { + return "audit"; + } + + /** + * Returns whether dev mode should be enabled. + * This enables e.g. the dev menu. + */ + @Override + protected boolean getUseDeveloperSupport() { + return BuildConfig.DEBUG; + } + + /** + * A list of packages used by the app. If the app uses additional views + * or modules besides the default ones, add more packages here. + */ + @Override + protected List getPackages() { + return Arrays.asList( + new MainReactPackage() + ,new ReactCBLiteManager() + ,new ImagePickerPackage() + ); + } + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + initCBLite(); + } + + private void initCBLite() { + try { + + allowedCredentials = new Credentials("", ""); + View.setCompiler(new JavaScriptViewCompiler()); + + AndroidContext context = new AndroidContext(this); + Manager.enableLogging(Log.TAG, Log.VERBOSE); + Manager.enableLogging(Log.TAG_SYNC, Log.VERBOSE); + Manager.enableLogging(Log.TAG_QUERY, Log.VERBOSE); + Manager.enableLogging(Log.TAG_VIEW, Log.VERBOSE); + Manager.enableLogging(Log.TAG_CHANGE_TRACKER, Log.VERBOSE); + Manager.enableLogging(Log.TAG_BLOB_STORE, Log.VERBOSE); + Manager.enableLogging(Log.TAG_DATABASE, Log.VERBOSE); + Manager.enableLogging(Log.TAG_LISTENER, Log.VERBOSE); + Manager.enableLogging(Log.TAG_MULTI_STREAM_WRITER, Log.VERBOSE); + Manager.enableLogging(Log.TAG_REMOTE_REQUEST, Log.VERBOSE); + Manager.enableLogging(Log.TAG_ROUTER, Log.VERBOSE); + Manager manager = new Manager(context, Manager.DEFAULT_OPTIONS); + + listenPort = startCBLListener(DEFAULT_LISTEN_PORT, manager, allowedCredentials); + + Log.i(TAG, "initCBLite() completed successfully with: " + String.format( + "http://%s:%s@localhost:%d/", + allowedCredentials.getLogin(), + allowedCredentials.getPassword(), + listenPort)); + + } catch (final Exception e) { + e.printStackTrace(); + } + } + + private int startCBLListener(int listenPort, Manager manager, Credentials allowedCredentials) { + LiteListener listener = new LiteListener(manager, listenPort, allowedCredentials); + int boundPort = listener.getListenPort(); + Thread thread = new Thread(listener); + thread.start(); + return boundPort; + } +} diff --git a/android/app/src/main/res/mipmap-hdpi/four_circles.png b/android/app/src/main/res/mipmap-hdpi/four_circles.png new file mode 100644 index 0000000000000000000000000000000000000000..7f88a456c3a36c18adc227aca2283c59fbcca47d Binary files /dev/null and b/android/app/src/main/res/mipmap-hdpi/four_circles.png differ diff --git a/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/android/app/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 0000000000000000000000000000000000000000..cde69bcccec65160d92116f20ffce4fce0b5245c Binary files /dev/null and b/android/app/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-mdpi/four_circles.png b/android/app/src/main/res/mipmap-mdpi/four_circles.png new file mode 100644 index 0000000000000000000000000000000000000000..7f88a456c3a36c18adc227aca2283c59fbcca47d Binary files /dev/null and b/android/app/src/main/res/mipmap-mdpi/four_circles.png differ diff --git a/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/android/app/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 0000000000000000000000000000000000000000..c133a0cbd379f5af6dbf1a899a0293ca5eccfad0 Binary files /dev/null and b/android/app/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xhdpi/four_circles.png b/android/app/src/main/res/mipmap-xhdpi/four_circles.png new file mode 100644 index 0000000000000000000000000000000000000000..7f88a456c3a36c18adc227aca2283c59fbcca47d Binary files /dev/null and b/android/app/src/main/res/mipmap-xhdpi/four_circles.png differ diff --git a/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 0000000000000000000000000000000000000000..bfa42f0e7b91d006d22352c9ff2f134e504e3c1d Binary files /dev/null and b/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xxhdpi/four_circles.png b/android/app/src/main/res/mipmap-xxhdpi/four_circles.png new file mode 100644 index 0000000000000000000000000000000000000000..c34cd1a853aafc267160fe487eb4687d8b651f89 Binary files /dev/null and b/android/app/src/main/res/mipmap-xxhdpi/four_circles.png differ diff --git a/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 0000000000000000000000000000000000000000..324e72cdd7480cb983fa1bcc7ce686e51ef87fe7 Binary files /dev/null and b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xxxhdpi/four_circles.png b/android/app/src/main/res/mipmap-xxxhdpi/four_circles.png new file mode 100644 index 0000000000000000000000000000000000000000..9ce08abb09d3c80c20133ddd2e57082041e737b2 Binary files /dev/null and b/android/app/src/main/res/mipmap-xxxhdpi/four_circles.png differ diff --git a/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 0000000000000000000000000000000000000000..aee44e138434630332d88b1680f33c4b24c70ab3 Binary files /dev/null and b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/values/colors.xml b/android/app/src/main/res/values/colors.xml new file mode 100644 index 0000000000000000000000000000000000000000..3ab3e9cbce07f7cdc941fc8ba424c05e83ed80f0 --- /dev/null +++ b/android/app/src/main/res/values/colors.xml @@ -0,0 +1,6 @@ + + + #3F51B5 + #303F9F + #FF4081 + diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml new file mode 100644 index 0000000000000000000000000000000000000000..9cd81ebd2315babcf471c25ffd7ea24d2f82c307 --- /dev/null +++ b/android/app/src/main/res/values/strings.xml @@ -0,0 +1,3 @@ + + BlocPower Audit + diff --git a/android/app/src/main/res/values/styles.xml b/android/app/src/main/res/values/styles.xml new file mode 100644 index 0000000000000000000000000000000000000000..5885930df6d10edf3d6df40d6556297d11f953da --- /dev/null +++ b/android/app/src/main/res/values/styles.xml @@ -0,0 +1,11 @@ + + + + + + diff --git a/android/build.gradle b/android/build.gradle new file mode 100644 index 0000000000000000000000000000000000000000..25ff56b708a7ec2cadfd28bc090e020505635975 --- /dev/null +++ b/android/build.gradle @@ -0,0 +1,31 @@ +// Top-level build file where you can add configuration options common to all sub-projects/modules. + +buildscript { + repositories { + jcenter() + } + dependencies { + classpath 'com.android.tools.build:gradle:2.1.2' + + // NOTE: Do not place your application dependencies here; they belong + // in the individual module build.gradle files + } +} + +allprojects { + repositories { + mavenLocal() + jcenter() + maven { + // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm + url "$rootDir/../node_modules/react-native/android" + } + maven { + url "http://files.couchbase.com/maven2/" + } + } +} + +task clean(type: Delete) { + delete rootProject.buildDir +} diff --git a/android/gradle.properties b/android/gradle.properties new file mode 100644 index 0000000000000000000000000000000000000000..0b2f133057be2e22061a200cda792dba852cf5fc --- /dev/null +++ b/android/gradle.properties @@ -0,0 +1,25 @@ +# Project-wide Gradle settings. + +# IDE (e.g. Android Studio) users: +# Gradle settings configured through the IDE *will override* +# any settings specified in this file. + +# For more details on how to configure your build environment visit +# http://www.gradle.org/docs/current/userguide/build_environment.html + +# Specifies the JVM arguments used for the daemon process. +# The setting is particularly useful for tweaking memory settings. +# Default value: -Xmx10248m -XX:MaxPermSize=256m +org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 + +# When configured, Gradle will run in incubating parallel mode. +# This option should only be used with decoupled projects. More details, visit +# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects +# org.gradle.parallel=true + +android.useDeprecatedNdk=true + +MYAPP_RELEASE_STORE_FILE='my-release-key.keystore' +MYAPP_RELEASE_KEY_ALIAS='my-key-alias' +MYAPP_RELEASE_STORE_PASSWORD='123456' +MYAPP_RELEASE_KEY_PASSWORD='123456' diff --git a/android/gradle/wrapper/gradle-wrapper.jar b/android/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000000000000000000000000000000000..13372aef5e24af05341d49695ee84e5f9b594659 Binary files /dev/null and b/android/gradle/wrapper/gradle-wrapper.jar differ diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000000000000000000000000000000000000..122a0dca2e800b3ccf474321fc5e63551f507d29 --- /dev/null +++ b/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Mon Dec 28 10:00:20 PST 2015 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-2.10-all.zip diff --git a/android/gradlew b/android/gradlew new file mode 100644 index 0000000000000000000000000000000000000000..9d82f78915133e1c35a6ea51252590fb38efac2f --- /dev/null +++ b/android/gradlew @@ -0,0 +1,160 @@ +#!/usr/bin/env bash + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn ( ) { + echo "$*" +} + +die ( ) { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; +esac + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules +function splitJvmOpts() { + JVM_OPTS=("$@") +} +eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS +JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" + +exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/android/gradlew.bat b/android/gradlew.bat new file mode 100644 index 0000000000000000000000000000000000000000..8a0b282aa6885fb573c106b3551f7275c5f17e8e --- /dev/null +++ b/android/gradlew.bat @@ -0,0 +1,90 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windowz variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/android/keystores/BUCK b/android/keystores/BUCK new file mode 100644 index 0000000000000000000000000000000000000000..15da20e6b92c3f1d08cb9ea6bfbb56138d7bec86 --- /dev/null +++ b/android/keystores/BUCK @@ -0,0 +1,8 @@ +keystore( + name = 'debug', + store = 'debug.keystore', + properties = 'debug.keystore.properties', + visibility = [ + 'PUBLIC', + ], +) diff --git a/android/keystores/debug.keystore.properties b/android/keystores/debug.keystore.properties new file mode 100644 index 0000000000000000000000000000000000000000..121bfb49f0dfda7b85011c9d1442c9b9f940c9bb --- /dev/null +++ b/android/keystores/debug.keystore.properties @@ -0,0 +1,4 @@ +key.store=debug.keystore +key.alias=androiddebugkey +key.store.password=android +key.alias.password=android diff --git a/android/settings.gradle b/android/settings.gradle new file mode 100644 index 0000000000000000000000000000000000000000..dfb2a3bcb5a257276346d4562e4a94c51652748e --- /dev/null +++ b/android/settings.gradle @@ -0,0 +1,10 @@ +rootProject.name = 'blocpoweraudit' + +include ':react-native-couchbase-lite' +project(':react-native-couchbase-lite').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-couchbase-lite/android') + +include ':react-native-image-picker' +project(':react-native-image-picker').projectDir = new File(settingsDir, '../node_modules/react-native-image-picker/android') + +include ':app' + diff --git a/app/actions/allActions.js b/app/actions/allActions.js new file mode 100644 index 0000000000000000000000000000000000000000..54a1680cd229fa25aa8bf692b6940a84d62e5984 --- /dev/null +++ b/app/actions/allActions.js @@ -0,0 +1,17 @@ +import U from '../utils/utils'; + +/** + * This sets up the actions for the application. There are two fixed sets of actions for data, and navigation. +There are a set of actions defined for every entity in the application and they each have the following sub-actions: +newObj, editObj, saveEntity, destroy, editField, loadChildren, saveAttachment + */ +export default function getActions(entities) { + const initialObject = { + data: U.getActionsObject(['sync', 'deleteDatabase'], 'data'), + nav: U.getActionsObject(['push', 'pop', 'navigator', 'homeback', 'hardwareback'], 'nav') + }; + + const addEntityActions = (actions, entity) => { actions[entity] = U.getActionsObject(entities.entityActions, entity); return actions; }; + + return entities.entityList.reduce(addEntityActions, initialObject ); +} \ No newline at end of file diff --git a/app/assets/4-circles.png b/app/assets/4-circles.png new file mode 100644 index 0000000000000000000000000000000000000000..7f88a456c3a36c18adc227aca2283c59fbcca47d Binary files /dev/null and b/app/assets/4-circles.png differ diff --git a/app/assets/4-circles@2x.png b/app/assets/4-circles@2x.png new file mode 100644 index 0000000000000000000000000000000000000000..c34cd1a853aafc267160fe487eb4687d8b651f89 Binary files /dev/null and b/app/assets/4-circles@2x.png differ diff --git a/app/assets/4-circles@3x.png b/app/assets/4-circles@3x.png new file mode 100644 index 0000000000000000000000000000000000000000..9ce08abb09d3c80c20133ddd2e57082041e737b2 Binary files /dev/null and b/app/assets/4-circles@3x.png differ diff --git a/app/assets/styles.js b/app/assets/styles.js new file mode 100644 index 0000000000000000000000000000000000000000..b003d9da5b16c2f6a1efbfc35f19c1ad07f98c16 --- /dev/null +++ b/app/assets/styles.js @@ -0,0 +1,214 @@ +import { Dimensions } from 'react' +import { StyleSheet } from 'react-native'; + +export default StyleSheet.create({ + appContainer: { + flex: 1, + backgroundColor: '#111111' + }, + container: { + flex: 1 + }, + rowContainer: { + padding: 10, + flex: 1, + alignItems: 'flex-start', + justifyContent: 'flex-start', + flexDirection: 'row', + backgroundColor: '#FFFFFF', + borderWidth: 1, + borderStyle: 'solid', + borderColor: '#DDDDDD', + elevation: 2, + marginLeft: 7, + marginRight: 7 + }, + rowAvatarContainer: { + flex: 1 + }, + rowAvatar: { + backgroundColor: '#f7f7f7' + }, + rowMain: { + flex: 6, + alignSelf: 'center', + flexDirection: 'column', + }, + rowText: { + fontWeight: '600', + color: '#000000', + fontSize: 19, + flex: 1 + }, + subRowText: { + fontWeight: '400', + fontSize: 19, + flex: 1 + }, + rowDelete: { + flex: 1, + marginTop: 5 + }, + label: { + fontSize: 19, + alignSelf: 'flex-start', + color: 'black' + }, + groupLabel: { + fontSize: 23, + textDecorationLine: 'underline', + color: 'black', + marginTop: 60, + marginBottom: 30, + fontWeight: '700' + }, + rowTitle: { + color: '#48BBEC', + fontSize: 16, + }, + mainEditContainer: { + }, + mainContainer: { + flex: 1, + padding: 30, + marginTop: 56, + flexDirection: 'column', + justifyContent: 'center', + backgroundColor: '#F8F8F8', + elevation: 0 + }, + entityInput: { + height: 50, + padding: 4, + marginTop: 0, + marginRight: 5, + marginBottom: 20, + fontSize: 23, + borderWidth: 1, + borderColor: 'white', + borderRadius: 8, + color: '#585858' + }, + entityTextBox: { + height: 100 + }, + inputNumberGroup: { + flex: 1, + marginBottom: 15, + alignItems: 'flex-start', + width: 200, + flexDirection: 'row', + flexWrap: 'nowrap' + }, + inputNumber: { + width: 50, + height: 50, + marginTop: -10, + marginLeft: 5, + marginBottom: 20, + marginRight: 5, + fontSize: 23, + textAlign: 'center' + }, + inputNumberFull: { + width: 200, + height: 50, + marginTop: -15, + marginLeft: 5, + marginRight: 5, + marginBottom: 15, + fontSize: 23, + }, + inputNumberLabel: { + height: 50 + }, + geoLocator: { + marginTop: 10, + marginBottom: 10 + }, + choicesGroup: { + flex: 1, + alignItems: 'flex-start', + flexDirection: 'column', + flexWrap: 'nowrap', + marginBottom: 15, + height: 100 + }, + items: { + fontSize: 23, + alignItems: 'center' + }, + lookupGroup: { + height: 50, + flexDirection: 'row', + flexWrap: 'wrap', + alignItems: 'stretch', + marginTop: 5, + marginBottom: 10, + marginLeft: 10 + }, + locationIcon: { + marginTop: 5, + marginRight: 5 + }, + coordinates: { + alignSelf: 'flex-start', + padding: 4, + marginTop: 10, + marginRight: 5, + fontSize: 23, + borderWidth: 1, + borderColor: '#585858', + borderRadius: 8, + color: '#585858', + margin: 5 + }, + buttonText: { + fontSize: 18, + color: '#111', + alignSelf: 'center' + }, + button: { + height: 45, + flexDirection: 'row', + backgroundColor: 'white', + borderColor: 'white', + borderWidth: 1, + borderRadius: 8, + marginBottom: 10, + marginTop: 10, + alignSelf: 'stretch', + justifyContent: 'center' + }, + actionButtonIcon: { + fontSize: 20, + height: 22, + color: 'white', + marginLeft: 10 + }, + buildingEdit: { + marginBottom: 50 + }, + picker: { + }, + dropdownPicker: { + fontSize: 26, + padding: 4, + color: '#585858' + }, + datePick: { + position: 'relative', + alignSelf: 'center', + width: 330, + height: 110, + marginTop: 15, + marginBottom: 40 + }, + dateInstructions: { + alignSelf: 'center' + }, +}); + +const ActionButtonStyle = { color: '#f7301d'}; + +export { ActionButtonStyle}; diff --git a/app/components/Toolbar.js b/app/components/Toolbar.js new file mode 100644 index 0000000000000000000000000000000000000000..47cbea0101dd38592a62a412b98d784b4ede0057 --- /dev/null +++ b/app/components/Toolbar.js @@ -0,0 +1,66 @@ +import React, { Component, PropTypes } from 'react'; +import { Text } from 'react-native'; +import { Toolbar, PRIMARY_COLORS } from 'react-native-material-design'; +//import { Toolbar } from './materialToolbar'; +import { subscriptionTracker as tracker} from '../utils/utils'; +import _ from 'lodash'; + +export default class Tb extends Component { + constructor(props) { + super(props); + this.navTracker = tracker(); + this.actionTracker = tracker(); + } + componentDidMount() { + console.log('toolbar', 'mount'); + this.navTracker.addSub( this.props.stores.nav.stack, this.handleRoute.bind(this)); + } + + componentWillUnmount() { + console.log('toolbar', 'un-mount'); + this.navTracker.cleanUp(); + } + + handleRoute(stack) { + if (!stack) { + return; + } + //Stop listening to any existing events. + this.actionTracker.cleanUp(); + + const route = stack.get(0); + //Connect listeners to all the response streams for the actions + if (route.actions) for (action of route.actions) { + this.actionTracker.addSub(_.get(this.props.stores[route.entityName], action.response), this.props.actions.nav.homeback.handler); + } + //Set the route data for the toolbar + this.setState({ + route: route, + isChild: stack.size > 1 + }); + } + + mapActions(f) { + if (!this.state || !this.state.route.actions) { + return; + } + return this.state.route.actions.map(f); + } + + getEntityAction(action) { + console.log('getEntityAction', this.state.route.entityName) + return _.get(this.props.actions[this.state.route.entityName], action); + } + + render() { + console.log('toolbar', this.actionTracker) + return ( ({icon: action.icon, onPress: this.getEntityAction(action.action).handler })) } + rightIconStyle={{ margin: 20 }} + overrides={{backgroundColor: '#585858', leftIconColor: '#f7301d'}} + />); + } +} diff --git a/app/components/addChildrenButton.js b/app/components/addChildrenButton.js new file mode 100644 index 0000000000000000000000000000000000000000..e7f773057d9417bcf8321b6224e6238c66aabbc9 --- /dev/null +++ b/app/components/addChildrenButton.js @@ -0,0 +1,35 @@ +import React, { Component } from 'react' +import { View, Text, ListView, TextInput, Picker, ScrollView, TouchableOpacity, TouchableHighlight } from 'react-native'; + +import ActionButton from 'react-native-action-button'; +import Icon from 'react-native-vector-icons/MaterialIcons'; +import styles, { ActionButtonStyle } from '../assets/styles'; + +export default class AddChildrenButton extends Component { + mapChildTypes(f) { + const render = f.bind(this); + const { entityType, actions, entityLink } = this.props; + console.log('entity rev', entityLink.entityMap.get('_rev')); + if (entityType && entityType.children && entityLink.entityMap.get('_rev')) { + return entityType.children.map((entityName, i) => { + const pressAction = actions[entityName].newObj.handlerConst({ parent_id: entityLink.entityMap.get('_id') }); + return render(entityName, i, pressAction); + }); + } + } + + renderActionButton(entityName, i, pressAction) { + return ( + + + + ); + } + + render() { + const { entityType, actions } = this.props; + if (entityType && entityType.children) { + return ({ this.mapChildTypes(this.renderActionButton) }); + } + } +} diff --git a/app/components/audit.js b/app/components/audit.js new file mode 100644 index 0000000000000000000000000000000000000000..ab33f69a3ed39bd5d4619e4b89b150915905d52b --- /dev/null +++ b/app/components/audit.js @@ -0,0 +1,52 @@ +import React, { Component } from 'react'; +import { Navigator, Text, View } from 'react-native'; +import { Card } from 'react-native-material-design'; +import Toolbar from './Toolbar'; +import U, { subscriptionTracker as tracker } from '../utils/utils'; + + +export default function getAudit(actions, routes, entities, setup$, styles) { + + return class audit extends Component { + constructor(props) { + super(props); + this.tracker = tracker(); + } + + componentDidMount() { + if (setup$) { + this.tracker.addSub(setup$, this.mapState.bind(this)); + } + } + + componentWillUnmount() { + this.tracker.cleanUp(); + } + + mapState(stores) { + this.setState({ + stores: stores + }) + } + + render() { + if (!this.state) { + return (LOADING...); + } + let route = null; + this.state.stores.nav.current.take(1).onValue((r) => { route = r; }); + return ( + } + renderScene={(route, navigator) => { return ( + + + )} + }> + + ); + } + } +} diff --git a/app/components/entityEdit.js b/app/components/entityEdit.js new file mode 100644 index 0000000000000000000000000000000000000000..3646662877ac24724d2fd80e52c9c6704424e6df --- /dev/null +++ b/app/components/entityEdit.js @@ -0,0 +1,60 @@ +import React, { Component } from 'react' +import { View, Text } from 'react-native'; +import EntityEditScreen from './entityEditScreen'; + +import U, { subscriptionTracker } from '../utils/utils'; +import styles from '../assets/styles'; + +export default class EntityEdit extends Component { + constructor(props) { + super(props); + this.boundState = this.mapState.bind(this); + this.tracker = subscriptionTracker(); + } + + componentDidMount() { + this.store = this.props.stores[this.props.route.entityName]; + this.actions = this.props.actions[this.props.route.entityName]; + + this.tracker.addSub(U.mergeToSingleObject([ + this.store.edit.map(v => obj => Object.assign(obj, {map: v.get('entity'), validation: v.get('validation')}) ), + this.store.children.map(v => ({ key: 'children', value: v})) + ]), this.boundState); + } + + componentWillUnmount() { + this.tracker.cleanUp(); + } + + mapState(state) { + this.setState(state); + } + + getEntity() { + return this.state && this.state.map; + } + + render() { + if (this.state) { + const { route, entities, actions} = this.props; + const entityName = route.entityName; + const entityLink = { + entityMap: this.state.map, + editHandler: actions[entityName].editField.handlerKV, + validation: this.state.validation + }; + + return (); + } else { + return (Loading Error); + } + } +} + diff --git a/app/components/entityEditScreen.js b/app/components/entityEditScreen.js new file mode 100644 index 0000000000000000000000000000000000000000..eb2d1044aed6dfa2401b663c6577fed32f40ca90 --- /dev/null +++ b/app/components/entityEditScreen.js @@ -0,0 +1,79 @@ +import React, { Component } from 'react' +import { View, Text, ScrollView, TouchableOpacity } from 'react-native'; +import { Avatar, Card, Icon } from 'react-native-material-design'; +import AddChildrenButton from './addChildrenButton'; +import Gallery from './formEdit/gallery'; +import styles from '../assets/styles'; +import { JsonText, KeyText } from '../utils/utils'; + +export default class EntityEditScreen extends Component { + mapChildEntities(f) { + if (!this.props || !this.props.childEntities || !this.props.childEntities.toArray) { + return; + } + const array = this.props.childEntities.toArray(); + if (array) { + return array.map(f); + } + } + + row(item) { + const {entityActions, store, routes } = this.props; + + const route = routes[item.type]; + const actions = this.props.actions[item.type]; + return ( + + + + + + { route.rowTemplate(item) } + { route.subRowTemplate(item) } + + + + + + ); + } + + render() { + const {entityLink, entityActions, store, routes } = this.props; + const entityMap = entityLink.entityMap; + const newObject = !entityMap.get('_rev'); + + //Hide the gallery and the children list when creating a new object. + const galleryAndChildrenIfNotNew = (newObject, entityLink) => { + if (newObject) { + return; + } + return ( + + {this.mapChildEntities(this.row.bind(this))} + + + + ); + }; + + const addNewIfNotNew = (newObject) => { + if (newObject) { + return; + } + return (); + } + + return ( + + + + + + + { galleryAndChildrenIfNotNew(newObject, entityLink) } + + { addNewIfNotNew(newObject) } + ); + } +} diff --git a/app/components/formEdit/allComponents.js b/app/components/formEdit/allComponents.js new file mode 100644 index 0000000000000000000000000000000000000000..525fa816e66e11f26b18010e78dde6ee8b914876 --- /dev/null +++ b/app/components/formEdit/allComponents.js @@ -0,0 +1,12 @@ +import Checkbox from './checkBox'; +import DatePick from './datePick'; +import DropDown from './dropDown'; +import Gallery from './gallery'; +import GeoLocator from './geoLocator'; +import NumberEdit from './numberEdit'; +import PhoneNumberEdit from './phoneNumberEdit'; +import RadioButtons from './radioButtons'; +import TextBox from './textBox'; +import TextEdit from './textEdit'; + +export {Checkbox, DatePick, DropDown, Gallery, GeoLocator, NumberEdit, PhoneNumberEdit, RadioButtons, TextBox, TextEdit }; \ No newline at end of file diff --git a/app/components/formEdit/checkBox.js b/app/components/formEdit/checkBox.js new file mode 100644 index 0000000000000000000000000000000000000000..9f1215e59d1541814f25abcad30b3d2667f2b718 --- /dev/null +++ b/app/components/formEdit/checkBox.js @@ -0,0 +1,20 @@ +import React, { Component } from 'react' +import { View, Text } from 'react-native'; +import { CheckboxGroup } from 'react-native-material-design'; + +import styles from '../../assets/styles'; + +export default class Checkbox extends Component { + render() { + const { entityLink, fieldName, label, items } = this.props; + return ( + + {label} { entityLink.validation.getMessage(fieldName)} + + ); + } +} diff --git a/app/components/formEdit/datePick.js b/app/components/formEdit/datePick.js new file mode 100644 index 0000000000000000000000000000000000000000..bba4db8138ff344250ef86ba0e588edb9a923ac4 --- /dev/null +++ b/app/components/formEdit/datePick.js @@ -0,0 +1,30 @@ +import React, { Component } from 'react' +import { View, Text } from 'react-native'; + +import DatePicker from 'react-native-datepicker'; +import styles from '../../assets/styles'; + +export default class DatePick extends Component { + + render() { + const {entityLink, fieldName, label} = this.props; + return ( + + {label} + + ); + } +} +DatePick.propTypes = { + fieldName: React.PropTypes.string.isRequired +} diff --git a/app/components/formEdit/dropDown.js b/app/components/formEdit/dropDown.js new file mode 100644 index 0000000000000000000000000000000000000000..4d5ade3b2b66b74f20d668a520e073217b1ff17a --- /dev/null +++ b/app/components/formEdit/dropDown.js @@ -0,0 +1,20 @@ +import React, { Component } from 'react' +import { View, Text, Picker } from 'react-native'; + +import styles from '../../assets/styles'; + +export default class Dropdown extends Component { + render() { + const { entityLink, fieldName, validation, label, children} = this.props; + return ( + + {label} { entityLink.validation.getMessage(fieldName)} + + + ); + } +} diff --git a/app/components/formEdit/gallery.js b/app/components/formEdit/gallery.js new file mode 100644 index 0000000000000000000000000000000000000000..0d316344d70e1a3a51b3dd5f52ea4952c2c4fca3 --- /dev/null +++ b/app/components/formEdit/gallery.js @@ -0,0 +1,145 @@ +import React, { Component, Dimensions } from 'react' +import { View, Text, TouchableOpacity, Image, StyleSheet } from 'react-native'; +import ImagePicker from 'react-native-image-picker'; +import { Card, Avatar } from 'react-native-material-design'; +import uuid from 'node-uuid'; +import styles from '../../assets/styles'; + +const galleryStyles = StyleSheet.create({ + galleryContainer: { + flex: 1, + alignItems: 'stretch', + flexDirection: 'column' + }, + headerRow: { + marginTop: 20, + flex: 1, + flexDirection: 'row', + justifyContent: 'space-between', + alignItems: 'flex-end', + }, + title: { + marginBottom: 5, + fontSize: 19, + color: '#000000', + fontWeight: '300' + }, + actionArea: { + alignSelf: 'flex-end', + alignItems: 'flex-end', + flexDirection: 'column', + width: 100, + marginBottom: 5, + }, + imageContainer: { + flexDirection: 'row', + flexWrap: 'wrap', + justifyContent: 'space-between', + }, + imageBox: { + flex: 1, + overflow: 'visible', + width: 110, + }, + image: { + width: 110, + height: 110, + marginBottom: 15, + }, + noImages: { + height: 40, + width: 2, + } +}); + +export default class Gallery extends Component { + constructor(props) { + super(props); + this.state = { + images: [] + } + } + + getImage() { + const that = this; + const options = { + title: 'Take Photo', + cancelButtonTitle: 'Cancel', + takePhotoButtonTitle: 'Take Photo...', + chooseFromLibraryButtonTitle: 'Choose from Library...', + customButtons: { + }, + cameraType: 'back', + mediaType: 'photo', + videoQuality: 'low', + durationLimit: 60, + maxWidth: 800, + maxHeight: 800, + aspectX: 1, + aspectY: 1, + quality: 0.9, + angle: 0, + allowsEditing: false, + storageOptions: { + skipBackup: true, + path: 'images' + } + }; + + ImagePicker && ImagePicker.showImagePicker(options, (response) => { + if (response.error) { + console.log('ImagePicker Error: ', response.error); + } else { + const source = {uri: response.uri, isStatic: true}; + + const { fieldName, entityActions, entityLink, store } = this.props; + const name = fieldName + '::' + uuid.v4(); + const newMap = entityLink.entityMap.update(fieldName, arr => [name].concat(arr || [])); + + entityActions.saveAttachment.handler({ + obj: newMap, + name: name, + uri: response.uri, + type: 'image/jpg' + }); + } + }); + } + + mapImages(f, noItems) { + const { fieldName, entityActions, entityLink, store } = this.props; + const entityMap = entityLink.entityMap; + if (!(entityMap && entityMap.get('_attachments'))) { + return noItems; + } + return Object.entries(entityMap.get('_attachments') || []) + .filter(arr => arr[0].startsWith(fieldName)) + .map((e, i) => f({ name: e[0], uri: store.getAttachmentUri(entityMap.get('_id'), e[0], entityMap.get('_rev')), raw: e }, i)) + } + + render() { + return ( + + + Images + + + + + + + + + + { this.mapImages((image, i) => ( + + + + ), ) } + + + + + ); + } +} diff --git a/app/components/formEdit/geoLocator.js b/app/components/formEdit/geoLocator.js new file mode 100644 index 0000000000000000000000000000000000000000..3f4837b8434f2af0a3fd275fda3c699582e7ed8f --- /dev/null +++ b/app/components/formEdit/geoLocator.js @@ -0,0 +1,49 @@ +import React, { Component } from 'react' +import { StyleSheet, Text, View, TouchableOpacity } from 'react-native'; +import { Avatar} from 'react-native-material-design'; +import _ from 'lodash'; +import styles from '../../assets/styles'; + +export default class GeoLocator extends Component { + constructor(props) { + super(props); + if (props.entityLink.entityMap && props.fieldName) { + this.state = props.entityLink.entityMap.get(props.fieldName); + } + this.state || (this.state = {latitude: 0, longitude: 0}); + } + + + lookupLocation() { + navigator.geolocation.getCurrentPosition( + + (position) => { + + var crd = position.coords; + var locationCoords = { + 'latitude' : crd.latitude, + 'longitude' : crd.longitude + }; + this.props.entityLink.editHandler(this.props.fieldName)(locationCoords); + this.setState(locationCoords); + }, + (error) => alert(error), + {enableHighAccuracy: true, timeout: 20000, maximumAge: 1000} + ); + } + + render() { + const {label} = this.props; + return ( + + {label} + + + + + { Math.round( this.state.latitude * 100) / 100}, {Math.round(this.state.longitude * 100) / 100} + + + ); + } +} diff --git a/app/components/formEdit/numberEdit.js b/app/components/formEdit/numberEdit.js new file mode 100644 index 0000000000000000000000000000000000000000..07038ca212a2defcfaa9288938643e4c38da8765 --- /dev/null +++ b/app/components/formEdit/numberEdit.js @@ -0,0 +1,20 @@ +import React, { Component } from 'react' +import { View, Text, TextInput } from 'react-native'; +import styles from '../../assets/styles'; + +export default class NumberEdit extends Component { + render() { + const { maxLength, entityLink, fieldName, elementStyle, numberGroup, label, labelStyle } = this.props; + return ( + + + {label} { entityLink.validation.getMessage(fieldName)} + ); + } +} + diff --git a/app/components/formEdit/phoneNumberEdit.js b/app/components/formEdit/phoneNumberEdit.js new file mode 100644 index 0000000000000000000000000000000000000000..f9cebdffa56594374b3350cc4908c0ad4551a9b9 --- /dev/null +++ b/app/components/formEdit/phoneNumberEdit.js @@ -0,0 +1,25 @@ +import React, { Component } from 'react' +import { View, Text, TextInput } from 'react-native'; +import styles from '../../assets/styles'; + +export default class PhoneNumberEdit extends Component { + render() { + const { maxLength, entityLink, fieldName, elementStyle, numberGroup, label, labelStyle } = this.props; + return ( + + {label} {entityLink.validation.getMessage(fieldName)} + + ); + } +} +PhoneNumberEdit.propTypes = { + elementStyle: Text.propTypes.style, + labelStyle: Text.propTypes.style, + numberGroup: Text.propTypes.style, + fieldName: React.PropTypes.string.isRequired +} diff --git a/app/components/formEdit/radioButtons.js b/app/components/formEdit/radioButtons.js new file mode 100644 index 0000000000000000000000000000000000000000..fadfccf7bb36c2532f0670849de0ccce0606a33c --- /dev/null +++ b/app/components/formEdit/radioButtons.js @@ -0,0 +1,20 @@ +import React, { Component } from 'react' +import { View, Text } from 'react-native'; +import { RadioButtonGroup } from 'react-native-material-design'; +import styles from '../../assets/styles'; + +export default class RadioButtons extends Component { + render() { + const { entityLink, fieldName, label, items } = this.props; + return ( + + {label} + { entityLink.validation.getMessage(fieldName)} + + ); + } +} diff --git a/app/components/formEdit/textBox.js b/app/components/formEdit/textBox.js new file mode 100644 index 0000000000000000000000000000000000000000..c1ba1f69635bf54a7ab2920a170af86c8e248409 --- /dev/null +++ b/app/components/formEdit/textBox.js @@ -0,0 +1,22 @@ +import React, { Component } from 'react' +import { View, Text, TextInput } from 'react-native'; + +import styles from '../../assets/styles'; + +export default class TextBox extends Component { + render() { + const { entityLink, fieldName, elementStyle, numberGroup, label, labelStyle } = this.props; + return ( + + {label} {entityLink.validation.getMessage(fieldName)} + + ); + } +} +TextBox.propTypes = { + fieldName: React.PropTypes.string, +}; diff --git a/app/components/formEdit/textEdit.js b/app/components/formEdit/textEdit.js new file mode 100644 index 0000000000000000000000000000000000000000..b133cb230b769d1d77062a09d286a8fe9d670ca6 --- /dev/null +++ b/app/components/formEdit/textEdit.js @@ -0,0 +1,24 @@ +import React, { Component } from 'react' +import { View, Text, TextInput } from 'react-native'; + +import styles from '../../assets/styles'; + +export default class TextEdit extends Component { + render() { + const { entityLink, fieldNames, elementStyle, numberGroup, label, labelStyle, multiline } = this.props; + return ( + + { fieldNames.map((fieldName, index) => {entityLink.validation.getMessage(fieldName)}) } + {label} + { fieldNames.map((fieldName, index) => ())} + ); + } +} +TextEdit.propTypes = { + fieldNames: React.PropTypes.arrayOf(React.PropTypes.string) +}; diff --git a/app/entities.js b/app/entities.js new file mode 100644 index 0000000000000000000000000000000000000000..abc9ce9f6450cbc3e2b5b1dbc9533350ec6b4006 --- /dev/null +++ b/app/entities.js @@ -0,0 +1,34 @@ +const requiredValidator = () => (fieldData, value) => ( value ? null : { + fieldName: fieldData.id, + message: `${fieldData.label} is required.`, + rule: fieldData.id + '_required' +}); + +const minLengthValidator = (minLength) => (fieldData, value) => ( (value && value.length > minLength) ? null : { + fieldName: fieldData.id, + message: `${fieldData.label} must be at least ${minLength} characters long.`, + rule: fieldData.id + '_min_length' +}); + +const entities = { + client: { children: ['building'], + fields: { + name: { id: 'name', label: 'Name', validators: [ requiredValidator(), minLengthValidator(4) ]} + } + }, + building: {children: ['boiler', 'room', 'controls', 'dhw', 'sensor', 'radiator', 'baseboards', 'retrofits']}, + room: {children: ['window']}, + boiler: {children: []}, + controls: {children: []}, + dhw: {children: []}, + sensor: {children: []}, + window:{children: []}, + radiator:{children: []}, + baseboards: {children: []}, + retrofits: {children: []} }; + +export default { + entityActions: ['newObj', 'editObj', 'saveEntity', 'destroy', 'editField', 'loadChildren', 'saveAttachment', 'destroyAttachment'], + entities: entities, + entityList: Object.keys(entities) +}; diff --git a/app/routes.js b/app/routes.js new file mode 100644 index 0000000000000000000000000000000000000000..4d092980ecf0911eead1b545a4c1b511247dd96e --- /dev/null +++ b/app/routes.js @@ -0,0 +1,46 @@ +import entityList from './scenes/entityList'; + +function getEntityRoute (entityName, title, name, icon, childComponent, rowTemplate = x=>x.name, rowDetailTemplate = x=>'', initialRoute = false) { + return { + initialRoute: initialRoute, + + title: title, + single: name, + newLabel: 'New ' + name, + component: entityList, + dataSource: entityName + '.all', + entityName: entityName, + listIcon: icon, + rowTemplate: rowTemplate, + subRowTemplate: rowDetailTemplate, + children: { + new: { + title: 'New ' + name, + component: childComponent, + entityName: entityName, + actions: [ { icon: 'save', action: 'saveEntity', response: 'entitySaved'}] + }, + edit: { + title: 'Edit ' + name, + component: childComponent, + entityName: entityName, + actions: [ { icon: 'save', action: 'saveEntity', response: 'entitySaved'}] + } + } + }; +} + + +export default { + baseboards: getEntityRoute('baseboards', 'Baseboards', 'Baseboards', 'call-to-action', require('./scenes/baseboardsEdit').default), + boiler: getEntityRoute('boiler', 'Boilers', 'Boiler', 'build', require('./scenes/boilerEdit').default, x => x.location, x => x.name), + building: getEntityRoute('building', 'Buildings', 'Building', 'account-balance', require('./scenes/buildingEdit').default, x => x.name, x=>`${x.address1 || ''}`, false), + client: getEntityRoute('client', 'Clients', 'Client', 'supervisor-account', require('./scenes/clientEdit').default, x => x.name, x=>`${x.contactFirstName || ''} ${x.contactLastName || ''}`, true), + controls: getEntityRoute('controls', 'Controls', 'Controlls', 'power-settings-new', require('./scenes/controlsEdit').default), + dhw: getEntityRoute('dhw', 'Water Heaters', 'Water Heater', 'home', require('./scenes/dhwEdit').default), + radiator: getEntityRoute('radiator', 'Radiators', 'Radiator', 'view-week', require('./scenes/radiatorEdit').default), + retrofits: getEntityRoute('retrofits', 'Retrofits', 'Retrofit', 'update', require('./scenes/retrofitsEdit').default), + room: getEntityRoute('room', 'Rooms', 'Room', 'view-quilt', require('./scenes/roomEdit').default), + sensor: getEntityRoute('sensor', 'Sensors', 'Sensor', 'timeline', require('./scenes/sensorEdit').default), + window: getEntityRoute('window', 'Windows', 'Window', 'border-all', require('./scenes/windowEdit').default), +} \ No newline at end of file diff --git a/app/scenes/baseboardsEdit.js b/app/scenes/baseboardsEdit.js new file mode 100644 index 0000000000000000000000000000000000000000..59aded243a112d91eeb7ae7dca60103134b0b097 --- /dev/null +++ b/app/scenes/baseboardsEdit.js @@ -0,0 +1,22 @@ +import React, { Component } from 'react' +import { Text, View } from 'react-native'; +import EntityEdit from '../components/entityEdit'; +import { Checkbox, DatePick, DropDown, GeoLocator, NumberEdit, PhoneNumberEdit, RadioButtons, TextBox, TextEdit } from '../components/formEdit/allComponents'; + +import styles from '../assets/styles'; + +class BaseboardsEditInfo extends Component { + render() { + const {entityLink} = this.props + return ( + + + ); + } +} + +export default class BaseboardsEdit extends Component { + render() { + return (); + } +} diff --git a/app/scenes/boilerEdit.js b/app/scenes/boilerEdit.js new file mode 100644 index 0000000000000000000000000000000000000000..4a463a83f75bc55ac95e67c54cab947c78754045 --- /dev/null +++ b/app/scenes/boilerEdit.js @@ -0,0 +1,22 @@ +import React, { Component } from 'react' +import { Text, View } from 'react-native'; +import EntityEdit from '../components/entityEdit'; +import { Checkbox, DatePick, DropDown, GeoLocator, NumberEdit, PhoneNumberEdit, RadioButtons, TextBox, TextEdit } from '../components/formEdit/allComponents'; + +import styles from '../assets/styles'; + +class BoilerEditInfo extends Component { + render() { + const {entityLink} = this.props + return ( + + + ); + } +} + +export default class BoilerEdit extends Component { + render() { + return (); + } +} diff --git a/app/scenes/buildingEdit.js b/app/scenes/buildingEdit.js new file mode 100644 index 0000000000000000000000000000000000000000..668760430fd5420ba8cb72768ce3b3f3eab789d9 --- /dev/null +++ b/app/scenes/buildingEdit.js @@ -0,0 +1,100 @@ +import React, { Component } from 'react' +import { Text, View, ScrollView, TouchableOpacity, Picker } from 'react-native'; +import EntityEdit from '../components/entityEdit'; +import { Checkbox, DatePick, DropDown, GeoLocator, NumberEdit, PhoneNumberEdit, RadioButtons, TextBox, TextEdit } from '../components/formEdit/allComponents'; +import DatePicker from 'react-native-datepicker'; + +import U, {JsonText, KeyText} from '../utils/utils'; +import styles from '../assets/styles'; + +const Item = Picker.Item; + +class BuildingEditInfo extends Component { + render() { + const {entityLink} = this.props + return ( + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + # of Occupied Residential Units + + + + + + + + + + + + + ); + } +} + +export default class BuildingEdit extends Component { + render() { + return (); + } +} diff --git a/app/scenes/clientEdit.js b/app/scenes/clientEdit.js new file mode 100644 index 0000000000000000000000000000000000000000..68028405d9d4fed16211ce22b32f6257aaf57c34 --- /dev/null +++ b/app/scenes/clientEdit.js @@ -0,0 +1,25 @@ +import React, { Component } from 'react' +import { Text, View } from 'react-native'; +import EntityEdit from '../components/entityEdit'; +import { Checkbox, DatePick, DropDown, GeoLocator, NumberEdit, PhoneNumberEdit, RadioButtons, TextBox, TextEdit } from '../components/formEdit/allComponents'; +import U, {JsonText, KeyText} from '../utils/utils'; + +import styles from '../assets/styles'; + +class ClientEditInfo extends Component { + render() { + const {entityLink, store, stores, entityActions } = this.props + return ( + + + + + ); + } +} + +export default class ClientEdit extends Component { + render() { + return (); + } +} diff --git a/app/scenes/controlsEdit.js b/app/scenes/controlsEdit.js new file mode 100644 index 0000000000000000000000000000000000000000..8165f5fcc2294a65751d086827e2e6dbe2a0839a --- /dev/null +++ b/app/scenes/controlsEdit.js @@ -0,0 +1,22 @@ +import React, { Component } from 'react' +import { Text, View } from 'react-native'; +import EntityEdit from '../components/entityEdit'; +import { Checkbox, DatePick, DropDown, GeoLocator, NumberEdit, PhoneNumberEdit, RadioButtons, TextBox, TextEdit } from '../components/formEdit/allComponents'; + +import styles from '../assets/styles'; + +class ControlEditInfo extends Component { + render() { + const {entityLink} = this.props + return ( + + + ); + } +} + +export default class ControlEdit extends Component { + render() { + return (); + } +} diff --git a/app/scenes/dhwEdit.js b/app/scenes/dhwEdit.js new file mode 100644 index 0000000000000000000000000000000000000000..a34aa02d2d8255d967f095dddf56f0662107db79 --- /dev/null +++ b/app/scenes/dhwEdit.js @@ -0,0 +1,22 @@ +import React, { Component } from 'react' +import { Text, View } from 'react-native'; +import EntityEdit from '../components/entityEdit'; +import { Checkbox, DatePick, DropDown, GeoLocator, NumberEdit, PhoneNumberEdit, RadioButtons, TextBox, TextEdit } from '../components/formEdit/allComponents'; + +import styles from '../assets/styles'; + +class DhwEditInfo extends Component { + render() { + const {entityLink} = this.props + return ( + + + ); + } +} + +export default class DhwEdit extends Component { + render() { + return (); + } +} diff --git a/app/scenes/entityList.js b/app/scenes/entityList.js new file mode 100644 index 0000000000000000000000000000000000000000..61cebb2b4bb4b721b2102e47acd1472bb183c496 --- /dev/null +++ b/app/scenes/entityList.js @@ -0,0 +1,83 @@ +import React, { Component } from 'react' +import { Text, View, StyleSheet, ScrollView, TextInput, TouchableOpacity, Alert} from 'react-native'; +import { Divider, Avatar, Card, Subheader, Icon as MdIcon } from 'react-native-material-design'; +import Icon from 'react-native-vector-icons/MaterialIcons'; +import ActionButton from 'react-native-action-button'; +import _ from 'lodash'; +import U, { subscriptionTracker as tracker } from '../utils/utils'; +import styles, { ActionButtonStyle } from '../assets/styles'; + +export default class EntityList extends Component { + constructor(props) { + super(props); + + this.tracker = tracker(); + } + + componentDidMount() { + if (this.props.route.dataSource) { + this.tracker.addSub(_.get(this.props.stores, this.props.route.dataSource ), this.handleState.bind(this)); + } + } + + componentWillUnmount() { + this.tracker.cleanUp(); + } + + handleState(value) { + this.setState({ + value: value + }) + } + + mapState(f, noResults) { + if (!this.state || !this.state.value) { + return noResults(this); + } + const listJs = Object.values(this.state.value.toJS()); + if (listJs.length === 0) { + return noResults(this); + } + return listJs.map(f); + } + + row(item, index) { + const { actions, route} = this.props; + return ( + + + + + + + { route.rowTemplate(item) } + { route.subRowTemplate(item) } + + + + + + + ); + } + + noRows() { + return (No { this.props && this.props.route.entityName } Records Found. ); + } + + render() { + const { actions, route} = this.props; + return ( + + + {this.mapState(this.row.bind(this), this.noRows.bind(this))} + + + + + + + + ); + } +} \ No newline at end of file diff --git a/app/scenes/radiatorEdit.js b/app/scenes/radiatorEdit.js new file mode 100644 index 0000000000000000000000000000000000000000..abf2183bf42c6be5c030ec4bccf7969a1c2b5fef --- /dev/null +++ b/app/scenes/radiatorEdit.js @@ -0,0 +1,23 @@ +import React, { Component } from 'react' +import { Text, View } from 'react-native'; +import EntityEdit from '../components/entityEdit'; +import { Checkbox, DatePick, DropDown, GeoLocator, NumberEdit, PhoneNumberEdit, RadioButtons, TextBox, TextEdit } from '../components/formEdit/allComponents'; + +import styles from '../assets/styles'; + + +class RadiatorEditInfo extends Component { + render() { + const {entityLink} = this.props + return ( + + + ); + } +} + +export default class RadiatorEdit extends Component { + render() { + return (); + } +} diff --git a/app/scenes/retrofitsEdit.js b/app/scenes/retrofitsEdit.js new file mode 100644 index 0000000000000000000000000000000000000000..db085d5d67e16439442dca20a342feaf4aef1a02 --- /dev/null +++ b/app/scenes/retrofitsEdit.js @@ -0,0 +1,23 @@ +import React, { Component } from 'react' +import { Text, View } from 'react-native'; +import EntityEdit from '../components/entityEdit'; +import { Checkbox, DatePick, DropDown, GeoLocator, NumberEdit, PhoneNumberEdit, RadioButtons, TextBox, TextEdit } from '../components/formEdit/allComponents'; + +import styles from '../assets/styles'; + + +class RetrofitEditInfo extends Component { + render() { + const {entityLink} = this.props + return ( + + + ); + } +} + +export default class RetrofitEdit extends Component { + render() { + return (); + } +} diff --git a/app/scenes/roomEdit.js b/app/scenes/roomEdit.js new file mode 100644 index 0000000000000000000000000000000000000000..deeed6e91c76debff95a6a04da5e1e01a46e6cd9 --- /dev/null +++ b/app/scenes/roomEdit.js @@ -0,0 +1,23 @@ +import React, { Component } from 'react' +import { Text, View } from 'react-native'; +import EntityEdit from '../components/entityEdit'; +import { Checkbox, DatePick, DropDown, GeoLocator, NumberEdit, PhoneNumberEdit, RadioButtons, TextBox, TextEdit } from '../components/formEdit/allComponents'; + +import styles from '../assets/styles'; + + +class RoomEditInfo extends Component { + render() { + const {entityLink} = this.props + return ( + + + ); + } +} + +export default class RoomEdit extends Component { + render() { + return (); + } +} diff --git a/app/scenes/sensorEdit.js b/app/scenes/sensorEdit.js new file mode 100644 index 0000000000000000000000000000000000000000..822490b8eb24e801f71eda923aed5dce198467d6 --- /dev/null +++ b/app/scenes/sensorEdit.js @@ -0,0 +1,23 @@ +import React, { Component } from 'react' +import { Text, View } from 'react-native'; +import EntityEdit from '../components/entityEdit'; +import { Checkbox, DatePick, DropDown, GeoLocator, NumberEdit, PhoneNumberEdit, RadioButtons, TextBox, TextEdit } from '../components/formEdit/allComponents'; + +import styles from '../assets/styles'; + + +class SensorEditInfo extends Component { + render() { + const {entityLink} = this.props + return ( + + + ); + } +} + +export default class SensorEdit extends Component { + render() { + return (); + } +} diff --git a/app/scenes/windowEdit.js b/app/scenes/windowEdit.js new file mode 100644 index 0000000000000000000000000000000000000000..0dcefb9db201201b22773a0b413e2580ce6bdf5e --- /dev/null +++ b/app/scenes/windowEdit.js @@ -0,0 +1,22 @@ +import React, { Component } from 'react' +import { Text, View } from 'react-native'; +import EntityEdit from '../components/entityEdit'; +import { Checkbox, DatePick, DropDown, GeoLocator, NumberEdit, PhoneNumberEdit, RadioButtons, TextBox, TextEdit } from '../components/formEdit/allComponents'; + +import styles from '../assets/styles'; + +class WindowEditInfo extends Component { + render() { + const {entityLink} = this.props + return ( + + + ); + } +} + +export default class WindowEdit extends Component { + render() { + return (); + } +} diff --git a/app/stores/allStores.js b/app/stores/allStores.js new file mode 100644 index 0000000000000000000000000000000000000000..4e9faeb8ecf0114e2669d690a39ca64c7018d710 --- /dev/null +++ b/app/stores/allStores.js @@ -0,0 +1,43 @@ +import getEntityStore from './entityStore'; +import getNavStore from './navStore'; +import getDataStore$ from './dataStore'; +import Kefir from 'kefir'; +import U from '../utils/utils'; + +export default (actions, routes, entities) => { + const nav = getNavStore(actions.nav, routes); + const data = getDataStore$(actions.data, 5984, 'admin', 'password', 'http://localhost:5984/', 'blocpower'); + const load$ = data.map(db => { + //This action is used for debugging + actions.data.deleteDatabase.raw.flatMap(() => db.deleteDatabase()).onValue(U.popJson); + + // db.getDesignDocument('main').flatMap(() => db.queryView('main', 'by_type', {include_docs: true, key: 'client'})).log(); + + const store = { + nav: nav, + db: db, + changes: db.changes$, + //This stream contains a actions that can be applied to a map to keep the map in sync to the data in the datbase + //The original object is included so it can be use to apply filters. + change_actions: db.changes$ + .flatten(e => e.results) + .map(r => Object.assign(r, { action: r.deleted ? + (m => m.delete(r.id)) : + (m => m.set(r.id, r.doc))} )), + } + entities.entityList.forEach(entity => { store[entity] = getEntityStore(actions[entity], store, entity, entities.entities[entity]); } ); + + store.changes.onError(x => U.popMsg('Unexpected Error', 'Change Error')); + //store.changes.onValue(U.popJsonMap('Database Change')); + // // store.change_actions.log('change-actions'); + + + store.replication = db.setupReplication('', '', 'http://couchbase1.sbdev.io:4984', 'blocpoweraudit' + (__DEV__ ? 'dev' : '')) + // store.replication.onError(x => U.popMsg('Unexpected Error', 'Replication Error')); + store.replication.onError(U.popJsonMap('Replication Error')); + + return store; + }); + + return load$; +} diff --git a/app/stores/dataStore.js b/app/stores/dataStore.js new file mode 100644 index 0000000000000000000000000000000000000000..cfa10f9927b22aad44e3a2df466511e211bc3b5d --- /dev/null +++ b/app/stores/dataStore.js @@ -0,0 +1,10 @@ +import Kefir from 'kefir'; +import U from '../utils/utils'; +import kc from '../utils/kefirCouchbase'; +import mainDesignDoc from './mainDesignDoc'; + +export default (actions, port, username, password, url, bucketName) => { + return kc.getListener$(port, username, password) + .flatMap(listener => listener.getDatabase(url, bucketName, { name: 'main', doc: mainDesignDoc})) + .map(data => { data.cb.startListen(data.info); return data.cb; }); +} \ No newline at end of file diff --git a/app/stores/entityStore.js b/app/stores/entityStore.js new file mode 100644 index 0000000000000000000000000000000000000000..21da91dee5957351c3504eaffb29b30aebf2bf21 --- /dev/null +++ b/app/stores/entityStore.js @@ -0,0 +1,115 @@ +import Immutable from 'immutable'; +import Kefir from 'kefir'; +import uuid from 'node-uuid'; +import U from '../utils/utils'; +import _ from 'lodash'; + +const getEmptyValidation = () => ({ + isValid() { return true; }, + getMessage() { return ''} +}); + +const getValidation = (entity) => (b) => { + if (!entity.fields) return getEmptyValidation(); + + const validation = {}; + for (let field of Object.values(entity.fields)) { + for (let validator of field.validators) { + let result = validator(field, b.get(field.id)); + if (result) { + validation[result.rule] = result; + } + } + } + return { + data: validation, + isValid() { return _.isEmpty(this.data)}, + getMessage(fieldName) { + for(let validation of Object.values(this.data)) { + if (validation.fieldName == fieldName) { + return validation.message; + } + } + return ''; + } + }; +} + +function getEdit(actions, type, changes, entityValidator) { + const edit = Immutable.Map({}); + const editStream$ = Kefir.merge([ + actions.newObj.raw + .map(initialObject => Immutable.Map(initialObject || {})) + .map(initialMap => initialMap.set('_id', uuid.v4()).set('type', type)) + .map((initialMap) => (obj) => obj.set('entity', initialMap).set('validation', getEmptyValidation())), + actions.editObj.raw.map((current) => (obj) => obj.set('entity', Immutable.Map(current)).set('validation', getEmptyValidation())), + actions.editField.raw.map((fieldData) => (obj) => obj.setIn(['entity', fieldData.key], fieldData.value)), + changes.filter(obj => (obj && obj.doc && obj.doc.type) == type).map(change => (obj) => (obj.getIn(['entity', '_id']) != change.id) ? obj : obj.set('entity', Immutable.Map(change.doc))), + actions.saveEntity.raw.map(() => (obj) => obj.set('validation', entityValidator(obj.get('entity')))) + ]); + + return editStream$.scan((current, change) => change(current), edit); +} + +module.exports = (actions, store, type, entity) => { + const kd = store.db; + const entityValidator = getValidation(entity); + + const edit$ = getEdit(actions, type, store.change_actions, entityValidator); + const editSaved$ = edit$ + .sampledBy(actions.saveEntity.raw) + .map(b => b.set('validation', entityValidator(b.get('entity')))) + .filter(b => b.get('validation').isValid()) + .map(b => b.get('entity').toJS()) + .flatMap(v => (v._rev) ? kd.updateDocument(v, v._id, v._rev) : kd.createDocument(v)); + + const deleteSaved$ = actions.destroy.raw + .flatMap(b => kd.deleteDocument(b._id, b._rev)); + + const initialLoad$ = kd.queryView('main', 'by_type', {include_docs: true, key: type}) + .map(list => list.rows.reduce((obj, field) => obj.set(field.id, field.doc), Immutable.OrderedMap())); + + const listState$ = U.mergeToOrderedMap([ + store.change_actions + .filter(e => (e.deleted || e.doc.type === type) && e.action) + .map(e => e.action), + initialLoad$.map(entity => (map) => map.merge(entity)) + ]); + + //Load children into a stream given an object with an _id field, an immutable map with an _id key, or just the id. + //Convert the stream to a property to makes sure the last result is available regardless of timing of connecting the onValue handler + const parentId$ = actions.loadChildren.raw + .map(obj => (!obj) ? '' : obj._id || (obj.get && obj.get('_id')) || obj); + const childrenStart$ = parentId$ + .flatMap(id => kd.queryView('main', 'by_parent_id_type', {include_docs: true, startkey: [id, 'a'], endkey:[id, 'zzzzzzzzzzzzzzz']})) + .map(list => list.rows.reduce((obj, field) => obj.set(field.id, field.doc), Immutable.OrderedMap())); + + const childrenState$ = U.mergeToOrderedMap([ + Kefir.combine([store.change_actions, parentId$]) + .filter(c => (c[0].deleted || c[0].doc.parent_id === c[1]) && c[0].action) + .map(c => c[0].action), + childrenStart$.map(entity => (map) => entity) + ]); + + const attachmentSaved$ = actions.saveAttachment.raw + .flatMap(a => kd.saveAttachment(a.obj.get('_id'), a.obj.get('_rev'), a.name, a.uri, a.type)); + + const errors$ = Kefir.merge([listState$, edit$, editSaved$, deleteSaved$, childrenState$, attachmentSaved$]).ignoreValues(); + + const streams = { + all: listState$, + edit: edit$, + entitySaved: editSaved$, + children: childrenState$, + /** A stream of all the errors from this store used to pull results from the streams and to drive user alerts when there is an issue. */ + errors: errors$, + /** A local api call to get the uri for an attachment. */ + getAttachmentUri: kd.getAttachmentUri.bind(kd) + } + + // for( let [key, value] of Object.entries(streams)) { + // value.log( `${type}-${key}`); + // } + + return streams; +}; diff --git a/app/stores/mainDesignDoc.js b/app/stores/mainDesignDoc.js new file mode 100644 index 0000000000000000000000000000000000000000..18ea0d023536a3d35c926d6feefd628ef6ea3bf3 --- /dev/null +++ b/app/stores/mainDesignDoc.js @@ -0,0 +1,7 @@ +export default { + views: { + language: 'javascript', + by_type: {map: 'function (doc) { if (doc.type) { emit(doc.type, null); } }'}, + by_parent_id_type: {map: 'function (doc) { if (doc.parent_id && doc.type) { emit([doc.parent_id, doc.type], null); } }'} + } +}; \ No newline at end of file diff --git a/app/stores/navStore.js b/app/stores/navStore.js new file mode 100644 index 0000000000000000000000000000000000000000..03942707ce06a61bdc7d73295dfc723d2f517388 --- /dev/null +++ b/app/stores/navStore.js @@ -0,0 +1,40 @@ +import _ from 'lodash'; +import Kefir from 'kefir'; +import Immutable from 'immutable'; +import U from '../utils/utils'; + +module.exports = (actions, routes) => { + const data = Immutable.List([ + Object.values(routes).find(r => r.initialRoute) + ]); + const stream$ = Kefir.merge([ + actions.push.raw.map( route => (state => state.unshift(_.get(routes, route)))), + actions.pop.raw.map( () => (state => state.shift())), + //This handles the home and back icons in the navigation bar. + actions.homeback.raw.map( () => (state) => state.size == 1 ? state : state.shift()), + ]); + + const state$ = stream$.scan((state, action) => action(state), data); + + const stateButtonSample$ = state$.sampledBy(actions.hardwareback.raw); + //Provide a close event for pressing the hardware back button on the main screens + const close$ = stateButtonSample$.filter(d => d.size == 1); + //Map hardware button presses to pop for non main screens. + actions.pop.raw.plug(stateButtonSample$.filter(d => d.size > 1)); + + + return { + /** This is the current full state of the navigation element. It includes the current screen and all the hidden parent screens. */ + stack: state$, + /** This is the current route object for the current screen. */ + current: state$.map(state => state.get(0)), + /** This is the count of how many routes are on the current stack. */ + depth: state$.map(state => state.size), + /** This is the pop action stream */ + pop: actions.pop, + /** This stream gets an event when the hardware back action is called on the home screen. */ + close: close$, + /** This is the current navigator that is set for the application. */ + navigator: actions.navigator.raw, + }; +} \ No newline at end of file diff --git a/app/utils/kefirCouchbase.js b/app/utils/kefirCouchbase.js new file mode 100644 index 0000000000000000000000000000000000000000..e1115b145e0c9a49089a11de0550bf65830bfee3 --- /dev/null +++ b/app/utils/kefirCouchbase.js @@ -0,0 +1,127 @@ +import Kefir from 'kefir'; +import U from './utils'; +import {manager as Manager, ReactCBLite} from 'react-native-couchbase-lite' + +/** + * This handles the mapping from a standard couchbase lite function to a kefir stream. Couchbase lite will return some errors as objects with an error property. This function maps them to the stream error channel. + */ +const couchbaseStreamDef = (db, actionName, arr) => (emitter) => { + try { + db[actionName](...arr) + .then(out => { + if (!out || out.error) { + emitter.error(Object.assign((out || {}), {src : arr, action: actionName, err: out})) + } else { + emitter.value(out); + } + }) + .catch(e => { emitter.error({action: actionName, src: arr, err: e}) } ); + } catch (e) { + emitter.error({action: actionName, src: arr, err: e}); + } +} + +const couchbaseStreamDefNoError = (db, actionName, arr) => (emitter) => { + try { + db[actionName](...arr) + .then(out => emitter.value(out)) + .catch(e => { emitter.value({action: actionName, src: arr, err: e}) } ); + } catch (e) { + emitter.value({action: actionName, src: arr, err: e}); + } +} + +/** This creates a couchbase lite manager object https://github.com/couchbaselabs/react-native-couchbase-lite#usage and wraps all the promise based methods with couchbase streams to better fit into this application. A raw 'NoError' method is provided for initalization. */ +class KefirCouchbase { + constructor(url, bucketName) { + this.database = new Manager(url, bucketName); + this.url = url; + this.bucketName = bucketName; + const database = this.database; + let that = this; + + ['createDatabase', 'deleteDatabase', 'getAllDatabases', 'createDocument', 'deleteDocument', + 'updateDocument', 'getAllDocuments', 'getDocument', 'getAllDocumentConflicts', 'replicate', 'getChanges', + 'getInfo', 'getDesignDocument', 'createDesignDocument', 'deleteDesignDocument', 'queryView', + 'saveAttachment', 'deleteAttachment', 'latestRevision', 'activeTasks'] + .reduce((pv, cv) => { + pv[cv] = (...arr) => Kefir.stream(couchbaseStreamDef(database, cv, arr)); + pv[cv+'NoError'] = (...arr) => Kefir.stream(couchbaseStreamDefNoError(database, cv, arr)); + return pv; + }, this); + + this.getAttachmentUri = database.getAttachmentUri.bind(database); + + this.changes$ = Kefir.fromEvents(this.database.changesEventEmitter, 'changes'); + this.startListen = (info) => { that.database.listen({since: info.update_seq - 1, feed: 'longpoll', include_docs: true}) }; + this.compact = () => { return Kefir.fromCallback( cb => database.makeRequest("POST", database.databaseUrl + database.databaseName + "/_compact", null, cb)); }; + } + + setupReplication(userId, password, remoteServerUrl , remoteBucketName) { + const remoteDbUrl = `${remoteServerUrl}/${remoteBucketName}`; + const sessionUrl = `${remoteDbUrl}/_session`; + const self = this; + + const settings = { + method: 'POST', + headers: {'Content-Type': 'application/json'}, + body: JSON.stringify({name: userId, password: password}) + }; + + return Kefir.stream(emitter => { + return fetch(sessionUrl, settings) + .then((res) => { + try { + switch (res.status) { + case 200: { + const sessionCookie = res.headers.map['set-cookie'][0]; + + this.database.replicate( + self.bucketName, + {headers: {Cookie: sessionCookie}, url: remoteDbUrl}, + true + ); + + this.database.replicate( + {headers: {Cookie: sessionCookie}, url: remoteDbUrl}, + self.bucketName, + true + ); + emitter.value('replication enabled'); + break; + } + default: { + emitter.error(res); + break; + } + } + } catch (e) { + emitter.error(e); + } + }) + .catch(e => emitter.error(e)) + } + ); + } +} + + +/** + * This is where the couchbase database is setup. The local database manager is initalized, then the database object is created. If the local database hasn't been created, then the database is created and the design document is setup, elsewise the database info is returned. + */ +export default store = { + getListener$(port, username, password) { + return Kefir + .fromCallback(cb => ReactCBLite.init(port, username, password, cb)) + .map(() => ({ + getDatabase(url, bucketName, designDoc) { + const cb = new KefirCouchbase(url, bucketName); + + return cb.createDatabaseNoError() + .flatMap(() => cb.createDesignDocumentNoError(designDoc.name, designDoc.doc)) + .flatMap(() => cb.getInfoNoError()) + .map((info) => ({cb: cb, info: info})); + } + })); + } +} diff --git a/app/utils/subscriptionTracker.js b/app/utils/subscriptionTracker.js new file mode 100644 index 0000000000000000000000000000000000000000..c20a0872f1500a58764f0128a59646e2f1af3cfb --- /dev/null +++ b/app/utils/subscriptionTracker.js @@ -0,0 +1,46 @@ +/** Subscription Tracker is used to manage subscribing onValue, onError, or onAny to a kefir stream. Calling cleanup on the object unregisters for any registered action. */ +export default () => { + return { + subscriptions: [], + errors: [], + any: [], + addSub(stream$, action) { + if (!stream$ || !action || !(stream$.onValue)) { + return; + } + stream$.onValue(action); + this.subscriptions.push([stream$, action]); + }, + addError(stream$, action) { + if (!stream$ || !action || !(stream$.onError)) { + return; + } + stream$.onError(action); + this.subscriptions.push([stream$, action]); + }, + addAny(stream$, action) { + if (!stream$ || !action || !(stream$.onAny)) { + return; + } + stream$.onAny(action); + this.subscriptions.push([stream$, action]); + }, + cleanUp() { + while(this.subscriptions.length > 0) { + let sub = this.subscriptions[0]; + sub[0].offValue(sub[1]); + this.subscriptions.shift(); + } + while(this.errors.length > 0) { + let sub = this.errors[0]; + sub[0].offValue(sub[1]); + this.errors.shift(); + } + while(this.any.length > 0) { + let sub = this.any[0]; + sub[0].offValue(sub[1]); + this.any.shift(); + } + } + } +} \ No newline at end of file diff --git a/app/utils/utils.js b/app/utils/utils.js new file mode 100644 index 0000000000000000000000000000000000000000..b7930658d2fb47624b6173e84f53aff15bf58a62 --- /dev/null +++ b/app/utils/utils.js @@ -0,0 +1,104 @@ +import Kefir from 'kefir'; +import Immutable from 'immutable'; +import StringifyCircular from 'json-stringify-safe'; +import React, { Component } from 'react'; +import { Alert, Text } from 'react-native'; +import subscriptionTracker from './subscriptionTracker'; + +const al = stream => { stream.onValue(v => Alert.alert('stuff', JSON.stringify(v), [{text:'OK'}])); return stream; }; + +/** Output a block of json data for each property of this component */ +class JsonText extends Component { + render() { + return ({StringifyCircular(this.props, null, '\t')}); + } +} + +/** Output the keys of the object in the obj property. */ +class KeyText extends Component { + render() { + return ({JSON.stringify(Object.keys(this.props.obj || {}))}); + } +} + +export { subscriptionTracker, JsonText, KeyText }; + +export default class Utils { + /** Add an object with properties are pulled from the actionList and the values are objects with the following properties: raw, handler, handlerConst and handlerKV. */ + static getActionsObject(actionList, type) { + return actionList.reduce((state, prop) => { + state[prop] = { + /** A kefir pool for the action. */ + raw: Kefir.pool(), //.log(type + '--' +prop), + /** A helper function that puts values in the raw pool. */ + handler: v => state[prop].raw.plug(Kefir.constant(v)), + /** A helper function that returns a function that puts a constant value in the pool. */ + handlerConst: (v) => () => state[prop].raw.plug(Kefir.constant(v)), + /** A helper function that returns a function that puts a key value object in the pool. */ + handlerKV: (k) => (v) => state[prop].raw.plug(Kefir.constant({key: k, value: v})), + } + return state; + }, {}) + } + + /** Takes an a function and returns the function, falsy input returns the identity function, and a key value object will return a function that sets the key and value in a regular object or an immutable js object. */ + static reducerToFunction(reducer) { + if (!reducer) { + return (x) => x; + } else { + let type = typeof reducer; + if (type === 'function') { + return reducer; + } else { + return (obj) => { + if (!obj) return obj; + if (obj.setIn) { + return obj.setIn(Array.isArray(reducer.key) ? reducer.key : [reducer.key], reducer.value); + } else { + obj[reducer.key] = reducer.value; return obj; } + } + } + } + } + + /** Takes a stream of reducer objects or functions and combines them into a single object. */ + static mergeToSingleObject(streamsItt, initialObject = {}) { + return Kefir + .combine(Array.from(streamsItt)) + .map(reducers => reducers.map(this.reducerToFunction).reduce((o, r) => r(o), initialObject)); + } + + /** Takes a stream of reducer objects or functions and combines them int an ordered map. */ + static mergeToOrderedMap(streamsItt, initialObject = Immutable.OrderedMap()) { + return Kefir + .merge(Array.from(streamsItt)) + .map(this.reducerToFunction) + .scan((current, change) => change(current), initialObject); + } + + /** pops up react native alert with a title and an optional maping function. Returns the input object so it can be used with map. */ + static popMsg(obj, title="Debug message", f=(x=>x)) { + Alert.alert(title, f(obj)); + return obj; + } + + /** pops up react native alert with a title and displays the json of every object sent in. Returns the input object so it can be used with map. */ + static popJson(obj, title="DebugObj") { + Alert.alert(title, obj ? StringifyCircular(obj, null, '\t') : 'empty'); + return obj; + } + + /** pops up react native alert with a title and displays the keys of every object sent in. Returns the input object so it can be used with map. */ + static popKeys(obj, title="DebugObj") { + Alert.alert(title, obj ? StringifyCircular(Object.keys(obj || {}), null, '\t') : 'empty'); + return obj; + } + + /** pops up react native alert with a title and displays the json of every object sent in. Returns the input object so it can be used with map. */ + static popJsonMap(title="DebugObj") { + return (obj) => { + Alert.alert(title, obj ? StringifyCircular(obj, null, '\t') : 'empty'); + return obj; + } + } +} \ No newline at end of file diff --git a/components.md b/components.md new file mode 100644 index 0000000000000000000000000000000000000000..aa2410553778bb08ab6db24819fc32d726efe38d --- /dev/null +++ b/components.md @@ -0,0 +1,78 @@ +# MobileAudit - BlocPower mobile audit prototype. + +### Form Components + +**Note**: All components will require entityMap and editHandler to be used. This works with binding to the CouchDB database. Including them as shown in the example below will work with every custom component: + +`` + +All components can also use a style prop for specific styling: + +`style={styles.picker}` + +--- + +##### `` +* Extends the [TextInput](https://facebook.github.io/react-native/docs/textinput.html) RN component +* Uses the following props: + * label (string) - `label=‘Person’` + * fieldNames (array of strings) - `fieldNames={[ 'firstName', 'lastName' ]}` + * placeholder (string) - `placeholder='Enter Your Name'` + * **Note**: Can have multiple fieldNames, but placeholder currently works best on single lines. + +##### `` +* Same props as ``, but inherits the TextInput props of `multiline={true}` in order to make it a text area instead of just a line of text. + +##### `` +* Extends the [TextInput](https://facebook.github.io/react-native/docs/textinput.html) RN component +* Uses the native numeric keyboard for iOS and Android +* Uses the following props: + * label (string) - `label='Number of items'` + * maxLength (integer) - `maxLength={3}` + * fieldNames (array of strings) - `fieldNames={[ 'items1', 'items2' ]}` + * placeholder (string) - `placeholder='0'`. + +##### `` +* An opinionated version of the `` component +* Already has maxLength set for domestic and international phone numbers + +##### `` +* Extends the DatePicker component npm module [react-native-datepicker](https://github.com/xgfe/react-native-datepicker) +* Uses native date picker for Android and iOS +* Uses the following props: + * label (string) - `label='Number of items'` + * fieldName (string) - `fieldName='items2'` + * customStyles (object) - `customStyles={{ dateIcon: { position: 'absolute' } }}` + +##### `` +* Extends the [Picker](https://facebook.github.io/react-native/docs/picker.html) RN component +* Uses the following props: + * label (string) - `label='Preferred time of day'` + * fieldName (string) - `fieldName='preferredTimeOfDay'` +* You also need Items for the Picker. The value of the selected Item which will save to `fieldName`. +* Full example: +``` + + + + + +``` + +##### `` & `` +* Extends the CheckboxGroup and RadioButtonGroup, respectively, from [react-native-material-design](https://github.com/react-native-material-design/react-native-material-design) +* Both follow the same structure and use the following props: + * label (string) - `label='Satisfaction rating?'` + * fieldName (string) - `fieldName='satisfactionRating'` + * items (array of objects) - `items={[{ value: 1, label: 'Satisfied' }, { value: 2, label: 'Somewhat Satisfied' }, { value: 3, label: 'Dissatisfied' }]}` + +##### `` +* Extends RN component, is using [Geolocator](https://facebook.github.io/react-native/docs/geolocation.html) which uses the [Geolocation Web API](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/getCurrentPosition) +* Pulls in an icon from the Material Design icon set, and uses the click of the icon to update the GPS coordinates + * label="Click icon to record location" + * fieldName='location' diff --git a/exporter/.babelrc b/exporter/.babelrc new file mode 100644 index 0000000000000000000000000000000000000000..428eee586032a0e299bee09091837cf5f7c1b3ed --- /dev/null +++ b/exporter/.babelrc @@ -0,0 +1,4 @@ +{ + "plugins": ["transform-runtime"], + "presets": ["es2017"] +} \ No newline at end of file diff --git a/exporter/code/csv_out.js b/exporter/code/csv_out.js new file mode 100644 index 0000000000000000000000000000000000000000..be66bf641eb6691a50d8f821ad07e1c93c4a95b3 --- /dev/null +++ b/exporter/code/csv_out.js @@ -0,0 +1,16 @@ +import kefir from 'kefir'; +import fs from 'fs'; +import Baby from 'babyparse'; +import path from 'path'; +import _ from 'lodash'; + + +const writeEntityCsv = outputDirectory => entities => { + const fileName = entities[0] + '.csv'; + const filePath = path.join(outputDirectory, fileName); + const csv = Baby.unparse((entities[1]||[]).map(o =>_.omit(o, ['_attachments'])), { quotes: true}); + + return kefir.fromNodeCallback(nc => fs.writeFile(filePath, csv, nc)); +}; + +export {writeEntityCsv}; \ No newline at end of file diff --git a/exporter/code/index.js b/exporter/code/index.js new file mode 100644 index 0000000000000000000000000000000000000000..970c43ca50fa77475409dcf7ff68e0a6cfc63391 --- /dev/null +++ b/exporter/code/index.js @@ -0,0 +1,55 @@ +#!/usr/bin/env node + +import {kSimpleDbInit} from './store'; +import {getEntityTrees, getEntitiesByType} from './model'; + +import {writeEntityPdf, mkdirSilent} from './pdf_out'; +import {writeEntityJson} from './json_out'; +import {writeEntityCsv} from './csv_out'; + +import program from 'commander'; + +program + .version('1.0') + .option('-g, --gateway ', 'Gateway url') + .option('-t, --type ', 'Document type to export') + .option('-o, --output ', 'Output folder'); + +program + .command('export ') + .description('export the specified type in either (pdf|csv|json) format.') + .action(format => { + const gatewayUrl = program.gateway || 'http://couchbase1.sbdev.io:4985/blocpowerauditdev/'; + const entityName = program.type || 'client'; + const outputFolder = program.output || './output'; + + const src$ = mkdirSilent(outputFolder) + .flatMap(() => kSimpleDbInit('local', gatewayUrl)); + + + const out$ = ((src$, format) => { + if (format == 'pdf') return src$.flatMap(getEntityTrees(entityName)).flatMap(writeEntityPdf(outputFolder)); + if (format == 'json') return src$.flatMap(getEntityTrees(entityName)).flatMap(writeEntityJson(outputFolder)); + if (format == 'csv') return src$.flatMap(getEntitiesByType).flatMap(writeEntityCsv(outputFolder)); + })(src$, format); + + out$.onEnd(() => process.exit(0)); + }); + +program + .command('ls') + .description('List the names of the specified objects') + .action(() => { + const gatewayUrl = program.gateway || 'http://couchbase1.sbdev.io:4985/blocpowerauditdev/'; + const entityName = program.type || 'client'; + + kSimpleDbInit('local', gatewayUrl) + .flatMap(getEntityTrees(entityName)) + .onValue(entity => { + entity.name && console.log(entity.name); + }) + }); + +program.parse(process.argv); + + diff --git a/exporter/code/json_out.js b/exporter/code/json_out.js new file mode 100644 index 0000000000000000000000000000000000000000..2060181055a21d8f5a9410781403a03da99c06de --- /dev/null +++ b/exporter/code/json_out.js @@ -0,0 +1,14 @@ +import kefir from 'kefir'; +import fs from 'fs'; +import path from 'path'; +import stringify from 'json-stringify-safe'; + +const writeEntityJson = outputDirectory => entity => { + const fileName = entity.name + '.json'; + const filePath = path.join(outputDirectory, fileName); + const json = stringify(entity, null, 2); + + return kefir.fromNodeCallback(nc => fs.writeFile(filePath, json, nc)); +}; + +export { writeEntityJson }; \ No newline at end of file diff --git a/exporter/code/model.js b/exporter/code/model.js new file mode 100644 index 0000000000000000000000000000000000000000..b8589901ed9cb9591774ea3ffe9c8225d6f7f33f --- /dev/null +++ b/exporter/code/model.js @@ -0,0 +1,58 @@ +import _ from 'lodash'; +import kefir from 'kefir'; + +const toArray = () => { + const list = []; + return (emit, event) => { + if (event.type === 'value') { + list.push(event.value); + } + if (event.type === 'error') { + emit.event(event); + } + if (event.type === 'end') { + emit.value(list); + emit.end(); + } + } +}; + +const buildEntityTree = entityName => docs => { + try { + const + byParent = _.groupBy(docs, x=>x.parent_id), + byType = _.groupBy(docs, x=>x.type); + + const buildTree = (entity) => { + entity._children = (byParent[entity._id] || []).map(c => buildTree(c)); + return entity; + }; + + return byType[entityName].map(buildTree); + } catch (e) { + console.log('error', e); + } +}; + +const getEntities = (simpleDb, attachments) => { + return simpleDb.allDocs() + .map(x => x.rows) + .flatten() + .flatMap(i => simpleDb.get(i.id, {attachments: attachments})) + .withHandler(toArray()); +}; + +const getEntitiesByType = simpleDb => { + return getEntities(simpleDb, false) + .map(entities => _.groupBy(entities, x=>x.type)) + .map(Object.entries) + .flatten(); +}; + +const getEntityTrees = entityName => simpleDb => { + return getEntities(simpleDb, true) + .map(buildEntityTree(entityName)) + .flatten(); +}; + +export {getEntities, getEntitiesByType, getEntityTrees} diff --git a/exporter/code/pdf_out.js b/exporter/code/pdf_out.js new file mode 100644 index 0000000000000000000000000000000000000000..08f312c0a278f7c95f4e2acf58a27fdcbc3fe66d --- /dev/null +++ b/exporter/code/pdf_out.js @@ -0,0 +1,87 @@ +import PDFDocument from 'pdfkit'; +import fs from 'fs'; +import {Buffer} from 'buffer'; +import kefir from 'kefir'; +import path from 'path'; + +const writePageContents = (doc, entity) => { + try { + doc.fontSize(24) + .text(entity.type + ' - ' + entity.name); + + for (const entry of Object.entries(entity)) { + if (entry[0] === 'name' || entry[0].startsWith('_') || entry[0] === 'parent_id') { + continue; + } + + doc.fontSize(16).text(entry[0] + ': ' + entry[1]); + } + if (entity._attachments) { + let y = doc.y; + let index = 0; + for (let attachment of Object.entries(entity._attachments)) { + let height = y + 300 * Math.floor(index / 2); + if (doc.page.height < (height + 300)) { + doc.addPage(); + y = 30; + index = 0; + height = y + 300 * Math.floor(index / 2); + } + doc.image(Buffer.from(attachment[1].data, 'base64'), 6 + 300 * (index % 2), height, {width: 290, height: 290}); + index++; + } + } + } catch (e) { + console.error(e); + } +}; + +const writePages = (doc, entity) => { + writePageContents(doc, entity); + if (!entity._children) { + return; + } + + for (const child of entity._children) { + if (child.type == 'building' || child._attachments) doc.addPage(); + writePages(doc, child); + } +}; + +const writeEntityPdf = outputDirectory => entity => { + const fileName = entity.name + '.pdf'; + const doc = new PDFDocument({ + Title: entity.type + '-' + entity.name, + CreationDate: new Date() + }); + + const filePath = path.join(outputDirectory, fileName); + const outStream = fs.createWriteStream(filePath); + doc.pipe(outStream); + doc.font('fonts/HindGuntur-Regular.ttf'); + + writePages(doc, entity); + + const result = kefir.fromEvents(outStream, 'finish').map(() => { + console.log(fileName + ' written'); + }).take(1).map(() => entity); + + doc.end(); + return result; +}; + +const mkdirSilent = (path) => { + return kefir.stream(emit => { + try { + fs.mkdir(path, 0o777, (err, val) => { + emit.value(val); + emit.end(); + }); + } catch (e) { + emit.value(e); + emit.end(); + } + }); +}; + +export {mkdirSilent, writeEntityPdf}; diff --git a/exporter/code/store.js b/exporter/code/store.js new file mode 100644 index 0000000000000000000000000000000000000000..717ed21ea70b35510cd3cacd3b9b0b675f14bd37 --- /dev/null +++ b/exporter/code/store.js @@ -0,0 +1,34 @@ +import PouchDB from 'pouchdb'; +import kefir from 'kefir'; + +const kDbInfo = (db) => kefir.fromPromise(db.info()); +const kDbGet = (db, id, options = {}) => kefir.fromPromise(db.get(id, options)); +const kDbAllDocs = (db, options = {}) => kefir.fromPromise(db.allDocs(options)); + +const kReplicate = (db, url) => { + return kefir.stream(emit => { + const replication = db.replicate.from(url); + replication.on('complete', () => { + emit.value(); + emit.end(); + }); + replication.on('error', (e) => { + emit.error(e); + emit.end(); + }); + }); +}; + +const kDbInit = (db, url) => kDbInfo(db).flatMap(() => kReplicate(db, url)).map(() => db); + +const kSimpleDbInit = (localDbName, gatewayUrl) => { + const localDb = new PouchDB(localDbName); + return kDbInit(localDb, gatewayUrl) + .map((db) => ({ + db: db, + allDocs: (options) => kDbAllDocs(db, options), + get: (id, options) => kDbGet(db, id, options) + })); +}; + +export { kSimpleDbInit }; \ No newline at end of file diff --git a/exporter/fonts/HindGuntur-Bold.ttf b/exporter/fonts/HindGuntur-Bold.ttf new file mode 100644 index 0000000000000000000000000000000000000000..a6070afe025d35cf1ca82d641928b80dc2bffb76 Binary files /dev/null and b/exporter/fonts/HindGuntur-Bold.ttf differ diff --git a/exporter/fonts/HindGuntur-Regular.ttf b/exporter/fonts/HindGuntur-Regular.ttf new file mode 100644 index 0000000000000000000000000000000000000000..37ad072d6add77ca12e30ac3b2014ba36b4405ef Binary files /dev/null and b/exporter/fonts/HindGuntur-Regular.ttf differ diff --git a/exporter/local/000667.ldb b/exporter/local/000667.ldb new file mode 100644 index 0000000000000000000000000000000000000000..6e64b8651d9c2b7100c59cfe8c5e4ce06ac6ef66 Binary files /dev/null and b/exporter/local/000667.ldb differ diff --git a/exporter/local/000669.ldb b/exporter/local/000669.ldb new file mode 100644 index 0000000000000000000000000000000000000000..7e53f0be6733aa35a1398b7d750a2dc7c289d263 Binary files /dev/null and b/exporter/local/000669.ldb differ diff --git a/exporter/local/CURRENT b/exporter/local/CURRENT new file mode 100644 index 0000000000000000000000000000000000000000..52b1c8bcdf99cb2d3517cbc4505195e515e1328b --- /dev/null +++ b/exporter/local/CURRENT @@ -0,0 +1 @@ +MANIFEST-000668 diff --git a/exporter/local/LOCK b/exporter/local/LOCK new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/exporter/local/LOG b/exporter/local/LOG new file mode 100644 index 0000000000000000000000000000000000000000..36c113942a08ed2659e4cb0535652ea417c1cbbd --- /dev/null +++ b/exporter/local/LOG @@ -0,0 +1,5 @@ +2016/07/04-22:38:50.092 4e64 Recovering log #666 +2016/07/04-22:38:50.092 4e64 Level-0 table #669: started +2016/07/04-22:38:50.105 4e64 Level-0 table #669: 597 bytes OK +2016/07/04-22:38:50.125 4e64 Delete type=0 #666 +2016/07/04-22:38:50.125 4e64 Delete type=3 #664 diff --git a/exporter/local/LOG.old b/exporter/local/LOG.old new file mode 100644 index 0000000000000000000000000000000000000000..a23429bbc2bd00a7668f4d73b0bfd8318ef4244d --- /dev/null +++ b/exporter/local/LOG.old @@ -0,0 +1,14 @@ +2016/07/04-22:35:40.284 614c Recovering log #663 +2016/07/04-22:35:40.284 614c Level-0 table #665: started +2016/07/04-22:35:40.297 614c Level-0 table #665: 600 bytes OK +2016/07/04-22:35:40.317 614c Delete type=0 #663 +2016/07/04-22:35:40.317 614c Delete type=3 #661 +2016/07/04-22:35:40.318 1e80 Compacting 4@0 + 1@1 files +2016/07/04-22:35:40.332 1e80 Generated table #667: 86 keys, 145488 bytes +2016/07/04-22:35:40.333 1e80 Compacted 4@0 + 1@1 files => 145488 bytes +2016/07/04-22:35:40.337 1e80 compacted to: files[ 0 1 0 0 0 0 0 ] +2016/07/04-22:35:40.337 1e80 Delete type=2 #654 +2016/07/04-22:35:40.338 1e80 Delete type=2 #656 +2016/07/04-22:35:40.338 1e80 Delete type=2 #659 +2016/07/04-22:35:40.338 1e80 Delete type=2 #662 +2016/07/04-22:35:40.339 1e80 Delete type=2 #665 diff --git a/exporter/local/MANIFEST-000668 b/exporter/local/MANIFEST-000668 new file mode 100644 index 0000000000000000000000000000000000000000..f292a16dad792d479f0a927b8803900b04431b21 Binary files /dev/null and b/exporter/local/MANIFEST-000668 differ diff --git a/exporter/package.json b/exporter/package.json new file mode 100644 index 0000000000000000000000000000000000000000..4f19a82820e39be4221937e418e8c5262d8239e1 --- /dev/null +++ b/exporter/package.json @@ -0,0 +1,33 @@ +{ + "name": "export_server", + "version": "1.0.0", + "description": "", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1", + "build": "babel -w code/ -d build -s", + "start": "node ./build/index.js -o output", + "debug": "node --debug ./build/index.js" + }, + "bin": { + "audit_export": "./build/index.js" + }, + "keywords": [], + "author": "", + "license": "ISC", + "devDependencies": { + "babel-cli": "^6.10.1", + "babel-plugin-transform-runtime": "6.9.0", + "babel-preset-es2017": "1.4.0" + }, + "dependencies": { + "babyparse": "0.4.6", + "commander": "2.9.0", + "immutable": "3.8.1", + "json-stringify-safe": "5.0.1", + "kefir": "3.2.3", + "lodash": "4.13.1", + "pdfkit": "0.7.2", + "pouchdb": "5.4.4" + } +} diff --git a/exporter/readme.md b/exporter/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..9b3212012a7e71055ee43673b7f51dd089942b66 --- /dev/null +++ b/exporter/readme.md @@ -0,0 +1,19 @@ +#audit_export command line utiltiy + +##Usage + + Usage: index [options] [command] + + + Commands: + + export export the specified type in either (pdf|csv|json) format. + ls List the names of the specified objects + + Options: + + -h, --help output usage information + -V, --version output the version number + -g, --gateway Gateway url + -t, --type Document type to export (default: client) + -o, --output Output folder (default: ./output) diff --git a/index.android.js b/index.android.js new file mode 100644 index 0000000000000000000000000000000000000000..9566d082b91a090137b9ccea9d11f78fd0db734a --- /dev/null +++ b/index.android.js @@ -0,0 +1,47 @@ +import { AppRegistry, BackAndroid } from 'react-native'; + +import U from './app/utils/utils'; +import Entities from './app/entities'; +import routes from './app/routes'; +import styles from './app/assets/styles'; + +import getActions from './app/actions/allActions'; +import getStores from './app/stores/allStores'; +import getAudit from './app/components/audit'; + +const actions = getActions(Entities); +let setup$ = null; +try { + //prevents stores from being reloaded and duplicates being attached to the databases and streams with javascript reloads + const stores$ = getStores(actions, routes, Entities); + setup$ = stores$.map(stores => { + stores.nav.navigator.onValue(navigator => { + const window$ = stores.nav.stack.slidingWindow(2, 2); + window$.filter(stacks => stacks[0].size < stacks[1].size).map(routes => routes[1].get(0)).onValue(route => navigator.push(route)); + window$.filter(stacks => stacks[0].size > stacks[1].size).onValue(routes => navigator.pop()); + }); + + for (let entityName of Entities.entityList) { + actions.nav.push.raw.plug(actions[entityName].newObj.raw.map(() => `${entityName}.children.new`)); + actions.nav.push.raw.plug(actions[entityName].editObj.raw.map(() => `${entityName}.children.edit`)); + //Load children when we activate a new object, or edit an existing one. + actions[entityName].loadChildren.raw.plug(actions[entityName].newObj.raw); + actions[entityName].loadChildren.raw.plug(actions[entityName].editObj.raw); + + stores[entityName].errors.onError(e => U.popJson(e, 'Database Error')); + } + + BackAndroid.addEventListener('hardwareBackPress', () => { actions.nav.hardwareback.handler(); return true; }); + + stores.nav.close.onValue(() => { + BackAndroid.exitApp(); + }); + + return stores; + }) + stores$.onError(e => U.popJson(e, 'Database load error')); +} catch (e) { + U.popJson(e, "Startup Error"); +} + +AppRegistry.registerComponent('audit', () => getAudit(actions, routes, Entities, setup$, styles)); diff --git a/package.json b/package.json new file mode 100644 index 0000000000000000000000000000000000000000..79d8fb0c4cc6febba8ce5af7bba179dde23a79fb --- /dev/null +++ b/package.json @@ -0,0 +1,22 @@ +{ + "name": "blocpower.blocpoweraudit", + "version": "0.0.1", + "private": true, + "scripts": { + "start": "node node_modules/react-native/local-cli/cli.js start" + }, + "dependencies": { + "immutable": "^3.8.1", + "json-stringify-safe": "^5.0.1", + "kefir": "^3.2.3", + "lodash": "^4.13.1", + "node-uuid": "^1.4.7", + "react": "^15.1", + "react-native": "^0.28.0-rc", + "react-native-action-button": "^1.1.5", + "react-native-couchbase-lite": "^0.3.0", + "react-native-datepicker": "^1.2.1", + "react-native-image-picker": "^0.19.3", + "react-native-material-design": "https://github.com/cldwalker/react-native-material-design#fix-checkbox-group-on-select" + } +} diff --git a/sync.json b/sync.json new file mode 100644 index 0000000000000000000000000000000000000000..c668112ef2c4ac28b7332c5eb776be96d487cc20 --- /dev/null +++ b/sync.json @@ -0,0 +1,5 @@ +{ + "interface":":4984", + "adminInterface":":4985", + "log":["REST", "Auth", "CRUD", "Events"] +} \ No newline at end of file diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..004f79698f6ede97868cd89f3d61ae178b275f61 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,9 @@ +{ + "compilerOptions": { + "allowJs": true + }, + "exclude": [ + "node_modules", + "exporter/node_modules" + ] +} \ No newline at end of file