<commit_before>// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// License: GNU General Public License v3. See license.txt

frappe.pages['sales-analytics'].on_page_load = function(wrapper) {
	frappe.ui.make_app_page({
		parent: wrapper,
		title: __('Sales Analytics'),
		single_column: true
	});
	new erpnext.SalesAnalytics(wrapper);

	frappe.breadcrumbs.add("Selling")

};

erpnext.SalesAnalytics = frappe.views.TreeGridReport.extend({
	init: function(wrapper) {
		this._super({
			title: __("Sales Analytics"),
			page: wrapper,
			parent: $(wrapper).find('.layout-main'),
			page: wrapper.page,
			doctypes: ["Item", "Item Group", "Customer", "Customer Group", "Company", "Territory",
				"Fiscal Year", "Sales Invoice", "Sales Invoice Item",
				"Sales Order", "Sales Order Item[Sales Analytics]",
				"Delivery Note", "Delivery Note Item[Sales Analytics]"],
			tree_grid: { show: true }
		});

		this.tree_grids = {
			"Customer Group": {
				label: __("Customer Group / Customer"),
				show: true,
				item_key: "customer",
				parent_field: "parent_customer_group",
				formatter: function(item) { return item.customer_name || item.name; }
			},
			"Customer": {
				label: __("Customer"),
				show: false,
				item_key: "customer",
				formatter: function(item) {
					return item.customer_name || item.name;
				}
			},
			"Item Group": {
				label: __("Item"),
				show: true,
				parent_field: "parent_item_group",
				item_key: "item_code",
				formatter: function(item) {
					return item.name;
				}
			},
			"Item": {
				label: __("Item"),
				show: false,
				item_key: "item_code",
				formatter: function(item) {
					return item.name;
				}
			},
			"Territory": {
				label: __("Territory / Customer"),
				show: true,
				item_key: "customer",
				parent_field: "parent_territory",
				formatter: function(item) {
					return item.name;
				}
			}
		}
	},
	setup_columns: function() {
		this.tree_grid = this.tree_grids[this.tree_type];

		var std_columns = [
			{id: "check", name: "Plot", field: "check", width: 30,
				formatter: this.check_formatter},
			{id: "name", name: this.tree_grid.label, field: "name", width: 300,
				formatter: this.tree_formatter},
			{id: "total", name: "Total", field: "total", plot: false,
				formatter: this.currency_formatter}
		];

		this.make_date_range_columns();
		this.columns = std_columns.concat(this.columns);
	},
	filters: [
		{fieldtype:"Select", fieldname: "tree_type", label: __("Tree Type"), options:["Customer Group", "Customer",
			"Item Group", "Item", "Territory"],
			filter: function(val, item, opts, me) {
				return me.apply_zero_filter(val, item, opts, me);
			}},
		{fieldtype:"Select", fieldname: "based_on", label: __("Based On"), options:["Sales Invoice",
			"Sales Order", "Delivery Note"]},
		{fieldtype:"Select", fieldname: "value_or_qty", label:  __("Value or Qty"),
			options:[{label: __("Value"), value: "Value"}, {label: __("Quantity"), value: "Quantity"}]},
		{fieldtype:"Date", fieldname: "from_date", label: __("From Date")},
		{fieldtype:"Label", fieldname: "to", label: __("To")},
		{fieldtype:"Date", fieldname: "to_date", label: __("To Date")},
		{fieldtype:"Select", fieldname: "company", label: __("Company"), link:"Company",
			default_value: __("Select Company...")},
		{fieldtype:"Select", label: __("Range"), fieldname: "range",
			options:[{label: __("Daily"), value: "Daily"}, {label: __("Weekly"), value: "Weekly"},
				{label: __("Monthly"), value: "Monthly"}, {label: __("Quarterly"), value: "Quarterly"},
				{label: __("Yearly"), value: "Yearly"}]}
	],
	setup_filters: function() {
		var me = this;
		this._super();

		this.trigger_refresh_on_change(["value_or_qty", "tree_type", "based_on", "company"]);

		this.show_zero_check()
		this.setup_chart_check();
	},
	init_filter_values: function() {
		this._super();
		this.filter_inputs.range.val('Monthly');
	},
	prepare_data: function() {
		var me = this;
		if (!this.tl) {
			// add 'Not Set' Customer & Item
			// (Customer / Item are not mandatory!!)
			frappe.report_dump.data["Customer"].push({
				name: "Not Set",
				parent_customer_group: "All Customer Groups",
				parent_territory: "All Territories",
				id: "Not Set",
			});

			frappe.report_dump.data["Item"].push({
				name: "Not Set",
				parent_item_group: "All Item Groups",
				id: "Not Set",
			});
		}

		if (!this.tl || !this.tl[this.based_on]) {
			this.make_transaction_list(this.based_on, this.based_on + " Item");
		}

		if(!this.data || me.item_type != me.tree_type) {
			if(me.tree_type=='Customer') {
				var items = frappe.report_dump.data["Customer"];
			} if(me.tree_type=='Customer Group') {
				var items = this.prepare_tree("Customer", "Customer Group");
			} else if(me.tree_type=="Item Group") {
				var items = this.prepare_tree("Item", "Item Group");
			} else if(me.tree_type=="Item") {
				var items = frappe.report_dump.data["Item"];
			} else if(me.tree_type=="Territory") {
				var items = this.prepare_tree("Customer", "Territory");
			}

			me.item_type = me.tree_type
			me.parent_map = {};
			me.item_by_name = {};
			me.data = [];

			$.each(items, function(i, v) {
				var d = copy_dict(v);

				me.data.push(d);
				me.item_by_name[d.name] = d;
				if(d[me.tree_grid.parent_field]) {
					me.parent_map[d.name] = d[me.tree_grid.parent_field];
				}
				me.reset_item_values(d);
			});

			this.set_indent();

		} else {
			// otherwise, only reset values
			$.each(this.data, function(i, d) {
				me.reset_item_values(d);
			});
		}

		this.prepare_balances();
		if(me.tree_grid.show) {
			this.set_totals(false);
			this.update_groups();
		} else {
			this.set_totals(true);
		}

	},
	prepare_balances: function() {
		var me = this;
		var from_date = dateutil.str_to_obj(this.from_date);
		var to_date = dateutil.str_to_obj(this.to_date);
		var is_val = this.value_or_qty == 'Value';

		$.each(this.tl[this.based_on], function(i, tl) {
			if (me.is_default('company') ? true : tl.company === me.company) {
				var posting_date = dateutil.str_to_obj(tl.posting_date);
				if (posting_date >= from_date && posting_date <= to_date) {
					var item = me.item_by_name[tl[me.tree_grid.item_key]] ||
						me.item_by_name['Not Set'];
					item[me.column_map[tl.posting_date].field] += (is_val ? tl.base_net_amount : tl.qty);
				}
			}
		});
	},
	update_groups: function() {
		var me = this;

		$.each(this.data, function(i, item) {
			var parent = me.parent_map[item.name];
			while(parent) {
				parent_group = me.item_by_name[parent];

				$.each(me.columns, function(c, col) {
					if (col.formatter == me.currency_formatter) {
						parent_group[col.field] =
							flt(parent_group[col.field])
							+ flt(item[col.field]);
					}
				});
				parent = me.parent_map[parent];
			}
		});
	},
	set_totals: function(sort) {
		var me = this;
		var checked = false;
		$.each(this.data, function(i, d) {
			d.total = 0.0;
			$.each(me.columns, function(i, col) {
				if(col.formatter==me.currency_formatter && !col.hidden && col.field!="total")
					d.total += d[col.field];
				if(d.checked) checked = true;
			})
		});

		if(sort)this.data = this.data.sort(function(a, b) { return a.total < b.total; });

		if(!this.checked) {
			this.data[0].checked = true;
		}
	}
});
<commit_msg>Sales analytics error after upgrade<commit_after>// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// License: GNU General Public License v3. See license.txt

frappe.pages['sales-analytics'].on_page_load = function(wrapper) {
	frappe.ui.make_app_page({
		parent: wrapper,
		title: __('Sales Analytics'),
		single_column: true
	});
	new erpnext.SalesAnalytics(wrapper);

	frappe.breadcrumbs.add("Selling")

};

