<commit_before>/**
 * mSupply Mobile
 * Sustainable Solutions (NZ) Ltd. 2019
 */

import { UIDatabase } from '../../database';

import { sortDataBy } from '../../utilities';
import { recordKeyExtractor } from './utilities';
import getColumns from './getColumns';
import getPageInfoColumns from './getPageInfoColumns';

import { ROUTES } from '../../navigation/constants';

/**
 * Gets data for initialising a customer invoice page from an associated transaction.
 *
 * @param    {Transaction}  transaction
 * @returns  {object}
 */
export const customerInvoiceInitialiser = transaction => {
  const { items: backingData } = transaction;

  const sortedData = backingData.sorted('item.name').slice();

  return {
    pageObject: transaction,
    backingData,
    data: sortedData,
    keyExtractor: recordKeyExtractor,
    dataState: new Map(),
    searchTerm: '',
    filterDataKeys: ['item.name', 'item.code'],
    sortBy: 'itemName',
    isAscending: true,
    modalKey: '',
    modalValue: null,
    hasSelection: false,
    route: ROUTES.CUSTOMER_INVOICE,
    columns: getColumns(ROUTES.CUSTOMER_INVOICE),
    getPageInfoColumns: getPageInfoColumns(ROUTES.CUSTOMER_INVOICE),
  };
};

/**
 * Gets data for initialising a customer invoices page.
 * Invoices shown initially are unfinalised and sorted by serial number.
 *
 * @returns  {object}
 */
export const customerInvoicesInitialiser = () => {
  const backingData = UIDatabase.objects('CustomerInvoice');
  const filteredData = backingData.filtered('status != $0', 'finalised').slice();
  const sortedData = sortDataBy(filteredData, 'serialNumber', false);

  return {
    backingData,
    data: sortedData,
    keyExtractor: recordKeyExtractor,
    dataState: new Map(),
    searchTerm: '',
    filterDataKeys: ['otherParty.name'],
    sortBy: 'serialNumber',
    isAscending: false,
    modalKey: '',
    hasSelection: false,
    route: ROUTES.CUSTOMER_INVOICES,
    columns: getColumns(ROUTES.CUSTOMER_INVOICES),
    getPageInfoColumns: getPageInfoColumns(ROUTES.CUSTOMER_INVOICES),
  };
};

/**
 * Gets data for initialising a customer requisition page from an associated requisition.
 *
 * @param    {Requisition}  requisition
 * @returns  {object}
 */
const customerRequisitionInitialiser = requisition => {
  const { items: backingData } = requisition;
  const sortedData = backingData.sorted('item.name').slice();

  return {
    pageObject: requisition,
    backingData: requisition.items,
    data: sortedData,
    keyExtractor: recordKeyExtractor,
    dataState: new Map(),
    searchTerm: '',
    filterDataKeys: ['item.name', 'item.code'],
    sortBy: 'itemName',
    isAscending: true,
    modalKey: '',
    modalValue: null,
    route: ROUTES.CUSTOMER_REQUISITION,
    columns: getColumns(ROUTES.CUSTOMER_REQUISITION),
    getPageInfoColumns: getPageInfoColumns(ROUTES.CUSTOMER_REQUISITION),
  };
};

/**
 * Gets data for initialising a customer requisitions page.
 *
 * @returns  {object}
 */
const customerRequisitionsInitialiser = () => {
  const backingData = UIDatabase.objects('ResponseRequisition');

  const filteredData = backingData.filtered('status != $0', 'finalised');
  const sortedData = sortDataBy(filteredData.slice(), 'serialNumber', false);

  return {
    backingData,
    data: sortedData,
    keyExtractor: recordKeyExtractor,
    searchTerm: '',
    filterDataKeys: ['serialNumber'],
    sortBy: 'serialNumber',
    isAscending: false,
    route: ROUTES.CUSTOMER_REQUISITIONS,
    columns: getColumns(ROUTES.CUSTOMER_REQUISITIONS),
    getPageInfoColumns: getPageInfoColumns(ROUTES.CUSTOMER_REQUISITIONS),
  };
};

/**
 * Gets data for initialising a stock page.
 *
 * @returns  {object}
 */
const stockInitialiser = () => {
  const backingData = UIDatabase.objects('Item').sorted('name');

  return {
    backingData,
    data: backingData.slice(),
    keyExtractor: recordKeyExtractor,
    dataState: new Map(),
    searchTerm: '',
    filterDataKeys: ['name', 'code'],
    sortBy: 'name',
    isAscending: true,
    selectedRow: null,
    route: ROUTES.STOCK,
    columns: getColumns(ROUTES.STOCK),
    getPageInfoColumns: getPageInfoColumns(ROUTES.STOCK),
  };
};

/**
 * Gets data for initialising a stocktakes page.
 * Initial data is unfinalised stocktakes, sorted by creation date.
 *
 * @returns  {object}
 */
const stocktakesInitialiser = () => {
  const backingData = UIDatabase.objects('Stocktake');

  const filteredData = backingData.filtered('status != $0', 'finalised');
  const sortedData = filteredData.sorted('createdDate', true).slice();

  return {
    backingData,
    data: sortedData,
    keyExtractor: recordKeyExtractor,
    dataState: new Map(),
    searchTerm: '',
    filterDataKeys: ['name', 'serialNumber'],
    sortBy: 'createdDate',
    isAscending: false,
    modalKey: '',
    hasSelection: false,
    route: ROUTES.STOCKTAKES,
    columns: getColumns(ROUTES.STOCKTAKES),
    getPageInfoColumns: getPageInfoColumns(ROUTES.STOCKTAKES),
  };
};

/**
 * Gets data for initialising a stocktake batch page from an associated stocktake item.
 *
 * @param    {StocktakeItem}  stocktakeItem
 * @returns  {object}
 */
const stocktakeBatchInitialiser = stocktakeItem => ({
  pageObject: stocktakeItem,
  backingData: stocktakeItem.batches,
  data: stocktakeItem.batches.slice(),
  keyExtractor: recordKeyExtractor,
  dataState: new Map(),
  sortBy: 'itemName',
  isAscending: true,
  modalKey: '',
  modalValue: null,
  columns: getColumns(ROUTES.CUSTOMER_INVOICE),
  getPageInfoColumns: getPageInfoColumns(ROUTES.CUSTOMER_INVOICE),
});

/**
 * Gets data for initialising a manage stocktake page from an associated stocktake item.
 *
 * @param    {Stocktake}  stocktake
 * @returns  {object}
 */
const stocktakeManagerInitialiser = stocktake => {
  const backingData = UIDatabase.objects('Item');

  return {
    stocktake,
    backingData,
    data: backingData.sorted('name').slice(),
    keyExtractor: recordKeyExtractor,
    dataState: new Map(),
    searchTerm: '',
    filterDataKeys: ['name', 'code'],
    name: stocktake ? stocktake.name : '',
    sortBy: 'name',
    isAscending: true,
    hasSelection: false,
    allSelected: false,
    showAll: true,
    route: ROUTES.STOCKTAKE_MANAGER,
    columns: getColumns(ROUTES.STOCKTAKE_MANAGER),
    getPageInfoColumns: getPageInfoColumns(ROUTES.STOCKTAKE_MANAGER),
  };
};

/**
 * Gets data for initialising an edit stocktake page from an associated stocktake item.
 *
 * @param    {Stocktake}  stocktake
 * @returns  {object}
 */
const stocktakeEditorInitialiser = stocktake => {
  const { items: backingData } = stocktake;
  const sortedData = backingData.sorted('item.name').slice();

  const hasNegativeAdjustmentReasons = UIDatabase.objects('NegativeAdjustmentReason').length > 0;
  const hasPositiveAdjustmentReasons = UIDatabase.objects('PositiveAdjustmentReason').length > 0;
  const usesReasons = hasNegativeAdjustmentReasons && hasPositiveAdjustmentReasons;

  const route = usesReasons ? ROUTES.STOCKTAKE_EDITOR_WITH_REASONS : ROUTES.STOCKTAKE_EDITOR;

  return {
    pageObject: stocktake,
    backingData,
    data: sortedData,
    keyExtractor: recordKeyExtractor,
    dataState: new Map(),
    searchTerm: '',
    filterDataKeys: ['item.name', 'item.code'],
    sortBy: 'itemName',
    isAscending: true,
    modalKey: '',
    modalValue: null,
    route,
    columns: getColumns(route),
    getPageInfoColumns: getPageInfoColumns(route),
  };
};

/**
 * Gets data for initialising an edit stocktake page when reasons
 * are defined from an associated stocktake.
 *
 * @param    {Stocktake}  stocktake
 * @returns  {object}
 */
const stocktakeEditorWithReasonsInitialiser = stocktake => {
  const { items: backingData } = stocktake;
  const sortedData = backingData.sorted('item.name').slice();

  return {
    pageObject: stocktake,
    backingData,
    data: sortedData,
    keyExtractor: recordKeyExtractor,
    dataState: new Map(),
    searchTerm: '',
    filterDataKeys: ['item.name', 'item.code'],
    sortBy: 'itemName',
    isAscending: true,
    modalKey: '',
    modalValue: null,
    route: ROUTES.STOCKTAKE_EDITOR_WITH_REASONS,
    columns: getColumns(ROUTES.STOCKTAKE_EDITOR_WITH_REASONS),
    getPageInfoColumns: getPageInfoColumns(ROUTES.STOCKTAKE_EDITOR_WITH_REASONS),
  };
};

/**
 * Gets data for initialising a supplier invoice page from an associated transaction item.
 *
 * @param    {Transaction}  transaction
 * @returns  {object}
 */
const supplierInvoiceInitialiser = transaction => {
  const backingData = transaction.getTransactionBatches(UIDatabase);

  const sortedData = backingData.sorted('itemName').slice();

  return {
    pageObject: transaction,
    backingData,
    data: sortedData,
    keyExtractor: recordKeyExtractor,
    dataState: new Map(),
    searchTerm: '',
    filterDataKeys: ['itemName'],
    sortBy: 'itemName',
    isAscending: true,
    modalKey: '',
    modalValue: null,
    hasSelection: false,
    route: ROUTES.SUPPLIER_INVOICE,
    columns: getColumns(ROUTES.SUPPLIER_INVOICE),
    getPageInfoColumns: getPageInfoColumns(ROUTES.SUPPLIER_INVOICE),
  };
};

/**
 * Gets data for initialising a supplier invoices page.
 * Data is initially unfinalised and sorted by serial number.
 *
 * @returns  {object}
 */
const supplierInvoicesInitialiser = () => {
  const backingData = UIDatabase.objects('SupplierInvoice');

  const filteredData = backingData.filtered('status != $0', 'finalised').slice();
  const sortedData = sortDataBy(filteredData, 'serialNumber', false);

  return {
    backingData,
    data: sortedData,
    keyExtractor: recordKeyExtractor,
    dataState: new Map(),
    searchTerm: '',
    filterDataKeys: ['serialNumber'],
    sortBy: 'serialNumber',
    isAscending: false,
    modalKey: '',
    hasSelection: false,
    route: ROUTES.SUPPLIER_INVOICES,
    columns: getColumns(ROUTES.SUPPLIER_INVOICES),
    getPageInfoColumns: getPageInfoColumns(ROUTES.SUPPLIER_INVOICES),
  };
};

/**
 * Gets data for initialising a supplier requisition page from an associated requisition.
 *
 * @param    {Requisition}  requisition
 * @returns  {object}
 */
