<commit_before>const commander = require('commander');
const request = require('superagent');
const denodeify = require('denodeify');
const fs = require('fs');
const writeFile = denodeify(fs.writeFile);
const mkdirp = denodeify(require('mkdirp'));

const baseFields = {
  nid: 'integer',
  uuid: 'string',
  vid: 'integer',
  langcode: 'string',
  title: 'string',
  status: 'boolean',
  created: 'integer',
  changed: 'integer',
  promote: 'boolean',
  sticky: 'boolean',
  revision_timestamp: 'integer',
  revision_log: 'string',
  revision_translation_affected: 'boolean',
  default_langcode: 'boolean',
  path: 'string',
  type: 'entity_reference',
  uid: 'entity_reference',
  revision_uid: 'entity_reference',
  tid: 'integer',
  name: 'string',
  description: 'string',
  weight: 'integer',
  parent: 'entity_reference'
};

const nodeBaseFields = [
  'nid',
  'uuid',
  'vid',
  'langcode',
  'title',
  'status',
  'created',
  'changed',
  'promote',
  'sticky',
  'revision_timestamp',
  'revision_log',
  'revision_translation_affected',
  'default_langcode',
  'path',
  'type',
  'uid',
  'revision_uid'
];

const taxonomyFields = [
  'tid',
  'langcode',
  'name',
  'description',
  'weight',
  'changed',
  'default_langcode',
  'path',
  'vid'
];

const formatters = {
  boolean(value) {
    return value === '1';
  },
  integer(value) {
    return parseInt(value, 10);
  },
  string_long(value) {
    try {
      return JSON.parse(value);
    } catch (err) {
      return value;
    }
  }
};

function commandLineOptions() {
  if (!process.env.DRUPAL_PASS || !process.env.DRUPAL_USER) {
    process.stderr.write("You must set DRUPAL_USER and DRUPAL_PASS environment variables\n");
    process.exit(-1);
  }

  commander
    .usage('[options] <drupal-jsonapi-url>')
    .option('-o --outdir <dir>', 'Output directory.', './out')
    .parse(process.argv);

  if (commander.args.length < 1) {
    commander.outputHelp();
    process.exit(-1);
  }

  commander.drupalURL = commander.args[0];
  return commander;
}

class Downloader {
  constructor({ drupalURL, outdir }) {
    this.drupalURL = drupalURL;
    this.outdir = outdir;
    this.fields = {};
  }
  get(url) {
    let authorization = 'Basic ' + new Buffer(process.env.DRUPAL_USER + ':' + process.env.DRUPAL_PASS, 'utf8').toString('base64');
    return request.get(url).set('Authorization', authorization);
  }

  rewriteType(type) {
    return type
      .replace(/^node--/, '')
      .replace(/^taxonomy_term--/, '');
  }

  rewriteFieldName(fieldName /* , type */) {
    return fieldName.replace(/^field_/, '');
  }

  async getNodeTypes() {
    return this.getCollection('/node_type/node_type');
  }

  async getFields(nodeType) {
    return this.getCollection(`/field_config/field_config?filter[entity_type][value]=node&filter[bundle][value]=${nodeType.attributes.type}`);
  }

  async getCollection(collectionPath) {
    let url = this.drupalURL + collectionPath;
    let records = [];
    while (url) {
      process.stdout.write(url + ' ');
      let response = await this.get(url);
      process.stdout.write(String(response.body.data.length) + "\n");
      records = records.concat(response.body.data);
      url = response.body.links.next;
    }
    return records;
  }

  async saveRecord(record) {
    let { type, id } = record;
    await mkdirp([this.outdir, type].join('/'));
    await writeFile([this.outdir, type, id + '.json'].join('/'), JSON.stringify({
      attributes: record.attributes,
      relationships: record.relationships
    }, null, 2));
  }

  rewriteRef(value) {
    if (!value || !value.data) {
      return value;
    }
    if (Array.isArray(value.data)) {
      return { data : value.data.map(r => ({ type: this.rewriteType(r.type), id: r.id })) };
    } else {
      return { data: { type: this.rewriteType(value.data.type), id: value.data.id } };
    }
  }

  rewriteRecord(record, fields) {
    let output = {
      id: record.id,
      type: this.rewriteType(record.type)
    };
    for (let [k,value] of Object.entries(record.attributes).concat(Object.entries(record.relationships))) {
      // uuid is always redundant because the drupal jsonapi module
      // uses it as the jsonapi id.
      if (k === 'uuid') { continue; }
      let fieldType;
      let field = fields.find(f => f.attributes.field_name === k);
      if (field) {
        fieldType = field.attributes.field_type;
      } else if (baseFields[k]) {
        fieldType = baseFields[k];
      } else {
        throw new Error(`Unknown field ${k} on ${record.type} ${record.id}`);
      }
      if (formatters[fieldType]) {
        value = formatters[fieldType](value);
      }
      if (['entity_reference', 'file'].includes(fieldType)) {
        if (!output.relationships) {
          output.relationships = {};
        }
        output.relationships[this.rewriteFieldName(k, record.type)] = this.rewriteRef(value);
      } else {
        if (!output.attributes) {
          output.attributes = {};
        }
        output.attributes[this.rewriteFieldName(k, record.type)] = value;
      }
    }
    return output;
  }

  rewriteFieldType(fieldType, sampleValue) {
    switch (fieldType) {
    case 'entity_reference':
      if (sampleValue && Array.isArray(sampleValue.data)) {
        return `@cardstack/core_types::has-many`;
      } else {
        return `@cardstack/core_types::belongs-to`;
      }
    default:
      return `@cardstack/core_types::${fieldType}`;
    }
  }

  async createField(origFieldName, fieldType, sampleValue) {
    let fieldName = this.rewriteFieldName(origFieldName);
    if (this.fields[fieldName]){
      if (!this.fields[fieldName] === fieldType) {
        throw new Error(`${fieldName} has conflicting types`);
      }
      return;
    }

    this.fields[fieldName] = fieldType;
    await this.saveRecord({
      type: 'fields',
      id: fieldName,
      attributes: {
        'field-type': this.rewriteFieldType(fieldType, sampleValue)
      }
    });
  }

  async defineTaxonomyType(type) {
    let contentType = {
      type: 'content-types',
      id: type.attributes.vid,
      relationships: {
        fields: {
          data: taxonomyFields.map(t => ({ type: 'fields', id: t }))
        }
      }
    };
    await this.saveRecord(contentType);

    // the only relationships (parent) is always plural
    let sample = { data: [] };

    for (let f of taxonomyFields) {
      await this.createField(f, baseFields[f], sample);
    }
  }

  async defineContentType(type, fields, sample) {
    let contentType = {
      type: 'content-types',
      id: type.attributes.type,
      relationships: {
        fields: {
          data: nodeBaseFields.map(t => ({ type: 'fields', id: t }))
            .concat(fields.map(f => ({ type: 'fields', id: this.rewriteFieldName(f.attributes.field_name) })))
        }
      }
    };
    await this.saveRecord(contentType);
    for (let f of nodeBaseFields) {
      let fieldType = baseFields[f];
      let sampleValue;
      if (['entity_reference', 'file'].includes(fieldType)) {
        sampleValue = sample.relationships[f];
      } else {
        sampleValue = sample.attributes[f];
      }
      await this.createField(f, fieldType, sampleValue);
    }
    for (let f of fields) {
      let fieldType = f.attributes.field_type;
      let fieldName = f.attributes.field_name;
      let sampleValue;
      if (['entity_reference', 'file'].includes(fieldType)) {
        sampleValue = sample.relationships[fieldName];
      } else {
        sampleValue = sample.attributes[fieldName];
      }
      await this.createField(fieldName, fieldType, sampleValue);
    }
  }

  async run() {
    for (let type of (await this.getCollection('/taxonomy_vocabulary/taxonomy_vocabulary'))) {
      await this.defineTaxonomyType(type);
      let records = await this.getCollection(`/taxonomy_term/${type.attributes.vid}`);
      for (let record of records) {
        await this.saveRecord(this.rewriteRecord(record, []));
      }
    }
    for (let type of (await this.getNodeTypes())) {
      let fields = await this.getFields(type);
      let records = await this.getCollection(`/node/${type.attributes.type}`);
      if (records.length > 0) {
        await this.defineContentType(type, fields, records[0]);
      }

      for (let record of records) {
        await this.saveRecord(this.rewriteRecord(record, fields));
      }
    }
  }
}

let downloader = new Downloader(commandLineOptions());
downloader.run();
<commit_msg>proper repo sections<commit_after>const commander = require('commander');
const request = require('superagent');
const denodeify = require('denodeify');
const fs = require('fs');
const writeFile = denodeify(fs.writeFile);
const mkdirp = denodeify(require('mkdirp'));

const baseFields = {
  nid: 'integer',
  uuid: 'string',
  vid: 'integer',
  langcode: 'string',
  title: 'string',
  status: 'boolean',
  created: 'integer',
  changed: 'integer',
  promote: 'boolean',
  sticky: 'boolean',
  revision_timestamp: 'integer',
  revision_log: 'string',
  revision_translation_affected: 'boolean',
  default_langcode: 'boolean',
  path: 'string',
  type: 'entity_reference',
  uid: 'entity_reference',
  revision_uid: 'entity_reference',
  tid: 'integer',
  name: 'string',
  description: 'string',
  weight: 'integer',
  parent: 'entity_reference'
};

const nodeBaseFields = [
  'nid',
  'uuid',
  'vid',
  'langcode',
  'title',
  'status',
  'created',
  'changed',
  'promote',
  'sticky',
  'revision_timestamp',
  'revision_log',
  'revision_translation_affected',
  'default_langcode',
  'path',
  'type',
  'uid',
  'revision_uid'
];

const taxonomyFields = [
  'tid',
  'langcode',
  'name',
  'description',
  'weight',
  'changed',
  'default_langcode',
  'path',
  'vid'
];

const formatters = {
  boolean(value) {
    return value === '1';
  },
  integer(value) {
    return parseInt(value, 10);
  },
  string_long(value) {
    try {
      return JSON.parse(value);
    } catch (err) {
      return value;
    }
  }
};

function commandLineOptions() {
  if (!process.env.DRUPAL_PASS || !process.env.DRUPAL_USER) {
    process.stderr.write("You must set DRUPAL_USER and DRUPAL_PASS environment variables\n");
    process.exit(-1);
  }

  commander
    .usage('[options] <drupal-jsonapi-url>')
    .option('-o --outdir <dir>', 'Output directory.', './out')
    .parse(process.argv);

  if (commander.args.length < 1) {
    commander.outputHelp();
    process.exit(-1);
  }

  commander.drupalURL = commander.args[0];
  return commander;
}

class Downloader {
  constructor({ drupalURL, outdir }) {
    this.drupalURL = drupalURL;
    this.outdir = outdir;
    this.fields = {};
  }
  get(url) {
    let authorization = 'Basic ' + new Buffer(process.env.DRUPAL_USER + ':' + process.env.DRUPAL_PASS, 'utf8').toString('base64');
    return request.get(url).set('Authorization', authorization);
  }

  rewriteType(type) {
    return type
      .replace(/^node--/, '')
      .replace(/^taxonomy_term--/, '');
  }