erpnext.SalesAnalytics = frappe.views.TreeGridReport.extend({
	init: function(wrapper) {
		this._super({
			title: __("Sales Analytics"),
			page: wrapper,
			parent: $(wrapper).find('.layout-main'),
			page: wrapper.page,
			doctypes: ["Item", "Item Group", "Customer", "Customer Group", "Company", "Territory",
				"Fiscal Year", "Sales Invoice", "Sales Invoice Item",
				"Sales Order", "Sales Order Item[Sales Analytics]",
				"Delivery Note", "Delivery Note Item[Sales Analytics]"],
			tree_grid: { show: true }
		});

		this.tree_grids = {
			"Customer Group": {
				label: __("Customer Group / Customer"),
				show: true,
				item_key: "customer",
				parent_field: "parent_customer_group",
				formatter: function(item) { return item.customer_name || item.name; }
			},
			"Customer": {
				label: __("Customer"),
				show: false,
				item_key: "customer",
				formatter: function(item) {
					return item.customer_name || item.name;
				}
			},
			"Item Group": {
				label: __("Item"),
				show: true,
				parent_field: "parent_item_group",
				item_key: "item_code",
				formatter: function(item) {
					return item.name;
				}
			},
			"Item": {
				label: __("Item"),
				show: false,
				item_key: "item_code",
				formatter: function(item) {
					return item.name;
				}
			},
			"Territory": {
				label: __("Territory / Customer"),
				show: true,
				item_key: "customer",
				parent_field: "parent_territory",
				formatter: function(item) {
					return item.name;
				}
			}
		}
	},
	setup_columns: function() {
		this.tree_grid = this.tree_grids[this.tree_type];

		var std_columns = [
			{id: "check", name: "Plot", field: "check", width: 30,
				formatter: this.check_formatter},
			{id: "name", name: this.tree_grid.label, field: "name", width: 300,
				formatter: this.tree_formatter},
			{id: "total", name: "Total", field: "total", plot: false,
				formatter: this.currency_formatter}
		];

		this.make_date_range_columns();
		this.columns = std_columns.concat(this.columns);
	},
	filters: [
		{fieldtype:"Select", fieldname: "tree_type", label: __("Tree Type"), options:["Customer Group", "Customer",
			"Item Group", "Item", "Territory"],
			filter: function(val, item, opts, me) {
				return me.apply_zero_filter(val, item, opts, me);
			}},
		{fieldtype:"Select", fieldname: "based_on", label: __("Based On"), options:["Sales Invoice",
			"Sales Order", "Delivery Note"]},
		{fieldtype:"Select", fieldname: "value_or_qty", label:  __("Value or Qty"),
			options:[{label: __("Value"), value: "Value"}, {label: __("Quantity"), value: "Quantity"}]},
		{fieldtype:"Date", fieldname: "from_date", label: __("From Date")},
		{fieldtype:"Label", fieldname: "to", label: __("To")},
		{fieldtype:"Date", fieldname: "to_date", label: __("To Date")},
		{fieldtype:"Select", fieldname: "company", label: __("Company"), link:"Company",
			default_value: __("Select Company...")},
		{fieldtype:"Select", label: __("Range"), fieldname: "range",
			options:[{label: __("Daily"), value: "Daily"}, {label: __("Weekly"), value: "Weekly"},
				{label: __("Monthly"), value: "Monthly"}, {label: __("Quarterly"), value: "Quarterly"},
				{label: __("Yearly"), value: "Yearly"}]}
	],
	setup_filters: function() {
		var me = this;
		this._super();

		this.trigger_refresh_on_change(["value_or_qty", "tree_type", "based_on", "company"]);

		this.show_zero_check()
		this.setup_chart_check();
	},
	init_filter_values: function() {
		this._super();
		this.filter_inputs.range.val('Monthly');
	},
	prepare_data: function() {
		var me = this;
		if (!this.tl) {
			// add 'Not Set' Customer & Item
			// (Customer / Item are not mandatory!!)
			frappe.report_dump.data["Customer"].push({
				name: "Not Set",
				parent_customer_group: "All Customer Groups",
				parent_territory: "All Territories",
				id: "Not Set",
			});

			frappe.report_dump.data["Item"].push({
				name: "Not Set",
				parent_item_group: "All Item Groups",
				id: "Not Set",
			});
		}

		if (!this.tl || !this.tl[this.based_on]) {
			this.make_transaction_list(this.based_on, this.based_on + " Item");
		}

		if(!this.data || me.item_type != me.tree_type) {
			if(me.tree_type=='Customer') {
				var items = frappe.report_dump.data["Customer"];
			} if(me.tree_type=='Customer Group') {
				var items = this.prepare_tree("Customer", "Customer Group");
			} else if(me.tree_type=="Item Group") {
				var items = this.prepare_tree("Item", "Item Group");
			} else if(me.tree_type=="Item") {
				var items = frappe.report_dump.data["Item"];
			} else if(me.tree_type=="Territory") {
				var items = this.prepare_tree("Customer", "Territory");
			}

			me.item_type = me.tree_type
			me.parent_map = {};
			me.item_by_name = {};
			me.data = [];

			$.each(items, function(i, v) {
				var d = copy_dict(v);

				me.data.push(d);
				me.item_by_name[d.name] = d;
				if(d[me.tree_grid.parent_field]) {
					me.parent_map[d.name] = d[me.tree_grid.parent_field];
				}
				me.reset_item_values(d);
			});

			this.set_indent();

		} else {
			// otherwise, only reset values
			$.each(this.data, function(i, d) {
				me.reset_item_values(d);
			});
		}

		this.prepare_balances();
		if(me.tree_grid.show) {
			this.set_totals(false);
			this.update_groups();
		} else {
			this.set_totals(true);
		}

	},
	prepare_balances: function() {
		var me = this;
		var from_date = dateutil.str_to_obj(this.from_date);
		var to_date = dateutil.str_to_obj(this.to_date);
		var is_val = this.value_or_qty == 'Value';

		$.each(this.tl[this.based_on], function(i, tl) {
			if (me.is_default('company') ? true : tl.company === me.company) {
				var posting_date = dateutil.str_to_obj(tl.posting_date);
				if (posting_date >= from_date && posting_date <= to_date) {
					var item = me.item_by_name[tl[me.tree_grid.item_key]] ||
						me.item_by_name['Not Set'];
					if(item){
						item[me.column_map[tl.posting_date].field] += (is_val ? tl.base_net_amount : tl.qty);
					}
				}
			}
		});
	},
	update_groups: function() {
		var me = this;

		$.each(this.data, function(i, item) {
			var parent = me.parent_map[item.name];
			while(parent) {
				parent_group = me.item_by_name[parent];

				$.each(me.columns, function(c, col) {
					if (col.formatter == me.currency_formatter) {
						parent_group[col.field] =
							flt(parent_group[col.field])
							+ flt(item[col.field]);
					}
				});
				parent = me.parent_map[parent];
			}
		});
	},
	set_totals: function(sort) {
		var me = this;
		var checked = false;
		$.each(this.data, function(i, d) {
			d.total = 0.0;
			$.each(me.columns, function(i, col) {
				if(col.formatter==me.currency_formatter && !col.hidden && col.field!="total")
					d.total += d[col.field];
				if(d.checked) checked = true;
			})
		});

		if(sort)this.data = this.data.sort(function(a, b) { return a.total < b.total; });

		if(!this.checked) {
			this.data[0].checked = true;
		}
	}
});
<|endoftext|>


<commit_before>'use strict';
var fs = require('fs');
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var del = require('del');
var browserSync = require('browser-sync');
var reload = browserSync.reload;
var watchify = require('watchify');
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var sourcemaps = require('gulp-sourcemaps');
var gutil = require('gulp-util');
var exit = require('gulp-exit');
var rev = require('gulp-rev');
var revReplace = require('gulp-rev-replace');
var notifier = require('node-notifier');
var cp = require('child_process');
var YAML = require('yamljs');
var SassString = require('node-sass').types.String;
var OAM_ADDONS = require('oam-design-system/gulp-addons');

// /////////////////////////////////////////////////////////////////////////////
// --------------------------- Variables -------------------------------------//
// ---------------------------------------------------------------------------//

// The package.json
var pkg;

// Environment
// Set the correct environment, which controls what happens in config.js
if (!process.env.DS_ENV) {
  if (!process.env.TRAVIS_BRANCH || process.env.TRAVIS_BRANCH !== process.env.DEPLOY_BRANCH) {
    process.env.DS_ENV = 'staging';
  } else if (process.env.TRAVIS_BRANCH === process.env.DEPLOY_BRANCH) {
    process.env.DS_ENV = 'production';
  } else {
    process.env.DS_ENV = 'development';
  }
}

var prodBuild = false;

// /////////////////////////////////////////////////////////////////////////////
// ------------------------- Helper functions --------------------------------//
// ---------------------------------------------------------------------------//

function readPackage () {
  pkg = JSON.parse(fs.readFileSync('package.json'));
}
readPackage();

// /////////////////////////////////////////////////////////////////////////////
// ------------------------- Callable tasks ----------------------------------//
// ---------------------------------------------------------------------------//

gulp.task('default', ['clean'], function () {
  prodBuild = true;
  gulp.start('build');
});

gulp.task('serve', ['vendorScripts', 'javascript', 'styles', 'jekyll'], function () {
  browserSync({
    port: 3000,
    server: {
      baseDir: ['.tmp', '_site'],
      routes: {
        '/node_modules': './node_modules'
      },
      middleware: OAM_ADDONS.graphicsMiddleware(fs)
    }
  });

  // watch for changes
  gulp.watch([
    'docs/**/*.html',
    'docs/**/*.md',
    'docs/assets/graphics/**/*',
    '!docs/assets/graphics/collecticons/**/*'
  ], ['jekyll', reload]);

  gulp.watch('docs/assets/graphics/collecticons/**', ['collecticons']);

  gulp.watch('docs/assets/styles/**/*.scss', ['styles']);
  gulp.watch('package.json', ['vendorScripts']);
});

gulp.task('clean', function () {
  return del(['.tmp', '_site'])
    .then(function () {
      $.cache.clearAll();
    });
});

// /////////////////////////////////////////////////////////////////////////////
// ------------------------- Browserify tasks --------------------------------//
// ------------------- (Not to be called directly) ---------------------------//
// ---------------------------------------------------------------------------//

// Compiles the user's script files to bundle.js.
// When including the file in the index.html we need to refer to bundle.js not
// main.js
gulp.task('javascript', function () {
  var watcher = watchify(browserify({
    entries: ['./docs/assets/scripts/main.js'],
    debug: true,
    cache: {},
    packageCache: {},
    fullPaths: true
  }));

  function bundler () {
    if (pkg.dependencies) {
      watcher.external(Object.keys(pkg.dependencies));
    }
    return watcher.bundle()
      .on('error', function (e) {
        notifier.notify({
          title: 'Oops! Browserify errored:',
          message: e.message
        });
        console.log('Javascript error:', e);
        if (prodBuild) {
          process.exit(1);
        }
        // Allows the watch to continue.
        this.emit('end');
      })
      .pipe(source('bundle.js'))
      .pipe(buffer())
      // Source maps.
      .pipe(sourcemaps.init({loadMaps: true}))
      .pipe(sourcemaps.write('./'))
      .pipe(gulp.dest('.tmp/assets/scripts'))
      .pipe(reload({stream: true}));
  }

  watcher
  .on('log', gutil.log)
  .on('update', bundler);

  return bundler();
});