const supplierRequisitionInitialiser = requisition => {
  const { program, items: backingData } = requisition;

  const usingPrograms = !!program;
  const route = program ? ROUTES.SUPPLIER_REQUISITION_WITH_PROGRAM : ROUTES.SUPPLIER_REQUISITION;

  const sortedData = backingData.sorted('item.name').slice();
  const filteredData = usingPrograms
    ? sortedData.filter(item => item.isLessThanThresholdMOS)
    : sortedData;

  return {
    pageObject: requisition,
    backingData,
    data: filteredData,
    keyExtractor: recordKeyExtractor,
    dataState: new Map(),
    searchTerm: '',
    filterDataKeys: ['item.name', 'item.code'],
    sortBy: 'itemName',
    isAscending: true,
    modalKey: '',
    hasSelection: false,
    modalValue: null,
    showAll: !usingPrograms,
    route: ROUTES.SUPPLIER_REQUISITION,
    columns: getColumns(route),
    getPageInfoColumns: getPageInfoColumns(route),
  };
};

/**
 * Gets data for initialising a supplier requisitions page.
 * Initial data are unfinalised requisitions, sorted by serial number.
 *
 * @returns  {object}
 */
const supplierRequisitionsInitialiser = () => {
  const backingData = UIDatabase.objects('RequestRequisition');

  const filteredData = backingData.filtered('status != $0', 'finalised').slice();
  const sortedData = sortDataBy(filteredData, 'serialNumber', false);

  return {
    backingData,
    data: sortedData,
    keyExtractor: recordKeyExtractor,
    dataState: new Map(),
    searchTerm: '',
    filterDataKeys: ['serialNumber'],
    sortBy: 'serialNumber',
    isAscending: false,
    modalKey: '',
    hasSelection: false,
    route: ROUTES.SUPPLIER_REQUISITIONS,
    columns: getColumns(ROUTES.SUPPLIER_REQUISITIONS),
    getPageInfoColumns: getPageInfoColumns(ROUTES.SUPPLIER_REQUISITIONS),
  };
};

const prescriptionsInitialiser = () => {
  const backingData = UIDatabase.objects('Prescription');
  const filteredData = backingData.filtered('status != $0', 'finalised').slice();
  const sortedData = sortDataBy(filteredData, 'serialNumber', false);

  return {
    backingData,
    data: sortedData,
    keyExtractor: recordKeyExtractor,
    dataState: new Map(),
    searchTerm: '',
    filterDataKeys: ['otherParty.name'],
    sortBy: 'serialNumber',
    isAscending: false,
    modalKey: '',
    hasSelection: false,
    route: ROUTES.PRESCRIPTIONS,
    columns: getColumns(ROUTES.PRESCRIPTIONS),
    getPageInfoColumns: getPageInfoColumns(ROUTES.PRESCRIPTIONS),
  };
};

export const prescriptionInitialiser = transaction => {
  const { items: backingData } = transaction;

  const sortedData = backingData.sorted('item.name').slice();

  return {
    pageObject: transaction,
    backingData,
    data: sortedData,
    keyExtractor: recordKeyExtractor,
    dataState: new Map(),
    searchTerm: '',
    filterDataKeys: ['item.name', 'item.code'],
    sortBy: 'itemName',
    isAscending: true,
    modalKey: '',
    modalValue: null,
    hasSelection: false,
    route: ROUTES.PRESCRIPTION,
    columns: getColumns(ROUTES.PRESCRIPTION),
    getPageInfoColumns: getPageInfoColumns(ROUTES.PRESCRIPTION),
  };
};

const pageInitialisers = {
  customerInvoice: customerInvoiceInitialiser,
  customerInvoices: customerInvoicesInitialiser,
  customerRequisition: customerRequisitionInitialiser,
  customerRequisitions: customerRequisitionsInitialiser,
  stock: stockInitialiser,
  stocktakeBatchEditModal: stocktakeBatchInitialiser,
  stocktakeBatchEditModalWithReasons: stocktakeBatchInitialiser,
  stocktakeEditor: stocktakeEditorInitialiser,
  stocktakeEditorWithReasons: stocktakeEditorWithReasonsInitialiser,
  stocktakeManager: stocktakeManagerInitialiser,
  stocktakes: stocktakesInitialiser,
  supplierInvoice: supplierInvoiceInitialiser,
  supplierInvoices: supplierInvoicesInitialiser,
  supplierRequisition: supplierRequisitionInitialiser,
  supplierRequisitions: supplierRequisitionsInitialiser,
  prescriptions: prescriptionsInitialiser,
  prescription: prescriptionInitialiser,
};

/**
 * A wrapper for mapping pages to initialisation functions.
 *
 * @param    {object}    A mapper from page names to initialisation functions.
 * @returns  {Function}  A lookup function for retrieving page initialisers.
 */
const getPageInitialiser = pageToInitialiser => page => pageToInitialiser[page];

export default getPageInitialiser(pageInitialisers);
<commit_msg>Add prescribers state init<commit_after>/**
 * mSupply Mobile
 * Sustainable Solutions (NZ) Ltd. 2019
 */

import { UIDatabase } from '../../database';

import { sortDataBy } from '../../utilities';
import { recordKeyExtractor } from './utilities';
import getColumns from './getColumns';
import getPageInfoColumns from './getPageInfoColumns';

import { ROUTES } from '../../navigation/constants';

/**
 * Gets data for initialising a customer invoice page from an associated transaction.
 *
 * @param    {Transaction}  transaction
 * @returns  {object}
 */
export const customerInvoiceInitialiser = transaction => {
  const { items: backingData } = transaction;

  const sortedData = backingData.sorted('item.name').slice();

  return {
    pageObject: transaction,
    backingData,
    data: sortedData,
    keyExtractor: recordKeyExtractor,
    dataState: new Map(),
    searchTerm: '',
    filterDataKeys: ['item.name', 'item.code'],
    sortBy: 'itemName',
    isAscending: true,
    modalKey: '',
    modalValue: null,
    hasSelection: false,
    route: ROUTES.CUSTOMER_INVOICE,
    columns: getColumns(ROUTES.CUSTOMER_INVOICE),
    getPageInfoColumns: getPageInfoColumns(ROUTES.CUSTOMER_INVOICE),
  };
};

/**
 * Gets data for initialising a customer invoices page.
 * Invoices shown initially are unfinalised and sorted by serial number.
 *
 * @returns  {object}
 */
export const customerInvoicesInitialiser = () => {
  const backingData = UIDatabase.objects('CustomerInvoice');
  const filteredData = backingData.filtered('status != $0', 'finalised').slice();
  const sortedData = sortDataBy(filteredData, 'serialNumber', false);

  return {
    backingData,
    data: sortedData,
    keyExtractor: recordKeyExtractor,
    dataState: new Map(),
    searchTerm: '',
    filterDataKeys: ['otherParty.name'],
    sortBy: 'serialNumber',
    isAscending: false,
    modalKey: '',
    hasSelection: false,
    route: ROUTES.CUSTOMER_INVOICES,
    columns: getColumns(ROUTES.CUSTOMER_INVOICES),
    getPageInfoColumns: getPageInfoColumns(ROUTES.CUSTOMER_INVOICES),
  };
};

/**
 * Gets data for initialising a customer requisition page from an associated requisition.
 *
 * @param    {Requisition}  requisition
 * @returns  {object}
 */
const customerRequisitionInitialiser = requisition => {
  const { items: backingData } = requisition;
  const sortedData = backingData.sorted('item.name').slice();

  return {
    pageObject: requisition,
    backingData: requisition.items,
    data: sortedData,
    keyExtractor: recordKeyExtractor,
    dataState: new Map(),
    searchTerm: '',
    filterDataKeys: ['item.name', 'item.code'],
    sortBy: 'itemName',
    isAscending: true,
    modalKey: '',
    modalValue: null,
    route: ROUTES.CUSTOMER_REQUISITION,
    columns: getColumns(ROUTES.CUSTOMER_REQUISITION),
    getPageInfoColumns: getPageInfoColumns(ROUTES.CUSTOMER_REQUISITION),
  };
};

/**
 * Gets data for initialising a customer requisitions page.
 *
 * @returns  {object}
 */
const customerRequisitionsInitialiser = () => {
  const backingData = UIDatabase.objects('ResponseRequisition');

  const filteredData = backingData.filtered('status != $0', 'finalised');
  const sortedData = sortDataBy(filteredData.slice(), 'serialNumber', false);

  return {
    backingData,
    data: sortedData,
    keyExtractor: recordKeyExtractor,
    searchTerm: '',
    filterDataKeys: ['serialNumber'],
    sortBy: 'serialNumber',
    isAscending: false,
    route: ROUTES.CUSTOMER_REQUISITIONS,
    columns: getColumns(ROUTES.CUSTOMER_REQUISITIONS),
    getPageInfoColumns: getPageInfoColumns(ROUTES.CUSTOMER_REQUISITIONS),
  };
};

/**
 * Gets data for initialising a stock page.
 *
 * @returns  {object}
 */
const stockInitialiser = () => {
  const backingData = UIDatabase.objects('Item').sorted('name');

  return {
    backingData,
    data: backingData.slice(),
    keyExtractor: recordKeyExtractor,
    dataState: new Map(),
    searchTerm: '',
    filterDataKeys: ['name', 'code'],
    sortBy: 'name',
    isAscending: true,
    selectedRow: null,
    route: ROUTES.STOCK,
    columns: getColumns(ROUTES.STOCK),
    getPageInfoColumns: getPageInfoColumns(ROUTES.STOCK),
  };
};

/**
 * Gets data for initialising a stocktakes page.
 * Initial data is unfinalised stocktakes, sorted by creation date.
 *
 * @returns  {object}
 */
const stocktakesInitialiser = () => {
  const backingData = UIDatabase.objects('Stocktake');

  const filteredData = backingData.filtered('status != $0', 'finalised');
  const sortedData = filteredData.sorted('createdDate', true).slice();

  return {
    backingData,
    data: sortedData,
    keyExtractor: recordKeyExtractor,
    dataState: new Map(),
    searchTerm: '',
    filterDataKeys: ['name', 'serialNumber'],
    sortBy: 'createdDate',
    isAscending: false,
    modalKey: '',
    hasSelection: false,
    route: ROUTES.STOCKTAKES,
    columns: getColumns(ROUTES.STOCKTAKES),
    getPageInfoColumns: getPageInfoColumns(ROUTES.STOCKTAKES),
  };
};

/**
 * Gets data for initialising a stocktake batch page from an associated stocktake item.
 *
 * @param    {StocktakeItem}  stocktakeItem
 * @returns  {object}
 */
const stocktakeBatchInitialiser = stocktakeItem => ({
  pageObject: stocktakeItem,
  backingData: stocktakeItem.batches,
  data: stocktakeItem.batches.slice(),
  keyExtractor: recordKeyExtractor,
  dataState: new Map(),
  sortBy: 'itemName',
  isAscending: true,
  modalKey: '',
  modalValue: null,
  columns: getColumns(ROUTES.CUSTOMER_INVOICE),
  getPageInfoColumns: getPageInfoColumns(ROUTES.CUSTOMER_INVOICE),
});

/**
 * Gets data for initialising a manage stocktake page from an associated stocktake item.
 *
 * @param    {Stocktake}  stocktake
 * @returns  {object}
 */
const stocktakeManagerInitialiser = stocktake => {
  const backingData = UIDatabase.objects('Item');

  return {
    stocktake,
    backingData,
    data: backingData.sorted('name').slice(),
    keyExtractor: recordKeyExtractor,
    dataState: new Map(),
    searchTerm: '',
    filterDataKeys: ['name', 'code'],
    name: stocktake ? stocktake.name : '',
    sortBy: 'name',
    isAscending: true,
    hasSelection: false,
    allSelected: false,
    showAll: true,
    route: ROUTES.STOCKTAKE_MANAGER,
    columns: getColumns(ROUTES.STOCKTAKE_MANAGER),
    getPageInfoColumns: getPageInfoColumns(ROUTES.STOCKTAKE_MANAGER),
  };
};

