Exemplo n.º 1
0
test('save method', function(assert) {
  assert.expect(4);
  let debounce = run.debounce;
  let Model = EmberObject.extend({
    save: () => {
      assert.ok(true);
    }
  });
  let model = Model.create();
  run.debounce = (ctx, fn, time) => {
    assert.deepEqual(ctx, model);
    assert.deepEqual(fn, model.save);
    assert.equal(time, 100);
    fn.call(ctx);
  };
  let AutoSaveProxy = ObjectProxy.extend(AutoSaveMixin);

  let subject = AutoSaveProxy.create({
    wait: 100,
    content: model
  });

  subject.save();
  run.debounce = debounce;
});
Exemplo n.º 2
0
    promise: $.getJSON('/some/remote/data.json')
  });

  promiseObject.get('name'); // null

  promiseObject.then(function() {
    promiseObject.get('name'); // 'Tomster'
  });
  ```

  @class PromiseObject
  @namespace DS
  @extends Ember.ObjectProxy
  @uses Ember.PromiseProxyMixin
*/
export let PromiseObject = ObjectProxy.extend(PromiseProxyMixin);

export function promiseObject(promise, label) {
  return PromiseObject.create({
    promise: Promise.resolve(promise, label)
  });
}

export function promiseArray(promise, label) {
  return PromiseArray.create({
    promise: Promise.resolve(promise, label)
  });
}

export const PromiseBelongsTo = PromiseObject.extend({
export default ObjectProxy.extend(Evented, {
  authenticator:       null,
  store:               null,
  isAuthenticated:     false,
  attemptedTransition: null,

  init() {
    this._super(...arguments);
    this.set('content', { authenticated: {} });
    this._busy = false;
    this._bindToStoreEvents();
  },

  authenticate(authenticatorFactory, ...args) {
    this._busy = true;
    assert(`Session#authenticate requires the authenticator to be specified, was "${authenticatorFactory}"!`, !isEmpty(authenticatorFactory));
    const authenticator = this._lookupAuthenticator(authenticatorFactory);
    assert(`No authenticator for factory "${authenticatorFactory}" could be found!`, !isNone(authenticator));

    return authenticator.authenticate(...args).then((content) => {
      this._busy = false;
      return this._setup(authenticatorFactory, content, true);
    }, (error) => {
      const rejectWithError = () => RSVP.Promise.reject(error);

      this._busy = false;
      return this._clear().then(rejectWithError, rejectWithError);
    });
  },

  invalidate() {
    this._busy = true;

    if (!this.get('isAuthenticated')) {
      this._busy = false;
      return RSVP.Promise.resolve();
    }

    let authenticator = this._lookupAuthenticator(this.authenticator);
    return authenticator.invalidate(this.content.authenticated, ...arguments).then(() => {
      authenticator.off('sessionDataUpdated', this, this._onSessionDataUpdated);
      this._busy = false;
      return this._clear(true);
    }, (error) => {
      this.trigger('sessionInvalidationFailed', error);
      this._busy = false;
      return RSVP.Promise.reject(error);
    });
  },

  restore() {
    this._busy = true;
    const reject = () => RSVP.Promise.reject();

    return this._callStoreAsync('restore').then((restoredContent) => {
      let { authenticator: authenticatorFactory } = restoredContent.authenticated || {};
      if (authenticatorFactory) {
        delete restoredContent.authenticated.authenticator;
        const authenticator = this._lookupAuthenticator(authenticatorFactory);
        return authenticator.restore(restoredContent.authenticated).then((content) => {
          this.set('content', restoredContent);
          this._busy = false;
          return this._setup(authenticatorFactory, content);
        }, (err) => {
          debug(`The authenticator "${authenticatorFactory}" rejected to restore the session - invalidating…`);
          if (err) {
            debug(err);
          }
          this._busy = false;
          return this._clearWithContent(restoredContent).then(reject, reject);
        });
      } else {
        delete (restoredContent || {}).authenticated;
        this._busy = false;
        return this._clearWithContent(restoredContent).then(reject, reject);
      }
    }, () => {
      this._busy = false;
      return this._clear().then(reject, reject);
    });
  },

  _callStoreAsync(method, ...params) {
    const result = this.store[method](...params);

    if (typeof result === 'undefined' || typeof result.then === 'undefined') {
      deprecate(`Ember Simple Auth: Synchronous stores have been deprecated. Make sure your custom store's ${method} method returns a promise.`, false, {
        id: `ember-simple-auth.session-store.synchronous-${method}`,
        until: '2.0.0'
      });
      return RSVP.Promise.resolve(result);
    } else {
      return result;
    }
  },

  _setup(authenticator, authenticatedContent, trigger) {
    trigger = Boolean(trigger) && !this.get('isAuthenticated');
    this.setProperties({
      isAuthenticated: true,
      authenticator,
      'content.authenticated': authenticatedContent
    });
    this._bindToAuthenticatorEvents();

    return this._updateStore()
      .then(() => {
        if (trigger) {
          this.trigger('authenticationSucceeded');
        }
      }, () => {
        this.setProperties({
          isAuthenticated: false,
          authenticator: null,
          'content.authenticated': {}
        });
      });
  },

  _clear(trigger) {
    trigger = Boolean(trigger) && this.get('isAuthenticated');
    this.setProperties({
      isAuthenticated: false,
      authenticator:   null,
      'content.authenticated': {}
    });

    return this._updateStore().then(() => {
      if (trigger) {
        this.trigger('invalidationSucceeded');
      }
    });
  },

  _clearWithContent(content, trigger) {
    this.set('content', content);
    return this._clear(trigger);
  },

  setUnknownProperty(key, value) {
    assert('"authenticated" is a reserved key used by Ember Simple Auth!', key !== 'authenticated');
    let result = this._super(key, value);
    if (!(/^_/).test(key)) {
      this._updateStore();
    }
    return result;
  },

  _updateStore() {
    let data = this.content;
    if (!isEmpty(this.authenticator)) {
      set(data, 'authenticated', assign({ authenticator: this.authenticator }, data.authenticated || {}));
    }
    return this._callStoreAsync('persist', data);
  },

  _bindToAuthenticatorEvents() {
    const authenticator = this._lookupAuthenticator(this.authenticator);
    authenticator.on('sessionDataUpdated', this, this._onSessionDataUpdated);
    authenticator.on('sessionDataInvalidated', this, this._onSessionDataInvalidated);
  },

  _onSessionDataUpdated(content) {
    this._setup(this.authenticator, content);
  },

  _onSessionDataInvalidated() {
    this._clear(true);
  },

  _bindToStoreEvents() {
    this.store.on('sessionDataUpdated', (content) => {
      if (!this._busy) {
        this._busy = true;
        let { authenticator: authenticatorFactory } = (content.authenticated || {});
        if (authenticatorFactory) {
          delete content.authenticated.authenticator;
          const authenticator = this._lookupAuthenticator(authenticatorFactory);
          authenticator.restore(content.authenticated).then((authenticatedContent) => {
            this.set('content', content);
            this._busy = false;
            this._setup(authenticatorFactory, authenticatedContent, true);
          }, (err) => {
            debug(`The authenticator "${authenticatorFactory}" rejected to restore the session - invalidating…`);
            if (err) {
              debug(err);
            }
            this._busy = false;
            this._clearWithContent(content, true);
          });
        } else {
          this._busy = false;
          this._clearWithContent(content, true);
        }
      }
    });
  },

  _lookupAuthenticator(authenticator) {
    return getOwner(this).lookup(authenticator);
  }
});
Exemplo n.º 4
0
export default ObjectProxy.extend(
  EmberValidations,
  FormMixin,
  ItemPropertiesMixin,
  {
    validations: {
      description: {
        presence: { if: 'invoiceForm.isSubmitted' }
      },
      quantity: {
        presence: { if: 'invoiceForm.isSubmitted' },
        numericality: { if: 'invoiceForm.isSubmitted' }
      },
      netPrice: {
        presence: { if: 'invoiceForm.isSubmitted' },
        numericality: { if: 'invoiceForm.isSubmitted' }
      },
      unitCode: {
        presence: { if: 'invoiceForm.isSubmitted' }
      },
      taxRateCode: {
        presence: { if: 'invoiceForm.isSubmitted' }
      }
    },

    description: oneWay('model.description'),
    quantity: oneWay('model.quantity'),
    netPrice: oneWay('model.netPrice'),
    unitCode: oneWay('model.unitCode'),
    taxRateCode: oneWay('model.taxRateCode')
  }
);
/* eslint ember/order-in-components: 0 */
import Component from '@ember/component';
import { computed } from '@ember/object';
import RSVP from 'rsvp';
import { isPresent } from '@ember/utils';
import ObjectProxy from '@ember/object/proxy';