// Vendor scripts. Basically all the dependencies in the package.js.
// Therefore be careful and keep the dependencies clean.
gulp.task('vendorScripts', function () {
  // Ensure package is updated.
  readPackage();
  var vb = browserify({
    debug: true,
    require: pkg.dependencies ? Object.keys(pkg.dependencies) : []
  });
  return vb.bundle()
    .on('error', gutil.log.bind(gutil, 'Browserify Error'))
    .pipe(source('vendor.js'))
    .pipe(buffer())
    .pipe(sourcemaps.init({loadMaps: true}))
    .pipe(sourcemaps.write('./'))
    .pipe(gulp.dest('.tmp/assets/scripts/'))
    .pipe(reload({stream: true}));
});

// /////////////////////////////////////////////////////////////////////////////
// ------------------------ Collecticon tasks --------------------------------//
// -------------------- (Font generation related) ----------------------------//
// ---------------------------------------------------------------------------//
gulp.task('collecticons', function (done) {
  var args = [
    'node_modules/collecticons-processor/bin/collecticons.js',
    'compile',
    'docs/assets/graphics/collecticons/',
    '--font-embed',
    '--font-dest', 'docs/assets/fonts',
    '--font-name', 'Collecticons',
    '--font-types', 'woff',
    '--style-format', 'sass',
    '--style-dest', 'docs/assets/styles/',
    '--style-name', 'collecticons',
    '--class-name', 'collecticons',
    '--author-name', 'Development Seed',
    '--author-url', 'https://developmentseed.org/',
    '--no-preview'
  ];

  return cp.spawn('node', args, {stdio: 'inherit'})
    .on('close', done);
});

// /////////////////////////////////////////////////////////////////////////////
// -------------------------- Jekyll tasks -----------------------------------//
// ---------------------------------------------------------------------------//
gulp.task('jekyll', function (done) {
  var args = ['exec', 'jekyll', 'build'];

  switch (process.env.DS_ENV) {
    case 'development':
      args.push('--config=_config.yml,_config-dev.yml');
      break;
    case 'staging':
      args.push('--config=_config.yml,_config-stage.yml');
      break;
    case 'production':
      args.push('--config=_config.yml');
      break;
  }

  return cp.spawn('bundle', args, {stdio: 'inherit'})
    .on('close', done);
});

// //////////////////////////////////////////////////////////////////////////////
// --------------------------- Helper tasks -----------------------------------//
// ----------------------------------------------------------------------------//

gulp.task('build', ['collecticons'], function () {
  gulp.start(['vendorScripts', 'javascript', 'styles', 'jekyll'], function () {
    gulp.start(['html', 'images'], function () {
      return gulp.src('_site/**/*')
        .pipe($.size({title: 'build', gzip: true}))
        .pipe(exit());
    });
  });
});

gulp.task('styles', function () {
  return gulp.src('docs/assets/styles/main.scss')
    .pipe($.plumber(function (e) {
      notifier.notify({
        title: 'Oops! Sass errored:',
        message: e.message
      });
      console.log('Sass error:', e.toString());
      if (prodBuild) {
        process.exit(1);
      }
      // Allows the watch to continue.
      this.emit('end');
    }))
    .pipe($.sourcemaps.init())
    .pipe($.sass({
      outputStyle: 'expanded',
      precision: 10,
      functions: {
        'urlencode($url)': function (url) {
          var v = new SassString();
          v.setValue(encodeURIComponent(url.getValue()));
          return v;
        }
      },
      includePaths: require('node-bourbon').with('.', 'node_modules/jeet/scss', OAM_ADDONS.scssPath)
    }))
    .pipe($.sourcemaps.write())
    .pipe(gulp.dest('.tmp/assets/styles'))
    .pipe(reload({stream: true}));
});

// After being rendered by jekyll process the html files. (merge css files, etc)
gulp.task('html', function () {
  var jkConf = YAML.load('_config.yml');
  return gulp.src('_site/**/*.html')
    .pipe($.useref({searchPath: ['.tmp', 'docs', '.']}))
    .pipe($.if('*.js', $.uglify()))
    .pipe($.if('*.css', $.csso()))
    .pipe($.if(/\.(css|js)$/, rev()))
    .pipe(revReplace({prefix: jkConf.baseurl}))
    .pipe(gulp.dest('_site'));
});

// Compress images.
gulp.task('images', function () {
  return gulp.src(['_site/assets/graphics/**/*', OAM_ADDONS.graphicsPath + '/**/*'])
    .pipe($.cache($.imagemin({
      progressive: true,
      interlaced: true,
      // don't remove IDs from SVGs, they are often used
      // as hooks for embedding and styling
      svgoPlugins: [{cleanupIDs: false}]
    })))
    .pipe(gulp.dest('_site/assets/graphics'));
});
<commit_msg>Fix env<commit_after>'use strict';
var fs = require('fs');
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var del = require('del');
var browserSync = require('browser-sync');
var reload = browserSync.reload;
var watchify = require('watchify');
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var sourcemaps = require('gulp-sourcemaps');
var gutil = require('gulp-util');
var exit = require('gulp-exit');
var rev = require('gulp-rev');
var revReplace = require('gulp-rev-replace');
var notifier = require('node-notifier');
var cp = require('child_process');
var YAML = require('yamljs');
var SassString = require('node-sass').types.String;
var OAM_ADDONS = require('oam-design-system/gulp-addons');

// /////////////////////////////////////////////////////////////////////////////
// --------------------------- Variables -------------------------------------//
// ---------------------------------------------------------------------------//

// The package.json
var pkg;

// Environment
// Set the correct environment, which controls what happens in config.js
if (!process.env.DS_ENV) {
  if (process.env.TRAVIS_BRANCH && process.env.TRAVIS_BRANCH !== process.env.DEPLOY_BRANCH) {
    process.env.DS_ENV = 'staging';
  } else if (process.env.TRAVIS_BRANCH && process.env.TRAVIS_BRANCH === process.env.DEPLOY_BRANCH) {
    process.env.DS_ENV = 'production';
  } else {
    process.env.DS_ENV = 'development';
  }
}

var prodBuild = false;

// /////////////////////////////////////////////////////////////////////////////
// ------------------------- Helper functions --------------------------------//
// ---------------------------------------------------------------------------//

function readPackage () {
  pkg = JSON.parse(fs.readFileSync('package.json'));
}
readPackage();

// /////////////////////////////////////////////////////////////////////////////
// ------------------------- Callable tasks ----------------------------------//
// ---------------------------------------------------------------------------//

gulp.task('default', ['clean'], function () {
  prodBuild = true;
  gulp.start('build');
});

gulp.task('serve', ['vendorScripts', 'javascript', 'styles', 'jekyll'], function () {
  browserSync({
    port: 3000,
    server: {
      baseDir: ['.tmp', '_site'],
      routes: {
        '/node_modules': './node_modules'
      },
      middleware: OAM_ADDONS.graphicsMiddleware(fs)
    }
  });

  // watch for changes
  gulp.watch([
    'docs/**/*.html',
    'docs/**/*.md',
    'docs/assets/graphics/**/*',
    '!docs/assets/graphics/collecticons/**/*'
  ], ['jekyll', reload]);

  gulp.watch('docs/assets/graphics/collecticons/**', ['collecticons']);

  gulp.watch('docs/assets/styles/**/*.scss', ['styles']);
  gulp.watch('package.json', ['vendorScripts']);
});

gulp.task('clean', function () {
  return del(['.tmp', '_site'])
    .then(function () {
      $.cache.clearAll();
    });
});

// /////////////////////////////////////////////////////////////////////////////
// ------------------------- Browserify tasks --------------------------------//
// ------------------- (Not to be called directly) ---------------------------//
// ---------------------------------------------------------------------------//

// Compiles the user's script files to bundle.js.
// When including the file in the index.html we need to refer to bundle.js not
// main.js
gulp.task('javascript', function () {
  var watcher = watchify(browserify({
    entries: ['./docs/assets/scripts/main.js'],
    debug: true,
    cache: {},
    packageCache: {},
    fullPaths: true
  }));

  function bundler () {
    if (pkg.dependencies) {
      watcher.external(Object.keys(pkg.dependencies));
    }
    return watcher.bundle()
      .on('error', function (e) {
        notifier.notify({
          title: 'Oops! Browserify errored:',
          message: e.message
        });
        console.log('Javascript error:', e);
        if (prodBuild) {
          process.exit(1);
        }
        // Allows the watch to continue.
        this.emit('end');
      })
      .pipe(source('bundle.js'))
      .pipe(buffer())
      // Source maps.
      .pipe(sourcemaps.init({loadMaps: true}))
      .pipe(sourcemaps.write('./'))
      .pipe(gulp.dest('.tmp/assets/scripts'))
      .pipe(reload({stream: true}));
  }

  watcher
  .on('log', gutil.log)
  .on('update', bundler);

  return bundler();
});

// Vendor scripts. Basically all the dependencies in the package.js.
// Therefore be careful and keep the dependencies clean.
gulp.task('vendorScripts', function () {
  // Ensure package is updated.
  readPackage();
  var vb = browserify({
    debug: true,
    require: pkg.dependencies ? Object.keys(pkg.dependencies) : []
  });
  return vb.bundle()
    .on('error', gutil.log.bind(gutil, 'Browserify Error'))
    .pipe(source('vendor.js'))
    .pipe(buffer())
    .pipe(sourcemaps.init({loadMaps: true}))
    .pipe(sourcemaps.write('./'))
    .pipe(gulp.dest('.tmp/assets/scripts/'))
    .pipe(reload({stream: true}));
});

// /////////////////////////////////////////////////////////////////////////////
// ------------------------ Collecticon tasks --------------------------------//
// -------------------- (Font generation related) ----------------------------//
// ---------------------------------------------------------------------------//
gulp.task('collecticons', function (done) {
  var args = [
    'node_modules/collecticons-processor/bin/collecticons.js',
    'compile',
    'docs/assets/graphics/collecticons/',
    '--font-embed',
    '--font-dest', 'docs/assets/fonts',
    '--font-name', 'Collecticons',
    '--font-types', 'woff',
    '--style-format', 'sass',
    '--style-dest', 'docs/assets/styles/',
    '--style-name', 'collecticons',
    '--class-name', 'collecticons',
    '--author-name', 'Development Seed',
    '--author-url', 'https://developmentseed.org/',
    '--no-preview'
  ];

  return cp.spawn('node', args, {stdio: 'inherit'})
    .on('close', done);
});