/**
 * Gets data for initialising an edit stocktake page from an associated stocktake item.
 *
 * @param    {Stocktake}  stocktake
 * @returns  {object}
 */
const stocktakeEditorInitialiser = stocktake => {
  const { items: backingData } = stocktake;
  const sortedData = backingData.sorted('item.name').slice();

  const hasNegativeAdjustmentReasons = UIDatabase.objects('NegativeAdjustmentReason').length > 0;
  const hasPositiveAdjustmentReasons = UIDatabase.objects('PositiveAdjustmentReason').length > 0;
  const usesReasons = hasNegativeAdjustmentReasons && hasPositiveAdjustmentReasons;

  const route = usesReasons ? ROUTES.STOCKTAKE_EDITOR_WITH_REASONS : ROUTES.STOCKTAKE_EDITOR;

  return {
    pageObject: stocktake,
    backingData,
    data: sortedData,
    keyExtractor: recordKeyExtractor,
    dataState: new Map(),
    searchTerm: '',
    filterDataKeys: ['item.name', 'item.code'],
    sortBy: 'itemName',
    isAscending: true,
    modalKey: '',
    modalValue: null,
    route,
    columns: getColumns(route),
    getPageInfoColumns: getPageInfoColumns(route),
  };
};

/**
 * Gets data for initialising an edit stocktake page when reasons
 * are defined from an associated stocktake.
 *
 * @param    {Stocktake}  stocktake
 * @returns  {object}
 */
const stocktakeEditorWithReasonsInitialiser = stocktake => {
  const { items: backingData } = stocktake;
  const sortedData = backingData.sorted('item.name').slice();

  return {
    pageObject: stocktake,
    backingData,
    data: sortedData,
    keyExtractor: recordKeyExtractor,
    dataState: new Map(),
    searchTerm: '',
    filterDataKeys: ['item.name', 'item.code'],
    sortBy: 'itemName',
    isAscending: true,
    modalKey: '',
    modalValue: null,
    route: ROUTES.STOCKTAKE_EDITOR_WITH_REASONS,
    columns: getColumns(ROUTES.STOCKTAKE_EDITOR_WITH_REASONS),
    getPageInfoColumns: getPageInfoColumns(ROUTES.STOCKTAKE_EDITOR_WITH_REASONS),
  };
};

/**
 * Gets data for initialising a supplier invoice page from an associated transaction item.
 *
 * @param    {Transaction}  transaction
 * @returns  {object}
 */
const supplierInvoiceInitialiser = transaction => {
  const backingData = transaction.getTransactionBatches(UIDatabase);

  const sortedData = backingData.sorted('itemName').slice();

  return {
    pageObject: transaction,
    backingData,
    data: sortedData,
    keyExtractor: recordKeyExtractor,
    dataState: new Map(),
    searchTerm: '',
    filterDataKeys: ['itemName'],
    sortBy: 'itemName',
    isAscending: true,
    modalKey: '',
    modalValue: null,
    hasSelection: false,
    route: ROUTES.SUPPLIER_INVOICE,
    columns: getColumns(ROUTES.SUPPLIER_INVOICE),
    getPageInfoColumns: getPageInfoColumns(ROUTES.SUPPLIER_INVOICE),
  };
};

/**
 * Gets data for initialising a supplier invoices page.
 * Data is initially unfinalised and sorted by serial number.
 *
 * @returns  {object}
 */
const supplierInvoicesInitialiser = () => {
  const backingData = UIDatabase.objects('SupplierInvoice');

  const filteredData = backingData.filtered('status != $0', 'finalised').slice();
  const sortedData = sortDataBy(filteredData, 'serialNumber', false);

  return {
    backingData,
    data: sortedData,
    keyExtractor: recordKeyExtractor,
    dataState: new Map(),
    searchTerm: '',
    filterDataKeys: ['serialNumber'],
    sortBy: 'serialNumber',
    isAscending: false,
    modalKey: '',
    hasSelection: false,
    route: ROUTES.SUPPLIER_INVOICES,
    columns: getColumns(ROUTES.SUPPLIER_INVOICES),
    getPageInfoColumns: getPageInfoColumns(ROUTES.SUPPLIER_INVOICES),
  };
};

/**
 * Gets data for initialising a supplier requisition page from an associated requisition.
 *
 * @param    {Requisition}  requisition
 * @returns  {object}
 */
const supplierRequisitionInitialiser = requisition => {
  const { program, items: backingData } = requisition;

  const usingPrograms = !!program;
  const route = program ? ROUTES.SUPPLIER_REQUISITION_WITH_PROGRAM : ROUTES.SUPPLIER_REQUISITION;

  const sortedData = backingData.sorted('item.name').slice();
  const filteredData = usingPrograms
    ? sortedData.filter(item => item.isLessThanThresholdMOS)
    : sortedData;

  return {
    pageObject: requisition,
    backingData,
    data: filteredData,
    keyExtractor: recordKeyExtractor,
    dataState: new Map(),
    searchTerm: '',
    filterDataKeys: ['item.name', 'item.code'],
    sortBy: 'itemName',
    isAscending: true,
    modalKey: '',
    hasSelection: false,
    modalValue: null,
    showAll: !usingPrograms,
    route: ROUTES.SUPPLIER_REQUISITION,
    columns: getColumns(route),
    getPageInfoColumns: getPageInfoColumns(route),
  };
};

/**
 * Gets data for initialising a supplier requisitions page.
 * Initial data are unfinalised requisitions, sorted by serial number.
 *
 * @returns  {object}
 */
const supplierRequisitionsInitialiser = () => {
  const backingData = UIDatabase.objects('RequestRequisition');

  const filteredData = backingData.filtered('status != $0', 'finalised').slice();
  const sortedData = sortDataBy(filteredData, 'serialNumber', false);

  return {
    backingData,
    data: sortedData,
    keyExtractor: recordKeyExtractor,
    dataState: new Map(),
    searchTerm: '',
    filterDataKeys: ['serialNumber'],
    sortBy: 'serialNumber',
    isAscending: false,
    modalKey: '',
    hasSelection: false,
    route: ROUTES.SUPPLIER_REQUISITIONS,
    columns: getColumns(ROUTES.SUPPLIER_REQUISITIONS),
    getPageInfoColumns: getPageInfoColumns(ROUTES.SUPPLIER_REQUISITIONS),
  };
};

const prescriptionsInitialiser = () => {
  const backingData = UIDatabase.objects('Prescription');
  const filteredData = backingData.filtered('status != $0', 'finalised').slice();
  const sortedData = sortDataBy(filteredData, 'serialNumber', false);

  return {
    backingData,
    data: sortedData,
    keyExtractor: recordKeyExtractor,
    dataState: new Map(),
    searchTerm: '',
    filterDataKeys: ['otherParty.name'],
    sortBy: 'serialNumber',
    isAscending: false,
    modalKey: '',
    hasSelection: false,
    route: ROUTES.PRESCRIPTIONS,
    columns: getColumns(ROUTES.PRESCRIPTIONS),
    getPageInfoColumns: getPageInfoColumns(ROUTES.PRESCRIPTIONS),
  };
};

export const prescriptionInitialiser = transaction => {
  const { items: backingData } = transaction;

  const sortedData = backingData.sorted('item.name').slice();

  return {
    pageObject: transaction,
    backingData,
    data: sortedData,
    keyExtractor: recordKeyExtractor,
    dataState: new Map(),
    searchTerm: '',
    filterDataKeys: ['item.name', 'item.code'],
    sortBy: 'itemName',
    isAscending: true,
    modalKey: '',
    modalValue: null,
    hasSelection: false,
    route: ROUTES.PRESCRIPTION,
    columns: getColumns(ROUTES.PRESCRIPTION),
    getPageInfoColumns: getPageInfoColumns(ROUTES.PRESCRIPTION),
  };
};

/**
 * Gets data for initialising a customer requisitions page.
 *
 * @returns  {object}
 */
const prescribersInitialiser = () => {
  const backingData = UIDatabase.objects('Prescriber');

  return {
    backingData,
    data: backingData.sorted('firstName').slice(),
    keyExtractor: recordKeyExtractor,
    searchTerm: '',
    filterDataKeys: ['serialNumber'],
    sortBy: 'firstName',
    isAscending: false,
    route: ROUTES.PRESCRIBERS,
    columns: getColumns(ROUTES.PRESCRIBERS),
    getPageInfoColumns: getPageInfoColumns(ROUTES.PRESCRIBERS),
  };
};

const pageInitialisers = {
  customerInvoice: customerInvoiceInitialiser,
  customerInvoices: customerInvoicesInitialiser,
  customerRequisition: customerRequisitionInitialiser,
  customerRequisitions: customerRequisitionsInitialiser,
  stock: stockInitialiser,
  stocktakeBatchEditModal: stocktakeBatchInitialiser,
  stocktakeBatchEditModalWithReasons: stocktakeBatchInitialiser,
  stocktakeEditor: stocktakeEditorInitialiser,
  stocktakeEditorWithReasons: stocktakeEditorWithReasonsInitialiser,
  stocktakeManager: stocktakeManagerInitialiser,
  stocktakes: stocktakesInitialiser,
  supplierInvoice: supplierInvoiceInitialiser,
  supplierInvoices: supplierInvoicesInitialiser,
  supplierRequisition: supplierRequisitionInitialiser,
  supplierRequisitions: supplierRequisitionsInitialiser,
  prescriptions: prescriptionsInitialiser,
  prescription: prescriptionInitialiser,
  prescribers: prescribersInitialiser,
};

/**
 * A wrapper for mapping pages to initialisation functions.
 *
 * @param    {object}    A mapper from page names to initialisation functions.
 * @returns  {Function}  A lookup function for retrieving page initialisers.
 */
const getPageInitialiser = pageToInitialiser => page => pageToInitialiser[page];

export default getPageInitialiser(pageInitialisers);
<|endoftext|>


<commit_before>'use strict';
var utils = require('../utils');
var DirBase = require('../dir-base');
var path = require('path');

var items = [];