  rewriteFieldName(fieldName /* , type */) {
    return fieldName.replace(/^field_/, '');
  }

  async getNodeTypes() {
    return this.getCollection('/node_type/node_type');
  }

  async getFields(nodeType) {
    return this.getCollection(`/field_config/field_config?filter[entity_type][value]=node&filter[bundle][value]=${nodeType.attributes.type}`);
  }

  async getCollection(collectionPath) {
    let url = this.drupalURL + collectionPath;
    let records = [];
    while (url) {
      process.stdout.write(url + ' ');
      let response = await this.get(url);
      process.stdout.write(String(response.body.data.length) + "\n");
      records = records.concat(response.body.data);
      url = response.body.links.next;
    }
    return records;
  }

  async saveRecord(record) {
    let { type, id } = record;
    let section = ['content-types', 'fields'].includes(type) ? 'schema' : 'content';
    let dir = [this.outdir, section, type].join('/');
    await mkdirp(dir);
    await writeFile([dir, id + '.json'].join('/'), JSON.stringify({
      attributes: record.attributes,
      relationships: record.relationships
    }, null, 2));
  }

  rewriteRef(value) {
    if (!value || !value.data) {
      return value;
    }
    if (Array.isArray(value.data)) {
      return { data : value.data.map(r => ({ type: this.rewriteType(r.type), id: r.id })) };
    } else {
      return { data: { type: this.rewriteType(value.data.type), id: value.data.id } };
    }
  }

  rewriteRecord(record, fields) {
    let output = {
      id: record.id,
      type: this.rewriteType(record.type)
    };
    for (let [k,value] of Object.entries(record.attributes).concat(Object.entries(record.relationships))) {
      // uuid is always redundant because the drupal jsonapi module
      // uses it as the jsonapi id.
      if (k === 'uuid') { continue; }
      let fieldType;
      let field = fields.find(f => f.attributes.field_name === k);
      if (field) {
        fieldType = field.attributes.field_type;
      } else if (baseFields[k]) {
        fieldType = baseFields[k];
      } else {
        throw new Error(`Unknown field ${k} on ${record.type} ${record.id}`);
      }
      if (formatters[fieldType]) {
        value = formatters[fieldType](value);
      }
      if (['entity_reference', 'file'].includes(fieldType)) {
        if (!output.relationships) {
          output.relationships = {};
        }
        output.relationships[this.rewriteFieldName(k, record.type)] = this.rewriteRef(value);
      } else {
        if (!output.attributes) {
          output.attributes = {};
        }
        output.attributes[this.rewriteFieldName(k, record.type)] = value;
      }
    }
    return output;
  }

  rewriteFieldType(fieldType, sampleValue) {
    switch (fieldType) {
    case 'entity_reference':
      if (sampleValue && Array.isArray(sampleValue.data)) {
        return `@cardstack/core_types::has-many`;
      } else {
        return `@cardstack/core_types::belongs-to`;
      }
    default:
      return `@cardstack/core_types::${fieldType}`;
    }
  }

  async createField(origFieldName, fieldType, sampleValue) {
    let fieldName = this.rewriteFieldName(origFieldName);
    if (this.fields[fieldName]){
      if (!this.fields[fieldName] === fieldType) {
        throw new Error(`${fieldName} has conflicting types`);
      }
      return;
    }

    this.fields[fieldName] = fieldType;
    await this.saveRecord({
      type: 'fields',
      id: fieldName,
      attributes: {
        'field-type': this.rewriteFieldType(fieldType, sampleValue)
      }
    });
  }

  async defineTaxonomyType(type) {
    let contentType = {
      type: 'content-types',
      id: type.attributes.vid,
      relationships: {
        fields: {
          data: taxonomyFields.map(t => ({ type: 'fields', id: t }))
        }
      }
    };
    await this.saveRecord(contentType);

    // the only relationships (parent) is always plural
    let sample = { data: [] };

    for (let f of taxonomyFields) {
      await this.createField(f, baseFields[f], sample);
    }
  }

  async defineContentType(type, fields, sample) {
    let contentType = {
      type: 'content-types',
      id: type.attributes.type,
      relationships: {
        fields: {
          data: nodeBaseFields.map(t => ({ type: 'fields', id: t }))
            .concat(fields.map(f => ({ type: 'fields', id: this.rewriteFieldName(f.attributes.field_name) })))
        }
      }
    };
    await this.saveRecord(contentType);
    for (let f of nodeBaseFields) {
      let fieldType = baseFields[f];
      let sampleValue;
      if (['entity_reference', 'file'].includes(fieldType)) {
        sampleValue = sample.relationships[f];
      } else {
        sampleValue = sample.attributes[f];
      }
      await this.createField(f, fieldType, sampleValue);
    }
    for (let f of fields) {
      let fieldType = f.attributes.field_type;
      let fieldName = f.attributes.field_name;
      let sampleValue;
      if (['entity_reference', 'file'].includes(fieldType)) {
        sampleValue = sample.relationships[fieldName];
      } else {
        sampleValue = sample.attributes[fieldName];
      }
      await this.createField(fieldName, fieldType, sampleValue);
    }
  }

  async run() {
    for (let type of (await this.getCollection('/taxonomy_vocabulary/taxonomy_vocabulary'))) {
      await this.defineTaxonomyType(type);
      let records = await this.getCollection(`/taxonomy_term/${type.attributes.vid}`);
      for (let record of records) {
        await this.saveRecord(this.rewriteRecord(record, []));
      }
    }
    for (let type of (await this.getNodeTypes())) {
      let fields = await this.getFields(type);
      let records = await this.getCollection(`/node/${type.attributes.type}`);
      if (records.length > 0) {
        await this.defineContentType(type, fields, records[0]);
      }

      for (let record of records) {
        await this.saveRecord(this.rewriteRecord(record, fields));
      }
    }
  }
}

let downloader = new Downloader(commandLineOptions());
downloader.run();
<|endoftext|>


<commit_before>'use strict';
import React from 'react';

import GMap from './GMap';

const Contact = () => (

Please contact us to discuss investment opportunities

            {[
              <i key={ `FAIcon_User` } className="fa fa-user-circle" />,
              `Ralph Isenrich, CFA`
            ]}

            {[
              <i key={ `FAIcon_Envelope` } className="fa fa-envelope" />,
              `ralph@daviepoplarcapital.com`
            ]}

            {[
              <i key={ `FAIcon_Phone` } className="fa fa-phone-square" />,
              `(m) +1 (919) 334-8367`
            ]}

            {[
              <i key={ `FAIcon_AddressCard` } className="fa fa-address-card invert" />,
              `Download vCard`
            ]}

Davie Poplar Capital, LLC.

185 Windchime Ct., Suite 201

Raleigh, NC 27615

            {[
              <i key={ `FAIcon_Newspaper` } className="fa fa-newspaper-o invert" />,
              `Subscribe for News & Updates`
            ]}

    <GMap />

);

export default Contact;

// ralph@daviepoplarcapital.com
 -->

// Download vCard

// G-Maps URL:  https://www.google.com/maps/place/
// Ferro+Management+Group,+185+Wind+Chime+Ct+%23+201,+Raleigh,+NC+27615/@35.8761861,-78.6425212,19z/data=!3m1!4b1!4m2!3m1!1s0x89ac58133cd16d47:0xb239755f849eed8d?hl=en

// onmouseenter="ent()" onmouseleave="leave()">

//

//

//
Ralph Isenrich, CFA

//
//        revertPic('linkedIn_Glyph') } />
//
//

//

//
ralph@daviepoplarcapital.com

//
//      revertPic('email_Glyph') } />
//
//

//
(m) +1 (919) 334-8367

//

//   185 Windchime Ct, Suite 201
//   Raleigh NC 27615 US
//

<commit_msg>chore: Wrap contact information in .info divs<commit_after>'use strict';
import React from 'react';

import GMap from './GMap';

const Contact = () => (

Please contact us to discuss investment opportunities

              {[
                <i key={ `FAIcon_User` } className="fa fa-user-circle" />,
                `Ralph Isenrich, CFA`
              ]}

              {[
                <i key={ `FAIcon_Envelope` } className="fa fa-envelope" />,
                `ralph@daviepoplarcapital.com`
              ]}

              {[
                <i key={ `FAIcon_Phone` } className="fa fa-phone-square" />,
                `(m) +1 (919) 334-8367`
              ]}

            {[
              <i key={ `FAIcon_AddressCard` } className="fa fa-address-card invert" />,
              `Download vCard`
            ]}

Davie Poplar Capital, LLC.

185 Windchime Ct., Suite 201

Raleigh, NC 27615

            {[
              <i key={ `FAIcon_Newspaper` } className="fa fa-newspaper-o invert" />,
              `Subscribe for News & Updates`
            ]}

    <GMap />

);

export default Contact;

// ralph@daviepoplarcapital.com
 -->

// Download vCard

// G-Maps URL:  https://www.google.com/maps/place/
// Ferro+Management+Group,+185+Wind+Chime+Ct+%23+201,+Raleigh,+NC+27615/@35.8761861,-78.6425212,19z/data=!3m1!4b1!4m2!3m1!1s0x89ac58133cd16d47:0xb239755f849eed8d?hl=en

// onmouseenter="ent()" onmouseleave="leave()">

//

//

//
Ralph Isenrich, CFA

//
//        revertPic('linkedIn_Glyph') } />
//
//

//

//
ralph@daviepoplarcapital.com

//
//      revertPic('email_Glyph') } />
//
//

//
(m) +1 (919) 334-8367

//

//   185 Windchime Ct, Suite 201
//   Raleigh NC 27615 US
//

<|endoftext|>


<commit_before>var _ = require('lodash');
var Q = require('q');
var axios = require('axios');
var urlJoin = require('urljoin.js');

var base64 = require('../utils/base64');
var arrayBuffer = require('../utils/arraybuffer');

// 1MB max size to return
var CONTENT_MAX_SIZE = 1*1024*1024;

// Get author from commit
function getAuthor(commit) {
    return  {
        'name': commit.commit.author.name,
        'email': commit.commit.author.email,
        'avatar': commit.author? commit.author.avatar_url : undefined
    };
}

// Normalize a patch
function normPatch(file) {
    return {
        filename: file.filename,
        patch: file.patch
    };
}

// Normalize a commit
function normCommit(commit) {
    var r = {
        'sha': commit.sha,
        'author': getAuthor(commit),
        'message': commit.commit.message,
        'date': commit.commit.author.date
    };
    if (commit.files) {
        r.files = _.map(commit.files, normPatch);
    }
    return r;
}

function Driver(options, fs) {
    this.fs = fs;
    this.options = _.defaults({}, options || {}, {
        repository: null,
        host: 'https://api.github.com',
        rawhost: 'https://raw.githubusercontent.com',
        username: null,
        token: null,
        includeTokenInRaw: false

    });
    if (!this.options.repository) throw new Error('GitHub driver requires a "repository" option');
}

// Return a raw url for a file
Driver.prototype.rawUrl = function(file) {
    return this.options.rawhost
        .replace(':repo', this.options.repository)
        .replace(':branch', this.fs.getCurrentBranch())
        .replace(':file', file);
};