// /////////////////////////////////////////////////////////////////////////////
// -------------------------- Jekyll tasks -----------------------------------//
// ---------------------------------------------------------------------------//
gulp.task('jekyll', function (done) {
  var args = ['exec', 'jekyll', 'build'];

  switch (process.env.DS_ENV) {
    case 'development':
      args.push('--config=_config.yml,_config-dev.yml');
      break;
    case 'staging':
      args.push('--config=_config.yml,_config-stage.yml');
      break;
    case 'production':
      args.push('--config=_config.yml');
      break;
  }

  return cp.spawn('bundle', args, {stdio: 'inherit'})
    .on('close', done);
});

// //////////////////////////////////////////////////////////////////////////////
// --------------------------- Helper tasks -----------------------------------//
// ----------------------------------------------------------------------------//

gulp.task('build', ['collecticons'], function () {
  gulp.start(['vendorScripts', 'javascript', 'styles', 'jekyll'], function () {
    gulp.start(['html', 'images'], function () {
      return gulp.src('_site/**/*')
        .pipe($.size({title: 'build', gzip: true}))
        .pipe(exit());
    });
  });
});

gulp.task('styles', function () {
  return gulp.src('docs/assets/styles/main.scss')
    .pipe($.plumber(function (e) {
      notifier.notify({
        title: 'Oops! Sass errored:',
        message: e.message
      });
      console.log('Sass error:', e.toString());
      if (prodBuild) {
        process.exit(1);
      }
      // Allows the watch to continue.
      this.emit('end');
    }))
    .pipe($.sourcemaps.init())
    .pipe($.sass({
      outputStyle: 'expanded',
      precision: 10,
      functions: {
        'urlencode($url)': function (url) {
          var v = new SassString();
          v.setValue(encodeURIComponent(url.getValue()));
          return v;
        }
      },
      includePaths: require('node-bourbon').with('.', 'node_modules/jeet/scss', OAM_ADDONS.scssPath)
    }))
    .pipe($.sourcemaps.write())
    .pipe(gulp.dest('.tmp/assets/styles'))
    .pipe(reload({stream: true}));
});

// After being rendered by jekyll process the html files. (merge css files, etc)
gulp.task('html', function () {
  var jkConf = YAML.load('_config.yml');
  return gulp.src('_site/**/*.html')
    .pipe($.useref({searchPath: ['.tmp', 'docs', '.']}))
    .pipe($.if('*.js', $.uglify()))
    .pipe($.if('*.css', $.csso()))
    .pipe($.if(/\.(css|js)$/, rev()))
    .pipe(revReplace({prefix: jkConf.baseurl}))
    .pipe(gulp.dest('_site'));
});

// Compress images.
gulp.task('images', function () {
  return gulp.src(['_site/assets/graphics/**/*', OAM_ADDONS.graphicsPath + '/**/*'])
    .pipe($.cache($.imagemin({
      progressive: true,
      interlaced: true,
      // don't remove IDs from SVGs, they are often used
      // as hooks for embedding and styling
      svgoPlugins: [{cleanupIDs: false}]
    })))
    .pipe(gulp.dest('_site/assets/graphics'));
});
<|endoftext|>


<commit_before>var gulp = require('gulp'),
    sass = require('gulp-sass'),
    rename = require('gulp-rename'),
    cleanCSS = require('gulp-clean-css'),
    gutil = require('gulp-util'),
    gulpSequence = require('gulp-sequence'),
    clean = require('gulp-clean'),
    autoprefixer = require('gulp-autoprefixer');

gulp.task('clean', function() {
    return gulp.src('dist', {read: false})
        .pipe(clean());
});

gulp.task('css', function() {
    return gulp.src('scss/hamburgers.scss')
        .pipe(sass({outputStyle: 'expanded'}).on('error', sass.logError))
        .pipe(autoprefixer('last 5 versions'))
        .pipe(gulp.dest('dist'))
        .pipe(rename({suffix: '.min'}))
        .pipe(sass({outputStyle: 'compressed'}))
        .pipe(gulp.dest('dist'))
});

gulp.task('watch', function (callback) {
    gulpSequence('build')(callback);
    gulp.watch('scss/**/*.scss', ['build'])
});

gulp.task('build', function(callback) {
    gulpSequence('clean', ['css'])(callback);
});

gulp.task('default', ['build']);<commit_msg>Semicolons<commit_after>var gulp = require('gulp'),
    sass = require('gulp-sass'),
    rename = require('gulp-rename'),
    cleanCSS = require('gulp-clean-css'),
    gutil = require('gulp-util'),
    gulpSequence = require('gulp-sequence'),
    clean = require('gulp-clean'),
    autoprefixer = require('gulp-autoprefixer');

gulp.task('clean', function() {
    return gulp.src('dist', {read: false})
        .pipe(clean());
});

gulp.task('css', function() {
    return gulp.src('scss/hamburgers.scss')
        .pipe(sass({outputStyle: 'expanded'}).on('error', sass.logError))
        .pipe(autoprefixer('last 5 versions'))
        .pipe(gulp.dest('dist'))
        .pipe(rename({suffix: '.min'}))
        .pipe(sass({outputStyle: 'compressed'}))
        .pipe(gulp.dest('dist'));
});

gulp.task('watch', function (callback) {
    gulpSequence('build')(callback);
    gulp.watch('scss/**/*.scss', ['build']);
});

gulp.task('build', function(callback) {
    gulpSequence('clean', ['css'])(callback);
});

gulp.task('default', ['build']);<|endoftext|>


<commit_before>var loadManyReferenceList = require('./builder').loadMany;
var dispatcher = require('../dispatcher');
module.exports =
function(referenceNames){
  return function(){
       return Promise.all(loadManyReferenceList(referenceNames))
           .then(function successReferenceLoading(data){
             dispatcher.handleViewAction({data: data, type: 'update'});
           }, function errorReferenceLoading(err){
             dispatcher.handleViewAction({data: err, type: 'error'});
           });
     };
};
<commit_msg>[reference] Change the buildin action of the refernece.<commit_after>var loadManyReferenceList = require('./builder').loadMany;
var dispatcher = require('../dispatcher');

/**
 * Focus reference action.
 * @param {array} referenceNames - An array which contains the name of all the references to load.
 * @returns {Promise} - The promise of loading all the references.
 */
function builtInReferenceAction(referenceNames){
  return function(){
       return Promise.all(loadManyReferenceList(referenceNames))
           .then(function successReferenceLoading(data){
             //Rebuilt a constructed information from the map.
             var reconstructedData = {};
             referenceNames.map((name, index)=>{
               reconstructedData[name] = data[index];
             });
             //
             dispatcher.handleViewAction({data: reconstructedData, type: 'update', subject: 'reference'});
           }, function errorReferenceLoading(err){
             dispatcher.handleViewAction({data: err, type: 'error'});
           });
     };
}

module.exports = builtInReferenceAction;
<|endoftext|>


<commit_before>import React, {Component, Fragment} from 'react';
import round from 'lodash/round';

import Table from 'src/Table';
import Switcher from 'src/Switcher';
import IconButton from 'src/IconButton';
import Widget from 'src/Widget';
import WidgetHeader from 'src/WidgetHeader';
import RaisedButton from 'src/RaisedButton';
import CircularLoading from 'src/CircularLoading';

import PropTypeDescTable from 'components/PropTypeDescTable';
import doc from 'assets/propTypes/Table.json';

import Util from 'vendors/Util';

import 'scss/containers/app/modules/layout/TableExamples.scss';

const LOADING_SYMBOL = Symbol('LOADING_SYMBOL');

class TableExamples extends Component {

    constructor(props) {

        super(props);

        this.state = {
            data: this.generateData(),
            sort: null
        };

        this.columns = [{
            fixed: Table.Fixed.LEFT,
            headRenderer: 'ID',
            bodyRenderer: rowDate => {

                if (rowDate[LOADING_SYMBOL]) {
                    return (
                        <CircularLoading/>
                    );
                }

                return rowDate.id;

            },
            footRenderer: 'Total',
            footSpan: 2,
            sortable: true,
            sortingProp: 'id'
        }, {
            fixed: Table.Fixed.LEFT,
            width: 300,
            headRenderer: 'Name',
            bodyClassName: 'nowrap',
            bodyRenderer: rowDate => rowDate.firstName && rowDate.lastName ? `${rowDate.firstName} ${rowDate.lastName}` : '',
            sortable: true,
            sortingProp: 'firstName'
        }, {
            headRenderer: 'Age',
            headAlign: Table.Align.RIGHT,
            bodyRenderer: rowDate => rowDate.age,
            bodyAlign: Table.Align.RIGHT,
            footRenderer: () => {
                const {data} = this.state;
                return (
                    <Fragment>

Average

{data.reduce((a, b) => a + b.age, 0) / data.length}

                    </Fragment>
                );
            },
            footAlign: Table.Align.RIGHT,
            sortable: true,
            sortingProp: 'age'
        }, {
            width: 300,
            headRenderer: 'Other Column 1',
            bodyRenderer: rowDate => rowDate.other ? `${rowDate.other} 1` : ''
        }, {
            width: 300,
            headRenderer: 'Other Column 2',
            bodyRenderer: rowDate => rowDate.other ? `${rowDate.other} 2` : ''
        }, {
            width: 300,
            headRenderer: 'Other Column 3',
            bodyRenderer: rowDate => rowDate.other ? `${rowDate.other} 3` : ''
        }, {
            width: 300,
            headRenderer: 'Other Column 4',
            bodyRenderer: rowDate => rowDate.other ? `${rowDate.other} 4` : ''
        }, {
            headRenderer: 'Deposit',
            headAlign: Table.Align.RIGHT,
            bodyRenderer: rowDate => rowDate.deposit ? `$${rowDate.deposit}` : '',
            bodyAlign: Table.Align.RIGHT,
            footRenderer: () =>
                <Fragment>

Sum

${this.state.data.reduce((a, b) => round(a + b.deposit, 2), 0)}

                </Fragment>,
            footAlign: Table.Align.RIGHT,
            sortable: true,
            sortingProp: 'deposit'
        }, {
            fixed: Table.Fixed.RIGHT,
            headRenderer: 'Status',
            bodyRenderer: rowData => rowData[LOADING_SYMBOL] ?
                null
                :
                <Switcher value={!rowData.disabled}
                          size="small"
                          onClick={e => e.stopPropagation()}/>
        }];

        this.pageSizes = [{
            value: 10,
            text: '10 / page'
        }, {
            value: 20,
            text: '20 / page'
        }, {
            value: 30,
            text: '30 / page'
        }, {
            value: 40,
            text: '40 / page'
        }, {
            value: 50,
            text: '50 / page'
        }];

    }