module.exports = DirBase.extend({
  constructor: function() {
    DirBase.apply(this, arguments);
    this.option('directory', {alias: 'd', desc: 'create constructor within specified directory'});
    this.option('itemview', {alias: 'itv', desc: 'create itemview'});
    this.option('collectionview', {alias: 'clv', desc: 'create collectionview'});
    this.option('compositeview', {alias: 'cmv', desc: 'create '});
    this.option('model', {alias: 'm', desc: 'create '});
    this.option('collection', {alias: 'c', desc: 'create '});
  },
  initializing: function() {
    this.directory = this.options.directory || this.options.d;
    this.itemview = this.options.itemview || this.options.itv;
    this.collectionview = this.options.collectionview || this.options.clv;
    this.compositeview = this.options.compositeview || this.options.cmv;
    this.model = this.options.model || this.options.m;
    this.collection = this.options.collection || this.options.c;

    if (!this.model) {
      if (this.itemview) {
        console.log('You need a model for your itemview');
        process.exit(1);
      }
      if (this.compositeview) {
        console.log('You need a model for your compositeview');
        process.exit(1);
      }
    }

    if (!this.collection) {
      if (this.compositeview) {
        console.log('You need a collection for your compositeview.');
        process.exit(1);
      }
      if (this.collectionview) {
        console.log('You need a collection for your collectionview.');
        process.exit(1);
      }
    }

    if (this.model) {
      this.model = utils.truncateBasePath(this.model);

      var mdlPathFractions = path.parse(this.model);
      this.customMdlName = mdlPathFractions.base;

      if (mdlPathFractions.dir) {
        this.customMdlDir = mdlPathFractions.dir;
      }

      //pathVerification.verifyPath(this.customMdlDir, mdlPathFractions.name, utils.type.model);
      items.push({path: utils.amd(mdlPathFractions.name, utils.type.model, mdlPathFractions.dir), name: 'Model', type: 'model'});
      utils.verifyPath(utils.fileNameWithPath(this.customMdlDir, mdlPathFractions.name, utils.type.model));

      items.push({path: utils.amd(mdlPathFractions.name, utils.type.model, mdlPathFractions.dir), name: 'Model', type: 'model'});
    }

    if (this.collection) {
      this.collection = utils.truncateBasePath(this.collection);

      var cllPathFractions = path.parse(this.collection);
      this.customCllName = cllPathFractions.base;

      if (cllPathFractions.dir) {
        this.customCllDir = cllPathFractions.dir;
      }

      //pathVerification.verifyPath(this.customCllDir, cllPathFractions.name, utils.type.collection);
      items.push({path: utils.amd(cllPathFractions.name, utils.type.collection, cllPathFractions.dir), name: 'Collection', type: 'collection'});
      utils.verifyPath(utils.fileNameWithPath(this.customCllDir, cllPathFractions.name, utils.type.collection));

      items.push({path: utils.amd(cllPathFractions.name, utils.type.collection, cllPathFractions.dir), name: 'Collection', type: 'collection'});
    }

    if (this.itemview) {
      this.itemview = utils.truncateBasePath(this.itemview);

      var itvPathFractions = path.parse(this.itemview);
      this.customCllName = itvPathFractions.base;

      if (itvPathFractions.dir) {
        this.customItvDir = itvPathFractions.dir;
      }

      utils.verifyPath(utils.fileNameWithPath(this.customItvDir, itvPathFractions.name, utils.type.itemview));

      var itvName = utils.className(itvPathFractions.name, utils.type.itemview);
      items.push({path: utils.amd(itvPathFractions.name, utils.type.itemview, itvPathFractions.dir), name: itvName, varName: utils.varName(itvName), type: 'itemview'});

      // if itemview is present, ignore all other
      return;
    }

    if (this.collectionview) {
      this.collectionview = utils.truncateBasePath(this.collectionview);

      var clvPathFractions = path.parse(this.collectionview);
      this.customClvName = clvPathFractions.base;

      if (clvPathFractions.dir) {
        this.customClvDir = clvPathFractions.dir;
      }

      //pathVerification.verifyPath(this.customClvDir, clvPathFractions.name, utils.type.collectionview);
      utils.verifyPath(utils.fileNameWithPath(this.customClvDir, clvPathFractions.name, utils.type.collectionview));

      var clvName = utils.className(clvPathFractions.name, utils.type.collectionview);
      items.push({path: utils.amd(clvPathFractions.name, utils.type.collectionview, clvPathFractions.dir), name: clvName, varName: utils.varName(clvName), type: 'collectionview'});

      // if collectionview is present, ignore all other
      return;
    }

    if (this.compositeview) {
      this.compositeview = utils.truncateBasePath(this.compositeview);

      var cmvPathFractions = path.parse(this.compositeview);
      this.customCmvName = cmvPathFractions.base;

      if (cmvPathFractions.dir) {
        this.customCmvDir = cmvPathFractions.dir;
      }

      //pathVerification.verifyPath(this.customCmvDir, cmvPathFractions.name, utils.type.compositeview);
      utils.verifyPath(utils.fileNameWithPath(this.customCmvDir, cmvPathFractions.name, utils.type.compositeview));

      var cmvName = utils.className(cmvPathFractions.name, utils.type.compositeview);
      items.push({path: utils.amd(cmvPathFractions.name, utils.type.compositeview, cmvPathFractions.dir), name: cmvName, varName: utils.varName(cmvName), type: 'compositeview'});

      // if compositeview is present, ignore all other
      return;
    }
  },
  writing: function() {
    this.fs.copyTpl(
      this.templatePath(this.sourceDir + '_controller.js'),
      this.destinationPath(utils.fileNameWithPath(this.options.directory, this.name, utils.type.controller)),
      {
        name: utils.fileName(this.name, utils.type.controller),
        items: items
      }
    );
    this.fs.copyTpl(
      this.templatePath(this.sourceDir + '_controller-test.js'),
      this.destinationPath(utils.testNameWithPath(this.options.directory, this.name, utils.type.controller)),
      {
        controllerPath: utils.amd(this.name, utils.type.controller, this.options.directory),
        controllerClassName: utils.className(this.name, utils.type.controller)
      }
    );

  }
});
<commit_msg>Fixed tests in separate dir for controller<commit_after>'use strict';
var utils = require('../utils');
var DirBase = require('../dir-base');
var path = require('path');

var items = [];

module.exports = DirBase.extend({
  constructor: function() {
    DirBase.apply(this, arguments);
    this.option('directory', {alias: 'd', desc: 'create constructor within specified directory'});
    this.option('itemview', {alias: 'itv', desc: 'create itemview'});
    this.option('collectionview', {alias: 'clv', desc: 'create collectionview'});
    this.option('compositeview', {alias: 'cmv', desc: 'create '});
    this.option('model', {alias: 'm', desc: 'create '});
    this.option('collection', {alias: 'c', desc: 'create '});
  },
  initializing: function() {
    this.directory = this.options.directory || this.options.d;
    this.itemview = this.options.itemview || this.options.itv;
    this.collectionview = this.options.collectionview || this.options.clv;
    this.compositeview = this.options.compositeview || this.options.cmv;
    this.model = this.options.model || this.options.m;
    this.collection = this.options.collection || this.options.c;

    if (!this.model) {
      if (this.itemview) {
        console.log('You need a model for your itemview');
        process.exit(1);
      }
      if (this.compositeview) {
        console.log('You need a model for your compositeview');
        process.exit(1);
      }
    }

    if (!this.collection) {
      if (this.compositeview) {
        console.log('You need a collection for your compositeview.');
        process.exit(1);
      }
      if (this.collectionview) {
        console.log('You need a collection for your collectionview.');
        process.exit(1);
      }
    }

    if (this.model) {
      this.model = utils.truncateBasePath(this.model);

      var mdlPathFractions = path.parse(this.model);
      this.customMdlName = mdlPathFractions.base;

      if (mdlPathFractions.dir) {
        this.customMdlDir = mdlPathFractions.dir;
      }

      //pathVerification.verifyPath(this.customMdlDir, mdlPathFractions.name, utils.type.model);
      items.push({path: utils.amd(mdlPathFractions.name, utils.type.model, mdlPathFractions.dir), name: 'Model', type: 'model'});
      utils.verifyPath(utils.fileNameWithPath(this.customMdlDir, mdlPathFractions.name, utils.type.model));

      items.push({path: utils.amd(mdlPathFractions.name, utils.type.model, mdlPathFractions.dir), name: 'Model', type: 'model'});
    }

    if (this.collection) {
      this.collection = utils.truncateBasePath(this.collection);

      var cllPathFractions = path.parse(this.collection);
      this.customCllName = cllPathFractions.base;

      if (cllPathFractions.dir) {
        this.customCllDir = cllPathFractions.dir;
      }

      //pathVerification.verifyPath(this.customCllDir, cllPathFractions.name, utils.type.collection);
      items.push({path: utils.amd(cllPathFractions.name, utils.type.collection, cllPathFractions.dir), name: 'Collection', type: 'collection'});
      utils.verifyPath(utils.fileNameWithPath(this.customCllDir, cllPathFractions.name, utils.type.collection));

      items.push({path: utils.amd(cllPathFractions.name, utils.type.collection, cllPathFractions.dir), name: 'Collection', type: 'collection'});
    }

    if (this.itemview) {
      this.itemview = utils.truncateBasePath(this.itemview);

      var itvPathFractions = path.parse(this.itemview);
      this.customCllName = itvPathFractions.base;

      if (itvPathFractions.dir) {
        this.customItvDir = itvPathFractions.dir;
      }

      utils.verifyPath(utils.fileNameWithPath(this.customItvDir, itvPathFractions.name, utils.type.itemview));

      var itvName = utils.className(itvPathFractions.name, utils.type.itemview);
      items.push({path: utils.amd(itvPathFractions.name, utils.type.itemview, itvPathFractions.dir), name: itvName, varName: utils.varName(itvName), type: 'itemview'});

      // if itemview is present, ignore all other
      return;
    }

    if (this.collectionview) {
      this.collectionview = utils.truncateBasePath(this.collectionview);

      var clvPathFractions = path.parse(this.collectionview);
      this.customClvName = clvPathFractions.base;

      if (clvPathFractions.dir) {
        this.customClvDir = clvPathFractions.dir;
      }

      //pathVerification.verifyPath(this.customClvDir, clvPathFractions.name, utils.type.collectionview);
      utils.verifyPath(utils.fileNameWithPath(this.customClvDir, clvPathFractions.name, utils.type.collectionview));

      var clvName = utils.className(clvPathFractions.name, utils.type.collectionview);
      items.push({path: utils.amd(clvPathFractions.name, utils.type.collectionview, clvPathFractions.dir), name: clvName, varName: utils.varName(clvName), type: 'collectionview'});

      // if collectionview is present, ignore all other
      return;
    }

    if (this.compositeview) {
      this.compositeview = utils.truncateBasePath(this.compositeview);

      var cmvPathFractions = path.parse(this.compositeview);
      this.customCmvName = cmvPathFractions.base;

      if (cmvPathFractions.dir) {
        this.customCmvDir = cmvPathFractions.dir;
      }

      //pathVerification.verifyPath(this.customCmvDir, cmvPathFractions.name, utils.type.compositeview);
      utils.verifyPath(utils.fileNameWithPath(this.customCmvDir, cmvPathFractions.name, utils.type.compositeview));

      var cmvName = utils.className(cmvPathFractions.name, utils.type.compositeview);
      items.push({path: utils.amd(cmvPathFractions.name, utils.type.compositeview, cmvPathFractions.dir), name: cmvName, varName: utils.varName(cmvName), type: 'compositeview'});

      // if compositeview is present, ignore all other
      return;
    }
  },
  writing: function() {
    this.fs.copyTpl(
      this.templatePath(this.sourceDir + '_controller.js'),
      this.destinationPath(utils.fileNameWithPath(this.options.directory, this.name, utils.type.controller)),
      {
        name: utils.fileName(this.name, utils.type.controller),
        items: items
      }
    );
    this.fs.copyTpl(
      this.templatePath(this.sourceDir + '_controller-test.js'),
      this.destinationPath(utils.testNameWithPath(this.options.directory, this.name, utils.type.controller, this.testBaseDir)),
      {
        controllerPath: utils.amd(this.name, utils.type.controller, this.options.directory),
        controllerClassName: utils.className(this.name, utils.type.controller)
      }
    );

  }
});
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2012 Google Inc. All Rights Reserved.
 *
 * 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.
 */
var labelToProperty = {
  App:          'app',
  Type:         'type',
  Priority:     'priority',
  Milestone:    'milestone',
  Cr:           'category',
  Iteration:    'iteration',
  ReleaseBlock: 'releaseBlock',
  OS:           'OS'
};