// Execute an HTTP API request
Driver.prototype.api = function (httpMethod, method, args, options) {
    var opts = {
        method: httpMethod,
        url: urlJoin(this.options.host, '/repos/'+this.options.repository+'/'+method)+'?t='+Date.now(),
        headers: {
            'Accept': 'application/vnd.github.v3+json',
            'Content-type': 'application/json;charset=UTF-8'
        }
    };

    if (this.options.username) {
        opts.headers['Authorization'] = 'Basic ' + base64.encode(this.options.username + ':' + this.options.token);
    }

    if (httpMethod == 'get') opts.params = args;
    else opts.data = args;

    return Q(axios(opts))
    .get('data')
    .fail(function(response) {
        if (response instanceof Error) throw response;

        var e = new Error(response.data.message || 'Error '+response.status+': '+response.data);
        e.statusCode = response.status;

        throw e;
    });
};

// Fetch all tree
Driver.prototype.fetchTree = function() {
    return this.api('get', 'git/trees/'+this.fs.currentBranch, {
        recursive: 1
    })
    .then(function(r) {
        return {
            sha: r.sha,
            entries: _.chain(r.tree)
                .map(function(entry) {
                    return [
                        entry.path,
                        {
                            sha: entry.sha,
                            path: entry.path,
                            size: entry.size
                        }
                    ];
                })
                .object()
                .value()
        };
    });
};

// Fetch content of a blob
Driver.prototype.fetchBlob = function(sha) {
    return this.api('get', 'git/blobs/'+sha)
    .then(function(r) {
        return {
            size: r.size,
            content: ((_.isString(r.content) && r.size < CONTENT_MAX_SIZE)? arrayBuffer.fromBase64(r.content.replace(/(\r\n|\n|\r)/gm,'')) : undefined)
        };
    });
};

// Commit pending changes
Driver.prototype.commitChanges = function(base, commit) {
    var that = this, newTree;

    return Q()
    .then(function() {
        newTree = {
            tree: _.values(commit.tree)
        };

        // Create new blobs
        return _.reduce(newTree.tree, function(prev, entry) {
            // Entry didn't changed
            if (entry.sha) return prev;

            return prev.then(function() {
                return that.api('post', 'git/blobs', {
                    content: entry.buffer,
                    encoding: 'base64'
                })
                .then(function(blob) {
                    entry.type = 'blob';
                    entry.sha = blob.sha;
                    entry.mode = entry.mode || '100644';
                });
            });
        }, Q());
    })

    // Create new tree
    .then(function() {
        return that.api('post', 'git/trees', newTree);
    })

    // Finally, create the new commit
    .then(function(tree) {
        return that.api('post', 'git/commits', {
            message: commit.message,
            parents: [base],
            tree: [tree.sha]
        });
    })

    // Update HEAD of branch
    .then(function(commit) {
        return that.api('post', 'git/refs/'+that.fs.currentBranch, {
            sha: commit.sha
        });
    });
};

// List branches
Driver.prototype.listBranches = function() {
    return this.api('get', 'branches')
    .then(function(branches) {
        return _.map(branches, function(branch) {
            return {
                name: branch.name,
                commit: branch.commit.sha,
                is_local: branch.is_local
            };
        });
    });
};

// Create a branch
Driver.prototype.createBranch = function(name, from) {
    var that = this;

    return this.api('get', 'branches/'+from)
    .then(function(branch) {
        return that.api('post', 'git/refs', {
            'ref': 'refs/heads/'+name,
            'sha': branch.commit.sha
        });
    });
};

// Remove a branch
Driver.prototype.removeBranch = function(name) {
    return this.api('delete', 'git/refs/heads/'+name);
};

// Merge branches
Driver.prototype.mergeBranches = function(from, to, opts) {
    return this.api('post', 'merges', {
        base: to,
        head: from,
        commit_message: opts.message
    });
};

// List commits
// https://developer.github.com/v3/repos/commits/#list-commits-on-a-repository
// todo: handle pagination and opts.start/opts.limit
Driver.prototype.listCommits = function(opts) {
    return this.api('get', 'commits', { sha: opts.ref })
    .then(function(commits) {
        return _.map(commits, normCommit);
    });
};

// Get a single commit
// https://developer.github.com/v3/repos/commits/#get-a-single-commit
Driver.prototype.getCommit = function(sha) {
    return this.api('get', 'commits/'+sha)
    .then(normCommit);
};

// Compare two commits
// https://developer.github.com/v3/repos/commits/#compare-two-commits
Driver.prototype.compareCommits = function(base, head, opts) {
    return this.api('get', 'compare/'+[base, head].join('...'))
    .then(function(r) {
        return {
            'status': r.status,
            'ahead_by': r.ahead_by,
            'behind_by': r.behind_by,
            'total_commits': r.total_commits,
            'base': normCommit(r.base_commit),
            'head': normCommit(r.merge_base_commit),
            'commits': _.map(r.commits, normCommit),
            'files': _.map(r.files, normPatch)
        };
    });
};

// List remotes
// Not supported on api.github.com
Driver.prototype.listRemotes = function(opts) {
    return this.api('get', 'remotes', opts);
};

// Edit a remote
// Not supported on api.github.com
Driver.prototype.editRemote = function(opts) {
    return this.api('post', 'remotes', opts);
};

// Checkout a branch
// Not supported on api.github.com
Driver.prototype.checkout = function(branch, opts) {
    var that = this;

    return Q()
    .then(function() {
        if (branch.is_local === undefined) return;
        return that.api('post', 'checkout', {
            branch: branch.name,
            remote: opts.remote
        });
    });
};

// Fetch a remote
// Not supported on api.github.com
Driver.prototype.fetch = function(opts) {
    return this.api('post', 'fetch', opts);
};

// Push to a remote
// Not supported on api.github.com
Driver.prototype.push = function(opts) {
    return this.api('post', 'push', opts);
};

// Pull from a remote
// Not supported on api.github.com
Driver.prototype.pull = function(opts) {
    return this.api('post', 'pull', opts);
};

Driver.id = 'github';
module.exports = Driver;

<commit_msg>Should accept oauth token<commit_after>var _ = require('lodash');
var Q = require('q');
var axios = require('axios');
var urlJoin = require('urljoin.js');

var base64 = require('../utils/base64');
var arrayBuffer = require('../utils/arraybuffer');

// 1MB max size to return
var CONTENT_MAX_SIZE = 1*1024*1024;

// Get author from commit
function getAuthor(commit) {
    return  {
        'name': commit.commit.author.name,
        'email': commit.commit.author.email,
        'avatar': commit.author? commit.author.avatar_url : undefined
    };
}

// Normalize a patch
function normPatch(file) {
    return {
        filename: file.filename,
        patch: file.patch
    };
}

// Normalize a commit
function normCommit(commit) {
    var r = {
        'sha': commit.sha,
        'author': getAuthor(commit),
        'message': commit.commit.message,
        'date': commit.commit.author.date
    };
    if (commit.files) {
        r.files = _.map(commit.files, normPatch);
    }
    return r;
}

function Driver(options, fs) {
    this.fs = fs;
    this.options = _.defaults({}, options || {}, {
        repository: null,
        host: 'https://api.github.com',
        rawhost: 'https://raw.githubusercontent.com',
        username: null,
        token: null,
        includeTokenInRaw: false

    });
    if (!this.options.repository) throw new Error('GitHub driver requires a "repository" option');
}

// Return a raw url for a file
Driver.prototype.rawUrl = function(file) {
    return this.options.rawhost
        .replace(':repo', this.options.repository)
        .replace(':branch', this.fs.getCurrentBranch())
        .replace(':file', file);
};

// Execute an HTTP API request
Driver.prototype.api = function (httpMethod, method, args, options) {
    var opts = {
        method: httpMethod,
        url: urlJoin(this.options.host, '/repos/'+this.options.repository+'/'+method)+'?t='+Date.now(),
        headers: {
            'Accept': 'application/vnd.github.v3+json',
            'Content-type': 'application/json;charset=UTF-8'
        }
    };

    if (this.options.username && this.options.token) {
        opts.headers['Authorization'] = 'Basic ' + base64.encode(this.options.username + ':' + this.options.token);
    } else if (this.options.token) {
        opts.headers['Authorization'] = 'Token ' + this.options.token;
    }

    if (httpMethod == 'get') opts.params = args;
    else opts.data = args;

    return Q(axios(opts))
    .get('data')
    .fail(function(response) {
        if (response instanceof Error) throw response;

        var e = new Error(response.data.message || 'Error '+response.status+': '+response.data);
        e.statusCode = response.status;

        throw e;
    });
};

// Fetch all tree
Driver.prototype.fetchTree = function() {
    return this.api('get', 'git/trees/'+this.fs.currentBranch, {
        recursive: 1
    })
    .then(function(r) {
        return {
            sha: r.sha,
            entries: _.chain(r.tree)
                .map(function(entry) {
                    return [
                        entry.path,
                        {
                            sha: entry.sha,
                            path: entry.path,
                            size: entry.size
                        }
                    ];
                })
                .object()
                .value()
        };
    });
};

// Fetch content of a blob
Driver.prototype.fetchBlob = function(sha) {
    return this.api('get', 'git/blobs/'+sha)
    .then(function(r) {
        return {
            size: r.size,
            content: ((_.isString(r.content) && r.size < CONTENT_MAX_SIZE)? arrayBuffer.fromBase64(r.content.replace(/(\r\n|\n|\r)/gm,'')) : undefined)
        };
    });
};

// Commit pending changes
Driver.prototype.commitChanges = function(base, commit) {
    var that = this, newTree;

    return Q()
    .then(function() {
        newTree = {
            tree: _.values(commit.tree)
        };

        // Create new blobs
        return _.reduce(newTree.tree, function(prev, entry) {
            // Entry didn't changed
            if (entry.sha) return prev;

            return prev.then(function() {
                return that.api('post', 'git/blobs', {
                    content: entry.buffer,
                    encoding: 'base64'
                })
                .then(function(blob) {
                    entry.type = 'blob';
                    entry.sha = blob.sha;
                    entry.mode = entry.mode || '100644';
                });
            });
        }, Q());
    })

    // Create new tree
    .then(function() {
        return that.api('post', 'git/trees', newTree);
    })

    // Finally, create the new commit
    .then(function(tree) {
        return that.api('post', 'git/commits', {
            message: commit.message,
            parents: [base],
            tree: [tree.sha]
        });
    })

    // Update HEAD of branch
    .then(function(commit) {
        return that.api('post', 'git/refs/'+that.fs.currentBranch, {
            sha: commit.sha
        });
    });
};

// List branches
Driver.prototype.listBranches = function() {
    return this.api('get', 'branches')
    .then(function(branches) {
        return _.map(branches, function(branch) {
            return {
                name: branch.name,
                commit: branch.commit.sha,
                is_local: branch.is_local
            };
        });
    });
};

// Create a branch
Driver.prototype.createBranch = function(name, from) {
    var that = this;

    return this.api('get', 'branches/'+from)
    .then(function(branch) {
        return that.api('post', 'git/refs', {
            'ref': 'refs/heads/'+name,
            'sha': branch.commit.sha
        });
    });
};