    generateData = (size = 100, base = '', expanded = true) => {

        let data = [];
        for (let i = 0; i < size; i++) {

            const id = `${base ? `${base}-` : ''}${i}`,
                item = {
                    id,
                    firstName: `firstName${id}`,
                    lastName: `lastName${id}`,
                    age: Math.floor(Math.random() * 100),
                    deposit: round(Math.random() * 1000000, 2),
                    other: 'Other Content'
                };

            if (expanded && id.split('-').pop() === '0') {
                item.children = [{
                    [LOADING_SYMBOL]: true
                }];
            }

            data.push(item);

        }

        return data;

    };

    deleteRow = id => {

        const {data} = this.state,
            newData = data.filter(item => item.id !== id);

        this.setState({
            data: newData
        });

    };

    handleSortChange = sort => {
        this.setState({
            sort
        });
        console.log('Sort Change Value: ', sort);
    };

    handlePageChange = (page, pageSize) => {
        console.log(`page: ${page}, pageSize: ${pageSize}`);
    };

    handleDataUpdate = currentPageData => {
        console.log('Data Update Value: ', currentPageData);
    };

    handleSelect = (rowData, rowIndex, value) => {
        console.log('Select Value: ', rowData);
    };

    handleDeselect = (rowData, rowIndex, value) => {
        console.log('Deselect Value: ', rowData);
    };

    handleSelectAll = value => {
        console.log('Select All Value: ', value);
    };

    handleSeselectAll = value => {
        console.log('Deselect All Value: ', value);
    };

    handleChange = value => {
        console.log('Changed Value: ', value);
    };

    handleExpand = rowData => {

        console.log('Expand: ', rowData);

        const {data} = this.state;

        if (!rowData || !data || !rowData.children[0][LOADING_SYMBOL]) {
            return;
        }

        setTimeout(() => {

            Util.postOrderTraverse({
                children: data
            }, node => {
                if (node && node.id === rowData.id) {
                    node.children = this.generateData(10, node.id);
                    return false;
                }
            });

            this.setState({
                data
            });

        }, 1000);

    };

    handleCollapse = rowData => {
        console.log('Collapse: ', rowData);
    };

    clearSort = () => {
        this.setState({
            sort: null
        });
    };

    render() {

        const {data, sort} = this.state;

        return (

Table

                    Table
                     are used to display data and to organize it.

Examples

                <Widget>

                    <WidgetHeader className="example-header" title="With isPagging"/>

A simple Table example.

                            <RaisedButton className="table-action"
                                          theme={RaisedButton.Theme.PRIMARY}
                                          value="Clear Table Sort"
                                          onClick={this.clearSort}/>

 rowData[LOADING_SYMBOL] ?
                                           null
                                           :
                                           <IconButton iconCls="fas fa-trash-alt"
                                                       onClick={() => this.deleteRow(rowData.id)}/>
                                   }]}
                                   sort={sort}
                                   selectMode={Table.SelectMode.MULTI_SELECT}
                                   isHeadFixed={true}
                                   isFootFixed={true}
                                   scroll={{
                                       width: 1200,
                                       height: 400
                                   }}
                                   paggingCountRenderer={count => Self Defined Total Count: {count}}
                                   onSortChange={this.handleSortChange}
                                   onPageChange={this.handlePageChange}
                                   onExpand={this.handleExpand}
                                   onCollapse={this.handleCollapse}
                                   onDataUpdate={this.handleDataUpdate}
                                   onChange={this.handleChange}
                                   onSelect={this.handleSelect}
                                   onSelectAll={this.handleSelectAll}
                                   onDeselect={this.handleDeselect}
                                   onDeselectAll={this.handleSeselectAll}/>

                </Widget>

Properties

                <PropTypeDescTable data={doc}/>

        );
    }
}

export default TableExamples;
<commit_msg>update TableExamples<commit_after>import React, {Component, Fragment} from 'react';
import round from 'lodash/round';

import Table from 'src/Table';
import Switcher from 'src/Switcher';
import IconButton from 'src/IconButton';
import Widget from 'src/Widget';
import WidgetHeader from 'src/WidgetHeader';
import RaisedButton from 'src/RaisedButton';
import CircularLoading from 'src/CircularLoading';

import PropTypeDescTable from 'components/PropTypeDescTable';
import doc from 'assets/propTypes/Table.json';

import Util from 'vendors/Util';

import 'scss/containers/app/modules/layout/TableExamples.scss';

const LOADING_SYMBOL = Symbol('LOADING_SYMBOL');

class TableExamples extends Component {

    constructor(props) {

        super(props);

        this.state = {
            data: this.generateData(),
            sorting: null
        };

        this.columns = [{
            fixed: Table.Fixed.LEFT,
            headRenderer: 'ID',
            bodyRenderer: rowDate => {

                if (rowDate[LOADING_SYMBOL]) {
                    return (
                        <CircularLoading/>
                    );
                }

                return rowDate.id;

            },
            footRenderer: 'Total',
            footSpan: 2,
            sortable: true,
            sortingProp: 'id'
        }, {
            fixed: Table.Fixed.LEFT,
            width: 300,
            headRenderer: 'Name',
            bodyClassName: 'nowrap',
            bodyRenderer: rowDate => rowDate.firstName && rowDate.lastName ? `${rowDate.firstName} ${rowDate.lastName}` : '',
            sortable: true,
            sortingProp: 'firstName'
        }, {
            headRenderer: 'Age',
            headAlign: Table.Align.RIGHT,
            bodyRenderer: rowDate => rowDate.age,
            bodyAlign: Table.Align.RIGHT,
            footRenderer: () => {
                const {data} = this.state;
                return (
                    <Fragment>

Average

{data.reduce((a, b) => a + b.age, 0) / data.length}

                    </Fragment>
                );
            },
            footAlign: Table.Align.RIGHT,
            sortable: true,
            sortingProp: 'age'
        }, {
            width: 300,
            headRenderer: 'Other Column 1',
            bodyRenderer: rowDate => rowDate.other ? `${rowDate.other} 1` : ''
        }, {
            width: 300,
            headRenderer: 'Other Column 2',
            bodyRenderer: rowDate => rowDate.other ? `${rowDate.other} 2` : ''
        }, {
            width: 300,
            headRenderer: 'Other Column 3',
            bodyRenderer: rowDate => rowDate.other ? `${rowDate.other} 3` : ''
        }, {
            width: 300,
            headRenderer: 'Other Column 4',
            bodyRenderer: rowDate => rowDate.other ? `${rowDate.other} 4` : ''
        }, {
            headRenderer: 'Deposit',
            headAlign: Table.Align.RIGHT,
            bodyRenderer: rowDate => rowDate.deposit ? `$${rowDate.deposit}` : '',
            bodyAlign: Table.Align.RIGHT,
            footRenderer: () =>
                <Fragment>

Sum

${this.state.data.reduce((a, b) => round(a + b.deposit, 2), 0)}

                </Fragment>,
            footAlign: Table.Align.RIGHT,
            sortable: true,
            sortingProp: 'deposit'
        }, {
            fixed: Table.Fixed.RIGHT,
            headRenderer: 'Status',
            bodyRenderer: rowData => rowData[LOADING_SYMBOL] ?
                null
                :
                <Switcher value={!rowData.disabled}
                          size="small"
                          onClick={e => e.stopPropagation()}/>
        }];

        this.pageSizes = [{
            value: 10,
            text: '10 / page'
        }, {
            value: 20,
            text: '20 / page'
        }, {
            value: 30,
            text: '30 / page'
        }, {
            value: 40,
            text: '40 / page'
        }, {
            value: 50,
            text: '50 / page'
        }];

    }

    generateData = (size = 100, base = '', expanded = true) => {

        let data = [];
        for (let i = 0; i < size; i++) {

            const id = `${base ? `${base}-` : ''}${i}`,
                item = {
                    id,
                    firstName: `firstName${id}`,
                    lastName: `lastName${id}`,
                    age: Math.floor(Math.random() * 100),
                    deposit: round(Math.random() * 1000000, 2),
                    other: 'Other Content'
                };

            if (expanded && id.split('-').pop() === '0') {
                item.children = [{
                    [LOADING_SYMBOL]: true
                }];
            }

            data.push(item);

        }

        return data;

    };

    deleteRow = id => {

        const {data} = this.state,
            newData = data.filter(item => item.id !== id);

        this.setState({
            data: newData
        });

    };

    handleSortChange = sorting => {
        this.setState({
            sorting
        });
        console.log('Sort Change Value: ', sorting);
    };

    handlePageChange = (page, pageSize) => {
        console.log(`page: ${page}, pageSize: ${pageSize}`);
    };

    handleDataUpdate = currentPageData => {
        console.log('Data Update Value: ', currentPageData);
    };

    handleSelect = (rowData, rowIndex, value) => {
        console.log('Select Value: ', rowData);
    };