var QIssue = FOAM({
    model_: 'Model',
    extendsModel: 'GeneratedQIssue',

    name: 'QIssue',

    tableProperties: [
      'starred',
      'id',
//      'app',
      'priority',
      'milestone',
      'iteration',
      'releaseBlock',
      'category',
      'status',
      'owner',
      'summary',
      'OS',
      'modified'
    ],

    ids: ['id'],

    properties: [
        {
          model_: 'IntegerProperty',
          name: 'id',
          shortName: 'i',
          label: 'ID',
          required: true,
          tableWidth: '48px',
          tableFormatter: function(value, row, table) {
            var id = table.nextID();

            table.on('mouseover', function(e) {
              table.browser.preview(e, value);
            }, id);

            return '
' + value + '
';
          }
        },
        {
          name: 'author',
          aliases: ['reporter']
        },
        {
          model_: 'StringProperty',
          name: 'priority',
          shortName: 'p',
          aliases: ['pr', 'pri', 'prior'],
          tableLabel: 'Priority',
          tableWidth: '60px',
          compareProperty: function(p1, p2) {
            var priorities = ['Low', 'Medium', 'High', 'Critical'];
            var r = priorities.indexOf(p1) - priorities.indexOf(p2);
            return r === 0 ? 0 : r < 0 ? -1 : 1;
          },
          required: true
        },
        {
          model_: 'StringProperty',
          name: 'app',
          tableWidth: '70px'
        },
        {
          model_: 'StringProperty',
          name: 'type',
          tableWidth: '70px'
        },
        {
            name: 'milestone',
            shortName: 'm',
            aliases: ['mstone'],
            tableLabel: 'M',
            type: 'Integer',
            tableWidth: '70px',
            defaultValue: ''
        },
        {
            name: 'iteration',
            shortName: 'it',
            aliases: ['iter'],
            type: 'String',
            tableWidth: '69px'
        },
        {
            name: 'releaseBlock',
            shortName: 'rb',
            aliases: ['rBlock', 'release'],
            type: 'String',
            tableWidth: '103px',
            defaultValue: ''
        },
        {
            name: 'category',
            shortName: 'c',
            aliases: ['cat', 'cr'],
            label: 'Cr',
            tableWidth: '87px',
            type: 'String',
            defaultValue: ''
        },
        {
            name: 'status',
            shortName: 's',
            aliases: ['stat'],
            type: 'String',
            tableWidth: '58px',
            defaultValue: ''
        },
        {
            name: 'owner',
            shortName: 'o',
            tableWidth: '181px',
            type: 'String'
        },
        {
            name: 'summary',
            shortName: 'su',
            label: 'Summary + Labels',
            type: 'String',
            tableWidth: '100%',
            tableFormatter: function(value, row) {
              return value +
                QIssue.LABELS.tableFormatter(row.labels, row);
            }
        },
        {
            name: 'labels',
            shortName: 'l',
            aliases: ['label'],
            type: 'String',
            view: 'QIssueLabelsView',
            tableFormatter: function(value, row) {
              var sb = [];
              //              var a = value.split(', ');
              var a = value;
              for ( var i = 0 ; i < a.length ; i++ ) {
                // The the column is already being shown, then exclude it's label
                if ( row.model_.tableProperties.indexOf(labelToProperty[a[i].split('-')[0]]) == -1 ) {
                  sb.push(' ');
                  sb.push(a[i]);
                  sb.push('');
                }
              }
              return sb.join('');
            },
            postSet: function(_, a) {
              for ( var i = 0 ; i < a.length ; i++ ) {
                for ( var key in labelToProperty ) {
                  if ( a[i].substring(0, key.length) == key ) {
                    var prop = labelToProperty[key];
                    var val = a[i].substring(key.length+1).intern();
                    // ???: Should be treated as last value or an array?
                    this[prop] = val;
//                  this[prop].push(val);
                    a.splice(i,1);
                    i--;
                    break;
                  }
                }
              }
            }
        },
        {
            name: 'OS',
            tableWidth: '61px',
            type: 'String'
        },
        {
          model_: 'BooleanProperty',
          name: 'blocked',
          tableWidth: '20px',
          getter: function() { return !! this.blockedOn.length; }
        },
        {
         model_: 'DateTimeProperty',
         name: 'modified',
         shortName: 'mod',
         mode: 'read-write',
         required: true,
         tableWidth: '100px',
         valueFactory: function() { return new Date(); }
      },
      {
        name: 'updated',
        hidden: true,
        setter: function(v) { this.modified = v; }
      },
      {
         model_: 'BooleanProperty',
         name: 'starred',
         tableLabel: '',
         tableWidth: '20px',
         tableFormatter: function(val, obj, tableView) {
           var temp = obj.clone();
           var view = ImageBooleanView.create({
               trueImage: 'data:image/gif;base64,R0lGODlhDwAPAMQfAF9h4RYVnZeQJC0u0lRQU42R6P/7Fv74L05NrRkZxi4tW52XXv71D8nAIWxnjnRxr3NuMJKOluXbBe7kCa2x7UFD1vPoB77D8Jqe6n6B5tvTUr62BMrP8lJPh1xbuv///yH5BAEAAB8ALAAAAAAPAA8AAAWD4CeOWQKMaDpESepi3tFlLgpExlK9RT9ohkYi08N8KhWP8nEwMBwIDyJRSTgO2CaDYcBOCAlMgtDYmhmTDSFQ+HAqgbLZIlAMLqiKw7m1EAYuFQsGEhITEwItKBc/EgIEAhINAUYkCBIQAQMBEGonIwAKa21iCgo7IxQDFRQjF1VtHyEAOw==', //'images/star_on.gif',
               falseImage: 'data:image/gif;base64,R0lGODlhDwAPALMPAP///8zj++r7/7vb/rHW/tPt/9Lk+qzT/rbY/sHh/8Te/N7q+Nzy/7nY/djn+f///yH5BAEAAA8ALAAAAAAPAA8AAARg8MkZjpo4k0KyNwlQBB42MICAfEF7APDRBsYzIEkewGKeDI1DgUckMg6GTdFIqC0QgyUgQVhgGkOi4OBBCJYdzILAywIGNcoOgCAQvowBRpE4kgzCQgPjQCAcEwsNTRIRADs=', //'images/star_off.gif',
               value: temp.propertyValue('starred')
             });

           temp.addPropertyListener('starred', function() {
             tableView.browser.IssueDAO.put(temp);
           });

           tableView.addChild(view);

           return view.toHTML();
         },
         view: {
           // TODO: make it so that initialized objects can be used as factories
           create: function() {
             return ImageBooleanView.create({
               trueImage: 'images/star_on.gif',
               falseImage: 'images/star_off.gif'
             });
           }
         },
         tableWidth: '20px',
         help: 'Whether the authenticated user has starred this issue.'
      },
      {
         model_: 'IntegerProperty',
         name: 'stars',
         tableWidth: '20px',
         help: 'Number of stars this issue has.'
      }
    ],

    methods: {
      isOpen: function() {
        return !! ({
          'New':      true,
          'Accepted': true,
          'Started':  true
        }[this.status]);
      },
      writeActions: function(other, out) {
        var diff = this.diff(other);
        delete diff.starred;

        if ( Object.keys(diff).length == 0 ) return;

        function convertArray(key) {
          if ( ! diff[key] ) {
            diff[key] = [];
            return;
          }

          var delta = diff[key].added;
          for ( var i = 0; i < diff[key].removed.length; i++ )
            delta.push("-" + diff[key].removed[i]);
          diff[key] = delta;
        }

        convertArray('blockedOn');
        convertArray('blocking');
        convertArray('cc');
        convertArray('labels');

        function propToLabel(prop, label) {
          if ( diff[prop] ) {
            diff.labels = diff.labels.concat(
              '-' + label + '-' + other[prop],
              label + '-' + diff[prop]);
            delete diff[prop];
          }
        }

        propToLabel('priority', 'Priority');
        propToLabel('app', 'App');
        propToLabel('milestone', 'Milestone');
        propToLabel('category', 'Cr');
        propToLabel('iteration', 'Iteration');
        propToLabel('releaseBlock', 'ReleaseBlock');
        propToLabel('OS', 'OS');

        var comment = QIssueComment.create({
          issueId: this.id,
          updates: IssueCommentUpdate.create(diff)
        });

        out(comment);
      }
    }
});

QIssue.getPrototype();

QIssue.properties.forEach(function(p) {
  if ( ! p["tableFormatter"] ) {
    p["tableFormatter"] = function(v) {
      return ('' + v).length ? v : '----';
    };
  }
});

GeneratedQIssue.properties.forEach(function(p) {
  if ( ! p["tableFormatter"] ) {
    p["tableFormatter"] = function(v) {
      return ('' + v).length ? v : '----';
    };
  }
  if ( ! p["tableWidth"] ) {
    p["tableWidth"] = '80px;'
  }
});

var QIssueComment = FOAM({
  model_: 'Model',
  name: 'QIssueComment',
  extendsModel: 'IssueComment',

  ids: [ 'id' ],

  properties: [
    {
      name: 'author',
      view: 'QIssueCommentAuthorView',
      preSet: function(newValue, _, prop) {
        if ( ! newValue.model_ ) return GLOBAL[prop.subType].create(newValue);
        return newValue;
      }
    },
    {
      name: 'updates',
      view: 'QIssueCommentUpdateView',
      preSet: function(newValue, _, prop) {
        if ( ! newValue.model_ ) return GLOBAL[prop.subType].create(newValue);
        return newValue;
      }
    },
    {
      name: 'published',
      view: 'RelativeDateTimeFieldView'
    },
    {
      model_: 'ReferenceProperty',
      name: 'issueId'
    }
  ]
});

var QUser = FOAM({
  model_: 'Model',
  name: 'QUser',
  extendsModel: 'User',

  properties: [
    {
      model_: 'StringProperty',
      name: 'email'
    },
    {
      name: 'projects',
      postSet: function(_, newValue) {
        if ( this.preferredProjects.length == 0 ) {
          this.preferredProjects = newValue.map(function(p) { return p.name; });
        }
      }
    },
    {
      model_: 'StringArrayProperty',
      name: 'preferredProjects',
      view: 'MultiLineStringArrayView'
    },
    {
      model_: 'StringProperty',
      name: 'defaultProject',
      defaultValue: 'chromium'
    }
  ]
});
<commit_msg>Crbug: TableView custom tableFormatters weren't escaping HTML.<commit_after>/**
 * @license
 * Copyright 2012 Google Inc. All Rights Reserved.
 *
 * 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.
 */
var labelToProperty = {
  App:          'app',
  Type:         'type',
  Priority:     'priority',
  Milestone:    'milestone',
  Cr:           'category',
  Iteration:    'iteration',
  ReleaseBlock: 'releaseBlock',
  OS:           'OS'
};