// Remove a branch
Driver.prototype.removeBranch = function(name) {
    return this.api('delete', 'git/refs/heads/'+name);
};

// Merge branches
Driver.prototype.mergeBranches = function(from, to, opts) {
    return this.api('post', 'merges', {
        base: to,
        head: from,
        commit_message: opts.message
    });
};

// List commits
// https://developer.github.com/v3/repos/commits/#list-commits-on-a-repository
// todo: handle pagination and opts.start/opts.limit
Driver.prototype.listCommits = function(opts) {
    return this.api('get', 'commits', { sha: opts.ref })
    .then(function(commits) {
        return _.map(commits, normCommit);
    });
};

// Get a single commit
// https://developer.github.com/v3/repos/commits/#get-a-single-commit
Driver.prototype.getCommit = function(sha) {
    return this.api('get', 'commits/'+sha)
    .then(normCommit);
};

// Compare two commits
// https://developer.github.com/v3/repos/commits/#compare-two-commits
Driver.prototype.compareCommits = function(base, head, opts) {
    return this.api('get', 'compare/'+[base, head].join('...'))
    .then(function(r) {
        return {
            'status': r.status,
            'ahead_by': r.ahead_by,
            'behind_by': r.behind_by,
            'total_commits': r.total_commits,
            'base': normCommit(r.base_commit),
            'head': normCommit(r.merge_base_commit),
            'commits': _.map(r.commits, normCommit),
            'files': _.map(r.files, normPatch)
        };
    });
};

// List remotes
// Not supported on api.github.com
Driver.prototype.listRemotes = function(opts) {
    return this.api('get', 'remotes', opts);
};

// Edit a remote
// Not supported on api.github.com
Driver.prototype.editRemote = function(opts) {
    return this.api('post', 'remotes', opts);
};

// Checkout a branch
// Not supported on api.github.com
Driver.prototype.checkout = function(branch, opts) {
    var that = this;

    return Q()
    .then(function() {
        if (branch.is_local === undefined) return;
        return that.api('post', 'checkout', {
            branch: branch.name,
            remote: opts.remote
        });
    });
};

// Fetch a remote
// Not supported on api.github.com
Driver.prototype.fetch = function(opts) {
    return this.api('post', 'fetch', opts);
};

// Push to a remote
// Not supported on api.github.com
Driver.prototype.push = function(opts) {
    return this.api('post', 'push', opts);
};

// Pull from a remote
// Not supported on api.github.com
Driver.prototype.pull = function(opts) {
    return this.api('post', 'pull', opts);
};

Driver.id = 'github';
module.exports = Driver;

<|endoftext|>


<commit_before>var AWS = require('aws-sdk');

module.exports = new DynaSidekick();

function DynaSidekick(){
	var self = this;

	self.GetDynamoConnection = function(config){
		var awsOptions = {region: config.region, profile: config.awsProfile};
		if (config.dynamoDb.localEndpoint) {
			awsOptions.endpoint = new AWS.Endpoint(config.dynamoDb.localEndpoint);
		}

		return new AWS.DynamoDB(awsOptions);
	};

	self.ParseIsoDate = function(dateStr){
		// Date.parseExact(data.ModifiedOn.S, 'yyyy-MM-ddTHH:mm:ss.sssZ');
		var year = parseInt(dateStr.substr(0, 4));
		var mon = parseInt(dateStr.substr(5, 2))-1;
		var day = parseInt(dateStr.substr(8, 2));
		var hr = parseInt(dateStr.substr(11, 2));
		var min = parseInt(dateStr.substr(14, 2));
		var sec = parseInt(dateStr.substr(17, 2));
		var ms = parseInt(dateStr.substr(20, 3));

		var d = new Date(year, mon, day, hr, min, sec, ms);
		d.setTime(d.getTime() + (d.getTimezoneOffset() * -1) * 60000);

		return d;
	};

	self.DynamoUpdateFormatter = function(modelPropertyValue, dataType) {
		var property = {};

		var propValue = modelPropertyValue.toString();

		if (propValue && propValue.length > 0) {
			property.Value = {};
			property.Value[dataType] = propValue;
			property.Action = "PUT";
		}
		else { property.Action = "DELETE"; }

		return property;
	};

	self.GetDynamoValue = function(dynamoVal, itemProperties){
		var dType = itemProperties.dynamo.type;

		if (dynamoVal) {
			var raw = dynamoVal[dType];
			if (itemProperties.type === 'date-iso') { return self.ParseIsoDate(raw); }
			else if (dType === 'N') { return parseInt(raw); }
			else if (dType === 'N') {
				var result = [];
				raw.forEach(function(val){ result.push(parseInt(val)); });
				return result;
			}
			else { return raw; }
		} else {
			if (dType === "SS" || dType === "NS" || dType === "BN" || dType === "L") { return []; }
			else if (dType === "M") { return {}; }
			else { return null; }
		}
	};

	self.SimpleQuery = function(conditions){
		var callback_ = arguments[arguments.length - 1];
		var callback = (typeof(callback_) == 'function' ? callback_ : function(){});

		var params = {'TableName': tableName};
		if (conditions) {
			params.KeyConditions = conditions;
		}

		dynamodb.query(params,function(err, data) {
			callback(err, data);
		});
	};

/*	self.LoadData = function(data) {
		var callback_ = arguments[arguments.length - 1];
		var callback = (typeof(callback_) == 'function' ? callback_ : function(){});

		var key = {
			ConspiracyId:{S: data.ConspiracyId}
		};
		var params = {
			Key: key,
			TableName: config.conspiracies.tableName // required
			//ProjectionExpression: 'STRING_VALUE'
		};
		dynamodb.getItem(params, function(err, data) {
			if (err) { callback(err); }
			else {
				for(var field in dataModel){
					var dName = dataModel[field].dynamo.name;

					self[field] = dynaHlpr.GetDynamoValue(data[dName], dataModel[field])
				}

				callback(null, data);
			}
		});
	};
*/

	self.SaveItem = function(dataModel, values, config){
		var callback_ = arguments[arguments.length - 1];
		var callback = (typeof(callback_) == 'function' ? callback_ : function(){});

		var itemParams = {};

		for(var field in dataModel.data){
			var fieldModel = dataModel[field];

			if (field in values) {
				itemParams[dataModel.dynamo.name] = self.DynamoUpdateFormatter(values[field], dataModel.dynamo.type);
			}
		}
		// If modified data not set, set it now
		if (!values.ModifiedOn) {
			var modDate = new Date();
			itemParams.ModifiedOn = {Value:{S: modDate.toISOString()},Action:"PUT"}
		}

		var key = {};
		for(var keyItem in dataModel.key) {
			var dynamoModel = dataModel.key[keyItem].dynamo;
			key[dynamoModel.name] = {};
			key[dynamoModel.name][dynamoModel.type] = values[keyItem];
		}

		var params = {'TableName': config.tableName,
			'Key': key,
			'AttributeUpdates': itemParams,
			'ReturnValues': 'UPDATED_NEW'
		};

		var dynamoDb = self.GetDynamoConnection(config);
		dynamoDb.updateItem(params, function(err, data) {
			if (err) { callback(err); }
			else { callback(null, data); }
		});
	};

};
<commit_msg>Fix to save item<commit_after>var AWS = require('aws-sdk');

module.exports = new DynaSidekick();

function DynaSidekick(){
	var self = this;

	self.GetDynamoConnection = function(config){
		var awsOptions = {region: config.region, profile: config.awsProfile};
		if (config.dynamoDb.localEndpoint) {
			awsOptions.endpoint = new AWS.Endpoint(config.dynamoDb.localEndpoint);
		}

		return new AWS.DynamoDB(awsOptions);
	};

	self.ParseIsoDate = function(dateStr){
		// Date.parseExact(data.ModifiedOn.S, 'yyyy-MM-ddTHH:mm:ss.sssZ');
		var year = parseInt(dateStr.substr(0, 4));
		var mon = parseInt(dateStr.substr(5, 2))-1;
		var day = parseInt(dateStr.substr(8, 2));
		var hr = parseInt(dateStr.substr(11, 2));
		var min = parseInt(dateStr.substr(14, 2));
		var sec = parseInt(dateStr.substr(17, 2));
		var ms = parseInt(dateStr.substr(20, 3));

		var d = new Date(year, mon, day, hr, min, sec, ms);
		d.setTime(d.getTime() + (d.getTimezoneOffset() * -1) * 60000);

		return d;
	};

	self.DynamoUpdateFormatter = function(modelPropertyValue, dataType) {
		var property = {};

		var propValue = modelPropertyValue.toString();

		if (propValue && propValue.length > 0) {
			property.Value = {};
			property.Value[dataType] = propValue;
			property.Action = "PUT";
		}
		else { property.Action = "DELETE"; }

		return property;
	};

	self.GetDynamoValue = function(dynamoVal, itemProperties){
		var dType = itemProperties.dynamo.type;

		if (dynamoVal) {
			var raw = dynamoVal[dType];
			if (itemProperties.type === 'date-iso') { return self.ParseIsoDate(raw); }
			else if (dType === 'N') { return parseInt(raw); }
			else if (dType === 'N') {
				var result = [];
				raw.forEach(function(val){ result.push(parseInt(val)); });
				return result;
			}
			else { return raw; }
		} else {
			if (dType === "SS" || dType === "NS" || dType === "BN" || dType === "L") { return []; }
			else if (dType === "M") { return {}; }
			else { return null; }
		}
	};

	self.SimpleQuery = function(conditions){
		var callback_ = arguments[arguments.length - 1];
		var callback = (typeof(callback_) == 'function' ? callback_ : function(){});

		var params = {'TableName': tableName};
		if (conditions) {
			params.KeyConditions = conditions;
		}

		dynamodb.query(params,function(err, data) {
			callback(err, data);
		});
	};

/*	self.LoadData = function(data) {
		var callback_ = arguments[arguments.length - 1];
		var callback = (typeof(callback_) == 'function' ? callback_ : function(){});

		var key = {
			ConspiracyId:{S: data.ConspiracyId}
		};
		var params = {
			Key: key,
			TableName: config.conspiracies.tableName // required
			//ProjectionExpression: 'STRING_VALUE'
		};
		dynamodb.getItem(params, function(err, data) {
			if (err) { callback(err); }
			else {
				for(var field in dataModel){
					var dName = dataModel[field].dynamo.name;

					self[field] = dynaHlpr.GetDynamoValue(data[dName], dataModel[field])
				}

				callback(null, data);
			}
		});
	};
*/

	self.SaveItem = function(dataModel, values, config){
		var callback_ = arguments[arguments.length - 1];
		var callback = (typeof(callback_) == 'function' ? callback_ : function(){});

		var itemParams = {};

		for(var field in dataModel.data){
			var fieldModel = dataModel[field];

			if (field in values) {
				itemParams[fieldModel.dynamo.name] = self.DynamoUpdateFormatter(values[field], dataModel.dynamo.type);
			}
		}
		// If modified data not set, set it now
		if (!values.ModifiedOn) {
			var modDate = new Date();
			itemParams.ModifiedOn = {Value:{S: modDate.toISOString()},Action:"PUT"}
		}

		var key = {};
		for(var keyItem in dataModel.key) {
			var dynamoModel = dataModel.key[keyItem].dynamo;
			key[dynamoModel.name] = {};
			key[dynamoModel.name][dynamoModel.type] = values[keyItem];
		}

		var params = {'TableName': config.tableName,
			'Key': key,
			'AttributeUpdates': itemParams,
			'ReturnValues': 'UPDATED_NEW'
		};

		var dynamoDb = self.GetDynamoConnection(config);
		dynamoDb.updateItem(params, function(err, data) {
			if (err) { callback(err); }
			else { callback(null, data); }
		});
	};

};
<|endoftext|>