const { Promise } = RSVP;

const SequenceBlockProxy = ObjectProxy.extend({
  content: null,
  showRemoveConfirmation: false
});

export default Component.extend({
  init() {
    this._super(...arguments);
    this.set('sequenceBlocks', []);
  },
  classNames: ['curriculum-inventory-sequence-block-list'],
  parent: null,
  report: null,
  canUpdate: false,
  sequenceBlocks: null,
  editorOn: false,
  saved: false,
  savedBlock: null,
  isSaving: null,

  isInOrderedSequence: computed('parent', function () {
    const parent = this.parent;
Exemplo n.º 6
0
export default ObjectProxy.extend({

  /*
  * {
  *    url: 'String'
  *    type: 'String' (such as 'open', 'message', 'close', and 'error')
  *    callback: The function to envoke
  *    context: The context of the function
  * }
  */
  listeners: null,

  protocols: null,

  init() {
    this._super(...arguments);
    this.listeners = [];
    this.setupInternalListeners();
  },

  /*
  * Adds a callback function into the listeners array which will
  * be invoked later whenever a given `type` event happens.
  *
  * type: must be either 'open', 'message', 'close', 'error'
  */
  on(type, callback, context) {
    assert(`${type} is not a recognized event name. Please use on of the following: ${events.join(', ')}`, indexOf.call(events, type) !== -1);
    assert('The second argument must be a function.', typeof callback === 'function');

    this.listeners.push({ url: this.socket.url, type, callback, context });
  },

  /*
  * Removes a callback function from the listeners array. This callback
  * will not longer be invoked when the given `type` event happens.
  */
  off(type, callback) {
    this.listeners = filter.call(this.listeners, listeners => !(listeners.callback === callback && listeners.type === type));
  },

  /*
  * Message is the message which will be passed into the native websockets send method
  * and shouldStringify is a boolean which determines if we should call JSON.stringify on
  * the message.
  */
  send(message, shouldStringify = false) {
    if(shouldStringify && JSON && JSON.stringify) {
      message = JSON.stringify(message);
    }

    assert('Cannot send message to the websocket while it is not open.', this.readyState() === WebSocket.OPEN);

    this.socket.send(message);
  },

  close() {
    this.socket.close();
  },

  reconnect() {
    this.set('socket', new WebSocket(this.socket.url, this.get('protocols')));
    this.setupInternalListeners();
  },

  setupInternalListeners() {
    forEach.call(events, eventName => {
      this.socket[`on${eventName}`] = event => {
        run(() => {
          var activeListeners = filter.call(this.listeners, listener => {
            return listener.url === event.currentTarget.url && listener.type === eventName;
          });

          // TODO: filter active listeners for contexts that are not destroyed
          forEach.call(activeListeners, item => {
            if (item.context) {
              item.callback.call(item.context, event);
            }
            else {
              item.callback(event);
            }
          });
        });
      };
    });
  },

  /*
  * A helper method to get access to the readyState of the websocket.
  */
  readyState() { return this.socket.readyState; }
});
import ObjectProxy from '@ember/object/proxy';
import AutoSaveMixin from 'ember-auto-save/mixins/auto-save';

// extend ObjectProxy using the AutoSaveMixin to create
// an AutoSaveProxy class
let AutoSaveProxy = ObjectProxy.extend(AutoSaveMixin);

// create an instance of the AutoSaveProxy class.  Set the
// target model as the content property of the proxy.
let autoSaveProxy =  AutoSaveProxy.create({
  content: this.get('model')
});
Exemplo n.º 8
0
export default ObjectProxy.extend(EmberValidations, FormMixin, {
  validations: {
    companyName: {
      presence: {
        if: 'isSubmitted',
        message: 'nie może być pusta'
      }
    },
    address: {
      presence: {
        if: 'isSubmitted',
        message: 'nie może być pusty'
      }
    },
    vatin: {
      presence: {
        if: 'isSubmitted',
        message: 'nie może być pusty'
      }
    },
    dueDays: {
      presence: {
        if: 'isSubmitted',
        message: 'nie może być pusty'
      },
      numericality: {
        if: 'isSubmitted',
        greaterThanOrEqualTo: 0,
        messages: {
          greaterThanOrEqualTo: 'nie może być ujemny'
        }
      }
    }
  },

  id: oneWay('model.id'),
  companyName: oneWay('model.companyName'),
  address: oneWay('model.address'),
  vatin: oneWay('model.vatin'),
  dueDays: oneWay('model.dueDays'),

  initDueDays: function() {
    if (this.get('dueDays') === undefined) {
      this.set('dueDays', 14);
    }
  }.on('init')
});
Exemplo n.º 9
0
import ObjectProxy from '@ember/object/proxy';
import { oneWay } from '@ember/object/computed';
import EmberValidations from 'ember-validations';
import FormMixin from 'fakturama/mixins/form';

export default ObjectProxy.extend(EmberValidations, FormMixin, {
  validations: {
    number: {
      presence: {
        if: 'isSubmitted',
        message: 'nie może być pusty'
      }
    }
  },

  id: oneWay('model.id'),
  bankName: oneWay('model.bankName'),
  swift: oneWay('model.swift'),
  number: oneWay('model.number'),
  description: oneWay('model.description')
});
Exemplo n.º 10
0
/* eslint ember/order-in-components: 0 */
import { inject as service } from '@ember/service';
import Component from '@ember/component';
import { computed } from '@ember/object';
import ObjectProxy from '@ember/object/proxy';

const ProgramProxy = ObjectProxy.extend({
  showRemoveConfirmation: false,
  canDelete: computed('content.curriculumInventoryReports.[]', 'content.programYears.[]', async function () {
    const program = this.content;
    const permissionChecker = this.permissionChecker;
    const hasCiReports = program.hasMany('curriculumInventoryReports').ids().length > 0;
    const hasProgramYears = program.hasMany('programYears').ids().length > 0;
    const canDelete = await permissionChecker.canDeleteProgram(program);

    return !hasCiReports && !hasProgramYears && canDelete;
  })
});


export default Component.extend({
  permissionChecker: service(),
  programs: null,
  proxiedPrograms: computed('programs.[]', function(){
    const permissionChecker = this.permissionChecker;
    const programs = this.programs;
    if (!programs) {
      return [];
    }
    return programs.map(program => {
      return ProgramProxy.create({
import { inject as service } from '@ember/service';
import { computed } from '@ember/object';
import ObjectProxy from '@ember/object/proxy';
import Component from '@ember/component';
const { alias, not } = computed;

const ReportProxy = ObjectProxy.extend({
  content: null,
  currentUser: null,
  permissionChecker: null,
  showRemoveConfirmation: false,
  intl: null,
  isPublished: alias('isFinalized'),
  isScheduled: false,
  isNotPublished: not('isPublished'),

  userCanDelete: computed('content', 'content.isFinalized', 'currentUser.model', async function(){
    const permissionChecker = this.permissionChecker;
    const report = this.content;
    if (report.get('isFinalized')) {
      return false;
    }
    return permissionChecker.canDeleteCurriculumInventoryReport(report);
  })
});

export default Component.extend({
  currentUser: service(),
  intl: service(),
  permissionChecker: service(),
  program: null,
Exemplo n.º 12
0
import ObjectProxy from '@ember/object/proxy';
import PromiseProxyMixin from '@ember/object/promise-proxy-mixin';
import RSVP from 'rsvp';
import computedUnsafe from 'ember-macro-helpers/computed-unsafe';

const { Promise } = RSVP;

const PromiseProxy = ObjectProxy.extend(PromiseProxyMixin);

/**
  Updates computed property when supplied callback (which must return a
  promise) is resolved.

  Example

  ```javascript
  data: promiseObject('dep', function(){
    return ajax('/data.json');
  })

  myObject.get('data') // => undefined

  // once resolved

  myObject.get('data') // => { foo: 'bar' };
  ```

  For example, if you have a template that renders `data` when the promise is
  resolved the template will be updated.

  @method computedPromise