var QIssue = FOAM({
    model_: 'Model',
    extendsModel: 'GeneratedQIssue',

    name: 'QIssue',

    tableProperties: [
      'starred',
      'id',
//      'app',
      'priority',
      'milestone',
      'iteration',
      'releaseBlock',
      'category',
      'status',
      'owner',
      'summary',
      'OS',
      'modified'
    ],

    ids: ['id'],

    properties: [
        {
          model_: 'IntegerProperty',
          name: 'id',
          shortName: 'i',
          label: 'ID',
          required: true,
          tableWidth: '48px',
          tableFormatter: function(value, row, table) {
            var id = table.nextID();

            table.on('mouseover', function(e) {
              table.browser.preview(e, value);
            }, id);

            return '
' + value + '
';
          }
        },
        {
          name: 'author',
          aliases: ['reporter']
        },
        {
          model_: 'StringProperty',
          name: 'priority',
          shortName: 'p',
          aliases: ['pr', 'pri', 'prior'],
          tableLabel: 'Priority',
          tableWidth: '60px',
          compareProperty: function(p1, p2) {
            var priorities = ['Low', 'Medium', 'High', 'Critical'];
            var r = priorities.indexOf(p1) - priorities.indexOf(p2);
            return r === 0 ? 0 : r < 0 ? -1 : 1;
          },
          required: true
        },
        {
          model_: 'StringProperty',
          name: 'app',
          tableWidth: '70px'
        },
        {
          model_: 'StringProperty',
          name: 'type',
          tableWidth: '70px'
        },
        {
            name: 'milestone',
            shortName: 'm',
            aliases: ['mstone'],
            tableLabel: 'M',
            type: 'Integer',
            tableWidth: '70px',
            defaultValue: ''
        },
        {
            name: 'iteration',
            shortName: 'it',
            aliases: ['iter'],
            type: 'String',
            tableWidth: '69px'
        },
        {
            name: 'releaseBlock',
            shortName: 'rb',
            aliases: ['rBlock', 'release'],
            type: 'String',
            tableWidth: '103px',
            defaultValue: ''
        },
        {
            name: 'category',
            shortName: 'c',
            aliases: ['cat', 'cr'],
            label: 'Cr',
            tableWidth: '87px',
            type: 'String',
            defaultValue: ''
        },
        {
            name: 'status',
            shortName: 's',
            aliases: ['stat'],
            type: 'String',
            tableWidth: '58px',
            defaultValue: ''
        },
        {
            name: 'owner',
            shortName: 'o',
            tableWidth: '181px',
            type: 'String'
        },
        {
            name: 'summary',
            shortName: 'su',
            label: 'Summary + Labels',
            type: 'String',
            tableWidth: '100%',
            tableFormatter: function(value, row, tableView) {
              return tableView.strToHTML(value) +
                QIssue.LABELS.tableFormatter(row.labels, row);
            }
        },
        {
            name: 'labels',
            shortName: 'l',
            aliases: ['label'],
            type: 'String',
            view: 'QIssueLabelsView',
          tableFormatter: function(value, row) {
              var sb = [];
              //              var a = value.split(', ');
              var a = value;
              for ( var i = 0 ; i < a.length ; i++ ) {
                // The the column is already being shown, then exclude it's label
                if ( row.model_.tableProperties.indexOf(labelToProperty[a[i].split('-')[0]]) == -1 ) {
                  sb.push(' ');
                  sb.push(a[i]);
                  sb.push('');
                }
              }
              return sb.join('');
            },
            postSet: function(_, a) {
              for ( var i = 0 ; i < a.length ; i++ ) {
                for ( var key in labelToProperty ) {
                  if ( a[i].substring(0, key.length) == key ) {
                    var prop = labelToProperty[key];
                    var val = a[i].substring(key.length+1).intern();
                    // ???: Should be treated as last value or an array?
                    this[prop] = val;
//                  this[prop].push(val);
                    a.splice(i,1);
                    i--;
                    break;
                  }
                }
              }
            }
        },
        {
            name: 'OS',
            tableWidth: '61px',
            type: 'String'
        },
        {
          model_: 'BooleanProperty',
          name: 'blocked',
          tableWidth: '20px',
          getter: function() { return !! this.blockedOn.length; }
        },
        {
         model_: 'DateTimeProperty',
         name: 'modified',
         shortName: 'mod',
         mode: 'read-write',
         required: true,
         tableWidth: '100px',
         valueFactory: function() { return new Date(); }
      },
      {
        name: 'updated',
        hidden: true,
        setter: function(v) { this.modified = v; }
      },
      {
         model_: 'BooleanProperty',
         name: 'starred',
         tableLabel: '',
         tableWidth: '20px',
         tableFormatter: function(val, obj, tableView) {
           var temp = obj.clone();
           var view = ImageBooleanView.create({
               trueImage: 'data:image/gif;base64,R0lGODlhDwAPAMQfAF9h4RYVnZeQJC0u0lRQU42R6P/7Fv74L05NrRkZxi4tW52XXv71D8nAIWxnjnRxr3NuMJKOluXbBe7kCa2x7UFD1vPoB77D8Jqe6n6B5tvTUr62BMrP8lJPh1xbuv///yH5BAEAAB8ALAAAAAAPAA8AAAWD4CeOWQKMaDpESepi3tFlLgpExlK9RT9ohkYi08N8KhWP8nEwMBwIDyJRSTgO2CaDYcBOCAlMgtDYmhmTDSFQ+HAqgbLZIlAMLqiKw7m1EAYuFQsGEhITEwItKBc/EgIEAhINAUYkCBIQAQMBEGonIwAKa21iCgo7IxQDFRQjF1VtHyEAOw==', //'images/star_on.gif',
               falseImage: 'data:image/gif;base64,R0lGODlhDwAPALMPAP///8zj++r7/7vb/rHW/tPt/9Lk+qzT/rbY/sHh/8Te/N7q+Nzy/7nY/djn+f///yH5BAEAAA8ALAAAAAAPAA8AAARg8MkZjpo4k0KyNwlQBB42MICAfEF7APDRBsYzIEkewGKeDI1DgUckMg6GTdFIqC0QgyUgQVhgGkOi4OBBCJYdzILAywIGNcoOgCAQvowBRpE4kgzCQgPjQCAcEwsNTRIRADs=', //'images/star_off.gif',
               value: temp.propertyValue('starred')
             });

           temp.addPropertyListener('starred', function() {
             tableView.browser.IssueDAO.put(temp);
           });

           tableView.addChild(view);

           return view.toHTML();
         },
         view: {
           // TODO: make it so that initialized objects can be used as factories
           create: function() {
             return ImageBooleanView.create({
               trueImage: 'images/star_on.gif',
               falseImage: 'images/star_off.gif'
             });
           }
         },
         tableWidth: '20px',
         help: 'Whether the authenticated user has starred this issue.'
      },
      {
         model_: 'IntegerProperty',
         name: 'stars',
         tableWidth: '20px',
         help: 'Number of stars this issue has.'
      }
    ],

    methods: {
      isOpen: function() {
        return !! ({
          'New':      true,
          'Accepted': true,
          'Started':  true
        }[this.status]);
      },
      writeActions: function(other, out) {
        var diff = this.diff(other);
        delete diff.starred;

        if ( Object.keys(diff).length == 0 ) return;

        function convertArray(key) {
          if ( ! diff[key] ) {
            diff[key] = [];
            return;
          }

          var delta = diff[key].added;
          for ( var i = 0; i < diff[key].removed.length; i++ )
            delta.push("-" + diff[key].removed[i]);
          diff[key] = delta;
        }

        convertArray('blockedOn');
        convertArray('blocking');
        convertArray('cc');
        convertArray('labels');

        function propToLabel(prop, label) {
          if ( diff[prop] ) {
            diff.labels = diff.labels.concat(
              '-' + label + '-' + other[prop],
              label + '-' + diff[prop]);
            delete diff[prop];
          }
        }

        propToLabel('priority', 'Priority');
        propToLabel('app', 'App');
        propToLabel('milestone', 'Milestone');
        propToLabel('category', 'Cr');
        propToLabel('iteration', 'Iteration');
        propToLabel('releaseBlock', 'ReleaseBlock');
        propToLabel('OS', 'OS');

        var comment = QIssueComment.create({
          issueId: this.id,
          updates: IssueCommentUpdate.create(diff)
        });

        out(comment);
      }
    }
});

QIssue.getPrototype();

QIssue.properties.forEach(function(p) {
  if ( ! p["tableFormatter"] ) {
    p["tableFormatter"] = function(v) {
      return ('' + v).length ? v : '----';
    };
  }
});

GeneratedQIssue.properties.forEach(function(p) {
  if ( ! p["tableFormatter"] ) {
    p["tableFormatter"] = function(v, _, tableView) {
      return ('' + tableView.strToHTML(v)).length ? v : '----';
    };
  }
  if ( ! p["tableWidth"] ) {
    p["tableWidth"] = '80px;'
  }
});

var QIssueComment = FOAM({
  model_: 'Model',
  name: 'QIssueComment',
  extendsModel: 'IssueComment',

  ids: [ 'id' ],

  properties: [
    {
      name: 'author',
      view: 'QIssueCommentAuthorView',
      preSet: function(newValue, _, prop) {
        if ( ! newValue.model_ ) return GLOBAL[prop.subType].create(newValue);
        return newValue;
      }
    },
    {
      name: 'updates',
      view: 'QIssueCommentUpdateView',
      preSet: function(newValue, _, prop) {
        if ( ! newValue.model_ ) return GLOBAL[prop.subType].create(newValue);
        return newValue;
      }
    },
    {
      name: 'published',
      view: 'RelativeDateTimeFieldView'
    },
    {
      model_: 'ReferenceProperty',
      name: 'issueId'
    }
  ]
});

var QUser = FOAM({
  model_: 'Model',
  name: 'QUser',
  extendsModel: 'User',

  properties: [
    {
      model_: 'StringProperty',
      name: 'email'
    },
    {
      name: 'projects',
      postSet: function(_, newValue) {
        if ( this.preferredProjects.length == 0 ) {
          this.preferredProjects = newValue.map(function(p) { return p.name; });
        }
      }
    },
    {
      model_: 'StringArrayProperty',
      name: 'preferredProjects',
      view: 'MultiLineStringArrayView'
    },
    {
      model_: 'StringProperty',
      name: 'defaultProject',
      defaultValue: 'chromium'
    }
  ]
});
<|endoftext|>


<commit_before>const generator = require('yeoman-generator');
const chalk = require('chalk');
const prompts = require('./prompts.js');
const fs = require('fs');

const jhipsterVar = {
    moduleName: 'fix-entity'
};

const jhipsterFunc = {};