    handleDeselect = (rowData, rowIndex, value) => {
        console.log('Deselect Value: ', rowData);
    };

    handleSelectAll = value => {
        console.log('Select All Value: ', value);
    };

    handleSeselectAll = value => {
        console.log('Deselect All Value: ', value);
    };

    handleChange = value => {
        console.log('Changed Value: ', value);
    };

    handleExpand = rowData => {

        console.log('Expand: ', rowData);

        const {data} = this.state;

        if (!rowData || !data || !rowData.children[0][LOADING_SYMBOL]) {
            return;
        }

        setTimeout(() => {

            Util.postOrderTraverse({
                children: data
            }, node => {
                if (node && node.id === rowData.id) {
                    node.children = this.generateData(10, node.id);
                    return false;
                }
            });

            this.setState({
                data
            });

        }, 1000);

    };

    handleCollapse = rowData => {
        console.log('Collapse: ', rowData);
    };

    clearSort = () => {
        this.setState({
            sorting: null
        });
    };

    render() {

        const {data, sorting} = this.state;

        return (

Table

                    Table
                     are used to display data and to organize it.

Examples

                <Widget>

                    <WidgetHeader className="example-header" title="With isPagging"/>

A simple Table example.

                            <RaisedButton className="table-action"
                                          theme={RaisedButton.Theme.PRIMARY}
                                          value="Clear Table Sort"
                                          onClick={this.clearSort}/>

 rowData[LOADING_SYMBOL] ?
                                           null
                                           :
                                           <IconButton iconCls="fas fa-trash-alt"
                                                       onClick={() => this.deleteRow(rowData.id)}/>
                                   }]}
                                   sorting={sorting}
                                   selectMode={Table.SelectMode.MULTI_SELECT}
                                   isHeadFixed={true}
                                   isFootFixed={true}
                                   scroll={{
                                       width: 1200,
                                       height: 400
                                   }}
                                   paggingCountRenderer={count => Self Defined Total Count: {count}}
                                   onSortChange={this.handleSortChange}
                                   onPageChange={this.handlePageChange}
                                   onExpand={this.handleExpand}
                                   onCollapse={this.handleCollapse}
                                   onDataUpdate={this.handleDataUpdate}
                                   onChange={this.handleChange}
                                   onSelect={this.handleSelect}
                                   onSelectAll={this.handleSelectAll}
                                   onDeselect={this.handleDeselect}
                                   onDeselectAll={this.handleSeselectAll}/>

                </Widget>

Properties

                <PropTypeDescTable data={doc}/>

        );
    }
}

export default TableExamples;
<|endoftext|>