<commit_before>/*
 * Copyright 2015-2016 OpenCB
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import {LitElement, html} from "lit";
import UtilsNew from "../../../core/utilsNew.js";
import "../forms/select-field-filter.js";

export default class ClinicalPriorityFilter extends LitElement {

    constructor() {
        super();

        // Set status and init private properties
        this._init();
    }

    createRenderRoot() {
        return this;
    }

    static get properties() {
        return {
            priorities: {
                type: Array
            },
            priority: {
                type: String
            },
            placeholder: {
                type: String
            },
            config: {
                type: Object
            }
        };
    }

    _init() {
        this._prefix = UtilsNew.randomString(6) + "_";
    }

    connectedCallback() {
        super.connectedCallback();
        this._config = {...this.getDefaultConfig(), ...this.config};
    }

    // update(changedProperties) {
    //     if (changedProperties.has("priority")) {
    //     }
    //     super.update(changedProperties);
    // }

    filterChange(e) {
        const event = new CustomEvent("filterChange", {
            detail: {
                value: e.detail.value
            }
        });
        this.dispatchEvent(event);
    }

    getDefaultConfig() {
        return {
            priorities: ["URGENT", "HIGH", "MEDIUM", "LOW"],
            multiple: true
        };
    }

    render() {
        return html`
            <select-field-filter
                .placeholder="${this.placeholder}"
                ?multiple="${this._config.multiple}"
                .data="${this.priorities?.length ? this.priorities : this._config.priorities}"
                .value=${this.priority}
                multiple
                @filterChange="${e => this.filterChange(e)}">
            </select-field-filter>
        `;
    }

}

customElements.define("clinical-priority-filter", ClinicalPriorityFilter);
<commit_msg>wc: code fixes and improvements in clinical-priority-filter<commit_after>/*
 * Copyright 2015-2016 OpenCB
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import {LitElement, html} from "lit";
import "../forms/select-field-filter.js";

export default class ClinicalPriorityFilter extends LitElement {

    constructor() {
        super();

        // Set status and init private properties
        this._init();
    }

    createRenderRoot() {
        return this;
    }

    static get properties() {
        return {
            priority: {
                type: String
            },
            priorities: {
                type: Array
            },
            placeholder: {
                type: String
            },
            multiple: {
                type: Boolean
            },
            classes: {
                type: String
            },
            disabled: {
                type: Boolean
            },
        };
    }

    _init() {
        this.priorities = ["URGENT", "HIGH", "MEDIUM", "LOW"];
        this.multiple = true;
        this.disabled = false;
    }

    filterChange(e) {
        const event = new CustomEvent("filterChange", {
            detail: {
                value: e.detail.value,
                query: {
                    priority: e.detail.value
                }
            }
        });
        this.dispatchEvent(event);
    }

    render() {
        return html`
            <select-field-filter
                .data="${this.priorities}"
                .value=${this.priority}
                .placeholder="${this.placeholder}"
                ?multiple="${this.multiple}"
                .classes="${this.classes}"
                .disabled="${this.disabled}"
                @filterChange="${e => this.filterChange(e)}">
            </select-field-filter>
        `;
    }

}

customElements.define("clinical-priority-filter", ClinicalPriorityFilter);
<|endoftext|>


<commit_before>import React, { useState } from 'react';
import { c } from 'ttag';
import PropTypes from 'prop-types';
import {
    Modal,
    Alert,
    ContentModal,
    FooterModal,
    PrimaryButton,
    Label,
    TextArea,
    Block,
    ResetButton,
    useApiWithoutResult,
    useUserSettings
} from 'react-components';
import { updateInvoiceText } from 'proton-shared/lib/api/settings';

const InvoiceTextModal = ({ show, onClose }) => {
    const [{ InvoiceText }] = useUserSettings();
    const [invoiceText, setInvoiceText] = useState(InvoiceText);
    const handleChange = ({ target }) => setInvoiceText(target.value);
    const { request, loading } = useApiWithoutResult(() => updateInvoiceText(invoiceText));

    return (
        <Modal type="small" show={show} onClose={onClose} title={c('Title').t`Add invoice details`}>
            <ContentModal onSubmit={request} onReset={onClose}>
                <Alert>{c('Info message for custom invoice modal')
                    .t`Add your name (or company name) and address to your invoices.`}</Alert>
                <Block>
                    {c('Label').t`Customize invoices`}
                </Block>
                <TextArea
                    id="invoiceTextarea"
                    autoFocus
                    value={invoiceText}
                    placeholder={c('Placeholder for custom invoice text')
                        .t`Add your name (or company name) and address to your invoices`}
                    onChange={handleChange}
                    disabled={loading}
                />
                <FooterModal>
                    <ResetButton disabled={loading}>{c('Action').t`Close`}</ResetButton>
                    <PrimaryButton loading={loading} type="submit">{c('Action').t`Save`}</PrimaryButton>
                </FooterModal>
            </ContentModal>
        </Modal>
    );
};

InvoiceTextModal.propTypes = {
    show: PropTypes.bool.isRequired,
    onClose: PropTypes.func.isRequired
};

export default InvoiceTextModal;
<commit_msg>Fix #18 - Handle submit properly<commit_after>import React, { useState } from 'react';
import { c } from 'ttag';
import PropTypes from 'prop-types';
import {
    Modal,
    Alert,
    ContentModal,
    FooterModal,
    PrimaryButton,
    Label,
    TextArea,
    Block,
    ResetButton,
    useApiWithoutResult,
    useUserSettings,
    useEventManager,
    useNotifications
} from 'react-components';
import { updateInvoiceText } from 'proton-shared/lib/api/settings';

const InvoiceTextModal = ({ show, onClose }) => {
    const [{ InvoiceText }] = useUserSettings();
    const { createNotification } = useNotifications();
    const { call } = useEventManager();
    const [invoiceText, setInvoiceText] = useState(InvoiceText);
    const handleChange = ({ target }) => setInvoiceText(target.value);
    const { request, loading } = useApiWithoutResult(() => updateInvoiceText(invoiceText));

    const handleSubmit = async () => {
        await request();
        await call();
        onClose();
        createNotification({ text: c('Success').t`Invoice customized` });
    };

    return (
        <Modal type="small" show={show} onClose={onClose} title={c('Title').t`Add invoice details`}>
            <ContentModal onSubmit={handleSubmit} onReset={onClose}>
                <Alert>{c('Info message for custom invoice modal')
                    .t`Add your name (or company name) and address to your invoices.`}</Alert>
                <Block>
                    {c('Label').t`Customize invoices`}
                </Block>
                <TextArea
                    id="invoiceTextarea"
                    autoFocus
                    required
                    value={invoiceText}
                    placeholder={c('Placeholder for custom invoice text')
                        .t`Add your name (or company name) and address to your invoices`}
                    onChange={handleChange}
                    disabled={loading}
                />
                <FooterModal>
                    <ResetButton disabled={loading}>{c('Action').t`Close`}</ResetButton>
                    <PrimaryButton loading={loading} type="submit">{c('Action').t`Save`}</PrimaryButton>
                </FooterModal>
            </ContentModal>
        </Modal>
    );
};

InvoiceTextModal.propTypes = {
    show: PropTypes.bool.isRequired,
    onClose: PropTypes.func.isRequired
};

export default InvoiceTextModal;
<|endoftext|>


<commit_before>var AWS = require('aws-sdk');

module.exports = new DynaSidekick();

function DynaSidekick(){
	var self = this;

	self.GetDynamoConnection = function(config){
		var awsOptions = {region: config.region, profile: config.awsProfile};
		if (config.dynamoDb.localEndpoint) {
			awsOptions.endpoint = new AWS.Endpoint(config.dynamoDb.localEndpoint);
		}

		return new AWS.DynamoDB(awsOptions);
	};

	self.ParseIsoDate = function(dateStr){
		// Date.parseExact(data.ModifiedOn.S, 'yyyy-MM-ddTHH:mm:ss.sssZ');
		var year = parseInt(dateStr.substr(0, 4));
		var mon = parseInt(dateStr.substr(5, 2))-1;
		var day = parseInt(dateStr.substr(8, 2));
		var hr = parseInt(dateStr.substr(11, 2));
		var min = parseInt(dateStr.substr(14, 2));
		var sec = parseInt(dateStr.substr(17, 2));
		var ms = parseInt(dateStr.substr(20, 3));

		var d = new Date(year, mon, day, hr, min, sec, ms);
		d.setTime(d.getTime() + (d.getTimezoneOffset() * -1) * 60000);

		return d;
	};

	self.DynamoUpdateFormatter = function(modelPropertyValue, dataType) {
		var property = {};

		var propValue = modelPropertyValue.toString();

		if (propValue && propValue.length > 0) {
			property.Value = {};
			property.Value[dataType] = propValue;
			property.Action = "PUT";
		}
		else { property.Action = "DELETE"; }

		return property;
	};

	self.GetDynamoValue = function(dynamoVal, itemProperties){
		var dType = itemProperties.dynamo.type;

		if (dynamoVal) {
			var raw = dynamoVal[dType];
			if (itemProperties.type === 'date-iso') { return self.ParseIsoDate(raw); }
			else if (dType === 'N') { return parseInt(raw); }
			else if (dType === 'N') {
				var result = [];
				raw.forEach(function(val){ result.push(parseInt(val)); });
				return result;
			}
			else { return raw; }
		} else {
			if (dType === "SS" || dType === "NS" || dType === "BN" || dType === "L") { return []; }
			else if (dType === "M") { return {}; }
			else { return null; }
		}
	};

	self.SimpleQuery = function(config, conditions){
		var callback_ = arguments[arguments.length - 1];
		var callback = (typeof(callback_) == 'function' ? callback_ : function(){});

		var params = {'TableName': config.tableName};
		if (conditions) {
			params.KeyConditions = conditions;
		}

		var dynamoDb = self.GetDynamoConnection(config);
		dynamoDb.query(params,function(err, data) {
			callback(err, data);
		});
	};

	self.SimpleScan = function(config, limit, start){
		var callback_ = arguments[arguments.length - 1];
		var callback = (typeof(callback_) == 'function' ? callback_ : function(){});

		var params = {'TableName': config.tableName, 'Limit': limit};

		var dynamoDb = self.GetDynamoConnection(config);
		dynamoDb.scan(params,function(err, data) {
			callback(err, data);
		});
	};

	self.SaveItem = function(dataModel, values, config){
		var callback_ = arguments[arguments.length - 1];
		var callback = (typeof(callback_) == 'function' ? callback_ : function(){});

		var itemParams = {};

		for(var field in dataModel.data){
			var dynaSpec = dataModel.data[field].dynamo;

			if (field in values) {
				itemParams[dynaSpec.name] = self.DynamoUpdateFormatter(values[field], dynaSpec.type);
			}
		}
		// If modified data not set, set it now
		if (!values.ModifiedOn) {
			var modDate = new Date();
			itemParams.ModifiedOn = {Value:{S: modDate.toISOString()},Action:"PUT"}
		}

		var key = {};
		for(var keyItem in dataModel.key) {
			var dynaSpec = dataModel.key[keyItem].dynamo;
			key[dynaSpec.name] = {};
			key[dynaSpec.name][dynaSpec.type] = values[keyItem];
		}

		var params = {'TableName': config.tableName,
			'Key': key,
			'AttributeUpdates': itemParams,
			'ReturnValues': 'UPDATED_NEW'
		};

		var dynamoDb = self.GetDynamoConnection(config);
		dynamoDb.updateItem(params, function(err, data) {
			if (err) { callback(err); }
			else { callback(null, data); }
		});
	};

};
<commit_msg>Added support for updating arrays<commit_after>var AWS = require('aws-sdk');

module.exports = new DynaSidekick();

function DynaSidekick(){
	var self = this;

	self.GetDynamoConnection = function(config){
		var awsOptions = {region: config.region, profile: config.awsProfile};
		if (config.dynamoDb.localEndpoint) {
			awsOptions.endpoint = new AWS.Endpoint(config.dynamoDb.localEndpoint);
		}

		return new AWS.DynamoDB(awsOptions);
	};

	self.ParseIsoDate = function(dateStr){
		// Date.parseExact(data.ModifiedOn.S, 'yyyy-MM-ddTHH:mm:ss.sssZ');
		var year = parseInt(dateStr.substr(0, 4));
		var mon = parseInt(dateStr.substr(5, 2))-1;
		var day = parseInt(dateStr.substr(8, 2));
		var hr = parseInt(dateStr.substr(11, 2));
		var min = parseInt(dateStr.substr(14, 2));
		var sec = parseInt(dateStr.substr(17, 2));
		var ms = parseInt(dateStr.substr(20, 3));

		var d = new Date(year, mon, day, hr, min, sec, ms);
		d.setTime(d.getTime() + (d.getTimezoneOffset() * -1) * 60000);

		return d;
	};

	self.DynamoUpdateFormatter = function(modelPropertyValue, dataType) {
		var property = {};

		var propValue = modelPropertyValue;
		var put = false;
		if (dataType === "S" && typeof propValue === 'string' && propValue.length > 0) put = true;
		if (dataType === "N" && typeof propValue === 'number') put = true;
		if ((dataType === "SS" || dataType === "NN") && propValue.isArray && propValue.length > 0) put = true;

		if (put) {
			if (dataType === "S" || dataType === "N") propValue = propValue.toString();
			property.Value = {};
			property.Value[dataType] = propValue;
			property.Action = "PUT";
		}
		else { property.Action = "DELETE"; }

		return property;
	};

	self.GetDynamoValue = function(dynamoVal, itemProperties){
		var dType = itemProperties.dynamo.type;

		if (dynamoVal) {
			var raw = dynamoVal[dType];
			if (itemProperties.type === 'date-iso') { return self.ParseIsoDate(raw); }
			else if (dType === 'N') { return parseInt(raw); }
			else if (dType === 'N') {
				var result = [];
				raw.forEach(function(val){ result.push(parseInt(val)); });
				return result;
			}
			else { return raw; }
		} else {
			if (dType === "SS" || dType === "NS" || dType === "BN" || dType === "L") { return []; }
			else if (dType === "M") { return {}; }
			else { return null; }
		}
	};

	self.SimpleQuery = function(config, conditions){
		var callback_ = arguments[arguments.length - 1];
		var callback = (typeof(callback_) == 'function' ? callback_ : function(){});

		var params = {'TableName': config.tableName};
		if (conditions) {
			params.KeyConditions = conditions;
		}

		var dynamoDb = self.GetDynamoConnection(config);
		dynamoDb.query(params,function(err, data) {
			callback(err, data);
		});
	};

	self.SimpleScan = function(config, limit, start){
		var callback_ = arguments[arguments.length - 1];
		var callback = (typeof(callback_) == 'function' ? callback_ : function(){});

		var params = {'TableName': config.tableName, 'Limit': limit};

		var dynamoDb = self.GetDynamoConnection(config);
		dynamoDb.scan(params,function(err, data) {
			callback(err, data);
		});
	};

	self.SaveItem = function(dataModel, values, config){
		var callback_ = arguments[arguments.length - 1];
		var callback = (typeof(callback_) == 'function' ? callback_ : function(){});

		var itemParams = {};

		for(var field in dataModel.data){
			var dynaSpec = dataModel.data[field].dynamo;

			if (values.hasOwnProperty(field)) {
				itemParams[dynaSpec.name] = self.DynamoUpdateFormatter(values[field], dynaSpec.type);
			}
		}
		// If modified data not set, set it now
		if (!values.ModifiedOn) {
			var modDate = new Date();
			itemParams.ModifiedOn = {Value:{S: modDate.toISOString()},Action:"PUT"}
		}

		var key = {};
		for(var keyItem in dataModel.key) {
			var dynaSpec = dataModel.key[keyItem].dynamo;
			key[dynaSpec.name] = {};
			key[dynaSpec.name][dynaSpec.type] = values[keyItem];
		}

		var params = {'TableName': config.tableName,
			'Key': key,
			'AttributeUpdates': itemParams,
			'ReturnValues': 'UPDATED_NEW'
		};

		var dynamoDb = self.GetDynamoConnection(config);
		dynamoDb.updateItem(params, function(err, data) {
			if (err) { callback(err); }
			else { callback(null, data); }
		});
	};

};
<|endoftext|>


<commit_before>var authorizer;

var xhrMock;
var XhrMock = Ember.Object.extend({
  init: function() {
    this.requestHeaders = {};
  },
  setRequestHeader: function(name, value) {
    this.requestHeaders[name] = value;
  }
});

module('Ember.SimpleAuth.Authorizers.OAuth2', {
  setup: function() {
    xhrMock    = XhrMock.create();
    authorizer = Ember.SimpleAuth.Authorizers.OAuth2.create({ session: Ember.SimpleAuth.Session.create() });
  },
  teardown: function() {
    Ember.run.cancel(Ember.SimpleAuth.Session._syncPropertiesTimeout);
  }
});

test('authorizes an AJAX request', function() {
  authorizer.set('session.authToken', undefined);
  authorizer.authorize(xhrMock, {});
  equal(xhrMock.requestHeaders['Authorization'], undefined, 'Ember.SimpleAuth.Authorizers.OAuth2 does not add the authToken to an AJAX request when the token is not empty.');

  var token = Math.random().toString(36);
  authorizer.set('session.authToken', token);
  authorizer.authorize(xhrMock, {});
  equal(xhrMock.requestHeaders['Authorization'], 'Bearer ' + token, 'Ember.SimpleAuth.Authorizers.OAuth2 adds the authToken to an AJAX request when the token is not empty.');
});
<commit_msg>fixed authorizer test<commit_after>var authorizer;

var sessionMock;

var xhrMock;
var XhrMock = Ember.Object.extend({
  init: function() {
    this.requestHeaders = {};
  },
  setRequestHeader: function(name, value) {
    this.requestHeaders[name] = value;
  }
});

module('Ember.SimpleAuth.Authorizers.OAuth2', {
  setup: function() {
    xhrMock     = XhrMock.create();
    sessionMock = Ember.Object.create();
    authorizer  = Ember.SimpleAuth.Authorizers.OAuth2.create({ session: sessionMock });
  }
});

test('authorizes an AJAX request', function() {
  authorizer.set('session.authToken', undefined);
  authorizer.authorize(xhrMock, {});
  equal(xhrMock.requestHeaders['Authorization'], undefined, 'Ember.SimpleAuth.Authorizers.OAuth2 does not add the authToken to an AJAX request when the token is not empty.');

  var token = Math.random().toString(36);
  authorizer.set('session.authToken', token);
  authorizer.authorize(xhrMock, {});
  equal(xhrMock.requestHeaders['Authorization'], 'Bearer ' + token, 'Ember.SimpleAuth.Authorizers.OAuth2 adds the authToken to an AJAX request when the token is not empty.');
});
<|endoftext|>


<commit_before>var app_version = '1.0';
var app = {

    initialize: function() {
        this.bind();
    },

    bind: function() {
        document.addEventListener("deviceready", this.deviceready, false);
        document.addEventListener("backbutton", closeScan, false);
        //document.addEventListener("online", function(){alert('online');}, false);
        //document.addEventListener("offline", function(){alert('offline');}, false);
        $('#normal_bulk').on("filterablebeforefilter", bulk_keypress_cb);
        $('#normal_bulk').on("tap", "li", select_bulk_cb);
        $('#normal_layer').on("change", set_layer_cb);
        $('#normal_employee').on("tap", bc_pressed);
        $('#normal_operation').on("tap", bc_pressed);
        $('#normal_bt_submit').on("tap", normal_submit);

        $('#flagno_bulk').on("filterablebeforefilter", bulk_keypress_cb);
        $('#flagno_bulk').on("tap", "li", select_bulk_cb);
        $('#flagno_employee').on("tap", bc_pressed);
        $('#flagno_bt_submit').on("tap", flagno_submit);
        $('#flagno_hours_container').on("slidestop", '#flagno_hours', hours_flagno_select);
        $('#flagno_minutes_container').on("slidestop", '#flagno_minutes', minutes_flagno_select);
    },

    deviceready: function() {
        app.start();
    },

    start: function() {
        //alert('application started...');
    }
};

var normal_data = {};
var flagno_data = {};
var scan_in_progress = false;
// var base_url = 'http://192.168.1.1';
var base_url = 'http://192.168.0.11';
var post_url = base_url+'/supervisor_input_b.php';
var get_operations = base_url+'/supervisor_getoperations.php';
var get_flagno_operations = base_url+'/supervisor_getoperations_flagno.php';
var get_bulks = base_url+'/supervisor_getbulks.php';

function is_wifi_enable(){
/*
    var networkState = navigator.connection.type;
    return (networkState == Connection.WIFI);
*/
return true;
}