module.exports = generator.extend({
    constructor: function (...args) { // eslint-disable-line object-shorthand
        generator.apply(this, args);
        // All information from entity generator
        this.entityConfig = this.options.entityConfig;
        this.entityTableName = this.options.entityConfig.entityTableName;
        this.dbhTableName = this.options.entityConfig.data.dbhTableName;
        this.fields = this.options.entityConfig.data.fields;

        // input from user (prompts.js will fill them)
        this.tableNameInput = null;
        this.columnsInput = [];
    },

    // check current project state, get configs, etc
    initializing() {
        this.log(chalk.bold.bgYellow('fix-entity generator'));
        this.log(chalk.bold.yellow('initializing'));
        this.composeWith('jhipster:modules',
            { jhipsterVar, jhipsterFunc },
            this.options.testmode ? { local: require.resolve('generator-jhipster/generators/modules') } : null
        );
        this.appConfig = jhipsterVar.jhipsterConfig;

        //* / TODO remove on prod
        this.prodDatabaseType = jhipsterVar.prodDatabaseType;
        this.log(chalk.blue('<<<<<BEFORE'));
        this.log(chalk.blue('entityConfig'));
        this.log(this.entityConfig);
        this.log(chalk.blue('fields'));
        this.log(this.fields);
        this.log(chalk.blue('jhipsterVar'));
        this.log(jhipsterVar);
        //*/
    },

    // prompt the user for options
    prompting: {
        askForTableName: prompts.askForTableName,
        askForColumnsName: prompts.askForColumnsName
    },

    // other Yeoman run loop steps would go here :

    // configuring() : Saving configurations and configure the project (creating .editorconfig files and other metadata files)

    // default() : If the method name doesn't match a priority, it will be pushed to this group.

    /**
     * After creating a new entity, replace the value of the table name.
     *
     * Allows consistent mapping with an existing database table without modifying JHipster's entity subgenerator.
     **/
    writing() {
        const files = {
            config: this.entityConfig.filename,
            ORM: `${jhipsterVar.javaDir}domain/${this.entityConfig.entityClass}.java`,
            liquibase: `${jhipsterVar.resourceDir}config/liquibase/changelog/${this.entityConfig.data.changelogDate}_added_entity_${this.entityConfig.entityClass}.xml`
        };

        // Add/Change/Keep dbhTableName
        const replaceTableName = (paramFiles) => {
            const pattern = `"entityTableName": "${this.entityTableName}"`;
            const key = 'dbhTableName';
            const oldValue = this.dbhTableName;
            const newValue = this.tableNameInput;

            if (oldValue === undefined) {
                // '(\\s*)' is for capturing indentation
                jhipsterFunc.replaceContent(paramFiles.config, `(\\s*)${pattern}`, `$1${pattern},$1"${key}": "${newValue}"`, true);
            } else {
                jhipsterFunc.replaceContent(paramFiles.config, `"${key}": "${oldValue}`, `"${key}": "${newValue}`);
            }

            // We search either for our value or jhipster value, so it works even if user didn't accept JHipster overwrite after a regeneration
            jhipsterFunc.replaceContent(paramFiles.ORM, `@Table\\(name = "(${this.entityTableName}|${oldValue})`, `@Table(name = "${newValue}`, true);
            jhipsterFunc.replaceContent(paramFiles.liquibase, `\\<createTable tableName="(${this.entityTableName}|${oldValue})`, `<createTable tableName="${newValue}`);
        };

        // DEBUG : log where we are
        this.log(chalk.bold.yellow('writing'));

        // verify files exist
        for (const file in files) {
            // hasOwnProperty to avoid inherited properties
            if (files.hasOwnProperty(file) && !fs.existsSync(files[file])) {
                throw new Error(`JHipster-db-helper : File not found (${file}: ${files[file]}).`);
            }
        }

        replaceTableName(files);

        // Add/Change/Keep dbhColumnName for each field
        this.columnsInput.forEach((columnItem) => {
            const pattern = `"fieldName": "${columnItem.fieldName}"`;
            const key = 'dbhColumnName';
            const oldValue = columnItem.dbhColumnName;
            const newValue = columnItem.columnNameInput;

            if (oldValue === undefined) {
                // '(\\s*)' is for capturing indentation
                jhipsterFunc.replaceContent(files.config, `(\\s*)${pattern}`, `$1${pattern},$1"${key}": "${newValue}"`, true);
            } else {
                jhipsterFunc.replaceContent(files.config, `"${key}": "${oldValue}`, `"${key}": "${newValue}`);
            }

            // We search either for our value or jhipster value, so it works even if user didn't accept JHipster overwrite after a regeneration
            jhipsterFunc.replaceContent(files.ORM, `@Column\\(name = "(${columnItem.fieldNameAsDatabaseColumn}|${oldValue})`, `@Column(name = "${newValue}`, true);
            jhipsterFunc.replaceContent(files.liquibase, `\\<column name="(${columnItem.fieldNameAsDatabaseColumn}|${oldValue})`, `<column name="${newValue}`, true);
        });
    },

    // conflict() : Where conflicts are handled (used internally)

    // run installation (npm, bower, etc)
    install() {
        // DEBUG : log where we are
        this.log(chalk.bold.yellow('install'));
    },

    // cleanup, say goodbye
    end() {
        // DEBUG : log where we are
        this.log(chalk.bold.yellow('End of fix-entity generator'));
    }
});
<commit_msg>add regex interpretation to replace table name<commit_after>const generator = require('yeoman-generator');
const chalk = require('chalk');
const prompts = require('./prompts.js');
const fs = require('fs');

const jhipsterVar = {
    moduleName: 'fix-entity'
};

const jhipsterFunc = {};

module.exports = generator.extend({
    constructor: function (...args) { // eslint-disable-line object-shorthand
        generator.apply(this, args);
        // All information from entity generator
        this.entityConfig = this.options.entityConfig;
        this.entityTableName = this.options.entityConfig.entityTableName;
        this.dbhTableName = this.options.entityConfig.data.dbhTableName;
        this.fields = this.options.entityConfig.data.fields;

        // input from user (prompts.js will fill them)
        this.tableNameInput = null;
        this.columnsInput = [];
    },

    // check current project state, get configs, etc
    initializing() {
        this.log(chalk.bold.bgYellow('fix-entity generator'));
        this.log(chalk.bold.yellow('initializing'));
        this.composeWith('jhipster:modules',
            { jhipsterVar, jhipsterFunc },
            this.options.testmode ? { local: require.resolve('generator-jhipster/generators/modules') } : null
        );
        this.appConfig = jhipsterVar.jhipsterConfig;

        /* / TODO remove on prod
        this.prodDatabaseType = jhipsterVar.prodDatabaseType;
        this.log(chalk.blue('<<<<<BEFORE'));
        this.log(chalk.blue('entityConfig'));
        this.log(this.entityConfig);
        this.log(chalk.blue('fields'));
        this.log(this.fields);
        this.log(chalk.blue('jhipsterVar'));
        this.log(jhipsterVar);
        //*/
    },

    // prompt the user for options
    prompting: {
        askForTableName: prompts.askForTableName,
        askForColumnsName: prompts.askForColumnsName
    },

    // other Yeoman run loop steps would go here :

    // configuring() : Saving configurations and configure the project (creating .editorconfig files and other metadata files)

    // default() : If the method name doesn't match a priority, it will be pushed to this group.

    /**
     * After creating a new entity, replace the value of the table name.
     *
     * Allows consistent mapping with an existing database table without modifying JHipster's entity subgenerator.
     **/
    writing() {
        const files = {
            config: this.entityConfig.filename,
            ORM: `${jhipsterVar.javaDir}domain/${this.entityConfig.entityClass}.java`,
            liquibase: `${jhipsterVar.resourceDir}config/liquibase/changelog/${this.entityConfig.data.changelogDate}_added_entity_${this.entityConfig.entityClass}.xml`
        };

        // Add/Change/Keep dbhTableName
        const replaceTableName = (paramFiles) => {
            const pattern = `"entityTableName": "${this.entityTableName}"`;
            const key = 'dbhTableName';
            const oldValue = this.dbhTableName;
            const newValue = this.tableNameInput;

            if (oldValue === undefined) {
                // '(\\s*)' is for capturing indentation
                jhipsterFunc.replaceContent(paramFiles.config, `(\\s*)${pattern}`, `$1${pattern},$1"${key}": "${newValue}"`, true);
            } else {
                jhipsterFunc.replaceContent(paramFiles.config, `"${key}": "${oldValue}`, `"${key}": "${newValue}`);
            }

            // We search either for our value or jhipster value, so it works even if user didn't accept JHipster overwrite after a regeneration
            jhipsterFunc.replaceContent(paramFiles.ORM, `@Table\\(name = "(${this.entityTableName}|${oldValue})`, `@Table(name = "${newValue}`, true);
            jhipsterFunc.replaceContent(paramFiles.liquibase, `\\<createTable tableName="(${this.entityTableName}|${oldValue})`, `<createTable tableName="${newValue}`, true);
        };

        // DEBUG : log where we are
        this.log(chalk.bold.yellow('writing'));

        // verify files exist
        for (const file in files) {
            // hasOwnProperty to avoid inherited properties
            if (files.hasOwnProperty(file) && !fs.existsSync(files[file])) {
                throw new Error(`JHipster-db-helper : File not found (${file}: ${files[file]}).`);
            }
        }

        replaceTableName(files);

        // Add/Change/Keep dbhColumnName for each field
        this.columnsInput.forEach((columnItem) => {
            const pattern = `"fieldName": "${columnItem.fieldName}"`;
            const key = 'dbhColumnName';
            const oldValue = columnItem.dbhColumnName;
            const newValue = columnItem.columnNameInput;

            if (oldValue === undefined) {
                // '(\\s*)' is for capturing indentation
                jhipsterFunc.replaceContent(files.config, `(\\s*)${pattern}`, `$1${pattern},$1"${key}": "${newValue}"`, true);
            } else {
                jhipsterFunc.replaceContent(files.config, `"${key}": "${oldValue}`, `"${key}": "${newValue}`);
            }

            // We search either for our value or jhipster value, so it works even if user didn't accept JHipster overwrite after a regeneration
            jhipsterFunc.replaceContent(files.ORM, `@Column\\(name = "(${columnItem.fieldNameAsDatabaseColumn}|${oldValue})`, `@Column(name = "${newValue}`, true);
            jhipsterFunc.replaceContent(files.liquibase, `\\<column name="(${columnItem.fieldNameAsDatabaseColumn}|${oldValue})`, `<column name="${newValue}`, true);
        });
    },

    // conflict() : Where conflicts are handled (used internally)

    // run installation (npm, bower, etc)
    install() {
        // DEBUG : log where we are
        this.log(chalk.bold.yellow('install'));
    },

    // cleanup, say goodbye
    end() {
        // DEBUG : log where we are
        this.log(chalk.bold.yellow('End of fix-entity generator'));
    }
});
<|endoftext|>


<commit_before>'use strict';
var util = require('util'),
shelljs = require('shelljs'),
generators = require('yeoman-generator'),
chalk = require('chalk'),
jhuml = require("jhipster-uml"),
scriptBase = require('../generator-base');

const constants = require('../generator-constants'),
SERVER_MAIN_SRC_DIR = constants.SERVER_MAIN_SRC_DIR;

var JDLGenerator = generators.Base.extend({});

util.inherits(JDLGenerator, scriptBase);

module.exports = JDLGenerator.extend({
    constructor: function () {
        generators.Base.apply(this, arguments);
        this.argument('jdlFile', {type: String, required: true});
    },

    initializing: {
        validate: function () {
            if (!shelljs.test('-f', this.jdlFile)) {
                this.env.error(chalk.red('\nCould not find ' + this.jdlFile + ', make sure the path is correct!\n'));
            }
        },

        getConfig: function () {
            this.log('The jdl is being imported.');
            this.databaseType = this.config.get('databaseType');
        }
    },

    _filterScheduledClasses: function(classToFilter, scheduledClasses) {
        return scheduledClasses.filter(function(element) {
            return element !== classToFilter;
        });
    },

    _initDatabaseTypeHolder: function(databaseTypeName) {
        switch (databaseTypeName) {
            case 'sql':
            return jhuml.SQLTypes;
            case 'mongodb':
            return jhuml.MongoDBTypes;
            case 'cassandra':
            return jhuml.CassandraTypes;
            default:
            return jhuml.SQLTypes;
        }
    },
    default: {

        parseJDL: function () {

            Editors = jhuml.editors;
            self.entityGenerator = jhuml.entityGenerator;
            self.EntitiesCreator = jhuml.EntitiesCreator;
            ClassScheduler = jhuml.ClassScheduler;
            self.cardinalities = cardinalities;

            var types = this._initDatabaseTypeHolder(this.databaseType);

            var parser = new Editors.Parsers['dsl'](this.jdlFile, types);
            var parsedData = parser.parse();
            var scheduler = new ClassScheduler(
                Object.keys(parsedData.classes),
                parsedData.associations
            );

            var scheduledClasses = scheduler.schedule();
            if (parsedData.userClassId) {
                scheduledClasses =
                this._filterScheduledClasses(parsedData.userClassId, scheduledClasses);
            }

            var creator = new EntitiesCreator(
                parsedData,
                parser.databaseTypes,
                [], {}, {});

                creator.createEntities();
                if (!this.options['force']) {
                    scheduledClasses = creator.filterOutUnchangedEntities(scheduledClasses);
                }
                creator.writeJSON(scheduledClasses);
            }
        },

        generateEntities: function () {

        }

    });
<commit_msg>add sub gen logic polish<commit_after>'use strict';
var util = require('util'),
shelljs = require('shelljs'),
generators = require('yeoman-generator'),
chalk = require('chalk'),
jhuml = require("jhipster-uml"),
scriptBase = require('../generator-base');

const constants = require('../generator-constants'),
SERVER_MAIN_SRC_DIR = constants.SERVER_MAIN_SRC_DIR;

var JDLGenerator = generators.Base.extend({});

util.inherits(JDLGenerator, scriptBase);