<commit_before>smartApp.controller('MigratePostToPreController', function($routeParams, $scope, AuthenService, MigratePostToPreService, ReasonService, SystemService) {

    // Templates
    var runTime = new Date().getTime();
    $scope.template = {
        header: 'app/views/header.html?' + runTime,
        customerprofile: 'app/views/customerprofile.html?' + runTime,
        effectivepriceplan: 'app/views/effectivepriceplan.html?' + runTime,
        reasonmemo: 'app/views/reasonmemo.html?' + runTime
    };

    // Prepare page parameters
    $scope.shopType = '0';
    $scope.SubNo = $routeParams.SubNo;

    // Initialize variables
    $scope.divID = 'migratePostToPreContent';
    $scope.subNoLength = 10;
    $scope.zipLength = 5;

    // Initalize states of the UI controls in the CustomerProfile template to display properly in the page
    $scope.onCustomerProfileTemplateLoaded = function() {
        $('#unMatch2').hide();
        $scope.isAuthorize = false;
        $scope.isCustomerProfile = false;
    };

    // (Start) Get current SIM data ----------------------
    var formatDate = function(date) {
        if (!date) return date;

        return moment(date).format('DD/MM/YYYY');
    };

    var onGetSIMData = function(result) {
        $scope.data = result.data;

        if (!$scope.data) {
            $scope.getSIMDataFailed = true;
            SystemService.hideLoading();

            return;
        }

        $scope.data.customerProfile['birthdate'] = formatDate($scope.data.customerProfile['birthdate']);
        $scope.data.customerProfile['id-expire-date'] = formatDate($scope.data.customerProfile['id-expire-date']);

        authenticate();
    };

    if ($scope.SubNo !== 'null') {
        SystemService.showLoading();
        MigratePostToPreService.getSIMData($scope.SubNo, onGetSIMData);
    }
    // (End) Get current SIM data ----------------------

    // (Start) Authentication ----------------------
    var orderData = {};

    var authenticate = function() {
        AuthenService.getAuthen(function(authResult) {
            $scope.getAuthen = authResult;

            $scope.shopType = $scope.getAuthen['shopType'];
            if ($scope.shopType === '0') {
                $scope.isCustomerProfile = true;
            }

            var partnerCode = utils.getObject($scope.getAuthen, 'partnerCodes.0');

            getProPosition(partnerCode);

            SystemService.getOrderId($scope.getAuthen.channel, partnerCode, function(order) {
                SystemService.hideLoading();

                orderData = order;

                if ($scope.shopType === '1') {
                    // Auto-open the CardReader dialog
                    setTimeout(function() {
                        var fancyboxOptions = {
                            helpers: {
                                overlay: {
                                    closeClick: false
                                }
                            },

                            beforeShow: function() {
                                $('#CitizenID').prop('disabled', true);
                                $('#loadingReadCard').hide();
                                $('#unMatch').hide();
                            },

                            afterClose: function() {
                                if (!$scope.onInputId()) {
                                    window.close();
                                }
                            }
                        };

                        $('#btn-fancy-ReadCard').fancybox(fancyboxOptions).trigger('click');
                    }, 1000);
                }
            });
        });
    };

    $scope.openSSO = function () {
        var getReadyCitizenInput = function() {
            $('#CitizenID').prop('disabled', false);
            $('#CitizenID').focus();
        };

        if ($scope.getAuthen.isSecondAuthen) {
            var openDialog = function(uri, name, options, closeCallback) {
                var win = window.open(uri, name, options);

                var interval = window.setInterval(function() {
                    try {
                        if (!win || win.closed) {
                            window.clearInterval(interval);
                            closeCallback(win);
                        }
                    }
                    catch (ex) {}
                }, 1000);

                return win;
            };

            var url = SystemService.secondAuthenURL + 'SecondAuthen.jsp?App=WEBUI&TrxID=' + orderData.TrxID + '&Retry=yes&Goto=';

            openDialog(url, 'MsgWindow', 'width=800, height=600', function(w) {
                SystemService.showLoading();

                SystemService.second_authen(orderData.TrxID, function(result) {
                    SystemService.hideLoading();

                    var displayMsg = utils.getObject(result, 'display-messages.0');
                    if (!displayMsg || !displayMsg['message-type']) {
                        setTimeout(function() {
                            getReadyCitizenInput();
                        }, 1000);
                    }
                    else {
                        setTimeout(function() {
                            SystemService.showAlert(displayMsg);
                        }, 1000);
                    }
                });
            });
        }
        else {
            getReadyCitizenInput();
        }
    };

    $scope.onInputId = function () {
        var value = $('#CitizenID').val();

        if (value.length === 13) {
            if (value === $scope.data.customerProfile['id-number']) {
                $scope.isCustomerProfile = true;

                $('#unMatch').hide();
                $('.fancybox-close').click();

                return true;
            }
            else {
                $('#unMatch').show();
            }
        }
    };

    $scope.onInputId2 = function () {
        var value = $('#CitizenID2').val();

        if (value.length === 13) {
            if (!SystemService.validatePID(value)) {
                $('#CitizenID2').blur().val('');
            }
        }
    };

    $scope.readCardError = function(msg) {
        SystemService.showAlert({
            'message': msg,
            'message-code': '',
            'message-type': 'WARNING',
            'en-message': '',
            'th-message': '',
            'technical-message': ''
        });
    };

    $scope.SetCardValue = function (result) {
        $scope.cardInfo = eval(result);

        $('#CitizenID').val($scope.cardInfo.CitizenID);
        $scope.onInputId();
    };
    // (End) Authentication ----------------------

    // (Start) Camera ----------------------
    $scope.varPhoto = '';

    $scope.initWebCam = function() {
        setTimeout(function() {
            $('#btnSavePhoto').hide();

            var html = webcam.get_html(320, 240);
            $('#dataCamera').html(html);

            webcam.set_api_url(getURL('services/file/upload.service'));
            webcam.set_quality(90); // JPEG quality (1 - 100)
            webcam.set_shutter_sound(true); // play shutter click sound
            webcam.set_hook('onComplete', onCompleteSnap);
        }, 500);
    };

    var onCompleteSnap = function(msg) {
        $scope.varPhoto = msg;

        var ie_preview_image = $('#ie_preview_image')[0];
        ie_preview_image.src = 'data:image/png;base64,' + msg;

        webcam.reset();

        $('#btnSavePhoto').show();
    }

    $scope.webcamSnap = function () {
        webcam.snap();
    };
    // (End) Camera ----------------------

    // (Start) Validation ----------------------
    $scope.isIdCardExpired = function(expireDate) {
        if (expireDate) {
            return moment(expireDate, 'DD/MM/YYYY').diff(moment(), 'days') >= 0;
        }

        return false;
    };

    SystemService.calendarDatePicker();
    // (End) Validation ----------------------

    // (Start) Number Information ----------------------
    var getProPosition = function(partnerCode) {
        var proPositionPayload = {
            'company-code': $scope.data.simData['company-code'],
            'customer-type': $scope.data.simData['account-category'],
            'propo-type': 'NEW',
            'mobile-servicetype': $scope.data.simData['mobile-servicetype'],
            'partner-code': partnerCode,
            'privilege': false
        };

        MigratePostToPreService.getProPosition(proPositionPayload, onGetProPosition);
    };

    var onGetProPosition = function(result) {
        $scope.proPositionList = result.data['response-data'];

        if ($scope.proPositionList && $scope.proPositionList.length) {
            $scope.selectedProPosition = $scope.proPositionList[0]['proposition-code'];
        }
    };

    var onGetPricePlan = function(result) {
        $scope.pricePlanList = utils.getObject(result, 'data.response-data');

        $scope.pricePlan = $scope.pricePlanList[0];
        $scope.pricePlanName = $scope.pricePlan.name;
    };

    $scope.changePricePlan = function(pp) {
        $scope.pricePlan = pp;
        $scope.pricePlanName = $scope.pricePlan.name;
    };

    $scope.$watch('selectedProPosition', function(val) {
        if (!val) return;

        var proposition = _.find($scope.proPositionList, function(item) {
            return item['proposition-code'] === val;
        });

        var payload = {
            'company-code': $scope.data.simData['company-code'],
            'customer-type': $scope.data.simData['account-category'],
            'customer-subtype': $scope.data.simData['account-sub-type'],
            'service-level': proposition['service-level'],
            'proposition': val,
            'partner-code': utils.getObject($scope.getAuthen, 'partnerCodes.0'),
            'privilege': false
        };

        MigratePostToPreService.getPricePlan(payload, onGetPricePlan);
    });
    // (End) Number Information ----------------------

    // (Start) Registration Address ----------------------
    var onSearchAddress = function(result) {
        var address = utils.getObject(result, 'data.response-data.0');

        if ($scope.data.customerAddress.zip === address.zipcode) {
            $scope.data.customerAddress['sub-district'] = address.subdistrict;
            $scope.data.customerAddress['district'] = address.district;
            $scope.data.customerAddress['province'] = address.province;
        }
    };

    $scope.useSameAddressAsCard = function() {
        $scope.data.customerAddress = angular.copy($scope.data.customerAddressOriginal);
    };

    $scope.clearAddress = function() {
        $scope.data.customerAddress = {};
    };

    $scope.$watch('data.customerAddress.zip', function(val) {
        if (val && val.length === $scope.zipLength) {
            var payload = {
                keyword: val
            };

            MigratePostToPreService.searchAddress(payload, onSearchAddress);
        }
    });
    // (End) Registration Address ----------------------

    $scope.showReadcard = "1";
    $scope.isMatch = true;

    $scope.isReadCardSuccess = false;

    $scope.isManualReadCard = true;
    $scope.isAuthorize = false;

    // Reasons control
    $scope.reasons = [];
    $scope.reason = "";
    $scope.selectReason = {};

    ReasonService.list("119", function (result) {
        $scope.reasons = result;
        $scope.reason = $scope.reasons[86];
        $scope.selectReason = $scope.reasons[86];
    });

    $scope.onReasonChange = function () {
        $scope.selectReason = $scope.reasons[$('#selectReasonId').val()];
        console.log($scope.selectReason);
    };

    $scope.manualInputReadCard = function () {
        $('#loadingReadCard').hide();
        $('#loadingReadCard2').hide();
        $('#unMatch').hide();
        $('#unMatch2').hide();
        //document.getElementById("CitizenID").disabled = false;

        setTimeout(function () {
            $('#CitizenID').val('');
        }, 0);
        $scope.isManualReadCard = false;
    };

    $scope.SetCardValue2 = function (result) {
        $('#loadingReadCard2').hide();

        $scope.cardInfo2 = eval(result);
        console.log($scope.cardInfo2);

        $('#CitizenID2').val($scope.cardInfo2.CitizenID);
        $('#authorizeFullName').val($scope.cardInfo2.PrefixTH + "" + $scope.cardInfo2.FirstNameTH + "  " + $scope.cardInfo2.LastNameTH);
        //$scope.CitizenID2 = $scope.cardInfo2.CitizenID;
        //$scope.authorizeFullName = $scope.cardInfo2.PrefixTH + "" + $scope.cardInfo2.FirstNameTH + "  " + $scope.cardInfo2.LastNameTH;
    };

    $scope.SetCardValue3 = function (result) {
        $('#loadingReadCard3').hide();

        $scope.cardInfo3 = eval(result);
        console.log($scope.cardInfo3);

        $('#citizenID3').val($scope.cardInfo3.CitizenID);
        $('#prefixTH3').val($scope.cardInfo3.PrefixTH);
        $('#firstNameTH3').val($scope.cardInfo3.FirstNameTH);
        $('#lastNameTH3').val($scope.cardInfo3.LastNameTH);
        $('#birthDay').val($scope.cardInfo3.BirthDay);
        $('#expireDay').val($scope.cardInfo3.ExpireDay);
        $('#sex3').val($scope.cardInfo3.Sex);

        //$scope.cardType = "6";
        $('#cardType').val('6');

        //binding Tax Id
        $('#taxId3').val($scope.cardInfo3.CitizenID);

        //binding user registerd - ระบุผู้ใช้หมายเลข
        $('#titleRegisterd').val($scope.cardInfo3.PrefixTH);
        $('#firstNameRegisterd').val($scope.cardInfo3.FirstNameTH);
        $('#lastNameRegisterd').val($scope.cardInfo3.LastNameTH);
        $('#birthDayRegisterd').val($scope.cardInfo3.BirthDay);

        //$scope.newOwner = {
        //    citizenID: $scope.cardInfo3.CitizenID,
        //    prefixTH: 'นาย',
        //    firstNameTH: $scope.cardInfo3.FirstNameTH,
        //    lastNameTH: $scope.cardInfo3.LastNameTH,
        //    prefixEN: $scope.cardInfo3.PrefixEN,
        //    firstNameEN: $scope.cardInfo3.FirstNameEN,
        //    lastNameEN: $scope.cardInfo3.LastNameEN,
        //    sex: $scope.cardInfo3.Sex,
        //    birthDay: $scope.cardInfo3.BirthDay,
        //    issueDay: $scope.cardInfo3.IssueDay,
        //    expireDay: $scope.cardInfo3.ExpireDay,
        //};
        //console.log($scope.newOwner);
    };

    $scope.confirmPrint = function () {
        //confirm
        SystemService.showBeforeClose({
            "message": "รายการคำขอเลขที่ OR30935 ",
            "message2": "ได้รับข้อมูลเรียบร้อยแล้ว",
        });
        //SystemService.showConfirm().then(function (value) {

        //}, function (reason) {
        //    //cancel

        //});
    };

});<commit_msg>p koh modify<commit_after>smartApp.controller('MigratePostToPreController', function($routeParams, $scope, AuthenService, MigratePostToPreService, ReasonService, SystemService) {

    // Templates
    var runTime = new Date().getTime();
    $scope.template = {
        header: 'app/views/header.html?' + runTime,
        customerprofile: 'app/views/customerprofile.html?' + runTime,
        effectivepriceplan: 'app/views/effectivepriceplan.html?' + runTime,
        reasonmemo: 'app/views/reasonmemo.html?' + runTime
    };

    // Prepare page parameters
    // $scope.shopType = '0';
    $scope.SubNo = $routeParams.subno ? $routeParams.subno : 'null';

    // Initialize variables
    $scope.divID = 'migratePostToPreContent';
    $scope.subNoLength = 10;
    $scope.zipLength = 5;

    // Initalize states of the UI controls in the CustomerProfile template to display properly in the page
    $scope.onCustomerProfileTemplateLoaded = function() {
        $('#unMatch2').hide();
        $scope.isAuthorize = false;
        $scope.isCustomerProfile = false;
    };

    // (Start) Get current SIM data ----------------------
    var formatDate = function(date) {
        if (!date) return date;

        return moment(date).format('DD/MM/YYYY');
    };

    var onGetSIMData = function(result) {
        $scope.data = result.data;

        if (!$scope.data) {
            $scope.getSIMDataFailed = true;
            SystemService.hideLoading();

            return;
        }

        $scope.data.customerProfile['birthdate'] = formatDate($scope.data.customerProfile['birthdate']);
        $scope.data.customerProfile['id-expire-date'] = formatDate($scope.data.customerProfile['id-expire-date']);

        authenticate();
    };

    if ($scope.SubNo !== 'null') {
        SystemService.showLoading();
        MigratePostToPreService.getSIMData($scope.SubNo, onGetSIMData);
    }
    // (End) Get current SIM data ----------------------

    // (Start) Authentication ----------------------
    var orderData = {};

    var authenticate = function() {
        AuthenService.getAuthen(function(authResult) {
            $scope.getAuthen = authResult;

            $scope.shopType = $scope.getAuthen['shopType'];
            if ($scope.shopType === '0') {
                $scope.isCustomerProfile = true;
            }

            var partnerCode = utils.getObject($scope.getAuthen, 'partnerCodes.0');

            getProPosition(partnerCode);

            SystemService.getOrderId($scope.getAuthen.channel, partnerCode, function(order) {
                SystemService.hideLoading();

                orderData = order;

                if ($scope.shopType === '1') {
                    // Auto-open the CardReader dialog
                    setTimeout(function() {
                        var fancyboxOptions = {
                            helpers: {
                                overlay: {
                                    closeClick: false
                                }
                            },

                            beforeShow: function() {
                                $('#CitizenID').prop('disabled', true);
                                $('#loadingReadCard').hide();
                                $('#unMatch').hide();
                            },

                            afterClose: function() {
                                if (!$scope.onInputId()) {
                                    //window.close();
                                }
                            }
                        };

                        $('#btn-fancy-ReadCard').fancybox(fancyboxOptions).trigger('click');
                    }, 1000);
                }
            });
        });
    };

    $scope.openSSO = function () {
        var getReadyCitizenInput = function() {
            $('#CitizenID').prop('disabled', false);
            $('#CitizenID').focus();
        };

        if ($scope.getAuthen.isSecondAuthen) {
            var openDialog = function(uri, name, options, closeCallback) {
                var win = window.open(uri, name, options);

                var interval = window.setInterval(function() {
                    try {
                        if (!win || win.closed) {
                            window.clearInterval(interval);
                            closeCallback(win);
                        }
                    }
                    catch (ex) {}
                }, 1000);

                return win;
            };

            var url = SystemService.secondAuthenURL + 'SecondAuthen.jsp?App=WEBUI&TrxID=' + orderData.TrxID + '&Retry=yes&Goto=';

            openDialog(url, 'MsgWindow', 'width=800, height=600', function(w) {
                SystemService.showLoading();

                SystemService.second_authen(orderData.TrxID, function(result) {
                    SystemService.hideLoading();

                    var displayMsg = utils.getObject(result, 'display-messages.0');
                    if (!displayMsg || !displayMsg['message-type']) {
                        setTimeout(function() {
                            getReadyCitizenInput();
                        }, 1000);
                    }
                    else {
                        setTimeout(function() {
                            SystemService.showAlert(displayMsg);
                        }, 1000);
                    }
                });
            });
        }
        else {
            getReadyCitizenInput();
        }
    };

    $scope.onInputId = function () {
        var value = $('#CitizenID').val();

        if (value.length === 13) {
            if (value === $scope.data.customerProfile['id-number']) {
                $scope.isCustomerProfile = true;

                $('#unMatch').hide();
                $('.fancybox-close').click();

                return true;
            }
            else {
                $('#unMatch').show();
            }
        }
    };

    $scope.onInputId2 = function () {
        var value = $('#CitizenID2').val();

        if (value.length === 13) {
            if (!SystemService.validatePID(value)) {
                $('#CitizenID2').blur().val('');
            }
        }
    };

    $scope.readCardError = function(msg) {
        SystemService.showAlert({
            'message': msg,
            'message-code': '',
            'message-type': 'WARNING',
            'en-message': '',
            'th-message': '',
            'technical-message': ''
        });
    };

    $scope.SetCardValue = function (result) {
        $scope.cardInfo = eval(result);

        $('#CitizenID').val($scope.cardInfo.CitizenID);
        $scope.onInputId();
    };
    // (End) Authentication ----------------------

    // (Start) Camera ----------------------
    $scope.varPhoto = '';

    $scope.initWebCam = function() {
        setTimeout(function() {
            $('#btnSavePhoto').hide();

            var html = webcam.get_html(320, 240);
            $('#dataCamera').html(html);

            webcam.set_api_url(getURL('services/file/upload.service'));
            webcam.set_quality(90); // JPEG quality (1 - 100)
            webcam.set_shutter_sound(true); // play shutter click sound
            webcam.set_hook('onComplete', onCompleteSnap);
        }, 500);
    };

    var onCompleteSnap = function(msg) {
        $scope.varPhoto = msg;

        var ie_preview_image = $('#ie_preview_image')[0];
        ie_preview_image.src = 'data:image/png;base64,' + msg;

        webcam.reset();

        $('#btnSavePhoto').show();
    }

    $scope.webcamSnap = function () {
        webcam.snap();
    };
    // (End) Camera ----------------------

    // (Start) Validation ----------------------
    $scope.isIdCardExpired = function(expireDate) {
        if (expireDate) {
            return moment(expireDate, 'DD/MM/YYYY').diff(moment(), 'days') >= 0;
        }

        return false;
    };

    SystemService.calendarDatePicker();
    // (End) Validation ----------------------

    // (Start) Number Information ----------------------
    var getProPosition = function(partnerCode) {
        var proPositionPayload = {
            'company-code': $scope.data.simData['company-code'],
            'customer-type': $scope.data.simData['account-category'],
            'propo-type': 'NEW',
            'mobile-servicetype': $scope.data.simData['mobile-servicetype'],
            'partner-code': partnerCode,
            'privilege': false
        };

        MigratePostToPreService.getProPosition(proPositionPayload, onGetProPosition);
    };

    var onGetProPosition = function(result) {
        $scope.proPositionList = result.data['response-data'];

        if ($scope.proPositionList && $scope.proPositionList.length) {
            $scope.selectedProPosition = $scope.proPositionList[0]['proposition-code'];
        }
    };

    var onGetPricePlan = function(result) {
        $scope.pricePlanList = utils.getObject(result, 'data.response-data');

        $scope.pricePlan = $scope.pricePlanList[0];
        $scope.pricePlanName = $scope.pricePlan.name;
    };

    $scope.changePricePlan = function(pp) {
        $scope.pricePlan = pp;
        $scope.pricePlanName = $scope.pricePlan.name;
    };

    $scope.$watch('selectedProPosition', function(val) {
        if (!val) return;

        var proposition = _.find($scope.proPositionList, function(item) {
            return item['proposition-code'] === val;
        });

        var payload = {
            'company-code': $scope.data.simData['company-code'],
            'customer-type': $scope.data.simData['account-category'],
            'customer-subtype': $scope.data.simData['account-sub-type'],
            'service-level': proposition['service-level'],
            'proposition': val,
            'partner-code': utils.getObject($scope.getAuthen, 'partnerCodes.0'),
            'privilege': false
        };

        MigratePostToPreService.getPricePlan(payload, onGetPricePlan);
    });
    // (End) Number Information ----------------------

    // (Start) Registration Address ----------------------
    var onSearchAddress = function(result) {
        var address = utils.getObject(result, 'data.response-data.0');

        if ($scope.data.customerAddress.zip === address.zipcode) {
            $scope.data.customerAddress['sub-district'] = address.subdistrict;
            $scope.data.customerAddress['district'] = address.district;
            $scope.data.customerAddress['province'] = address.province;
        }
    };

    $scope.useSameAddressAsCard = function() {
        $scope.data.customerAddress = angular.copy($scope.data.customerAddressOriginal);
    };

    $scope.clearAddress = function() {
        $scope.data.customerAddress = {};
    };

    $scope.$watch('data.customerAddress.zip', function(val) {
        if (val && val.length === $scope.zipLength) {
            var payload = {
                keyword: val
            };

            MigratePostToPreService.searchAddress(payload, onSearchAddress);
        }
    });
    // (End) Registration Address ----------------------

    $scope.showReadcard = "1";
    $scope.isMatch = true;

    $scope.isReadCardSuccess = false;

    $scope.isManualReadCard = true;
    $scope.isAuthorize = false;

    // Reasons control
    $scope.reasons = [];
    $scope.reason = "";
    $scope.selectReason = {};

    ReasonService.list("119", function (result) {
        $scope.reasons = result;
        $scope.reason = $scope.reasons[86];
        $scope.selectReason = $scope.reasons[86];
    });

    $scope.onReasonChange = function () {
        $scope.selectReason = $scope.reasons[$('#selectReasonId').val()];
        console.log($scope.selectReason);
    };

    $scope.manualInputReadCard = function () {
        $('#loadingReadCard').hide();
        $('#loadingReadCard2').hide();
        $('#unMatch').hide();
        $('#unMatch2').hide();
        //document.getElementById("CitizenID").disabled = false;

        setTimeout(function () {
            $('#CitizenID').val('');
        }, 0);
        $scope.isManualReadCard = false;
    };

    $scope.SetCardValue2 = function (result) {
        $('#loadingReadCard2').hide();

        $scope.cardInfo2 = eval(result);
        console.log($scope.cardInfo2);

        $('#CitizenID2').val($scope.cardInfo2.CitizenID);
        $('#authorizeFullName').val($scope.cardInfo2.PrefixTH + "" + $scope.cardInfo2.FirstNameTH + "  " + $scope.cardInfo2.LastNameTH);
        //$scope.CitizenID2 = $scope.cardInfo2.CitizenID;
        //$scope.authorizeFullName = $scope.cardInfo2.PrefixTH + "" + $scope.cardInfo2.FirstNameTH + "  " + $scope.cardInfo2.LastNameTH;
    };

    $scope.SetCardValue3 = function (result) {
        $('#loadingReadCard3').hide();

        $scope.cardInfo3 = eval(result);
        console.log($scope.cardInfo3);

        $('#citizenID3').val($scope.cardInfo3.CitizenID);
        $('#prefixTH3').val($scope.cardInfo3.PrefixTH);
        $('#firstNameTH3').val($scope.cardInfo3.FirstNameTH);
        $('#lastNameTH3').val($scope.cardInfo3.LastNameTH);
        $('#birthDay').val($scope.cardInfo3.BirthDay);
        $('#expireDay').val($scope.cardInfo3.ExpireDay);
        $('#sex3').val($scope.cardInfo3.Sex);

        //$scope.cardType = "6";
        $('#cardType').val('6');

        //binding Tax Id
        $('#taxId3').val($scope.cardInfo3.CitizenID);

        //binding user registerd - ระบุผู้ใช้หมายเลข
        $('#titleRegisterd').val($scope.cardInfo3.PrefixTH);
        $('#firstNameRegisterd').val($scope.cardInfo3.FirstNameTH);
        $('#lastNameRegisterd').val($scope.cardInfo3.LastNameTH);
        $('#birthDayRegisterd').val($scope.cardInfo3.BirthDay);

        //$scope.newOwner = {
        //    citizenID: $scope.cardInfo3.CitizenID,
        //    prefixTH: 'นาย',
        //    firstNameTH: $scope.cardInfo3.FirstNameTH,
        //    lastNameTH: $scope.cardInfo3.LastNameTH,
        //    prefixEN: $scope.cardInfo3.PrefixEN,
        //    firstNameEN: $scope.cardInfo3.FirstNameEN,
        //    lastNameEN: $scope.cardInfo3.LastNameEN,
        //    sex: $scope.cardInfo3.Sex,
        //    birthDay: $scope.cardInfo3.BirthDay,
        //    issueDay: $scope.cardInfo3.IssueDay,
        //    expireDay: $scope.cardInfo3.ExpireDay,
        //};
        //console.log($scope.newOwner);
    };

    $scope.confirmPrint = function () {
        //confirm
        SystemService.showBeforeClose({
            "message": "รายการคำขอเลขที่ OR30935 ",
            "message2": "ได้รับข้อมูลเรียบร้อยแล้ว",
        });
        //SystemService.showConfirm().then(function (value) {

        //}, function (reason) {
        //    //cancel

        //});
    };

});<|endoftext|>