function bc_pressed(){
    var elem_id = $(this).attr('id');
    if(elem_id == 'normal_employee' || elem_id == 'normal_operation'){
        startScan(elem_id.split('_')[1],'normal');
    } else if(elem_id == 'flagno_employee'){
        startScan(elem_id.split('_')[1],'flagno');
    }
}

function date_select(page){
    /* callback for date select event */
    if(page == 'normal'){
        normal_data['date']=$('#normal_scan_date').val();
    } else if(page == 'flagno'){
        flagno_data['date']=$('#flagno_scan_date').val();
    }
    check_params();
}

function bulk_keypress_cb(e, data){
    var $ul = $( this ),
        $input = $( data.input ),
        value = $input.val(),
        html = "";
    $ul.html( "" );
    //console.log(value);
    if ( value && value.length > 0 ) {
        //console.log('performing ajax call');
        $ul.html( "

" );
        $ul.listview( "refresh" );
        if($.mobile.activePage.attr('id') == 'normal'){
            normal_data['bulk'] = value;
        } else {
            flagno_data['bulk'] = value;
        }
        $.post(get_bulks,{'bulk':value},function(response){
            $.each( response, function ( i, val ) {
                html += "
" + val + "
";
            });
            $ul.html( html );
            $ul.listview( "refresh" );
            $ul.trigger( "updatelayout");
            //console.log(html);
        },'json');
    }
    check_params();
}

function select_bulk_cb(){
    var text = $(this).text();
    //console.log(text);
    $(this).closest("ul").prev("form").find("input").val(text);
    $(this).closest("ul").empty();
    if($.mobile.activePage.attr('id') == 'normal'){
        normal_data['bulk'] = text;
        fill_manual_operation(text);
    } else {
        flagno_data['bulk'] = text;
    }
    check_params();
}

function set_layer_cb(event){
    normal_data['layer'] = event.currentTarget.value;
    check_params();
}

function hours_flagno_select(){
    /* callback for onchange on flagno hours */
    flagno_data['tot_ore_flag_no'] = $('#flagno_hours').val();
    check_params();
}

function minutes_flagno_select(){
    /* callback for onchange on flagno minutes */
    flagno_data['tot_min_flag_no'] = $('#flagno_minutes').val();
    check_params();
}

function operation_flagno_select(elem){
    /* callback for onchange on flagno operation field */
    flagno_data['operation'] = elem.value;
    check_params();
}

function operation_manual_select(elem){
    /* callback for onchange on operation manual */
    normal_data['operation'] = elem.value;
    $('#normal_operation').val(elem.value);
    check_params();
}

function fill_manual_operation(bulk){
    /* get all operation for a bulk and enable select control */
    $.post(get_operations,{'bulk':bulk},function(operations){
        $('#normal_manual_operation').empty().append('<option>Select Operation (for bulk)</option>');
        $.each(operations, function(k,v){
            var opt = '<option value="' +k+ '">'+k+' - '+v+'</option>';
            $('#normal_manual_operation').append(opt);
        });
        $('#normal_manual_operation').selectmenu('refresh',true).selectmenu('enable');
        check_params();
    },'json');
}

function fill_flagno_operations(){
    /* get all flagno operation */
    $.post(get_flagno_operations,function(operations){
        $('#flagno_operation').empty().append('<option>Select Operation</option>');
        $.each(operations, function(k,v){
            var opt = '<option value="' +k+ '">'+k+' - '+v+'</option>';
            $('#flagno_operation').append(opt);
        });
        $('#flagno_operation').selectmenu('refresh',true).selectmenu('enable');
        check_params();
    },'json');
}

function closeScan(){
    /* this is an hack to prevent exiting from the application when
       someone clicks on back button during when the scanner is active */
    if(scan_in_progress){
        alert('Scan cancelled');
    }
}

function check_params(){
    /* Check if all params are correctly set and enable the submit button*/
    /* normal page */
    if(normal_data['date']!='' &&
        normal_data['bulk']!='' &&
        normal_data['operation']!='' &&
        normal_data['employee']!='' &&
        normal_data['layer']!=''){
        $('#normal_bt_submit').removeClass('ui-disabled');
    } else {
        $('#normal_bt_submit').addClass('ui-disabled');
    }

    /* flagno page */
    if(flagno_data['date']!='' &&
        flagno_data['employee']!='' &&
        flagno_data['bulk']!='' &&
        flagno_data['operation']!='' &&
        !(flagno_data['tot_ore_flag_no']=='0' && flagno_data['tot_min_flag_no']=='0'))
    {
        //console.log('ALLOW',flagno_data);
        $('#flagno_bt_submit').removeClass('ui-disabled');
    } else {
        //console.log('DISALLOW',flagno_data);
        $('#flagno_bt_submit').addClass('ui-disabled');
    }
}

function reset_fields(){
    /* reset all fields at app startup and after every submit */
    var d = new Date();
    normal_data = {};
    flagno_data = {};

    /* normal page */
    $('#normal_bt_submit').addClass('ui-disabled');
    $('#normal_employee').val('');
    $('#normal_bulk').val(''); // TODO: comment it!
    $('#normal_manual_operation').selectmenu('disable').empty();
    $('#normal_operation').val('');
    $('#normal_layer').val('1');
    $('#normal_scan_date').val(d.toISOString().split('T')[0]);
    normal_data['date']=$('#normal_scan_date').val();
    normal_data['employee']='';
    normal_data['bulk']='';
    normal_data['operation']='';
    normal_data['layer']='1';
    normal_data['id_device'] = window.localStorage.getItem('id_device');

    /* flag no page */
    $('#flagno_bt_submit').addClass('ui-disabled');
    $('#flagno_employee').val('');
    $('#flagno_bulk').val('');
    $('#flagno_operation').val('');
    $('#flagno_scan_date').val(d.toISOString().split('T')[0]);
    $('#flagno_hours').val('0');
    $('#flagno_minutes').val('0');
    flagno_data['date']=$('#flagno_scan_date').val();
    flagno_data['employee']='';
    flagno_data['bulk']='';
    flagno_data['operation']='';
    flagno_data['tot_ore_flag_no']='0';
    flagno_data['tot_min_flag_no']='0';
    flagno_data['id_device'] = window.localStorage.getItem('id_device');
}

function normal_submit(){
    /* here we have to subm it the data to the server */
    if(!is_wifi_enable()){
        alert('wifi connection is not enable');
        return false;
    }
    $.mobile.loading('show');
    $.post(post_url,normal_data,function(data){
        if(data.OK != undefined && data.OK != ''){
            alert(data.OK);
            $.mobile.loading('hide');
            reset_fields();
        }else{
            alert(data.ERR);
            $.mobile.loading('hide');
        }
    },'json')
    .fail(function(){
        alert('Communication error!');
        $.mobile.loading('hide');
    });
}

function flagno_submit(){
    /* here we have to subm it the data to the server */
    if(!is_wifi_enable()){
        alert('wifi connection is not enable');
        return false;
    }
    $.mobile.loading('show');
    $.post(post_url,flagno_data,function(data){
        if(data.OK != undefined && data.OK != ''){
            alert(data.OK);
            $.mobile.loading('hide');
            reset_fields();
        }else{
            alert(data.ERR);
            $.mobile.loading('hide');
        }
    },'json')
    .fail(function(){
        alert('Communication error!');
        $.mobile.loading('hide');
    });
}

function quit(){
    navigator.app.exitApp();
}

function startScan(elem, page) {
    if(typeof cordova==='undefined'){
        if(page == 'normal'){
            normal_data[elem] = 'testvalue';
            $('#normal_'+elem).val('testvalue');
        } else if(page == 'flagno'){
            flagno_data[elem] = 'testvalue';
            $('#flagno_'+elem).val('testvalue');
        }
        check_params();
        return true;
    }
    scan_in_progress = true;
    $.mobile.loading('show');
    cordova.plugins.barcodeScanner.scan(
    function (result) {
        var s = "Result: " + result.text + "
" +
            "Format: " + result.format + "
" +
            "Cancelled: " + result.cancelled;
        if(!result.cancelled){
            if(page == 'normal'){
                normal_data[elem] = result.text;
                $('#normal_'+elem).val(result.text);
            } else if(page == 'flagno'){
                flagno_data[elem] = result.text;
                $('#flagno_'+elem).val(result.text);
            }
            scan_in_progress = false;
        }
        check_params();
        $.mobile.loading('hide');
    },
    function (error) {
        alert("Scanning failed: " + error);
        scan_in_progress = false;
        $.mobile.loading('hide');
    });
}

function save_id_device(){
    var id_device = $('#id_device').val();
    if(id_device != ''){
        window.localStorage.setItem('id_device',id_device);
        $('.id_device').text(' - '+id_device);
        $("body").pagecontainer("change", "#normal", {
            transition: 'slidedown',
            reload    : true
        });
    }
}

$(document).on('pageinit','#normal',function(){
    $('#version').append(app_version);
    var id_device = window.localStorage.getItem('id_device');
    if(id_device==null){
        $("body").pagecontainer("change", "#line_input", {
            transition: 'slidedown',
            reload    : true
        });
    }
    $('.id_device').text(' - '+id_device);
    /* this is needed only to have a better graphic for input text fields */
    $('.ui-input-text').removeClass('ui-state-disabled');
    reset_fields();
    app.initialize();
});

$(document).on('pageinit','#flagno',function(){
    /* this is needed only to have a better graphic for input text fields */
    $('.ui-input-text').removeClass('ui-state-disabled');
    fill_flagno_operations();
});
<commit_msg>various fixes with Oswaldo<commit_after>var app_version = '1.0';
var app = {

    initialize: function() {
        this.bind();
    },

    bind: function() {
        document.addEventListener("deviceready", this.deviceready, false);
        document.addEventListener("backbutton", closeScan, false);
        //document.addEventListener("online", function(){alert('online');}, false);
        //document.addEventListener("offline", function(){alert('offline');}, false);
        $('#normal_bulk').on("filterablebeforefilter", bulk_keypress_cb);
        $('#normal_bulk').on("tap", "li", select_bulk_cb);
        $('#normal_layer').on("change", set_layer_cb);
        $('#normal_employee').on("tap", bc_pressed);
        $('#normal_operation').on("tap", bc_pressed);
        $('#normal_bt_submit').on("tap", normal_submit);

        $('#flagno_bulk').on("filterablebeforefilter", bulk_keypress_cb);
        $('#flagno_bulk').on("tap", "li", select_bulk_cb);
        $('#flagno_employee').on("tap", bc_pressed);
        $('#flagno_bt_submit').on("tap", flagno_submit);
        $('#flagno_hours_container').on("slidestop", '#flagno_hours', hours_flagno_select);
        $('#flagno_minutes_container').on("slidestop", '#flagno_minutes', minutes_flagno_select);
    },

    deviceready: function() {
        app.start();
    },

    start: function() {
        //alert('application started...');
    }
};

var normal_data = {};
var flagno_data = {};
var scan_in_progress = false;
//var base_url = 'http://192.168.1.48';
var base_url = 'http://192.168.0.11';
var post_url = base_url+'/supervisor_input.php';
var get_operations = base_url+'/supervisor_getoperations.php';
var get_flagno_operations = base_url+'/supervisor_getoperations_flagno.php';
var get_bulks = base_url+'/supervisor_getbulks.php';

function is_wifi_enable(){
/*
    var networkState = navigator.connection.type;
    return (networkState == Connection.WIFI);
*/
return true;
}

function bc_pressed(){
    var elem_id = $(this).attr('id');
    if(elem_id == 'normal_employee' || elem_id == 'normal_operation'){
        startScan(elem_id.split('_')[1],'normal');
    } else if(elem_id == 'flagno_employee'){
        startScan(elem_id.split('_')[1],'flagno');
    }
}

function date_select(page){
    /* callback for date select event */
    if(page == 'normal'){
        normal_data['date']=$('#normal_scan_date').val();
    } else if(page == 'flagno'){
        flagno_data['date']=$('#flagno_scan_date').val();
    }
    check_params();
}

function bulk_keypress_cb(e, data){
    var $ul = $( this ),
        $input = $( data.input ),
        value = $input.val(),
        html = "";
    $ul.html( "" );
    //console.log(value);
    if ( value && value.length > 0 ) {
        //console.log('performing ajax call');
        $ul.html( "

" );
        $ul.listview( "refresh" );
        if($.mobile.activePage.attr('id') == 'normal'){
            normal_data['bulk'] = value;
        } else {
            flagno_data['bulk'] = value;
        }
        $.post(get_bulks,{'bulk':value},function(response){
            if (response.res == 'OK'){
                $.each( response.msg, function ( i, val ) {
                    html += "
" + val + "
";
                });
                $ul.html( html );
                $ul.listview( "refresh" );
                $ul.trigger( "updatelayout");
                //console.log(html);
            }
        },'json');
    }
    check_params();
}

function select_bulk_cb(){
    var text = $(this).text();
    //console.log(text);
    $(this).closest("ul").prev("form").find("input").val(text);
    $(this).closest("ul").empty();
    if($.mobile.activePage.attr('id') == 'normal'){
        normal_data['bulk'] = text;
        fill_manual_operation(text);
    } else {
        flagno_data['bulk'] = text;
    }
    check_params();
}

function set_layer_cb(event){
    normal_data['layer'] = event.currentTarget.value;
    check_params();
}

function hours_flagno_select(){
    /* callback for onchange on flagno hours */
    flagno_data['tot_ore_flag_no'] = $('#flagno_hours').val();
    check_params();
}

function minutes_flagno_select(){
    /* callback for onchange on flagno minutes */
    flagno_data['tot_min_flag_no'] = $('#flagno_minutes').val();
    check_params();
}

function operation_flagno_select(elem){
    /* callback for onchange on flagno operation field */
    flagno_data['operation'] = elem.value;
    check_params();
}

function operation_manual_select(elem){
    /* callback for onchange on operation manual */
    normal_data['operation'] = elem.value;
    $('#normal_operation').val(elem.value);
    check_params();
}

function fill_manual_operation(bulk){
    /* get all operation for a bulk and enable select control */
    $.post(get_operations,{'bulk':bulk},function(operations){
        $('#normal_manual_operation').empty().append('<option>Select Operation (for bulk)</option>');
        $.each(operations, function(k,v){
            var opt = '<option value="' +k+ '">'+k+' - '+v+'</option>';
            $('#normal_manual_operation').append(opt);
        });
        $('#normal_manual_operation').selectmenu('refresh',true).selectmenu('enable');
        check_params();
    },'json');
}

function fill_flagno_operations(){
    /* get all flagno operation */
    $.post(get_flagno_operations,function(operations){
        $('#flagno_operation').empty().append('<option>Select Operation</option>');
        $.each(operations, function(k,v){
            var opt = '<option value="' +k+ '">'+k+' - '+v+'</option>';
            $('#flagno_operation').append(opt);
        });
        $('#flagno_operation').selectmenu('refresh',true).selectmenu('enable');
        check_params();
    },'json');
}

function closeScan(){
    /* this is an hack to prevent exiting from the application when
       someone clicks on back button during when the scanner is active */
    if(scan_in_progress){
        alert('Scan cancelled');
    }
}

function check_params(){
    /* Check if all params are correctly set and enable the submit button*/
    /* normal page */
    if(normal_data['date']!='' &&
        normal_data['bulk']!='' &&
        normal_data['operation']!='' &&
        normal_data['employee']!='' &&
        normal_data['layer']!=''){
        $('#normal_bt_submit').removeClass('ui-disabled');
    } else {
        $('#normal_bt_submit').addClass('ui-disabled');
    }

    /* flagno page */
    if(flagno_data['date']!='' &&
        flagno_data['employee']!='' &&
        flagno_data['bulk']!='' &&
        flagno_data['operation']!='' &&
        !(flagno_data['tot_ore_flag_no']=='0' && flagno_data['tot_min_flag_no']=='0'))
    {
        //console.log('ALLOW',flagno_data);
        $('#flagno_bt_submit').removeClass('ui-disabled');
    } else {
        //console.log('DISALLOW',flagno_data);
        $('#flagno_bt_submit').addClass('ui-disabled');
    }
}

function reset_fields(){
    /* reset all fields at app startup and after every submit */
    var d = new Date();
    //normal_data = {};
    //flagno_data = {};

    /* normal page */
    $('#normal_bt_submit').addClass('ui-disabled');
    $('#normal_employee').val('');
    //$('#normal_bulk').val('');
    //$('#normal_manual_operation').selectmenu('disable').empty();
    //$('#normal_operation').val('');
    $('#normal_layer').val('1');
    $('#normal_scan_date').val(d.toISOString().split('T')[0]);
    normal_data['date']=$('#normal_scan_date').val();
    normal_data['employee']='';
    //normal_data['bulk']='';
    //normal_data['operation']='';
    normal_data['layer']='1';
    normal_data['id_device'] = window.localStorage.getItem('id_device');

    /* flag no page */
    $('#flagno_bt_submit').addClass('ui-disabled');
    $('#flagno_employee').val('');
    $('#flagno_bulk').val('');
    $('#flagno_operation').val('');
    $('#flagno_scan_date').val(d.toISOString().split('T')[0]);
    $('#flagno_hours').val('0');
    $('#flagno_minutes').val('0');
    flagno_data['date']=$('#flagno_scan_date').val();
    flagno_data['employee']='';
    //flagno_data['bulk']='';
    //flagno_data['operation']='';
    flagno_data['tot_ore_flag_no']='0';
    $('#flagno_minutes').siblings('.ui-slider-track').children('a').attr('style','left:0');
    flagno_data['tot_min_flag_no']='0';
    $('#flagno_hours').siblings('.ui-slider-track').children('a').attr('style','left:0');
    flagno_data['id_device'] = window.localStorage.getItem('id_device');
}

function normal_submit(){
    /* here we have to subm it the data to the server */
    if(!is_wifi_enable()){
        alert('wifi connection is not enable');
        return false;
    }
    $.mobile.loading('show');
    $.post(post_url,normal_data,function(data){
        if(data.OK != undefined && data.OK != ''){
            alert(data.OK);
            $.mobile.loading('hide');
            reset_fields();
        }else{
            alert(data.ERR);
            $.mobile.loading('hide');
        }
    },'json')
    .fail(function(){
        alert('Communication error!');
        $.mobile.loading('hide');
    });
}

function flagno_submit(){
    /* here we have to subm it the data to the server */
    if(!is_wifi_enable()){
        alert('wifi connection is not enable');
        return false;
    }
    $.mobile.loading('show');
    $.post(post_url,flagno_data,function(data){
        if(data.OK != undefined && data.OK != ''){
            alert(data.OK);
            $.mobile.loading('hide');
            reset_fields();
        }else{
            alert(data.ERR);
            $.mobile.loading('hide');
        }
    },'json')
    .fail(function(){
        alert('Communication error!');
        $.mobile.loading('hide');
    });
}

function quit(){
    navigator.app.exitApp();
}

function startScan(elem, page) {
    if(typeof cordova==='undefined'){
        if(page == 'normal'){
            normal_data[elem] = 'testvalue';
            $('#normal_'+elem).val('testvalue');
        } else if(page == 'flagno'){
            flagno_data[elem] = 'testvalue';
            $('#flagno_'+elem).val('testvalue');
        }
        check_params();
        return true;
    }
    scan_in_progress = true;
    $.mobile.loading('show');
    cordova.plugins.barcodeScanner.scan(
    function (result) {
        var s = "Result: " + result.text + "
" +
            "Format: " + result.format + "
" +
            "Cancelled: " + result.cancelled;
        if(!result.cancelled){
            if(page == 'normal'){
                normal_data[elem] = result.text;
                $('#normal_'+elem).val(result.text);
            } else if(page == 'flagno'){
                flagno_data[elem] = result.text;
                $('#flagno_'+elem).val(result.text);
            }
            scan_in_progress = false;
        }
        check_params();
        $.mobile.loading('hide');
    },
    function (error) {
        alert("Scanning failed: " + error);
        scan_in_progress = false;
        $.mobile.loading('hide');
    });
}

function save_id_device(){
    var id_device = $('#id_device').val();
    if(id_device != ''){
        window.localStorage.setItem('id_device',id_device);
        $('.id_device').text(' - '+id_device);
        normal_data['id_device'] = window.localStorage.getItem('id_device');
        flagno_data['id_device'] = window.localStorage.getItem('id_device');
        $("body").pagecontainer("change", "#normal", {
            transition: 'slidedown',
            reload    : true
        });
    }
}

$(document).on('pageinit','#normal',function(){
    $('#version').append(app_version);
    var id_device = window.localStorage.getItem('id_device');
    if(id_device==null){
        $("body").pagecontainer("change", "#line_input", {
            transition: 'slidedown',
            reload    : true
        });
    }
    $('.id_device').text(' - '+id_device);
    /* this is needed only to have a better graphic for input text fields */
    $('.ui-input-text').removeClass('ui-state-disabled');
    reset_fields();
    app.initialize();
});

$(document).on('pageinit','#flagno',function(){
    /* this is needed only to have a better graphic for input text fields */
    $('.ui-input-text').removeClass('ui-state-disabled');
    fill_flagno_operations();
});
<|endoftext|>


<commit_before>var cordova = require('cordova')
var rs = ["Royal Progress", "RSUP Dr Cipto Mangunkusumo", "RSUP Fatmawati", "RSUP Persahabatan"]

if (cordova.platformId == 'android') {
	StatusBar.backgroundColorByHexString("#009688");
};

function pesan(){

}<commit_msg>Remove pesan function<commit_after>var cordova = require('cordova')
var rs = ["Royal Progress", "RSUP Dr Cipto Mangunkusumo", "RSUP Fatmawati", "RSUP Persahabatan"]

if (cordova.platformId == 'android') {
	StatusBar.backgroundColorByHexString("#009688");
};
<|endoftext|>


<commit_before>var cordova = require('cordova')
var rs = ["Royal Progress", "RSUP Dr Cipto Mangunkusumo", "RSUP Fatmawati", "RSUP Persahabatan"]

var input = document.getElementbyId('hospital-form').value;

function checkTextField(input) {
    if (input.value == '') {
        alert("Field is empty");
    }
}

if (cordova.platformId == 'android') {
	StatusBar.backgroundColorByHexString("#009688");
};<commit_msg>Send bpjs number data to firebase<commit_after>var cordova = require('cordova')
var rs = ["Royal Progress", "RSUP Dr Cipto Mangunkusumo", "RSUP Fatmawati", "RSUP Persahabatan"]

var input = document.getElementbyId('hospital-form').value;

function checkTextField(input) {
    if (input.value == '') {
        alert("Field is empty");
    }
}

if (cordova.platformId == 'android') {
	StatusBar.backgroundColorByHexString("#009688");
};

var ref = "https://cepatsembuh.firebaseio.com/";

function data() {
	var bpjs-rs = document.getElementbyId("bpjs-rs");
	var bpjs-puskesmas = document.getElementbyId("bpjs-puskesmas");

	ref.push(bpjs-rs);
	ref.push(bpjs-puskesmas);
	Firebase.goOnline

}<|endoftext|>