module.exports = JDLGenerator.extend({
    constructor: function () {
        generators.Base.apply(this, arguments);
        this.argument('jdlFile', {type: String, required: true});
    },

    initializing: {
        validate: function () {
            if (!shelljs.test('-f', this.jdlFile)) {
                this.env.error(chalk.red('\nCould not find ' + this.jdlFile + ', make sure the path is correct!\n'));
            }
        },

        getConfig: function () {
            this.log('The jdl is being imported.');
            this.databaseType = this.config.get('databaseType');
        }
    },

    _filterScheduledClasses: function(classToFilter, scheduledClasses) {
        return scheduledClasses.filter(function(element) {
            return element !== classToFilter;
        });
    },

    _initDatabaseTypeHolder: function(databaseTypeName) {
        switch (databaseTypeName) {
            case 'sql':
            return jhuml.SQLTypes;
            case 'mongodb':
            return jhuml.MongoDBTypes;
            case 'cassandra':
            return jhuml.CassandraTypes;
            default:
            return jhuml.SQLTypes;
        }
    },
    default: {

        parseJDL: function () {

            var Editors = jhuml.editors;
            var EntitiesCreator = jhuml.EntitiesCreator;
            var ClassScheduler = jhuml.ClassScheduler;

            var types = this._initDatabaseTypeHolder(this.databaseType);

            var parser = new Editors.Parsers['dsl'](this.jdlFile, types);
            var parsedData = parser.parse();
            var scheduler = new ClassScheduler(
                Object.keys(parsedData.classes),
                parsedData.associations
            );

            var scheduledClasses = scheduler.schedule();
            if (parsedData.userClassId) {
                scheduledClasses =
                this._filterScheduledClasses(parsedData.userClassId, scheduledClasses);
            }

            var creator = new EntitiesCreator(
                parsedData,
                parser.databaseTypes,
                [], {}, {});

            creator.createEntities();
            if (!this.options['force']) {
                scheduledClasses = creator.filterOutUnchangedEntities(scheduledClasses);
            }
            creator.writeJSON(scheduledClasses);
        },

        generateEntities: function () {

        }

    });
<|endoftext|>


<commit_before>if (!org.bustany.TrackerBird.TrackerSparql || !org.bustany.TrackerBird.TrackerSparql.__initialized)
org.bustany.TrackerBird.TrackerSparql = {
	__initialized: true,

	_trackerSparqlPath: "libtracker-sparql-0.10.so.0",
	_lib: null,

	init: function () {
		var tracker = org.bustany.TrackerBird.TrackerSparql;

		// Safeguard just in case a fool would call that twice
		if (tracker._lib) {
			return true;
		}

		Components.utils.import ("resource://gre/modules/ctypes.jsm");

		try {
			tracker._lib = ctypes.open (tracker._trackerSparqlPath);
		} catch (e) {
			tracker._trackerSparqlPath = "libtracker-sparql-0.12.so.0";

			try {
				tracker._lib = ctypes.open (tracker._trackerSparqlPath);
			} catch (e) {
				dump ("Could not load libtracker-sparql 0.10 or 0.12: " + e + "\n");
				return false;
			}
		}

		// GLib types
		tracker.Object = new ctypes.StructType ("GObject");
		tracker.Cancellable = new ctypes.StructType ("GCancellable");
		tracker.Error = new ctypes.StructType ("GError", [
			{domain  : ctypes.uint32_t},
			{code    : ctypes.int32_t},
			{message : ctypes.char.ptr}
		]);
		tracker.AsyncResult = new ctypes.StructType ("GAsyncResult");
		tracker.AsyncReadyCallback = new ctypes.FunctionType(
			ctypes.default_abi,
			ctypes.void_t,
			[ tracker.Object.ptr, tracker.AsyncResult.ptr, ctypes.voidptr_t ]);

		// TrackerSparql types
		tracker.Connection = ctypes.StructType ("TrackerSparqlConnection");
		tracker.Cursor = ctypes.StructType ("TrackerSparqlCursor");

		// GLib methods
		tracker.free = tracker._lib.declare (
			"g_free",
			ctypes.default_abi,
			ctypes.void_t,
			ctypes.void_t.ptr
		);

		tracker.object_unref = tracker._lib.declare (
			"g_object_unref",
			ctypes.default_abi,
			ctypes.void_t,
			ctypes.void_t.ptr // Binding GObject* as a void* since we don't have GObject binding...
		);

		tracker.error_free = tracker._lib.declare (
			"g_error_free",
			ctypes.default_abi,
			ctypes.void_t,
			tracker.Error.ptr
		);

		// TrackerSparql methods (name, ABI, args with first arg = return type)
		tracker.connection_open = tracker._lib.declare (
			"tracker_sparql_connection_get",
			ctypes.default_abi,
			tracker.Connection.ptr,
			tracker.Cancellable.ptr,
			tracker.Error.ptr.ptr
		);

		tracker.connection_open_async = tracker._lib.declare (
			"tracker_sparql_connection_get_async",
			ctypes.default_abi,
			ctypes.void_t,
			tracker.Cancellable.ptr,
			tracker.AsyncReadyCallback.ptr,
			ctypes.voidptr_t);

		tracker.connection_open_finish = tracker._lib.declare (
			"tracker_sparql_connection_get_finish",
			ctypes.default_abi,
			tracker.Connection.ptr,
			tracker.AsyncResult.ptr,
			tracker.Error.ptr.ptr);

		tracker.connection_query = tracker._lib.declare (
			"tracker_sparql_connection_query",
			ctypes.default_abi,
			tracker.Cursor.ptr,
			tracker.Connection.ptr,
			ctypes.char.ptr,
			tracker.Cancellable.ptr,
			tracker.Error.ptr.ptr
		);

		tracker.connection_update = tracker._lib.declare (
			"tracker_sparql_connection_update",
			ctypes.default_abi,
			ctypes.void_t,
			tracker.Connection.ptr,
			ctypes.char.ptr,
			ctypes.int32_t,
			tracker.Cancellable.ptr,
			tracker.Error.ptr.ptr
		);

		tracker.cursor_next = tracker._lib.declare (
			"tracker_sparql_cursor_next",
			ctypes.default_abi,
			ctypes.bool,
			tracker.Cursor.ptr,
			tracker.Cancellable.ptr,
			tracker.Error.ptr.ptr
		);

		tracker.cursor_get_string = tracker._lib.declare (
			"tracker_sparql_cursor_get_string",
			ctypes.default_abi,
			ctypes.char.ptr,
			tracker.Cursor.ptr,
			ctypes.int,
			ctypes.long.ptr
		);

		tracker.escape_string = tracker._lib.declare (
			"tracker_sparql_escape_string",
			ctypes.default_abi,
			ctypes.char.ptr,
			ctypes.char.ptr
		);

		return true;
	},

	shutdown: function () {
		var tracker = org.bustany.TrackerBird.TrackerSparql;

		if (this._connection) {
			tracker.object_unref(this._connection);
		}

		if (this._lib) {
			this._lib.close ();
		}
	}
}
<commit_msg>thunderbird: Fix parameters types in bindings.js<commit_after>if (!org.bustany.TrackerBird.TrackerSparql || !org.bustany.TrackerBird.TrackerSparql.__initialized)
org.bustany.TrackerBird.TrackerSparql = {
	__initialized: true,

	_trackerSparqlPath: "libtracker-sparql-0.10.so.0",
	_lib: null,

	init: function () {
		var tracker = org.bustany.TrackerBird.TrackerSparql;

		// Safeguard just in case a fool would call that twice
		if (tracker._lib) {
			return true;
		}

		Components.utils.import ("resource://gre/modules/ctypes.jsm");

		try {
			tracker._lib = ctypes.open (tracker._trackerSparqlPath);
		} catch (e) {
			tracker._trackerSparqlPath = "libtracker-sparql-0.12.so.0";

			try {
				tracker._lib = ctypes.open (tracker._trackerSparqlPath);
			} catch (e) {
				dump ("Could not load libtracker-sparql 0.10 or 0.12: " + e + "\n");
				return false;
			}
		}

		// GLib types
		tracker.Object = new ctypes.StructType ("GObject");
		tracker.Cancellable = new ctypes.StructType ("GCancellable");
		tracker.Error = new ctypes.StructType ("GError", [
			{domain  : ctypes.uint32_t},
			{code    : ctypes.int32_t},
			{message : ctypes.char.ptr}
		]);
		tracker.AsyncResult = new ctypes.StructType ("GAsyncResult");
		tracker.AsyncReadyCallback = new ctypes.FunctionType(
			ctypes.default_abi,
			ctypes.void_t,
			[ tracker.Object.ptr, tracker.AsyncResult.ptr, ctypes.voidptr_t ]);

		// TrackerSparql types
		tracker.Connection = ctypes.StructType ("TrackerSparqlConnection");
		tracker.Cursor = ctypes.StructType ("TrackerSparqlCursor");

		// GLib methods
		tracker.free = tracker._lib.declare (
			"g_free",
			ctypes.default_abi,
			ctypes.void_t,
			ctypes.voidptr_t
		);

		tracker.object_unref = tracker._lib.declare (
			"g_object_unref",
			ctypes.default_abi,
			ctypes.void_t,
			tracker.Object.ptr
		);

		tracker.error_free = tracker._lib.declare (
			"g_error_free",
			ctypes.default_abi,
			ctypes.void_t,
			tracker.Error.ptr
		);

		// TrackerSparql methods (name, ABI, args with first arg = return type)
		tracker.connection_open = tracker._lib.declare (
			"tracker_sparql_connection_get",
			ctypes.default_abi,
			tracker.Connection.ptr,
			tracker.Cancellable.ptr,
			tracker.Error.ptr.ptr
		);

		tracker.connection_open_async = tracker._lib.declare (
			"tracker_sparql_connection_get_async",
			ctypes.default_abi,
			ctypes.void_t,
			tracker.Cancellable.ptr,
			tracker.AsyncReadyCallback.ptr,
			ctypes.voidptr_t);

		tracker.connection_open_finish = tracker._lib.declare (
			"tracker_sparql_connection_get_finish",
			ctypes.default_abi,
			tracker.Connection.ptr,
			tracker.AsyncResult.ptr,
			tracker.Error.ptr.ptr);

		tracker.connection_query = tracker._lib.declare (
			"tracker_sparql_connection_query",
			ctypes.default_abi,
			tracker.Cursor.ptr,
			tracker.Connection.ptr,
			ctypes.char.ptr,
			tracker.Cancellable.ptr,
			tracker.Error.ptr.ptr
		);

		tracker.connection_update = tracker._lib.declare (
			"tracker_sparql_connection_update",
			ctypes.default_abi,
			ctypes.void_t,
			tracker.Connection.ptr,
			ctypes.char.ptr,
			ctypes.int32_t,
			tracker.Cancellable.ptr,
			tracker.Error.ptr.ptr
		);

		tracker.cursor_next = tracker._lib.declare (
			"tracker_sparql_cursor_next",
			ctypes.default_abi,
			ctypes.bool,
			tracker.Cursor.ptr,
			tracker.Cancellable.ptr,
			tracker.Error.ptr.ptr
		);

		tracker.cursor_get_string = tracker._lib.declare (
			"tracker_sparql_cursor_get_string",
			ctypes.default_abi,
			ctypes.char.ptr,
			tracker.Cursor.ptr,
			ctypes.int,
			ctypes.long.ptr
		);

		tracker.escape_string = tracker._lib.declare (
			"tracker_sparql_escape_string",
			ctypes.default_abi,
			ctypes.char.ptr,
			ctypes.char.ptr
		);

		return true;
	},

	shutdown: function () {
		var tracker = org.bustany.TrackerBird.TrackerSparql;

		if (this._connection) {
			tracker.object_unref(this._connection);
		}

		if (this._lib) {
			this._lib.close ();
		}
	}
}
<|endoftext|>