export default AbstractEditController.extend(IncidentStatuses, FriendlyId, PatientSubmodule, SelectValues, UserSession, CustomFormManager, { lookupListsToUpdate: [{ name: 'incidentDepartmentList', property: 'model.department', id: 'incident_departments' }], sequenceName: 'incident', sequenceView: 'incident_by_friendly_id', updateCapability: 'add_incident', database: service(), filesystem: service(), lookupLists: service(), customFormsToAdd: alias('formsForSelect'), customFormsToDisplay: alias('formsToDisplay'), showAddFormButton: alias('showAddButton'), incidentController: controller('incident'), canManageIncident: computed('model.{isNew,status}', function() { let canManageIncident = this.currentUserCan('manage_incidents'); let status = get(this, 'model.status'); let isNew = get(this, 'model.isNew'); if (isNew || status === CLOSED) { canManageIncident = false; } return canManageIncident; }), canUpdateStatus: computed('model.isNew', function() { let canManageIncident = this.currentUserCan('manage_incidents'); let isNew = get(this, 'model.isNew'); return canManageIncident && !isNew; }), categoryNameList: computed('*****@*****.**', function() { return PromiseArray.create({ promise: get(this, 'incidentCategoryList').then((categoryList) => { return categoryList.map((value) => { return { id: get(value, 'incidentCategoryName'), value: get(value, 'incidentCategoryName') }; }); }) }); }).volatile(), incidentCategoryList: computed(function() { let lookupLists = get(this, 'lookupLists'); return lookupLists.getLookupList('incidentCategories'); }).volatile(), incidentDepartmentList: computed('lookupListsLastUpdate', function() { let lookupLists = get(this, 'lookupLists'); return PromiseObject.create({ promise: lookupLists.getLookupList('incident_departments') }); }).volatile(), incidentStatuses: computed(function() { return get(this, 'statusList').map((status) => { return { id: status, value: this.getLocalizedStatus(status) }; }); }), itemList: computed('model.categoryName', function() { let categoryNameSelected = get(this, 'model.categoryName'); if (!isEmpty(categoryNameSelected)) { return PromiseArray.create({ promise: get(this, 'incidentCategoryList').then((categoryList) => { let incidentCategory = categoryList.findBy('incidentCategoryName', categoryNameSelected); return get(incidentCategory, 'incidentCategoryItems'); }) }); } }), afterUpdate() { let i18n = get(this, 'i18n'); this.displayAlert(i18n.t('incident.titles.incidentSaved'), i18n.t('incident.messages.saved')); }, beforeUpdate() { let model = get(this, 'model'); set(model, 'modifiedByDisplayName', this.getUserName(false)); if (get(model, 'isNew')) { return this.generateFriendlyId('incident').then((friendlyId) => { set(model, 'friendlyId', friendlyId); }); } else { return resolve(); } }, setupCustomForms() { this.set('formType', 'incident'); this.initFormsForType(); }, /** * Adds or removes the specified object from the specified list. * @param {String} listName The name of the list to operate on. * @param {Object} listObject The object to add or removed from the * specified list. * @param {boolean} removeObject If true remove the object from the list; * otherwise add the specified object to the list. */ _updateList(listName, listObject, removeObject) { let model = get(this, 'model'); get(model, listName).then(function(list) { if (removeObject) { list.removeObject(listObject); } else { list.addObject(listObject); } this.send('update', true); this.send('closeModal'); }.bind(this)); }, actions: { addNote(newNote) { this._updateList('notes', newNote); }, addAttachment(newAttachment) { this._updateList('incidentAttachments', newAttachment); }, addCustomForm() { this.send('openModal', 'custom-form-add', EmberObject.create({ modelToAddTo: this.get('model'), customForms: this.get('customFormsToAdd') })); }, showAddAttachment() { let newNote = get(this, 'store').createRecord('attachment', { dateAdded: new Date(), addedBy: this.getUserName(true), addedByDisplayName: this.getUserName(false), saveToDir: `/incidents/${get(this, 'model.id')}/` }); this.send('openModal', 'incident.attachment', newNote); }, showAddNote() { let newNote = get(this, 'store').createRecord('incident-note', { dateRecorded: new Date(), givenBy: this.getUserName(true), givenByDisplayName: this.getUserName(false) }); this.send('openModal', 'incident.note.edit', newNote); }, deleteAttachment(model) { let attachment = get(model, 'itemToDelete'); this._updateList('incidentAttachments', attachment, true); attachment.destroyRecord().then(() => { let attachmentId = get(attachment, 'id'); let database = get(this, 'database'); let filePath = get(attachment, 'fileName'); let fileSystem = get(this, 'filesystem'); let isFileSystemEnabled = get(fileSystem, 'isFileSystemEnabled'); if (isFileSystemEnabled) { let pouchDbId = database.getPouchId(attachmentId, 'attachment'); fileSystem.deleteFile(filePath, pouchDbId).catch((/* ignored */) => {}); } }); }, deleteNote(note) { this._updateList('notes', note, true); }, showDeleteAttachment(attachment) { let i18n = get(this, 'i18n'); let modelName = i18n.t('models.attachment.names.singular'); let message = i18n.t('messages.delete_singular', { name: modelName }); let model = EmberObject.create({ itemToDelete: attachment }); let title = i18n.t('incident.titles.deleteAttachment'); this.displayConfirm(title, message, 'deleteAttachment', model); }, showDeleteNote(note) { this.send('openModal', 'incident.note.delete', note); }, showEditAttachment(attachment) { this.send('openModal', 'incident.attachment', attachment); }, showEditNote(note) { this.send('openModal', 'incident.note.edit', note); } } });
export default AbstractEditController.extend(ChargeActions, PatientSubmodule, { visitsController: Ember.inject.controller('visits'), filesystem: Ember.inject.service(), chargePricingCategory: 'Procedure', chargeRoute: 'procedures.charge', canAddPhoto: function() { let isFileSystemEnabled = this.get('isFileSystemEnabled'); return (this.currentUserCan('add_photo') && isFileSystemEnabled); }.property(), canDeletePhoto: function() { return this.currentUserCan('delete_photo'); }.property(), anesthesiaTypes: Ember.computed.alias('visitsController.anesthesiaTypes'), anesthesiologistList: Ember.computed.alias('visitsController.anesthesiologistList'), cptCodeList: Ember.computed.alias('visitsController.cptCodeList'), medicationList: null, physicianList: Ember.computed.alias('visitsController.physicianList'), procedureList: Ember.computed.alias('visitsController.procedureList'), procedureLocations: Ember.computed.alias('visitsController.procedureLocations'), lookupListsToUpdate: [{ name: 'anesthesiaTypes', property: 'model.anesthesiaType', id: 'anesthesia_types' }, { name: 'anesthesiologistList', property: 'model.anesthesiologist', id: 'anesthesiologists' }, { name: 'cptCodeList', property: 'model.cptCode', id: 'cpt_code_list' }, { name: 'physicianList', property: 'model.assistant', id: 'physician_list' }, { name: 'physicianList', property: 'model.physician', id: 'physician_list' }, { name: 'procedureList', property: 'model.description', id: 'procedure_list' }, { name: 'procedureLocations', property: 'model.location', id: 'procedure_locations' }], editController: Ember.inject.controller('visits/edit'), pricingList: null, // This gets filled in by the route pricingTypes: Ember.computed.alias('visitsController.procedurePricingTypes'), newProcedure: false, isFileSystemEnabled: Ember.computed.alias('filesystem.isFileSystemEnabled'), title: function() { let isNew = this.get('model.isNew'); if (isNew) { return this.get('i18n').t('procedures.titles.add'); } return this.get('i18n').t('procedures.titles.edit'); }.property('model.isNew'), updateCapability: 'add_procedure', actions: { addPhoto(savedPhotoRecord) { let photos = this.get('model.photos'); photos.addObject(savedPhotoRecord); this.send('closeModal'); }, deletePhoto(model) { let photo = model.get('photoToDelete'); let photoId = photo.get('id'); let photos = this.get('model.photos'); let filePath = photo.get('fileName'); photos.removeObject(photo); photo.destroyRecord().then(function() { let fileSystem = this.get('filesystem'); let isFileSystemEnabled = this.get('isFileSystemEnabled'); if (isFileSystemEnabled) { let pouchDbId = this.get('database').getPouchId(photoId, 'photo'); fileSystem.deleteFile(filePath, pouchDbId); } }.bind(this)); }, editPhoto(photo) { this.send('openModal', 'patients.photo', photo); }, showAddPhoto() { let newPatientPhoto = this.get('store').createRecord('photo', { patient: this.get('model.visit.patient'), procedure: this.get('model'), saveToDir: `${this.get('model.visit.patient.id')}/photos/` }); newPatientPhoto.set('editController', this); this.send('openModal', 'patients.photo', newPatientPhoto); }, showAddMedication() { let newCharge = this.get('store').createRecord('proc-charge', { dateCharged: new Date(), newMedicationCharge: true, quantity: 1 }); this.send('openModal', 'procedures.medication', newCharge); }, showEditMedication(charge) { let medicationList = this.get('medicationList'); let selectedMedication = medicationList.findBy('id', charge.get('medication.id')); charge.set('itemName', selectedMedication.name); this.send('openModal', 'procedures.medication', charge); }, showDeleteMedication(charge) { this.send('openModal', 'dialog', Ember.Object.create({ closeModalOnConfirm: false, confirmAction: 'deleteCharge', title: this.get('i18n').t('procedures.titles.deleteMedicationUsed'), name: this.get('i18n').t('models.medication.names.singular'), message: this.get('i18n').t('messages.delete_singular', { name: this.name }), chargeToDelete: charge, updateButtonAction: 'confirm', updateButtonText: this.get('i18n').t('buttons.ok') })); }, showDeletePhoto(photo) { this.send('openModal', 'dialog', Ember.Object.create({ confirmAction: 'deletePhoto', title: this.get('i18n').t('patients.titles.deletePhoto'), message: this.get('i18n').t('patients.titles.deletePhoto', { object: 'photo' }), photoToDelete: photo, updateButtonAction: 'confirm', updateButtonText: this.get('i18n').t('buttons.ok') })); } }, beforeUpdate() { return new Ember.RSVP.Promise(function(resolve, reject) { this.updateCharges().then(function() { if (this.get('model.isNew')) { this.addChildToVisit(this.get('model'), 'procedures').then(resolve, reject); } else { resolve(); } }.bind(this), reject); }.bind(this)); }, afterUpdate() { let alertTitle = this.get('i18n').t('procedures.titles.saved'); let alertMessage = this.get('i18n').t('procedures.messages.saved'); this.saveVisitIfNeeded(alertTitle, alertMessage); } });
export default AbstractEditController.extend({ updateCapability: 'add_incident_category', afterUpdate(record) { let intl = get(this, 'intl'); let message = intl.t('incident.messages.incidentCategorySaved', { name: get(record, 'incidentCategoryName') }); let title = intl.t('incident.titles.incidentCategorySaved'); this.displayAlert(title, message); }, actions: { addItem(newItem) { let categoryItems = this.getWithDefault('model.incidentCategoryItems', []); let model = get(this, 'model'); categoryItems.addObject(newItem); model.set('incidentCategoryItems', categoryItems); this.send('update', true); this.send('closeModal'); }, deleteItem(model) { let item = model.get('itemToDelete'); let categoryItems = get(this, 'model.incidentCategoryItems'); categoryItems.removeObject(item); this.send('update', true); }, showAddItem() { this.send('openModal', 'inc-category.add-item', EmberObject.create()); }, showDeleteItem(item) { let intl = get(this, 'intl'); let modelName = intl.t('models.item.names.singular'); let message = intl.t('messages.delete_singular', { name: modelName }); let title = intl.t('incident.titles.deleteItem'); this.displayConfirm(title, message, 'deleteItem', EmberObject.create({ itemToDelete: item })); } } });
export default AbstractEditController.extend(FulfillRequest, InventoryLocations, InventorySelection, PatientSubmodule, { medicationController: Ember.inject.controller('medication'), medicationList: [], lookupListsToUpdate: [{ name: 'aisleLocationList', // Name of property containing lookup list property: 'model.aisleLocation', // Corresponding property on model that potentially contains a new value to add to the list id: 'aisle_location_list' // Id of the lookup list to update }, { name: 'expenseAccountList', // Name of property containing lookup list property: 'model.expenseAccount', // Corresponding property on model that potentially contains a new value to add to the list id: 'expense_account_list' // Id of the lookup list to update }, { name: 'warehouseList', // Name of property containing lookup list property: 'model.location', // Corresponding property on model that potentially contains a new value to add to the list id: 'warehouse_list' // Id of the lookup list to update }], patientMedicationList: [], setNewMedicationList: false, aisleLocationList: Ember.computed.alias('medicationController.aisleLocationList'), expenseAccountList: Ember.computed.alias('medicationController.expenseAccountList'), warehouseList: Ember.computed.alias('medicationController.warehouseList'), updateCapability: 'add_medication', medicationChanged: function() { var medication = this.get('model.medication'); if (!Ember.isEmpty(medication)) { var inventoryItem = medication.get('inventoryItem'); this.set('model.inventoryItemTypeAhead', `${inventoryItem.get('name')} - ${inventoryItem.get('friendlyId')}`); this.set('model.inventoryItem', inventoryItem); } else { this.set('model.inventoryItem'); } Ember.run.later(function() { this.get('model').validate().catch(Ember.K); }.bind(this)); }.observes('model.medication'), patientVisitsChanged: function() { var patientVisits = this.get('patientVisits'); if (!Ember.isEmpty(patientVisits)) { this.set('model.visit', patientVisits.get('firstObject')); } }.observes('patientVisits'), showPatientMedicationList: function() { var patientMedicationList = this.get('patientMedicationList'); this.get('patientMedication'); // Request patient medication be updated return !Ember.isEmpty(patientMedicationList); }.property('patientMedicationList', 'model.patient', 'model.visit'), patientMedication: function() { var setNewMedicationList = this.get('setNewMedicationList'), visit = this.get('model.visit'); if (setNewMedicationList) { this.set('setNewMedicationList', false); } else if (!Ember.isEmpty(visit)) { visit.get('medication').then(function(medication) { medication = medication.filterBy('status', 'Fulfilled'); this.set('model.medication', medication.get('firstObject')); this.set('patientMedicationList', medication.map(SelectValues.selectObjectMap)); this.set('setNewMedicationList', true); }.bind(this)); } return this.get('patientMedicationList'); }.property('setNewMedicationList', 'model.patient', 'model.visit'), _finishUpdate: function() { var aisle = this.get('model.deliveryAisle'), location = this.get('model.deliveryLocation'), inventoryItem = this.get('model.inventoryItem'); // find location on inventoryItem this._findOrCreateLocation(inventoryItem, location, aisle).then(function(inventoryLocation) { this.set('model.adjustPurchases', true); this.set('model.inventoryLocations', [inventoryLocation]); this.set('model.markAsConsumed', true); // Make sure inventory item is resolved first. this.get('model.inventoryItem').then(function() { this.send('fulfillRequest', this.get('model'), false, true, true); }.bind(this)); }.bind(this)); }, actions: { doneFulfillRequest: function() { let i18n = this.get('i18n'); this.updateLookupLists(); this.displayAlert(i18n.t('medication.alerts.returned_title'), i18n.t('medication.alerts.returned_message'), 'allItems'); }, update: function() { var medication = this.get('model.medication'), quantity = this.get('model.quantity'); if (!Ember.isEmpty(medication)) { medication.reload().then(function() { medication.decrementProperty('quantity', quantity); if (medication.get('quantity') < 0) { medication.set('quantity', 0); } medication.save().then(this._finishUpdate.bind(this)); }.bind(this)); } else { this._finishUpdate(); } } }, updateButtonText: t('medication.return_medication') });
export default AbstractEditController.extend({ cancelAction: 'closeModal', newNote: false, updateCapability: 'manage_incidents', editController: controller('incident/edit'), title: computed('model.isNew', function() { let intl = get(this, 'intl'); let isNew = get(this, 'model.isNew'); if (isNew) { return intl.t('incident.titles.addNote'); } return intl.t('incident.titles.editNote'); }), afterUpdate(note) { if (get(this, 'newNote')) { get(this, 'editController').send('addNote', note); } else { this.send('closeModal'); } }, beforeUpdate() { set(this, 'newNote', get(this, 'model.isNew')); return RSVP.resolve(); } });
export default AbstractEditController.extend(UserRoles, { usersController: Ember.inject.controller('users/index'), updateCapability: 'add_user', users: Ember.computed.alias('usersController.model'), actions: { update: function() { var updateModel = this.get('model'), users = this.get('users'); if (updateModel.get('isNew')) { var newData = updateModel.getProperties('password', 'email', 'roles', 'displayName'); newData.name = newData.email; newData.id = 'org.couchdb.user:'******'store').createRecord('user', newData); this.set('model', updateModel); } if (Ember.isEmpty(updateModel.get('userPrefix'))) { var counter = 1, prefix = 'p', userPrefix = prefix + 0, usedPrefix = users.findBy('userPrefix', prefix); while (!Ember.isEmpty(usedPrefix)) { prefix = userPrefix + counter++; usedPrefix = users.findBy('userPrefix', prefix); } updateModel.set('userPrefix', prefix); } updateModel.save().then(function() { this.displayAlert(this.get('i18n').t('messages.user_saved'), this.get('i18n').t('messages.user_has_been_saved')); }.bind(this)); } } });
export default AbstractEditController.extend(ChargeActions, PatientSubmodule, UserSession, VisitTypes, { needs: 'visits', canAddImaging: function() { return this.currentUserCan('add_imaging'); }.property(), canAddLab: function() { return this.currentUserCan('add_lab'); }.property(), canAddMedication: function() { return this.currentUserCan('add_medication'); }.property(), canAddDiagnosis: function() { return this.currentUserCan('add_diagnosis'); }.property(), canAddProcedure: function() { return this.currentUserCan('add_procedure'); }.property(), canAddVitals: function() { return this.currentUserCan('add_vitals'); }.property(), canDeleteDiagnosis: function() { return this.currentUserCan('delete_diagnosis'); }.property(), canDeleteImaging: function() { return this.currentUserCan('delete_imaging'); }.property(), canDeleteLab: function() { return this.currentUserCan('delete_lab'); }.property(), canDeleteMedication: function() { return this.currentUserCan('delete_medication'); }.property(), canDeleteProcedure: function() { return this.currentUserCan('delete_procedure'); }.property(), canDeleteVitals: function() { return this.currentUserCan('delete_vitals'); }.property(), cancelAction: 'returnToPatient', chargePricingCategory: 'Ward', chargeRoute: 'visits.charge', clincList: Ember.computed.alias('controllers.visits.clinicList'), diagnosisList: Ember.computed.alias('controllers.visits.diagnosisList'), findPatientVisits: false, pricingList: null, //This gets filled in by the route pricingTypes: Ember.computed.alias('controllers.visits.wardPricingTypes'), physicianList: Ember.computed.alias('controllers.visits.physicianList'), locationList: Ember.computed.alias('controllers.visits.locationList'), lookupListsToUpdate: [{ name: 'clinicList', property: 'clinic', id: 'clinic_list' }, { name: 'diagnosisList', property: 'primaryDiagnosis', id: 'diagnosis_list' }, { name: 'physicianList', property: 'examiner', id: 'physician_list' }, { name: 'locationList', property: 'location', id: 'visit_location_list' }], newVisit: false, visitStatuses: [ 'Admitted', 'Discharged' ], updateCapability: 'add_visit', primaryDiagnosisIdChanged: function() { this.get('model').validate(); }.observes('primaryDiagnosisId'), afterUpdate: function() { this.displayAlert('Visit Saved', 'The visit record has been saved.'); }, beforeUpdate: function() { if (this.get('isNew')) { this.set('newVisit', true); } return new Ember.RSVP.Promise(function(resolve, reject) { this.updateCharges().then(resolve, reject); }.bind(this)); }, /** * Adds or removes the specified object from the specified list. * @param {String} listName The name of the list to operate on. * @param {Object} listObject The object to add or removed from the * specified list. * @param {boolean} removeObject If true remove the object from the list; * otherwise add the specified object to the list. */ updateList: function(listName, listObject, removeObject) { this.get(listName).then(function(list) { if (removeObject) { list.removeObject(listObject); } else { list.addObject(listObject); } this.send('update', true); this.send('closeModal'); }.bind(this)); }, actions: { addDiagnosis: function(newDiagnosis) { var additionalDiagnoses = this.get('additionalDiagnoses'); if (!Ember.isArray(additionalDiagnoses)) { additionalDiagnoses = []; } additionalDiagnoses.addObject(newDiagnosis); this.set('additionalDiagnoses', additionalDiagnoses); this.send('update', true); this.send('closeModal'); }, deleteDiagnosis: function(diagnosis) { var additionalDiagnoses = this.get('additionalDiagnoses'); additionalDiagnoses.removeObject(diagnosis); this.set('additionalDiagnoses', additionalDiagnoses); this.send('update', true); }, addVitals: function(newVitals) { this.updateList('vitals', newVitals); }, cancel: function() { var cancelledItem = this.get('model'); if (this.get('isNew')) { cancelledItem.deleteRecord(); } else { cancelledItem.rollback(); } this.send(this.get('cancelAction')); }, deleteProcedure: function(procedure) { this.updateList('procedures', procedure, true); }, deleteVitals: function(vitals) { this.updateList('vitals', vitals, true); }, editImaging: function(imaging) { imaging.setProperties({ 'isCompleting': false, 'returnToVisit': true }); this.transitionToRoute('imaging.edit', imaging); }, editLab: function(lab) { lab.setProperties({ 'isCompleting': false, 'returnToVisit': true }); this.transitionToRoute('labs.edit', lab); }, editMedication: function(medication) { medication.set('returnToVisit', true); this.transitionToRoute('medication.edit', medication); }, showAddVitals: function() { var newVitals = this.get('store').createRecord('vital', { dateRecorded: new Date() }); this.send('openModal', 'visits.vitals.edit', newVitals); }, newImaging: function() { var newImaging = this.get('store').createRecord('imaging', { isCompleting: false, patient: this.get('patient'), visit: this.get('model'), returnToVisit: true }); this.transitionToRoute('imaging.edit', newImaging); }, newLab: function() { var newLab = this.get('store').createRecord('lab', { isCompleting: false, patient: this.get('patient'), visit: this.get('model'), returnToVisit: true }); this.transitionToRoute('labs.edit', newLab); }, newMedication: function() { var newMedication = this.get('store').createRecord('medication', { prescriptionDate: moment().startOf('day').toDate(), patient: this.get('patient'), visit: this.get('model'), returnToVisit: true }); this.transitionToRoute('medication.edit', newMedication); }, showAddDiagnosis: function() { this.send('openModal', 'visits.add-diagnosis', AddDiagnosisModel.create()); }, showAddProcedure: function() { var newProcedure = this.get('store').createRecord('procedure', { dateRecorded: new Date(), visit: this.get('model'), }); this.transitionToRoute('procedures.edit', newProcedure); }, showDeleteImaging: function(imaging) { this.send('openModal', 'imaging.delete', imaging); }, showDeleteLab: function(lab) { this.send('openModal', 'labs.delete', lab); }, showDeleteMedication: function(medication) { this.send('openModal', 'medication.delete', medication); }, showDeleteProcedure: function(procedure) { this.send('openModal', 'visits.procedures.delete', procedure); }, showDeleteVitals: function(vitals) { this.send('openModal', 'visits.vitals.delete', vitals); }, showEditProcedure: function(procedure) { if (Ember.isEmpty(procedure.get('visit'))) { procedure.set('visit', this.get('model')); } this.transitionToRoute('procedures.edit', procedure); }, showEditVitals: function(vitals) { this.send('openModal', 'visits.vitals.edit', vitals); } } });
export default AbstractEditController.extend({ customForms: Ember.inject.service(), preview: false, previewModel: Ember.Object.create(), updateCapability: 'update_config', afterUpdate() { let customForms = this.get('customForms'); let model = this.get('model'); customForms.resetCustomFormByType(model.get('formType')); this.displayAlert(this.get('i18n').t('admin.customForms.titles.formSaved'), this.get('i18n').t('admin.customForms.messages.formSaved', this.get('model'))); }, actions: { addField() { let newField = this.store.createRecord('custom-field'); this.send('openModal', 'admin.custom-forms.field-edit', newField); }, deleteField(field) { let fields = this.get('model.fields'); fields.removeObject(field); }, editField(field) { if (isEmpty(field)) { field = this.store.createRecord('custom-field'); } this.send('openModal', 'admin.custom-forms.field-edit', field); }, moveFieldDown(field) { let fields = this.get('model.fields'); let currentFieldIdx = fields.indexOf(field); let nextField = fields.objectAt(currentFieldIdx + 1); fields.replace(currentFieldIdx, 2, [nextField, field]); }, moveFieldUp(field) { let fields = this.get('model.fields'); let previousFieldIdx = (fields.indexOf(field) - 1); let previousField = fields.objectAt(previousFieldIdx); fields.replace(previousFieldIdx, 2, [field, previousField]); }, togglePreview() { this.toggleProperty('preview'); }, updateField(field) { if (field.get('isNew')) { this._addNewField(field); } this.get('model').save(); } }, formName: computed('model.name', function() { let i18n = this.get('i18n'); let formName = this.get('model.name'); if (isEmpty(formName)) { return i18n.t('admin.customForms.labels.newForm'); } else { return formName; } }), formTypeValues: [ 'operativePlan', 'patient', 'socialwork', 'visit' ], formTypes: computed(function() { let i18n = this.get('i18n'); let formTypeValues = this.get('formTypeValues'); return formTypeValues.map((formTypeId) => { return { id: formTypeId, value: i18n.t(`admin.customForms.labels.${formTypeId}FormType`) }; }).sort(function(a, b) { return Ember.compare(a.value.toString(), b.value.toString()); }); }), lastFieldIndex: computed('model.fields.length', function() { return this.get('model.fields.length') - 1; }), fieldTypeLabel(fieldType) { let i18n = this.get('i18n'); return i18n.t(`admin.customForms.labels.${fieldType}`); }, _addNewField(field) { let changedAttributes = field.changedAttributes(); let fieldAttributes = {}; let store = this.get('store'); this._generatePropertyNames(field); Object.keys(changedAttributes).forEach((attributeName) => { let [, newValue] = changedAttributes[attributeName]; fieldAttributes[attributeName] = newValue; }); fieldAttributes.property = field.get('property'); let newField = store.push({ data: { id: uuid.v4(), type: 'custom-field', attributes: fieldAttributes } }); let formFields = this.get('model.fields'); formFields.addObject(newField); }, _generatePropertyNames(field) { let type = field.get('type'); let propertyName = this._getPropertyName(field); if (type === 'checkbox') { let values = field.get('values'); values.forEach((value, index) => { value.set('property', `${propertyName}${(index + 1)}`); }); } else { field.set('property', propertyName); } }, _getPropertyName(field) { let camelizedLabel = field.get('label').camelize(); let labelIndex = 1; let propertyName = camelizedLabel; while (this._isPropertyUsed(propertyName) && labelIndex < 10) { propertyName = `${camelizedLabel}${++labelIndex}`; } return propertyName; }, _isPropertyUsed(propertyName) { let fields = this.get('model.fields'); let existingProperty = fields.findBy('property', propertyName); if (!isEmpty(existingProperty)) { return true; } else { let checkboxes = fields.filterBy('type', 'checkbox'); return checkboxes.any((checkbox) =>{ existingProperty = checkbox.get('values').findBy('property', propertyName); if (!isEmpty(existingProperty)) { return true; } }); } } });
export default AbstractEditController.extend(FulfillRequest, InventoryLocations, InventorySelection, { inventoryController: Ember.inject.controller('inventory'), inventoryItems: null, cancelAction: 'allRequests', warehouseList: Ember.computed.alias('inventoryController.warehouseList'), aisleLocationList: Ember.computed.alias('inventoryController.aisleLocationList'), expenseAccountList: Ember.computed.alias('inventoryController.expenseAccountList'), inventoryList: function() { var inventoryItems = this.get('inventoryItems'); if (!Ember.isEmpty(inventoryItems)) { var mappedItems = inventoryItems.map(function(item) { return item.doc; }); return mappedItems; } }.property('inventoryItems.[]'), lookupListsToUpdate: [{ name: 'expenseAccountList', // Name of property containing lookup list property: 'model.expenseAccount', // Corresponding property on model that potentially contains a new value to add to the list id: 'expense_account_list' // Id of the lookup list to update }, { name: 'aisleLocationList', // Name of property containing lookup list property: 'model.deliveryAisle', // Corresponding property on model that potentially contains a new value to add to the list id: 'aisle_location_list' // Id of the lookup list to update }, { name: 'warehouseList', // Name of property containing lookup list property: 'model.deliveryLocation', // Corresponding property on model that potentially contains a new value to add to the list id: 'warehouse_list' // Id of the lookup list to update }], canFulfill: function() { var requestedItems = this.get('model.requestedItems'); return Ember.isEmpty(requestedItems) && this.currentUserCan('fulfill_inventory'); }.property('model.requestedItems.[]'), isFulfilling: function() { var canFulfill = this.get('canFulfill'), isRequested = this.get('isRequested'), fulfillRequest = this.get('model.shouldFulfillRequest'), isFulfilling = (canFulfill && (isRequested || fulfillRequest)); if (isFulfilling) { if (Ember.isEmpty(this.get('model.dateCompleted'))) { this.set('model.dateCompleted', new Date()); } } else { this.set('model.dateCompleted'); } return isFulfilling; }.property('isRequested', 'model.shouldFulfillRequest'), isRequested: function() { var status = this.get('model.status'); return (status === 'Requested'); }.property('model.status'), quantityLabel: function() { var selectedInventoryItem = this.get('selectedInventoryItem'); if (Ember.isEmpty(selectedInventoryItem)) { return this.get('i18n').t('labels.quantity').toString(); } else { return this.get('i18n').t('inventory.labels.quantity', { unit: selectedInventoryItem.distributionUnit }).toString(); } }.property('selectedInventoryItem'), showRequestedItems: function() { var requestedItems = this.get('model.requestedItems'); return !Ember.isEmpty(requestedItems); }.property('model.requestedItems.[]'), updateViaFulfillRequest: false, updateButtonText: function() { if (this.get('isFulfilling')) { return this.get('i18n').t('buttons.fulfill'); } return this._super(); }.property('model.isNew', 'isFulfilling'), updateCapability: 'add_inventory_request', actions: { addInventoryItem: function() { var model = this.get('model'), inventoryItem = model.get('inventoryItem'), requestedItems = model.get('requestedItems'), quantity = model.get('quantity'); model.validate().then(function() { if (model.get('isValid') && !Ember.isEmpty(inventoryItem) && !Ember.isEmpty(quantity)) { var requestedItem = Ember.Object.create({ item: inventoryItem.get('content'), quantity: quantity }); requestedItems.addObject(requestedItem); model.set('inventoryItem'); model.set('inventoryItemTypeAhead'); model.set('quantity'); this.set('selectedInventoryItem'); } }.bind(this)).catch(Ember.K); }, allRequests: function() { this.transitionToRoute('inventory.index'); }, removeItem: function(removeInfo) { var requestedItems = this.get('model.requestedItems'), item = removeInfo.itemToRemove; requestedItems.removeObject(item); this.send('closeModal'); }, showRemoveItem: function(item) { var message = this.get('i18n').t('inventory.messages.removeItemRequest'), model = Ember.Object.create({ itemToRemove: item }), title = this.get('i18n').t('inventory.titles.removeItem'); this.displayConfirm(title, message, 'removeItem', model); }, /** * Update the model and perform the before update and after update * @param skipAfterUpdate boolean (optional) indicating whether or not * to skip the afterUpdate call. */ update: function(skipAfterUpdate) { this.beforeUpdate().then(function() { var updateViaFulfillRequest = this.get('updateViaFulfillRequest'); if (updateViaFulfillRequest) { this.updateLookupLists(); this.performFulfillRequest(this.get('model'), false, false, true).then(this.afterUpdate.bind(this)); } else { var isNew = this.get('model.isNew'), requestedItems = this.get('model.requestedItems'); if (isNew && !Ember.isEmpty(requestedItems)) { var baseModel = this.get('model'), propertiesToCopy = baseModel.getProperties([ 'dateRequested', 'deliveryAisle', 'deliveryLocation', 'expenseAccount', 'requestedBy', 'status' ]), inventoryPromises = [], newModels = [], savePromises = []; if (!Ember.isEmpty(this.get('model.inventoryItem')) && !Ember.isEmpty(this.get('model.quantity'))) { savePromises.push(baseModel.save()); } requestedItems.forEach(function(requestedItem) { propertiesToCopy.inventoryItem = requestedItem.get('item'); propertiesToCopy.quantity = requestedItem.get('quantity'); var modelToSave = this.get('store').createRecord('inv-request', propertiesToCopy); inventoryPromises.push(modelToSave.get('inventoryItem')); newModels.push(modelToSave); }.bind(this)); Ember.RSVP.all(inventoryPromises, 'Get inventory items for inventory requests').then(function() { newModels.forEach(function(newModel) { savePromises.push(newModel.save()); }); Ember.RSVP.all(savePromises, 'Save batch inventory requests').then(function() { this.updateLookupLists(); this.afterUpdate(); }.bind(this)); }.bind(this)); } else { this.get('model').save().then(function(record) { this.updateLookupLists(); if (!skipAfterUpdate) { this.afterUpdate(record); } }.bind(this)); } } }.bind(this)); } }, afterUpdate: function() { var updateViaFulfillRequest = this.get('updateViaFulfillRequest'); if (updateViaFulfillRequest) { this.displayAlert(this.get('i18n').t('inventory.titles.requestFulfilled'), this.get('i18n').t('inventory.messages.requestFulfilled'), 'allRequests'); } else { this.displayAlert(this.get('i18n').t('inventory.titles.requestUpdated'), this.get('i18n').t('inventory.messages.requestUpdated')); } }, beforeUpdate: function() { if (this.get('isFulfilling')) { this.set('updateViaFulfillRequest', true); } else { this.set('updateViaFulfillRequest', false); } if (this.get('model.isNew')) { this.set('model.dateRequested', new Date()); this.set('model.requestedBy', this.get('model').getUserName()); if (!this.get('isFulfilling')) { this.set('model.status', 'Requested'); } } return Ember.RSVP.resolve(); } });
import AbstractEditController from 'hospitalrun/controllers/abstract-edit-controller'; export default AbstractEditController.extend({ actions: { cancel: function() { this.send('closeModal'); } }, afterUpdate: function(record) { var message = `The pricing profile ${record.get('name')} has been saved.`; this.displayAlert('Pricing Profile Saved', message, 'refreshProfiles'); }, title: function() { var isNew = this.get('model.isNew'); if (isNew) { return 'New Pricing Profile'; } else { return 'Edit Pricing Profile'; } }.property('model.isNew') });
export default AbstractEditController.extend(FriendlyId, InventoryLocations, InventoryTypeList, ReturnTo, UnitTypes, UserSession, { inventory: Ember.inject.controller(), savingNewItem: false, sequenceView: 'inventory_by_friendly_id', canAddPurchase: function() { return this.currentUserCan('add_inventory_purchase'); }.property(), canAdjustLocation() { return this.currentUserCan('adjust_inventory_location'); }, warehouseList: Ember.computed.alias('inventory.warehouseList'), aisleLocationList: Ember.computed.alias('inventory.aisleLocationList'), inventoryTypeList: Ember.computed.alias('inventory.inventoryTypeList.value'), inventoryUnitList: Ember.computed.alias('inventory.inventoryUnitList.value'), vendorList: Ember.computed.alias('inventory.vendorList'), database: Ember.inject.service(), lookupListsToUpdate: [{ name: 'aisleLocationList', // Name of property containing lookup list property: 'model.aisleLocation', // Corresponding property on model that potentially contains a new value to add to the list id: 'aisle_location_list' // Id of the lookup list to update }, { name: 'vendorList', // Name of property containing lookup list property: 'model.vendor', // Corresponding property on model that potentially contains a new value to add to the list id: 'vendor_list' // Id of the lookup list to update }, { name: 'warehouseList', // Name of property containing lookup list property: 'model.location', // Corresponding property on model that potentially contains a new value to add to the list id: 'warehouse_list' // Id of the lookup list to update }], canEditQuantity: function() { return (this.get('model.isNew')); }.property('model.isNew'), haveTransactions: function() { let transactions = this.get('transactions'); return transactions !== null; }.property('transactions.[]'), locationQuantityTotal: function() { let locations = this.get('model.locations'); let total = locations.reduce(function(previousValue, location) { return previousValue + parseInt(location.get('quantity')); }, 0); return total; }.property('model.locations'), /** * Check to see if the total quantity by location matches the quantity calculated on the item * @return {boolean} true if there is a discrepency;otherwise false. */ quantityDiscrepency: function() { let locationQuantityTotal = this.get('locationQuantityTotal'); let quantity = this.get('model.quantity'); return (!Ember.isEmpty(locationQuantityTotal) && !Ember.isEmpty(quantity) && locationQuantityTotal !== quantity); }.property('locationQuantityTotal', 'model.quantity'), /** * Get the difference in quantity between the total quantity by location and the quantity on the item. * @return {int} the difference. */ quantityDifferential: function() { let locationQuantityTotal = this.get('locationQuantityTotal'); let quantity = this.get('model.quantity'); return Math.abs(locationQuantityTotal - quantity); }.property('locationQuantityTotal', 'model.quantity'), originalQuantityUpdated: function() { let isNew = this.get('model.isNew'); let quantity = this.get('model.originalQuantity'); if (isNew && !Ember.isEmpty(quantity)) { this.set('model.quantity', quantity); } }.observes('model.isNew', 'model.originalQuantity'), sequenceName: computed('model.inventoryType', function() { let inventoryType = get(this, 'model.inventoryType'); return `inventory_${inventoryType}`; }), showTransactions: function() { let transactions = this.get('transactions'); return !Ember.isEmpty(transactions); }.property('transactions.[]'), transactions: null, updateCapability: 'add_inventory_item', actions: { adjustItems(inventoryLocation) { let adjustmentQuantity = parseInt(inventoryLocation.get('adjustmentQuantity')); let inventoryItem = this.get('model'); let transactionType = inventoryLocation.get('transactionType'); let request = this.get('store').createRecord('inv-request', { adjustPurchases: true, dateCompleted: inventoryLocation.get('dateCompleted'), expenseAccount: inventoryLocation.get('expenseAccount'), inventoryItem, quantity: adjustmentQuantity, transactionType, reason: inventoryLocation.get('reason'), deliveryAisle: inventoryLocation.get('aisleLocation'), deliveryLocation: inventoryLocation.get('location') }); request.set('inventoryLocations', [inventoryLocation]); let increment = false; if (transactionType === 'Adjustment (Add)' || transactionType === 'Return') { increment = true; } request.set('markAsConsumed', true); // Make sure inventory item is resolved first. request.get('inventoryItem').then(function() { this.send('fulfillRequest', request, true, increment, true); }.bind(this)); }, editNewItem() { this.send('editItem', this.get('model.id')); }, showAdjustment(inventoryLocation) { inventoryLocation.setProperties({ dateCompleted: new Date(), adjustmentItem: this.get('model'), adjustmentQuantity: '', reason: '', transferItem: null, transactionType: 'Adjustment (Add)' }); this.send('openModal', 'inventory.adjust', inventoryLocation); }, showTransfer(inventoryLocation) { inventoryLocation.set('adjustmentQuantity'); inventoryLocation.set('transferItem', this.get('model')); inventoryLocation.set('dateCompleted', new Date()); this.send('openModal', 'inventory.transfer', inventoryLocation); }, transferItems(inventoryLocation) { let inventoryItem = this.get('model'); let request = this.get('store').createRecord('inv-request', { adjustPurchases: false, dateCompleted: inventoryLocation.get('dateCompleted'), inventoryItem, quantity: inventoryLocation.get('adjustmentQuantity'), deliveryAisle: inventoryLocation.get('transferAisleLocation'), deliveryLocation: inventoryLocation.get('transferLocation'), transactionType: 'Transfer' }); this.transferToLocation(inventoryItem, inventoryLocation).then(function() { inventoryLocation.setProperties({ transferItem: null, transferLocation: null, transferAisleLocation: null, adjustmentQuantity: null }); request.set('locationsAffected', [{ name: inventoryLocation.get('locationName'), quantity: request.get('quantity') }]); request.get('inventoryItem').then(function() { // Make sure relationships are resolved before saving this._saveRequest(request); }.bind(this)); }.bind(this)); }, updatePurchase(purchase, updateQuantity) { if (updateQuantity) { this.get('model').updateQuantity(); this.send('update', true); } this.send('closeModal'); } }, _completeBeforeUpdate(friendlyId) { let promises = []; let model = this.get('model'); let newPurchase = model.getProperties('aisleLocation', 'dateReceived', 'purchaseCost', 'lotNumber', 'expirationDate', 'giftInKind', 'invoiceNo', 'location', 'originalQuantity', 'quantityGroups', 'vendor', 'vendorItemNo'); let quantity = this.get('model.originalQuantity'); if (!Ember.isEmpty(quantity)) { newPurchase.currentQuantity = quantity; newPurchase.inventoryItem = this.get('model.id'); let purchase = this.get('store').createRecord('inv-purchase', newPurchase); promises.push(purchase.save()); this.get('model.purchases').addObject(purchase); promises.push(this.newPurchaseAdded(this.get('model'), purchase)); } model.set('friendlyId', friendlyId); return Ember.RSVP.all(promises, 'All before update done for inventory item'); }, /** * Saves the specified request, then updates the inventory item and closes the modal. */ _saveRequest(request) { request.set('status', 'Completed'); request.set('completedBy', request.getUserName()); request.save().then(function() { this.send('update', true); this.send('closeModal'); this.getTransactions(); }.bind(this)); }, getTransactions() { let inventoryId = this.get('model.id'); this.set('transactions', null); this.store.query('inv-request', { options: { endkey: [inventoryId, 'Completed', 0], startkey: [inventoryId, 'Completed', 9999999999999], descending: true }, mapReduce: 'inventory_request_by_item' }).then(function(transactions) { this.set('transactions', transactions); }.bind(this)); }, beforeUpdate() { if (this.get('model.isNew')) { let model = this.get('model'); return model.validate().then(() => { if (model.get('isValid')) { this.set('savingNewItem', true); return this.generateFriendlyId('inventory').then((friendlyId) => { return this._completeBeforeUpdate(friendlyId); }); } else { throw Error('invalid model'); } }).catch(() => { this.send('showDisabledDialog'); }); } else { return Ember.RSVP.Promise.resolve(); } }, afterUpdate() { let afterUpdateAction = null; if (this.get('savingNewItem')) { afterUpdateAction = 'editNewItem'; this.set('savingNewItem', false); } this.displayAlert('Inventory Item Saved', 'The inventory item has been saved.', afterUpdateAction); } });
export default AbstractEditController.extend({ inventoryController: controller('inventory'), warehouseList: alias('inventoryController.warehouseList'), aisleLocationList: alias('inventoryController.aisleLocationList'), lookupListsToUpdate: [{ name: 'aisleLocationList', // Name of property containing lookup list property: 'model.transferAisleLocation', // Corresponding property on model that potentially contains a new value to add to the list id: 'aisle_location_list' // Id of the lookup list to update }, { name: 'warehouseList', // Name of property containing lookup list property: 'model.transferLocation', // Corresponding property on model that potentially contains a new value to add to the list id: 'warehouse_list' // Id of the lookup list to update }], title: t('inventory.titles.transfer'), updateButtonText: t('inventory.labels.transfer'), updateButtonAction: 'transfer', updateCapability: 'adjust_inventory_location', actions: { cancel() { this.send('closeModal'); }, transfer() { this.updateLookupLists(); this.send('transferItems', this.get('model'), true); } } });
export default AbstractEditController.extend({ cancelAction: 'closeModal', newCharge: false, requestingController: controller('procedures/edit'), medicationList: alias('requestingController.medicationList'), updateCapability: 'add_charge', title: computed('model.isNew', function() { let isNew = this.get('model.isNew'); if (isNew) { return this.get('intl').t('procedures.titles.addMedicationUsed'); } return this.get('intl').t('procedures.titles.editMedicationUsed'); }), beforeUpdate() { let isNew = this.get('model.isNew'); if (isNew) { this.set('newCharge', true); let model = this.get('model'); let inventoryItem = model.get('inventoryItem'); model.set('medication', inventoryItem); model.set('medicationTitle', inventoryItem.get('name')); model.set('priceOfMedication', inventoryItem.get('price')); } return EmberPromise.resolve(); }, afterUpdate(record) { if (this.get('newCharge')) { this.get('requestingController').send('addCharge', record); } else { this.send('closeModal'); } } });
export default AbstractEditController.extend(GenderList, NewBelieverInfo, { canBeSeen: false, showPreview: false, submitPage: false, //Function sets default variables for new report reportDateChanged: function() { if (Ember.isEmpty(this.get('reportDate'))) { this.set('reportDate', new Date()); this.set('reportArchived', false); } }.observes('reportDate'), //summary page totals peopleReachedTotals: function() { var peopleBedside, peoplePlayroom, peopleJesus, peopleOpenAir, peopleMobile, peopleMore, peopleTotal; if(this.get('peopleBedside') === undefined || this.get('peopleBedside') === "") { peopleBedside = 0; } else { peopleBedside = parseInt(this.get('peopleBedside')); } if(this.get('peoplePlayroom') === undefined || this.get('peoplePlayroom') === "") { peoplePlayroom = 0; } else { peoplePlayroom = parseInt(this.get('peoplePlayroom')); } if(this.get('peopleJesus') === undefined || this.get('peopleJesus') === "") { peopleJesus = 0; } else { peopleJesus = parseInt(this.get('peopleJesus')); } if(this.get('peopleOpenAir') === undefined || this.get('peopleOpenAir') === "") { peopleOpenAir = 0; } else { peopleOpenAir = parseInt(this.get('peopleOpenAir')); } if(this.get('peopleMobile') === undefined || this.get('peopleMobile') === "") { peopleMobile = 0; } else { peopleMobile = parseInt(this.get('peopleMobile')); } if(this.get('peopleMore') === undefined || this.get('peopleMore') === "") { peopleMore = 0; } else { peopleMore = parseInt(this.get('peopleMore')); } peopleTotal = peopleBedside + peoplePlayroom + peopleJesus + peopleOpenAir + peopleMobile + peopleMore; this.set('peopleTotal', peopleTotal); }.observes('peopleBedside', 'peoplePlayroom', 'peopleJesus', 'peopleOpenAir', 'peopleMobile', 'peopleMore'), bibleReachedTotals: function() { var bibleBedside, biblePlayroom, bibleJesus, bibleOpenAir, bibleMobile, bibleMore, bibleTotal; if(this.get('bibleBedside') === undefined || this.get('bibleBedside') === "") { bibleBedside = 0; } else { bibleBedside = parseInt(this.get('bibleBedside')); } if(this.get('biblePlayroom') === undefined || this.get('biblePlayroom') === "") { biblePlayroom = 0; } else { biblePlayroom = parseInt(this.get('biblePlayroom')); } if(this.get('bibleJesus') === undefined || this.get('bibleJesus') === "") { bibleJesus = 0; } else { bibleJesus = parseInt(this.get('bibleJesus')); } if(this.get('bibleOpenAir') === undefined || this.get('bibleOpenAir') === "") { bibleOpenAir = 0; } else { bibleOpenAir = parseInt(this.get('bibleOpenAir')); } if(this.get('bibleMobile') === undefined || this.get('bibleMobile') === "") { bibleMobile = 0; } else { bibleMobile = parseInt(this.get('bibleMobile')); } if(this.get('bibleMore') === undefined || this.get('bibleMore') === "") { bibleMore = 0; } else { bibleMore = parseInt(this.get('bibleMore')); } bibleTotal = bibleBedside + biblePlayroom + bibleJesus + bibleOpenAir + bibleMobile + bibleMore; this.set('bibleTotal', bibleTotal); }.observes('bibleBedside', 'biblePlayroom', 'bibleJesus', 'bibleOpenAir', 'bibleMobile', 'bibleMore'), actions: { // These are here until I can find a more efficient way to do it. // They change the active classes to show and hide the respective tabs additionalInformationTab: function () { this.set('submitPage', false); $('#submit').removeClass('active'); $('#additionalInformation').addClass('active'); $('ul.nav li.active').removeClass('active'); $('ul.nav li:nth-child(4)').addClass('active'); }, /*demographicsTab: function () { this.set('submitPage', false); $('#submit').removeClass('active'); $('#demographics').addClass('active'); $('ul.nav li.active').removeClass('active'); $('ul.nav li:nth-child(6)').addClass('active'); },*/ eventsTab: function () { this.set('submitPage', false); $('#submit').removeClass('active'); $('#events').addClass('active'); $('ul.nav li.active').removeClass('active'); $('ul.nav li:nth-child(2)').addClass('active'); }, faithDeclarationsTab: function () { this.set('submitPage', false); $('#submit').removeClass('active'); $('#faithDeclarations').addClass('active'); $('ul.nav li.active').removeClass('active'); $('ul.nav li:nth-child(3)').addClass('active'); }, hospitalTab: function () { this.set('submitPage', false); $('#submit').removeClass('active'); $('#hospital').addClass('active'); $('ul.nav li.active').removeClass('active'); $('ul.nav li:nth-child(1)').addClass('active'); }, summaryTab: function () { this.set('submitPage', false); $('#submit').removeClass('active'); $('#summary').addClass('active'); $('ul.nav li.active').removeClass('active'); $('ul.nav li:nth-child(5)').addClass('active'); }, // ======= Function to move onto the next tab ========== // nextMinistryTab: function () { if ($("#submit").hasClass("active")) { return; } $('.tab-pane.active').removeClass('active').next('.tab-pane').addClass('active'); $('ul.nav li.active').removeClass('active').next('li').addClass('active'); }, // ======= Function to go back to prveious tab ========= // prevMinistryTab: function () { if ($("#hospital").hasClass("active")) { return; } $('.tab-pane.active').removeClass('active').prev('.tab-pane').addClass('active'); $('ul.nav li.active').removeClass('active').prev('li').addClass('active'); }, // hideNextPrevious: function () { // this.set('submitPage', true); // $('.tab-pane.active').removeClass('active'); // $('#submit').addClass('active'); // $('ul.nav li.active').removeClass('active'); // $('ul.nav li:nth-child(10)').addClass('active'); // }, showCurrentBelievers: function() { $('.showHideBelievers').show(500); $('.showCurrentBelievers').hide(); $('.hideCurrentBelievers').show();// Function generated to show and hide the }, // current believers that are within hideCurrentBelievers: function() { // the database of the system. $('.showHideBelievers').hide(500); $('.hideCurrentBelievers').hide(); $('.showCurrentBelievers').show(); }, // Function generated to show and hide the Christianity Explored content. // showChristianityExplored: function() { // $('.showHideChristianityExplored').show(500); // $('.showChristianityExplored').hide(); // $('.hideChristianityExplored').show(); // }, // hideChristianityExplored: function() { // $('.showHideChristianityExplored').hide(500); // $('.hideChristianityExplored').hide(); // $('.showChristianityExplored').show(); // }, // To show and hide the general information view within the faith declarations // tab at the moment. Will probably change in future. toggleGenInfo: function() { this.toggleProperty('canBeSeen'); }, showAddBeliever: function() { this.send('openModal', 'ministry.add-believer', { title: 'Add Believer', updateButtonText: 'Add', updateButtonAction: 'add', showUpdateButton: true, }); }, showEditBeliever: function(believer) { this.send('openModal', 'ministry.add-believer', { title: "Edit this believer's information", updateButtonText: 'Update', updateButtonAction: 'update', showUpdateButton: true, believerToEdit: believer, }); }, addBeliever: function(newBeliever) { var believers = this.getWithDefault('believers', []); believers.addObject(newBeliever); this.set('believers', believers); this.send('update', true); this.send('closeModal'); }, editBeliever: function(updatedBeliever) { // Add new info to believer var believers = this.getWithDefault('believers', []); believers.addObject(updatedBeliever); console.log(believers); this.set('believers', believers); // this.send('update', true); this.send('closeModal'); this.displayAlert('Believer Updated', 'The believer has been updated.'); }, // deleteBeliever: function(model) { // var believer = model.get('believerToDelete'); // var believers = this.get('believers'); // believers.removeObject(believer); // this.set('believers', believers); // this.send('update', true); // this.send('closeModal'); // }, //Toggle Preview togglePreview: function() { this.toggleProperty('showPreview'); }, /* toggleArrowInPreview: function() { if ($('.showDownArrow').is(":visible")) { $('.showDownArrow').click(toggle()); $('.showUpArrow').click(toggle()); } else { $('.showDownArrow').toggle(); $('.showUpArrow').toggle(); } }, */ toggleArrowInPreview: function() { this.toggleProperty('showDetails'); }, //Save Report updateReport: function() { this.get('model').save().then(function() { this.displayAlert('Report Saved', 'The report has been saved.'); }.bind(this)); }, //Submit Report submitReport: function() { this.set('reportArchived', true); console.log(this.get('reportArchived')); this.get('model').save().then(function() { this.displayAlert('Report Submitted', 'The report has been submitted.'); window.location.href = "#/ministry"; }.bind(this)); }, addCommunity: function(newCommunity) { var commEvents = this.getWithDefault('commEvents', []); commEvents.addObject(newCommunity); this.set('commEvents', commEvents); this.send('update', true); this.send('closeModal'); }, editCommunity: function(communityToEdit) { if (Ember.isEmpty(communityToEdit)) { communityToEdit = this.store.createRecord('community-event'); } this.send('openModal', 'ministry.add-community', communityToEdit); }, addLeadership: function(newLeadership) { var leadEvents = this.getWithDefault('leadEvents', []); leadEvents.addObject(newLeadership); this.set('leadEvents', leadEvents); this.send('update', true); this.send('closeModal'); }, editLeadership: function(leadershipToEdit) { if (Ember.isEmpty(leadershipToEdit)) { leadershipToEdit = this.store.createRecord('leadership-event'); } this.send('openModal', 'ministry.add-leadership', leadershipToEdit); }, addLeadershipParticipant: function(newParticipant) { var leadParticipants = this.getWithDefault('leadParticipants', []); leadParticipants.addObject(newParticipant); this.set('leadParticipants', leadParticipants); this.send('update', true); this.send('closeModal'); }, editParticipant: function(participantToEdit) { if (Ember.isEmpty(participantToEdit)) { participantToEdit = this.store.createRecord('leadership-participant'); } this.send('openModal', 'ministry.add-leadership-participant', participantToEdit); }, showDeleteCommunity: function(commEvent){ this.send('openModal', 'dialog', Ember.Object.create({ confirmAction: 'deleteCommEvent', title: 'Delete Community Event', message: 'Are you sure you want to delete this event?', commEventToDelete: commEvent, updateButtonAction: 'confirm', updateButtonText: 'Ok' })); }, deleteCommEvent: function(model) { var commEvent = model.get('commEventToDelete'); var commEvents = this.get('commEvents'); commEvents.removeObject(commEvent); this.set('commEvents', commEvents); this.send('update', true); }, showDeleteLeadership: function(leadEvent){ this.send('openModal', 'dialog', Ember.Object.create({ confirmAction: 'deleteLeadEvent', title: 'Delete Leadership Event', message: 'Are you sure you want to delete this event?', leadEventToDelete: leadEvent, updateButtonAction: 'confirm', updateButtonText: 'Ok' })); }, deleteLeadEvent: function(model) { var leadEvent = model.get('leadEventToDelete'); var leadEvents = this.get('leadEvents'); leadEvents.removeObject(leadEvent); this.set('leadEvents', leadEvents); this.send('update', true); } } });
export default AbstractEditController.extend({ addAction: 'addPhoto', editTitle: t('patients.titles.editPhoto'), fileRequiredMessage: t('patients.messages.photoFileRequired'), modelName: 'photo', newTitle: t('patients.titles.addPhoto'), newModel: false, showFileRequired: false, showUpdateButton: true, database: inject.service(), editController: inject.controller('patients/edit'), filesystem: inject.service(), photoFileNotSet: computed('model.photoFile', function() { let model = get(this, 'model'); let isNew = get(model, 'isNew'); let photoFile = get(model, 'photoFile'); return (isNew && isEmpty(photoFile)); }), title: computed('model.isNew', function() { let isNew = get(this, 'model.isNew'); if (isNew) { return get(this, 'newTitle'); } else { return get(this, 'editTitle'); } }), updateButtonAction: computed('photoFileNotSet', function() { let photoFileNotSet = get(this, 'photoFileNotSet'); if (photoFileNotSet) { return 'showFileRequired'; } else { set(this, 'showFileRequired', false); return 'update'; } }), updateButtonClass: computed('photoFileNotSet', function() { let photoFileNotSet = get(this, 'photoFileNotSet'); if (photoFileNotSet) { return 'disabled-btn'; } }), afterUpdate(model) { let isNew = get(this, 'newModel'); let editController = get(this, 'editController'); if (isNew) { let photoFile = get(model, 'photoFile'); let saveToDir = get(model, 'saveToDir'); let fileSystem = get(this, 'filesystem'); let modelName = get(this, 'modelName'); let pouchDbId = get(this, 'database').getPouchId(get(model, 'id'), modelName); fileSystem.addFile(photoFile, saveToDir, pouchDbId).then((fileEntry) => { model.setProperties({ localFile: true, fileName: fileEntry.fullPath, url: fileEntry.toURL() }); model.save().then(() => { editController.send(get(this, 'addAction'), model); }).catch((err) => { throw err; }); }); } else { this.send('closeModal'); } }, beforeUpdate() { let model = get(this, 'model'); let photoFile = get(model, 'photoFile'); let isImage = get(model, 'isImage'); let isNew = get(model, 'isNew'); set(this, 'newModel', isNew); if (isNew) { model.setProperties({ files: [Ember.Object.create({ content_type: photoFile.type, data: photoFile, name: 'file' })], isImage }); } return RSVP.resolve(); }, actions: { cancel() { this.send('closeModal'); }, showFileRequired() { set(this, 'showFileRequired', true); } } });
export default AbstractEditController.extend({ updateCapability: 'add_diagnosis', editController: Ember.computed.alias('model.editController'), diagnosisList: Ember.computed.alias('editController.diagnosisList'), newDiagnosis: false, lookupListsToUpdate: [{ name: 'diagnosisList', property: 'model.diagnosis', id: 'diagnosis_list' }], additionalButtons: computed('model.isNew', function() { let i8n = this.get('i18n'); let isNew = this.get('model.isNew'); if (!isNew) { return [{ class: 'btn btn-default warning', buttonAction: 'deleteDiagnosis', buttonIcon: 'octicon octicon-x', buttonText: i8n.t('buttons.delete') }]; } }), canDeleteDiagnosis: computed(function() { return this.currentUserCan('delete_diagnosis'); }), title: computed('model.isNew', function() { let i8n = this.get('i18n'); let isNew = this.get('model.isNew'); if (isNew) { return i8n.t('diagnosis.titles.addDiagnosis'); } else { return i8n.t('diagnosis.titles.editDiagnosis'); } }), afterUpdate(diagnosis) { let newDiagnosis = this.get('newDiagnosis'); if (newDiagnosis) { this.get('editController').send('addDiagnosis', diagnosis); } else { this.send('closeModal'); } }, beforeUpdate() { let diagnosis = this.get('model'); this.set('newDiagnosis', diagnosis.get('isNew')); return Ember.RSVP.Promise.resolve(); }, actions: { cancel() { this.send('closeModal'); }, deleteDiagnosis() { let diagnosis = this.get('model'); this.get('editController').send('deleteDiagnosis', diagnosis); } } });
export default AbstractEditController.extend(ChargeActions, PatientSubmodule, { visitsController: Ember.inject.controller('visits'), canAddProcedure: function() { return this.currentUserCan('add_procedure'); }.property(), chargePricingCategory: 'Procedure', chargeRoute: 'procedures.charge', anesthesiaTypes: Ember.computed.alias('visitsController.anesthesiaTypes'), anesthesiologistList: Ember.computed.alias('visitsController.anesthesiologistList'), cptCodeList: Ember.computed.alias('visitsController.cptCodeList'), medicationList: null, physicianList: Ember.computed.alias('visitsController.physicianList'), procedureList: Ember.computed.alias('visitsController.procedureList'), procedureLocations: Ember.computed.alias('visitsController.procedureLocations'), lookupListsToUpdate: [{ name: 'anesthesiaTypes', property: 'model.anesthesiaType', id: 'anesthesia_types' }, { name: 'anesthesiologistList', property: 'model.anesthesiologist', id: 'anesthesiologists' }, { name: 'cptCodeList', property: 'model.cptCode', id: 'cpt_code_list' }, { name: 'physicianList', property: 'model.assistant', id: 'physician_list' }, { name: 'physicianList', property: 'model.physician', id: 'physician_list' }, { name: 'procedureList', property: 'model.description', id: 'procedure_list' }, { name: 'procedureLocations', property: 'model.location', id: 'procedure_locations' }], editController: Ember.inject.controller('visits/edit'), pricingList: null, // This gets filled in by the route pricingTypes: Ember.computed.alias('visitsController.procedurePricingTypes'), newProcedure: false, title: function() { var isNew = this.get('model.isNew'); if (isNew) { return 'Add Procedure'; } return 'Edit Procedure'; }.property('model.isNew'), updateCapability: 'add_charge', actions: { showAddMedication: function() { var newCharge = this.get('store').createRecord('proc-charge', { dateCharged: new Date(), newMedicationCharge: true, quantity: 1 }); this.send('openModal', 'procedures.medication', newCharge); }, showEditMedication: function(charge) { this.send('openModal', 'procedures.medication', charge); }, showDeleteMedication: function(charge) { this.send('openModal', 'dialog', Ember.Object.create({ confirmAction: 'deleteCharge', title: 'Delete Medication Used', message: 'Are you sure you want to delete this medication?', chargeToDelete: charge, updateButtonAction: 'confirm', updateButtonText: 'Ok' })); } }, beforeUpdate: function() { return new Ember.RSVP.Promise(function(resolve, reject) { this.updateCharges().then(function() { if (this.get('model.isNew')) { this.addChildToVisit(this.get('model'), 'procedures').then(resolve, reject); } else { resolve(); } }.bind(this), reject); }.bind(this)); }, afterUpdate: function() { var alertTitle = 'Procedure Saved', alertMessage = 'The procedure record has been saved.'; this.saveVisitIfNeeded(alertTitle, alertMessage); } });
export default AbstractEditController.extend(ChargeActions, PatientSubmodule, { labsController: Ember.inject.controller('labs'), chargePricingCategory: 'Lab', chargeRoute: 'labs.charge', selectedLabType: null, canComplete: function() { var isNew = this.get('model.isNew'), labTypeName = this.get('model.labTypeName'), selectedLabType = this.get('selectedLabType'); if (isNew && (Ember.isEmpty(labTypeName) || (Ember.isArray(selectedLabType) && selectedLabType.length > 1))) { return false; } else { return this.currentUserCan('complete_lab'); } }.property('selectedLabType.[]', 'model.labTypeName'), actions: { completeLab: function() { this.set('model.status', 'Completed'); this.get('model').validate().then(function() { if (this.get('model.isValid')) { this.set('model.labDate', new Date()); this.send('update'); } }.bind(this)).catch(Ember.K); }, /** * Update the model and perform the before update and after update */ update: function() { if (this.get('model.isNew')) { var newLab = this.get('model'), selectedLabType = this.get('selectedLabType'); if (Ember.isEmpty(this.get('model.status'))) { this.set('model.status', 'Requested'); } this.set('model.requestedBy', newLab.getUserName()); this.set('model.requestedDate', new Date()); if (Ember.isEmpty(selectedLabType)) { this.saveNewPricing(this.get('model.labTypeName'), 'Lab', 'model.labType').then(function() { this.addChildToVisit(newLab, 'labs', 'Lab').then(function() { this.saveModel(); }.bind(this)); }.bind(this)); } else { this.getSelectedPricing('selectedLabType').then(function(pricingRecords) { if (Ember.isArray(pricingRecords)) { this.createMultipleRequests(pricingRecords, 'labType', 'labs', 'Lab'); } else { this.set('model.labType', pricingRecords); this.addChildToVisit(newLab, 'labs', 'Lab').then(function() { this.saveModel(); }.bind(this)); } }.bind(this)); } } else { this.saveModel(); } } }, additionalButtons: function() { var canComplete = this.get('canComplete'), isValid = this.get('model.isValid'), i18n = this.get('i18n'); if (isValid && canComplete) { return [{ buttonAction: 'completeLab', buttonIcon: 'glyphicon glyphicon-ok', class: 'btn btn-primary on-white', buttonText: i18n.t('buttons.complete') }]; } }.property('canComplete', 'model.isValid'), pricingTypeForObjectType: 'Lab Procedure', pricingTypes: Ember.computed.alias('labsController.labPricingTypes'), pricingList: null, // This gets filled in by the route updateCapability: 'add_lab', afterUpdate: function(saveResponse, multipleRecords) { var i18n = this.get('i18n'), afterDialogAction, alertMessage, alertTitle; if (this.get('model.status') === 'Completed') { alertTitle = i18n.t('labs.alerts.request_completed_title'); alertMessage = i18n.t('labs.alerts.request_completed_message'); } else { alertTitle = i18n.t('labs.alerts.request_saved_title'); alertMessage = i18n.t('labs.alerts.request_saved_message'); } if (multipleRecords) { afterDialogAction = this.get('cancelAction'); } this.saveVisitIfNeeded(alertTitle, alertMessage, afterDialogAction); this.set('model.selectPatient', false); } });
export default AbstractEditController.extend(NumberFormat, PatientSubmodule, PublishStatuses, { invoiceController: Ember.inject.controller('invoices'), expenseAccountList: Ember.computed.alias('invoiceController.expenseAccountList.value'), patientList: Ember.computed.alias('invoiceController.patientList'), pharmacyCharges: [], pricingProfiles: Ember.computed.map('invoiceController.pricingProfiles', SelectValues.selectObjectMap), supplyCharges: [], updateCapability: 'add_invoice', wardCharges: [], additionalButtons: function() { var buttons = [], isValid = this.get('model.isValid'), status = this.get('model.status'); if (isValid && status === 'Draft') { buttons.push({ class: 'btn btn-default default', buttonAction: 'finalizeInvoice', buttonIcon: 'glyphicon glyphicon-ok', buttonText: 'Invoice Ready' }); } buttons.push({ class: 'btn btn-default neutral', buttonAction: 'printInvoice', buttonIcon: 'glyphicon glyphicon-print', buttonText: 'Print' }); return buttons; }.property('model.isValid', 'model.status'), canAddCharge: function() { return this.currentUserCan('add_charge'); }.property(), canAddPayment: function() { return this.currentUserCan('add_payment'); }.property(), pharmacyExpenseAccount: function() { var expenseAccountList = this.get('expenseAccountList'); if (!Ember.isEmpty(expenseAccountList)) { var account = expenseAccountList.find(function(value) { if (value.toLowerCase().indexOf('pharmacy') > -1) { return true; } }); return account; } }.property('expenseAccountList.value'), actions: { addItemCharge: function(lineItem) { var details = lineItem.get('details'); var detail = this.store.createRecord('line-item-detail', { id: PouchDB.utils.uuid() }); details.addObject(detail); }, addLineItem: function(lineItem) { var lineItems = this.get('model.lineItems'); lineItems.addObject(lineItem); this.send('update', true); this.send('closeModal'); }, deleteCharge: function(deleteInfo) { this._deleteObject(deleteInfo.itemToDelete, deleteInfo.deleteFrom); }, deleteLineItem: function(deleteInfo) { this._deleteObject(deleteInfo.itemToDelete, this.get('model.lineItems')); }, finalizeInvoice: function() { var currentInvoice = this.get('model'), invoicePayments = currentInvoice.get('payments'), paymentsToSave = []; currentInvoice.get('patient.payments').then(function(patientPayments) { patientPayments.forEach(function(payment) { var invoice = payment.get('invoice'); if (Ember.isEmpty(invoice)) { payment.set('invoice', currentInvoice); paymentsToSave.push(payment.save()); invoicePayments.addObject(payment); } }.bind(this)); Ember.RSVP.all(paymentsToSave).then(function() { this.set('model.status', 'Billed'); this.send('update'); }.bind(this)); }.bind(this)); }, printInvoice: function() { this.transitionToRoute('print.invoice', this.get('model')); }, removePayment: function(removeInfo) { var payments = this.get('model.payments'), payment = removeInfo.itemToRemove; payment.set('invoice'); payments.removeObject(removeInfo.itemToRemove); this.send('update', true); this.send('closeModal'); }, showAddLineItem: function() { var newLineItem = this.store.createRecord('billing-line-item', { id: PouchDB.utils.uuid() }); this.send('openModal', 'invoices.add-line-item', newLineItem); }, showDeleteItem: function(itemToDelete, deleteFrom) { this.showDeleteModal(itemToDelete, Ember.Object.create({ confirmAction: 'deleteCharge', deleteFrom: deleteFrom, title: 'Delete Charge' })); }, showDeleteLineItem: function(item) { this.showDeleteModal(item, Ember.Object.create({ confirmAction: 'deleteLineItem', title: 'Delete Line Item' })); }, showDeleteModal(item, options) { options = Ember.merge(options, Ember.Object.create({ message: `Are you sure you want to delete ${item.get('name')}?`, itemToDelete: item, updateButtonAction: 'confirm', updateButtonText: this.get('i18n').t('buttons.ok') })); this.send('openModal', 'dialog', options); }, showRemovePayment: function(payment) { var message = 'Are you sure you want to remove this payment from this invoice?', model = Ember.Object.create({ itemToRemove: payment }), title = 'Remove Payment'; this.displayConfirm(title, message, 'removePayment', model); }, toggleDetails: function(item) { item.toggleProperty('showDetails'); } }, changePaymentProfile: function() { var patient = this.get('model.patient'), paymentProfile = this.get('model.paymentProfile'); if (!Ember.isEmpty(patient) && Ember.isEmpty(paymentProfile)) { this.set('model.paymentProfile', patient.get('paymentProfile')); } }.observes('model.patient'), paymentProfileChanged: function() { var discountPercentage = this._getValidNumber(this.get('model.paymentProfile.discountPercentage')), originalPaymentProfileId = this.get('model.originalPaymentProfileId'), profileId = this.get('model.paymentProfile.id'); if (profileId !== originalPaymentProfileId) { var lineItems = this.get('model.lineItems'); lineItems.forEach(function(lineItem) { var details = lineItem.get('details'), lineDiscount = 0; details.forEach(function(detail) { var pricingOverrides = detail.get('pricingItem.pricingOverrides'); if (!Ember.isEmpty(pricingOverrides)) { var pricingOverride = pricingOverrides.findBy('profile.id', profileId); if (!Ember.isEmpty(pricingOverride)) { Ember.set(detail, 'price', pricingOverride.get('price')); } } }.bind(this)); if (discountPercentage > 0) { var lineTotal = lineItem.get('total'); lineDiscount = this._numberFormat((discountPercentage / 100) * (lineTotal), true); lineItem.set('discount', lineDiscount); } }.bind(this)); this.set('model.originalPaymentProfileId', profileId); } }.observes('model.paymentProfile'), visitChanged: function() { var visit = this.get('model.visit'), lineItems = this.get('model.lineItems'); if (!Ember.isEmpty(visit) && Ember.isEmpty(lineItems)) { this.set('model.originalPaymentProfileId'); var promises = this.resolveVisitChildren(); Ember.RSVP.allSettled(promises, 'Resolved visit children before generating invoice').then(function(results) { var chargePromises = this._resolveVisitDescendents(results, 'charges'); if (!Ember.isEmpty(chargePromises)) { var promiseLabel = 'Reloaded charges before generating invoice'; Ember.RSVP.allSettled(chargePromises, promiseLabel).then(function(chargeResults) { var pricingPromises = []; chargeResults.forEach(function(result) { if (!Ember.isEmpty(result.value)) { var pricingItem = result.value.get('pricingItem'); if (!Ember.isEmpty(pricingItem)) { pricingPromises.push(pricingItem.reload()); } } }); promiseLabel = 'Reloaded pricing items before generating invoice'; Ember.RSVP.allSettled(pricingPromises, promiseLabel).then(function() { this._generateLineItems(visit, results); this.paymentProfileChanged(); }.bind(this)); }.bind(this)); } else { this._generateLineItems(visit, results); this.paymentProfileChanged(); } }.bind(this), function(err) { console.log('Error resolving visit children', err); }); } }.observes('model.visit'), _addPharmacyCharge: function(charge, medicationItemName) { return charge.getMedicationDetails(medicationItemName).then((medicationDetails) => { let quantity = charge.get('quantity'); let pharmacyCharges = this.get('pharmacyCharges'); let pharmacyExpenseAccount = this.get('pharmacyExpenseAccount'); let pharmacyCharge = this.store.createRecord('line-item-detail', { id: PouchDB.utils.uuid(), name: medicationDetails.name, quantity: quantity, price: medicationDetails.price, department: 'Pharmacy', expenseAccount: pharmacyExpenseAccount }); pharmacyCharges.addObject(pharmacyCharge); }); }, _addSupplyCharge: function(charge, department) { var supplyCharges = this.get('supplyCharges'), supplyCharge = this._createChargeItem(charge, department); supplyCharges.addObject(supplyCharge); }, _createChargeItem: function(charge, department) { var chargeItem = this.store.createRecord('line-item-detail', { id: PouchDB.utils.uuid(), name: charge.get('pricingItem.name'), expenseAccount: charge.get('pricingItem.expenseAccount'), quantity: charge.get('quantity'), price: charge.get('pricingItem.price'), department: department, pricingItem: charge.get('pricingItem') }); return chargeItem; }, /** * Remove the specified object from the specified list, update the model and close the modal. * @param objectToDelete {object} - the object to remove * @param deleteFrom {Array} - the array to remove the object from. */ _deleteObject: function(objectToDelete, deleteFrom) { deleteFrom.removeObject(objectToDelete); if (!objectToDelete.get('isNew')) { objectToDelete.destroyRecord(); } this.send('update', true); this.send('closeModal'); }, _mapWardCharge: function(charge) { return this._createChargeItem(charge, 'Ward'); }, _completeBeforeUpdate: function(sequence, resolve, reject) { var invoiceId = 'inv', sequenceValue; sequence.incrementProperty('value', 1); sequenceValue = sequence.get('value'); if (sequenceValue < 100000) { invoiceId += String('00000' + sequenceValue).slice(-5); } else { invoiceId += sequenceValue; } this.set('model.id', invoiceId); sequence.save().then(resolve, reject); }, _generateLineItems: function(visit, visitChildren) { var endDate = visit.get('endDate'), imaging = visitChildren[0].value, labs = visitChildren[1].value, lineDetail, lineItem, lineItems = this.get('model.lineItems'), medication = visitChildren[2].value, procedures = visitChildren[3].value, startDate = visit.get('startDate'), visitCharges = visit.get('charges'); this.setProperties({ pharmacyCharges: [], supplyCharges: [], wardCharges: [] }); if (!Ember.isEmpty(endDate) && !Ember.isEmpty(startDate)) { endDate = moment(endDate); startDate = moment(startDate); var stayDays = endDate.diff(startDate, 'days'); if (stayDays > 1) { lineDetail = this.store.createRecord('line-item-detail', { id: PouchDB.utils.uuid(), name: 'Days', quantity: stayDays }); lineItem = this.store.createRecord('billing-line-item', { id: PouchDB.utils.uuid(), category: 'Hospital Charges', name: 'Room/Accomodation' }); lineItem.get('details').addObject(lineDetail); lineItems.addObject(lineItem); } } let pharmacyChargePromises = []; medication.forEach(function(medicationItem) { pharmacyChargePromises.push(this._addPharmacyCharge(medicationItem, 'inventoryItem')); }.bind(this)); this.set('wardCharges', visitCharges.map(this._mapWardCharge.bind(this))); procedures.forEach(function(procedure) { var charges = procedure.get('charges'); charges.forEach(function(charge) { if (charge.get('medicationCharge')) { pharmacyChargePromises.push(this._addPharmacyCharge(charge, 'medication')); } else { this._addSupplyCharge(charge, 'O.R.'); } }.bind(this)); }.bind(this)); labs.forEach(function(lab) { if (!Ember.isEmpty(lab.get('labType'))) { this._addSupplyCharge(Ember.Object.create({ pricingItem: lab.get('labType'), quantity: 1 }), 'Lab'); } lab.get('charges').forEach(function(charge) { this._addSupplyCharge(charge, 'Lab'); }.bind(this)); }.bind(this)); imaging.forEach(function(imaging) { if (!Ember.isEmpty(imaging.get('imagingType'))) { this._addSupplyCharge(Ember.Object.create({ pricingItem: imaging.get('imagingType'), quantity: 1 }), 'Imaging'); } imaging.get('charges').forEach(function(charge) { this._addSupplyCharge(charge, 'Imaging'); }.bind(this)); }.bind(this)); Ember.RSVP.all(pharmacyChargePromises).then(() => { lineItem = this.store.createRecord('billing-line-item', { id: PouchDB.utils.uuid(), name: 'Pharmacy', category: 'Hospital Charges' }); lineItem.get('details').addObjects(this.get('pharmacyCharges')); lineItems.addObject(lineItem); lineItem = this.store.createRecord('billing-line-item', { id: PouchDB.utils.uuid(), name: 'X-ray/Lab/Supplies', category: 'Hospital Charges' }); lineItem.get('details').addObjects(this.get('supplyCharges')); lineItems.addObject(lineItem); lineItem = this.store.createRecord('billing-line-item', { id: PouchDB.utils.uuid(), name: 'Ward Items', category: 'Hospital Charges' }); lineItem.get('details').addObjects(this.get('wardCharges')); lineItems.addObject(lineItem); lineItem = this.store.createRecord('billing-line-item', { id: PouchDB.utils.uuid(), name: 'Physical Therapy', category: 'Hospital Charges' }); lineItems.addObject(lineItem); lineItem = this.store.createRecord('billing-line-item', { id: PouchDB.utils.uuid(), name: 'Others/Misc', category: 'Hospital Charges' }); lineItems.addObject(lineItem); this.send('update', true); }); }, _resolveVisitDescendents: function(results, childNameToResolve) { var promises = []; results.forEach(function(result) { if (!Ember.isEmpty(result.value)) { result.value.forEach(function(record) { var children = record.get(childNameToResolve); if (!Ember.isEmpty(children)) { children.forEach(function(child) { // Make sure children are fully resolved promises.push(child.reload()); }); } }); } }); return promises; }, beforeUpdate: function() { return new Ember.RSVP.Promise(function(resolve, reject) { var lineItems = this.get('model.lineItems'), savePromises = []; lineItems.forEach(function(lineItem) { lineItem.get('details').forEach(function(detail) { savePromises.push(detail.save()); }.bind(this)); savePromises.push(lineItem.save()); }.bind(this)); Ember.RSVP.all(savePromises, 'Saved invoice children before saving invoice').then(function() { if (this.get('model.isNew')) { this.store.find('sequence', 'invoice').then(function(sequence) { this._completeBeforeUpdate(sequence, resolve, reject); }.bind(this), function() { var store = this.get('store'); var newSequence = store.push(store.normalize('sequence', { id: 'invoice', value: 0 })); this._completeBeforeUpdate(newSequence, resolve, reject); }.bind(this)); } else { resolve(); } }.bind(this), reject); }.bind(this)); }, afterUpdate: function() { var message = 'The invoice record has been saved.'; this.displayAlert('Invoice Saved', message); } });
export default AbstractEditController.extend(AdjustmentTypes, { inventoryController: Ember.inject.controller('inventory'), expenseAccountList: Ember.computed.alias('inventoryController.expenseAccountList'), title: 'Adjustment', transactionTypeChanged: function() { Ember.run.once(this, function() { this.get('model').validate().catch(Ember.K); }); }.observes('transactionType'), updateButtonText: function() { return this.get('model.transactionType'); }.property('model.transactionType'), updateButtonAction: 'adjust', updateCapability: 'adjust_inventory_location', actions: { cancel: function() { this.send('closeModal'); }, adjust: function() { this.send('adjustItems', this.get('model'), true); } } });
export default AbstractEditController.extend(BloodTypes, GenderList, ReturnTo, UserSession, { canAddAppointment: function() { return this.currentUserCan('add_appointment'); }.property(), canAddContact: function() { return this.currentUserCan('add_patient'); }.property(), canAddImaging: function() { return this.currentUserCan('add_imaging'); }.property(), canAddLab: function() { return this.currentUserCan('add_lab'); }.property(), canAddMedication: function() { return this.currentUserCan('add_medication'); }.property(), canAddPhoto: function() { var isFileSystemEnabled = this.get('isFileSystemEnabled'); return (this.currentUserCan('add_photo') && isFileSystemEnabled); }.property(), canAddSocialWork: function() { return this.currentUserCan('add_socialwork'); }.property(), canAddVisit: function() { return this.currentUserCan('add_visit'); }.property(), canDeleteAppointment: function() { return this.currentUserCan('delete_appointment'); }.property(), canDeleteContact: function() { return this.currentUserCan('add_patient'); }.property(), canDeleteImaging: function() { return this.currentUserCan('delete_imaging'); }.property(), canDeleteLab: function() { return this.currentUserCan('delete_lab'); }.property(), canDeleteMedication: function() { return this.currentUserCan('delete_medication'); }.property(), canDeletePhoto: function() { return this.currentUserCan('delete_photo'); }.property(), canDeleteSocialWork: function() { return this.currentUserCan('delete_socialwork'); }.property(), canDeleteVisit: function() { return this.currentUserCan('delete_visit'); }.property(), economicClassificationTypes: [ 'A', 'B', 'C1', 'C2', 'C3', 'D' ].map(SelectValues.selectValuesMap), livingArrangementList: [ 'Homeless', 'Institution', 'Owned', 'Rent', 'Shared' ], patientTypes: [ 'Charity', 'Private' ], philhealthTypes: [ 'Employed: Government', 'Employed: Non Paying Member/Lifetime', 'Employed: OWWA/OFW', 'Employed: Private', 'Employed: Sponsored/Indigent', 'Self Employed' ].map(SelectValues.selectValuesMap), filesystem: Ember.inject.service(), database: Ember.inject.service(), patientController: Ember.inject.controller('patients'), addressOptions: Ember.computed.alias('patientController.addressOptions'), address1Include: Ember.computed.alias('patientController.addressOptions.value.address1Include'), address1Label: Ember.computed.alias('patientController.addressOptions.value.address1Label'), address2Include: Ember.computed.alias('patientController.addressOptions.value.address2Include'), address2Label: Ember.computed.alias('patientController.addressOptions.value.address2Label'), address3Include: Ember.computed.alias('patientController.addressOptions.value.address3Include'), address3Label: Ember.computed.alias('patientController.addressOptions.value.address3Label'), address4Include: Ember.computed.alias('patientController.addressOptions.value.address4Include'), address4Label: Ember.computed.alias('patientController.addressOptions.value.address4Label'), clinicList: Ember.computed.alias('patientController.clinicList'), countryList: Ember.computed.alias('patientController.countryList'), isFileSystemEnabled: Ember.computed.alias('filesystem.isFileSystemEnabled'), pricingProfiles: Ember.computed.map('patientController.pricingProfiles', SelectValues.selectObjectMap), statusList: Ember.computed.alias('patientController.statusList'), haveAdditionalContacts: function() { var additionalContacts = this.get('model.additionalContacts'); return (!Ember.isEmpty(additionalContacts)); }.property('model.additionalContacts'), haveAddressOptions: function() { var addressOptions = this.get('addressOptions'); return (!Ember.isEmpty(addressOptions)); }.property('addressOptions'), lookupListsToUpdate: [{ name: 'countryList', property: 'model.country', id: 'country_list' }, { name: 'clinicList', property: 'model.clinic', id: 'clinic_list' }, { name: 'statusList', property: 'model.status', id: 'patient_status_list' }], patientImaging: function() { return this._getVisitCollection('imaging'); }.property('model.visits.[].imaging'), patientLabs: function() { return this._getVisitCollection('labs'); }.property('model.visits.[].labs'), patientMedications: function() { return this._getVisitCollection('medication'); }.property('model.visits.[].medication'), patientProcedures: function() { return this._getVisitCollection('procedures'); }.property('model.visits.[].procedures'), showExpenseTotal: true, totalExpenses: function() { var expenses = this.get('model.expenses'); if (!Ember.isEmpty(expenses)) { var total = expenses.reduce(function(previousValue, expense) { if (!Ember.isEmpty(expense.cost)) { return previousValue + parseInt(expense.cost); } }, 0); this.set('showExpenseTotal', true); return total; } else { this.set('showExpenseTotal', false); } }.property('model.expenses'), updateCapability: 'add_patient', actions: { addContact: function(newContact) { var additionalContacts = this.getWithDefault('model.additionalContacts', []), model = this.get('model'); additionalContacts.addObject(newContact); model.set('additionalContacts', additionalContacts); this.send('update', true); this.send('closeModal'); }, returnToPatient: function() { this.transitionToRoute('patients.index'); }, /** * Add the specified photo to the patient's record. * @param {File} photoFile the photo file to add. * @param {String} caption the caption to store with the photo. * @param {boolean} coverImage flag indicating if image should be marked as the cover image (currently unused). */ addPhoto: function(photoFile, caption, coverImage) { var dirToSaveTo = this.get('model.id') + '/photos/', fileSystem = this.get('filesystem'), photos = this.get('model.photos'), newPatientPhoto = this.get('store').createRecord('photo', { patient: this.get('model'), localFile: true, caption: caption, coverImage: coverImage }); newPatientPhoto.save().then(function(savedPhotoRecord) { var pouchDbId = this.get('database').getPouchId(savedPhotoRecord.get('id'), 'photo'); fileSystem.addFile(photoFile, dirToSaveTo, pouchDbId).then(function(fileEntry) { fileSystem.fileToDataURL(photoFile).then(function(photoDataUrl) { savedPhotoRecord = this.get('store').find('photo', savedPhotoRecord.get('id')).then(function(savedPhotoRecord) { var dataUrlParts = photoDataUrl.split(','); savedPhotoRecord.setProperties({ fileName: fileEntry.fullPath, url: fileEntry.toURL(), _attachments: { file: { content_type: photoFile.type, data: dataUrlParts[1] } } }); savedPhotoRecord.save().then(function(savedPhotoRecord) { photos.addObject(savedPhotoRecord); this.send('closeModal'); }.bind(this)); }.bind(this)); }.bind(this)); }.bind(this)); }.bind(this)); }, appointmentDeleted: function(deletedAppointment) { var appointments = this.get('model.appointments'); appointments.removeObject(deletedAppointment); this.send('closeModal'); }, deleteContact: function(model) { var contact = model.get('contactToDelete'); var additionalContacts = this.get('model.additionalContacts'); additionalContacts.removeObject(contact); this.send('update', true); }, deleteExpense: function(model) { var expense = model.get('expenseToDelete'), expenses = this.get('model.expenses'); expenses.removeObject(expense); this.send('update', true); }, deleteFamily: function(model) { var family = model.get('familyToDelete'), familyInfo = this.get('model.familyInfo'); familyInfo.removeObject(family); this.send('update', true); }, deletePhoto: function(model) { var photo = model.get('photoToDelete'), photoId = photo.get('id'), photos = this.get('model.photos'), filePath = photo.get('fileName'); photos.removeObject(photo); photo.destroyRecord().then(function() { var fileSystem = this.get('filesystem'), isFileSystemEnabled = this.get('isFileSystemEnabled'); if (isFileSystemEnabled) { var pouchDbId = this.get('database').getPouchId(photoId, 'photo'); fileSystem.deleteFile(filePath, pouchDbId); } }.bind(this)); }, editAppointment: function(appointment) { appointment.set('returnToPatient', true); appointment.set('returnTo', null); this.transitionToRoute('appointments.edit', appointment); }, editImaging: function(imaging) { if (imaging.get('canEdit')) { imaging.setProperties({ 'returnToPatient': true }); this.transitionToRoute('imaging.edit', imaging); } }, editLab: function(lab) { if (lab.get('canEdit')) { lab.setProperties({ 'returnToPatient': true }); this.transitionToRoute('labs.edit', lab); } }, editMedication: function(medication) { if (medication.get('canEdit')) { medication.set('returnToPatient', true); this.transitionToRoute('medication.edit', medication); } }, editPhoto: function(photo) { this.send('openModal', 'patients.photo', photo); }, editProcedure: function(procedure) { this.transitionToRoute('procedures.edit', procedure); }, editVisit: function(visit) { this.transitionToRoute('visits.edit', visit); }, newAppointment: function() { this._addChildObject('appointments.edit'); }, newImaging: function() { this._addChildObject('imaging.edit'); }, newLab: function() { this._addChildObject('labs.edit'); }, newMedication: function() { this._addChildObject('medication.edit'); }, newVisit: function() { var patient = this.get('model'), visits = this.get('model.visits'); this.send('createNewVisit', patient, visits); }, showAddContact: function() { this.send('openModal', 'patients.add-contact', {}); }, showAddPhoto: function() { this.send('openModal', 'patients.photo', { isNew: true }); }, showDeleteAppointment: function(appointment) { appointment.set('deleteFromPatient', true); this.send('openModal', 'appointments.delete', appointment); }, showDeleteContact: function(contact) { this.send('openModal', 'dialog', Ember.Object.create({ confirmAction: 'deleteContact', title: 'Delete Contact', message: 'Are you sure you want to delete this contact?', contactToDelete: contact, updateButtonAction: 'confirm', updateButtonText: 'Ok' })); }, showDeleteExpense: function(expense) { this.send('openModal', 'dialog', Ember.Object.create({ confirmAction: 'deleteExpense', title: 'Delete Expense', message: 'Are you sure you want to delete this expense?', expenseToDelete: expense, updateButtonAction: 'confirm', updateButtonText: 'Ok' })); }, showDeleteFamily: function(familyInfo) { this.send('openModal', 'dialog', Ember.Object.create({ confirmAction: 'deleteFamily', title: 'Delete Family Member', message: 'Are you sure you want to delete this family member?', familyToDelete: familyInfo, updateButtonAction: 'confirm', updateButtonText: 'Ok' })); }, showDeleteImaging: function(imaging) { this.send('openModal', 'imaging.delete', imaging); }, showDeleteLab: function(lab) { this.send('openModal', 'labs.delete', lab); }, showDeleteMedication: function(medication) { this.send('openModal', 'medication.delete', medication); }, showDeletePhoto: function(photo) { this.send('openModal', 'dialog', Ember.Object.create({ confirmAction: 'deletePhoto', title: 'Delete Photo', message: 'Are you sure you want to delete this photo?', photoToDelete: photo, updateButtonAction: 'confirm', updateButtonText: 'Ok' })); }, showDeleteVisit: function(visit) { visit.set('deleteFromPatient', true); this.send('openModal', 'visits.delete', visit); }, showEditExpense: function(model) { if (Ember.isEmpty(model)) { model = this.get('store').createRecord('social-expense'); } this.send('openModal', 'patients.socialwork.expense', model); }, showEditFamily: function(model) { if (Ember.isEmpty(model)) { model = this.get('store').createRecord('family-info'); } this.send('openModal', 'patients.socialwork.family-info', model); }, updateExpense: function(model) { var expenses = this.getWithDefault('model.expenses', []), isNew = model.isNew, patient = this.get('model'); if (isNew) { delete model.isNew; expenses.addObject(model); } patient.set('expenses', expenses); this.send('update', true); this.send('closeModal'); }, updateFamilyInfo: function(model) { var familyInfo = this.getWithDefault('model.familyInfo', []), isNew = model.isNew, patient = this.get('model'); if (isNew) { delete model.isNew; familyInfo.addObject(model); patient.set('familyInfo', familyInfo); } this.send('update', true); this.send('closeModal'); }, updatePhoto: function(photo) { photo.save().then(function() { this.send('closeModal'); }.bind(this)); }, visitDeleted: function(deletedVisit) { var visits = this.get('model.visits'); visits.removeObject(deletedVisit); this.send('closeModal'); } }, _addChildObject: function(route) { this.transitionToRoute(route, 'new').then(function(newRoute) { newRoute.currentModel.setProperties({ patient: this.get('model'), returnToPatient: true, selectPatient: false }); }.bind(this)); }, _getVisitCollection: function(name) { var returnList = [], visits = this.get('model.visits'); if (!Ember.isEmpty(visits)) { visits.forEach(function(visit) { visit.get(name).then(function(items) { returnList.addObjects(items); if (returnList.length > 0) { returnList[0].set('first', true); } }); }); } return returnList; }, afterUpdate: function(record) { this.send('openModal', 'dialog', Ember.Object.create({ title: 'Patient Saved', message: `The patient record for ${record.get('displayName')} has been saved.`, updateButtonAction: 'returnToPatient', updateButtonText: 'Back to Patient List', cancelButtonText: 'Close' })); } });
export default AbstractEditController.extend(InventorySelection, { cancelAction: 'closeModal', newCharge: false, requestingController: Ember.inject.controller('procedures/edit'), medicationList: Ember.computed.alias('requestingController.medicationList'), updateCapability: 'add_charge', title: function() { var isNew = this.get('model.isNew'); if (isNew) { return 'Add Medication Used'; } return 'Edit Medication Used'; }.property('model.isNew'), beforeUpdate: function() { var isNew = this.get('model.isNew'); if (isNew) { this.set('newCharge', true); let model = this.get('model'); let inventoryItem = model.get('inventoryItem'); model.set('medication', inventoryItem); model.set('medicationTitle', inventoryItem.get('name')); model.set('priceOfMedication', inventoryItem.get('price')); } return Ember.RSVP.Promise.resolve(); }, afterUpdate: function(record) { if (this.get('newCharge')) { this.get('requestingController').send('addCharge', record); } else { this.send('closeModal'); } } });
export default AbstractEditController.extend({ editController: controller('admin/custom-forms/edit'), cancelAction: 'closeModal', i18n: service(), actions: { addValue() { let fieldValues = this.get('model.values'); let fieldType = this.get('model.type'); if (isEmpty(fieldValues)) { let model = this.get('model'); fieldValues = []; model.set('values', fieldValues); } if (fieldType === 'header' && fieldValues.length < 1 || fieldType != 'header') { fieldValues.addObject(EmberObject.create()); } }, deleteValue(valueToDelete) { let fieldValues = this.get('model.values'); fieldValues.removeObject(valueToDelete); }, selectType(fieldType) { this.get('model').set('type', fieldType); }, update() { this.get('editController').send('updateField', this.get('model')); this.send('closeModal'); } }, fieldTypeValues: [ 'header', 'checkbox', 'radio', 'select', 'text', 'textarea' ], fieldTypes: computed(function() { let i18n = this.get('i18n'); let fieldTypeValues = this.get('fieldTypeValues'); return fieldTypeValues.map((fieldTypeId) => { return { id: fieldTypeId, value: i18n.t(`admin.customForms.labels.${fieldTypeId}`) }; }).sort(function(a, b) { return compare(a.value.toString(), b.value.toString()); }); }), showValues: computed('model.type', function() { let type = this.get('model.type'); return (type === 'checkbox' || type === 'radio' || type === 'select' || type === 'header'); }) });
export default AbstractEditController.extend(LabPricingTypes, ImagingPricingTypes, ReturnTo, { pricingController: Ember.inject.controller('pricing'), actions: { addOverride: function(override) { let pricingOverrides = this.get('model.pricingOverrides'); pricingOverrides.addObject(override); this.send('update', true); this.send('closeModal'); }, deleteOverride: function(model) { let overrideToDelete = model.overrideToDelete; let pricingOverrides = this.get('model.pricingOverrides'); pricingOverrides.removeObject(overrideToDelete); overrideToDelete.destroyRecord().then(function() { this.send('update', true); this.send('closeModal'); }.bind(this)); }, editOverride: function(overrideToEdit) { if (Ember.isEmpty(overrideToEdit)) { overrideToEdit = this.store.createRecord('override-price'); } this.send('openModal', 'pricing.override', overrideToEdit); }, showDeleteOverride: function(overrideToDelete) { let message = 'Are you sure you want to delete this override?'; let model = Ember.Object.create({ overrideToDelete: overrideToDelete }); let title = 'Delete Override'; this.displayConfirm(title, message, 'deleteOverride', model); } }, categories: [ 'Imaging', 'Lab', 'Procedure', 'Ward' ].map(SelectValues.selectValuesMap), expenseAccountList: Ember.computed.alias('pricingController.expenseAccountList'), imagingPricingTypes: Ember.computed.alias('pricingController.imagingPricingTypes'), labPricingTypes: Ember.computed.alias('pricingController.labPricingTypes'), procedurePricingTypes: Ember.computed.alias('pricingController.procedurePricingTypes'), wardPricingTypes: Ember.computed.alias('pricingController.wardPricingTypes'), lookupListsToUpdate: function() { let category = this.get('model.category').toLowerCase(); let listsToUpdate = [{ name: 'expenseAccountList', property: 'model.expenseAccount', id: 'expense_account_list' }]; listsToUpdate.push({ name: `${category}PricingTypes`, property: 'model.pricingType', id: `${category}_pricing_types` }); return listsToUpdate; }.property('model.category'), pricingTypes: function() { let category = this.get('model.category'); if (!Ember.isEmpty(category)) { let typesList = this.get(`${category.toLowerCase()}PricingTypes`); if (Ember.isEmpty(typesList) || Ember.isEmpty(typesList.get('value'))) { if (category === 'Lab') { return Ember.Object.create({ value: this.defaultLabPricingTypes }); } else if (category === 'Imaging') { return Ember.Object.create({ value: this.defaultImagingPricingTypes }); } } return typesList; } }.property('model.category'), updateCapability: 'add_pricing', afterUpdate: function(record) { let message = `The pricing record for ${record.get('name')} has been saved.`; this.displayAlert('Pricing Item Saved', message); } });
export default AbstractEditController.extend(AllergyActions, BloodTypes, DiagnosisActions, ReturnTo, UserSession, PatientId, PatientNotes, PatientVisits, { canAddAppointment: function() { return this.currentUserCan('add_appointment'); }.property(), canAddContact: function() { return this.currentUserCan('add_patient'); }.property(), canAddImaging: function() { return this.currentUserCan('add_imaging'); }.property(), canAddLab: function() { return this.currentUserCan('add_lab'); }.property(), canAddMedication: function() { return this.currentUserCan('add_medication'); }.property(), canAddPhoto: function() { let isFileSystemEnabled = this.get('isFileSystemEnabled'); return (this.currentUserCan('add_photo') && isFileSystemEnabled); }.property(), canAddSocialWork: function() { return this.currentUserCan('add_socialwork'); }.property(), canAddVisit: function() { return this.currentUserCan('add_visit'); }.property(), canDeleteAppointment: function() { return this.currentUserCan('delete_appointment'); }.property(), canDeleteContact: function() { return this.currentUserCan('add_patient'); }.property(), canDeleteImaging: function() { return this.currentUserCan('delete_imaging'); }.property(), canDeleteLab: function() { return this.currentUserCan('delete_lab'); }.property(), canDeleteMedication: function() { return this.currentUserCan('delete_medication'); }.property(), canDeletePhoto: function() { return this.currentUserCan('delete_photo'); }.property(), canDeleteSocialWork: function() { return this.currentUserCan('delete_socialwork'); }.property(), canDeleteVisit: function() { return this.currentUserCan('delete_visit'); }.property(), patientTypes: Ember.computed(function() { let i18n = get(this, 'i18n'); let types = [ 'Charity', 'Private' ]; return types.map((type) => { return i18n.t(`patients.labels.patientType${type}`); }); }), config: Ember.inject.service(), filesystem: Ember.inject.service(), database: Ember.inject.service(), patientController: Ember.inject.controller('patients'), addressOptions: Ember.computed.alias('patientController.addressOptions'), address1Include: Ember.computed.alias('patientController.addressOptions.value.address1Include'), address1Label: Ember.computed.alias('patientController.addressOptions.value.address1Label'), address2Include: Ember.computed.alias('patientController.addressOptions.value.address2Include'), address2Label: Ember.computed.alias('patientController.addressOptions.value.address2Label'), address3Include: Ember.computed.alias('patientController.addressOptions.value.address3Include'), address3Label: Ember.computed.alias('patientController.addressOptions.value.address3Label'), address4Include: Ember.computed.alias('patientController.addressOptions.value.address4Include'), address4Label: Ember.computed.alias('patientController.addressOptions.value.address4Label'), clinicList: Ember.computed.alias('patientController.clinicList'), countryList: Ember.computed.alias('patientController.countryList'), diagnosisList: Ember.computed.alias('patientController.diagnosisList'), isFileSystemEnabled: Ember.computed.alias('filesystem.isFileSystemEnabled'), pricingProfiles: Ember.computed.map('patientController.pricingProfiles', SelectValues.selectObjectMap), sexList: Ember.computed.alias('patientController.sexList'), statusList: Ember.computed.alias('patientController.statusList'), haveAdditionalContacts: function() { let additionalContacts = this.get('model.additionalContacts'); return (!Ember.isEmpty(additionalContacts)); }.property('model.additionalContacts'), haveAddressOptions: function() { let addressOptions = this.get('addressOptions'); return (!Ember.isEmpty(addressOptions)); }.property('addressOptions'), lookupListsToUpdate: [{ name: 'countryList', property: 'model.country', id: 'country_list' }, { name: 'clinicList', property: 'model.clinic', id: 'clinic_list' }, { name: 'sexList', property: 'model.sex', id: 'sex' }, { name: 'statusList', property: 'model.status', id: 'patient_status_list' }], patientImaging: function() { return this.getVisitCollection('imaging'); }.property('model.visits.[].imaging'), patientLabs: function() { return this.getVisitCollection('labs'); }.property('model.visits.[].labs'), patientMedications: function() { return this.getVisitCollection('medication'); }.property('model.visits.[].medication'), patientProcedures: function() { let visits = this.get('model.visits'); let operationReports = get(this, 'model.operationReports'); return this._getPatientProcedures(operationReports, visits); }.property('model.visits.[].procedures', 'model.operationReports.[].procedures'), showExpenseTotal: function() { let expenses = this.get('model.expenses'); return (!Ember.isEmpty(expenses)); }.property('model.expenses.[]'), totalExpenses: function() { let expenses = this.get('model.expenses'); if (!Ember.isEmpty(expenses)) { let total = expenses.reduce(function(previousValue, expense) { if (!Ember.isEmpty(expense.cost)) { return previousValue + parseInt(expense.cost); } }, 0); return total; } }.property('*****@*****.**'), updateCapability: 'add_patient', actions: { addAllergy(newAllergy) { let patient = get(this, 'model'); this.savePatientAllergy(patient, newAllergy); }, addContact(newContact) { let additionalContacts = this.getWithDefault('model.additionalContacts', []); let model = this.get('model'); additionalContacts.addObject(newContact); model.set('additionalContacts', additionalContacts); this.send('update', true); this.send('closeModal'); }, addDiagnosis(newDiagnosis) { let diagnoses = this.get('model.diagnoses'); diagnoses.addObject(newDiagnosis); this.send('update', true); this.send('closeModal'); }, returnToPatient() { this.transitionToRoute('patients.index'); }, /** * Add the specified photo to the patient's record. */ addPhoto(savedPhotoRecord) { let photos = this.get('model.photos'); photos.addObject(savedPhotoRecord); this.send('closeModal'); }, appointmentDeleted(deletedAppointment) { let appointments = this.get('model.appointments'); appointments.removeObject(deletedAppointment); this.send('closeModal'); }, deleteAllergy(allergy) { let patient = get(this, 'model'); this.deletePatientAllergy(patient, allergy); }, deleteContact(model) { let contact = model.get('contactToDelete'); let additionalContacts = this.get('model.additionalContacts'); additionalContacts.removeObject(contact); this.send('update', true); }, deleteExpense(model) { let expense = model.get('expenseToDelete'); let expenses = this.get('model.expenses'); expenses.removeObject(expense); this.send('update', true); }, deleteFamily(model) { let family = model.get('familyToDelete'); let familyInfo = this.get('model.familyInfo'); familyInfo.removeObject(family); this.send('update', true); }, deletePhoto(model) { let photo = model.get('photoToDelete'); let photoId = photo.get('id'); let photos = this.get('model.photos'); let filePath = photo.get('fileName'); photos.removeObject(photo); photo.destroyRecord().then(function() { let fileSystem = this.get('filesystem'); let isFileSystemEnabled = this.get('isFileSystemEnabled'); if (isFileSystemEnabled) { let pouchDbId = this.get('database').getPouchId(photoId, 'photo'); fileSystem.deleteFile(filePath, pouchDbId); } }.bind(this)); }, editAppointment(appointment) { if (this.get('canAddAppointment')) { appointment.set('returnToPatient', this.get('model.id')); appointment.set('returnTo', null); this.transitionToRoute('appointments.edit', appointment); } }, editImaging(imaging) { if (this.get('canAddImaging')) { if (imaging.get('canEdit')) { imaging.set('returnToPatient', this.get('model.id')); this.transitionToRoute('imaging.edit', imaging); } } }, editLab(lab) { if (this.get('canAddLab')) { if (lab.get('canEdit')) { lab.setProperties('returnToPatient', this.get('model.id')); this.transitionToRoute('labs.edit', lab); } } }, editMedication(medication) { if (this.get('canAddMedication')) { if (medication.get('canEdit')) { medication.set('returnToPatient', this.get('model.id')); this.transitionToRoute('medication.edit', medication); } } }, editOperativePlan(operativePlan) { let model = operativePlan; if (isEmpty(model)) { this._addChildObject('patients.operative-plan', (route) =>{ route.controller.getPatientDiagnoses(this.get('model'), route.currentModel); }); } else { model.set('returnToVisit'); model.set('returnToPatient', this.get('model.id')); this.transitionToRoute('patients.operative-plan', model); } }, editOperationReport(operationReport) { operationReport.set('returnToPatient', this.get('model.id')); this.transitionToRoute('patients.operation-report', operationReport); }, editPhoto(photo) { this.send('openModal', 'patients.photo', photo); }, editProcedure(procedure) { if (this.get('canAddVisit')) { procedure.set('patient', this.get('model')); procedure.set('returnToVisit'); procedure.set('returnToPatient', this.get('model.id')); this.transitionToRoute('procedures.edit', procedure); } }, editVisit(visit) { if (this.get('canAddVisit')) { visit.set('returnToPatient', this.get('model.id')); this.transitionToRoute('visits.edit', visit); } }, newAppointment() { this._addChildObject('appointments.edit'); }, newImaging() { this._addChildObject('imaging.edit'); }, newLab() { this._addChildObject('labs.edit'); }, newMedication() { this._addChildObject('medication.edit'); }, newSurgicalAppointment() { this.transitionToRoute('appointments.edit', 'newsurgery').then((newRoute) => { newRoute.currentModel.setProperties({ patient: this.get('model'), returnToPatient: this.get('model.id'), selectPatient: false }); }); }, newVisit() { let patient = this.get('model'); this.send('createNewVisit', patient, true); }, showAddContact() { this.send('openModal', 'patients.add-contact', {}); }, showAddPhoto() { let newPatientPhoto = this.get('store').createRecord('photo', { patient: this.get('model'), saveToDir: `${this.get('model.id')}/photos/` }); newPatientPhoto.set('editController', this); this.send('openModal', 'patients.photo', newPatientPhoto); }, showAddPatientNote(model) { if (this.get('canAddNote')) { if (Ember.isEmpty(model)) { model = this.get('store').createRecord('patient-note', { patient: this.get('model'), createdBy: this.getUserName() }); } this.send('openModal', 'patients.notes', model); } }, showDeleteAppointment(appointment) { appointment.set('deleteFromPatient', true); this.send('openModal', 'appointments.delete', appointment); }, showDeleteContact(contact) { this.send('openModal', 'dialog', Ember.Object.create({ confirmAction: 'deleteContact', title: this.get('i18n').t('patients.titles.deleteContact'), message: this.get('i18n').t('patients.titles.deletePhoto', { object: 'contact' }), contactToDelete: contact, updateButtonAction: 'confirm', updateButtonText: this.get('i18n').t('buttons.ok') })); }, showDeleteExpense(expense) { this.send('openModal', 'dialog', Ember.Object.create({ confirmAction: 'deleteExpense', title: this.get('i18n').t('patients.titles.deleteExpense'), message: this.get('i18n').t('patients.titles.deletePhoto', { object: 'expense' }), expenseToDelete: expense, updateButtonAction: 'confirm', updateButtonText: this.get('i18n').t('buttons.ok') })); }, showDeleteFamily(familyInfo) { this.send('openModal', 'dialog', Ember.Object.create({ confirmAction: 'deleteFamily', title: this.get('i18n').t('patients.titles.deleteFamilyMember'), message: this.get('i18n').t('patients.titles.deletePhoto', { object: 'family member' }), familyToDelete: familyInfo, updateButtonAction: 'confirm', updateButtonText: this.get('i18n').t('buttons.ok') })); }, showDeleteImaging(imaging) { this.send('openModal', 'imaging.delete', imaging); }, showDeleteLab(lab) { this.send('openModal', 'labs.delete', lab); }, showDeleteMedication(medication) { this.send('openModal', 'medication.delete', medication); }, showDeletePhoto(photo) { this.send('openModal', 'dialog', Ember.Object.create({ confirmAction: 'deletePhoto', title: this.get('i18n').t('patients.titles.deletePhoto'), message: this.get('i18n').t('patients.titles.deletePhoto', { object: 'photo' }), photoToDelete: photo, updateButtonAction: 'confirm', updateButtonText: this.get('i18n').t('buttons.ok') })); }, showDeleteVisit(visit) { visit.set('deleteFromPatient', true); this.send('openModal', 'visits.delete', visit); }, showEditExpense(expenseInfo) { this._showEditSocial(expenseInfo, 'social-expense', 'expense'); }, showEditFamily(familyInfo) { this._showEditSocial(familyInfo, 'family-info', 'family-info'); }, updateExpense(model) { this._updateSocialRecord(model, 'expenses'); }, updateFamilyInfo(model) { this._updateSocialRecord(model, 'familyInfo'); }, visitDeleted(deletedVisit) { let visits = this.get('model.visits'); let patient = this.get('model'); let patientCheckedIn = patient.get('checkedIn'); let patientAdmitted = patient.get('admitted'); visits.removeObject(deletedVisit); if (patientAdmitted || patientCheckedIn) { let patientUpdate = false; if (patientAdmitted && Ember.isEmpty(visits.findBy('status', VisitStatus.ADMITTED))) { patient.set('admitted', false); patientUpdate = true; } if (patientCheckedIn && Ember.isEmpty(visits.findBy('status', VisitStatus.CHECKED_IN))) { patient.set('checkedIn', false); patientUpdate = true; } if (patientUpdate === true) { patient.save().then(() => this.send('closeModal')); } else { this.send('closeModal'); } } else { this.send('closeModal'); } } }, _addChildObject(route, afterTransition) { let options = { queryParams: { forPatientId: this.get('model.id') } }; this.transitionToRoute(route, 'new', options).then((newRoute) => { if (afterTransition) { afterTransition(newRoute); } }); }, _showEditSocial(editAttributes, modelName, route) { let model; if (Ember.isEmpty(editAttributes)) { model = this.get('store').createRecord(modelName, { newRecord: true }); } else { model = this.get('store').push({ data: { id: Ember.get(editAttributes, 'id'), type: modelName, attributes: editAttributes } }); } this.send('openModal', `patients.socialwork.${route}`, model); }, getVisitCollection(name) { let visits = this.get('model.visits'); return this._getVisitCollection(visits, name); }, _updateSocialRecord(recordToUpdate, name) { let socialRecords = this.getWithDefault(`model.${name}`, []); let isNew = recordToUpdate.get('isNew'); let patient = this.get('model'); let objectToUpdate = recordToUpdate.serialize(); objectToUpdate.id = recordToUpdate.get('id'); if (isNew) { socialRecords.addObject(Ember.Object.create(objectToUpdate)); } else { let updateRecord = socialRecords.findBy('id', objectToUpdate.id); Ember.setProperties(updateRecord, objectToUpdate); } patient.set(name, socialRecords); this.send('update', true); this.send('closeModal'); }, _updateSequence(record) { let config = this.get('config'); let friendlyId = record.get('friendlyId'); return config.getPatientPrefix().then((prefix) => { let re = new RegExp(`^${prefix}\\d{5}$`); if (!re.test(friendlyId)) { return; } return this.store.find('sequence', 'patient').then((sequence) => { let sequenceNumber = sequence.get('value'); let patientNumber = parseInt(friendlyId.slice(prefix.length)); if (patientNumber > sequenceNumber) { sequence.set('value', patientNumber); return sequence.save(); } }); }); }, beforeUpdate() { if (!this.get('model.isNew')) { return Ember.RSVP.resolve(); } return this.generateFriendlyId('patient').then((friendlyId) => { this.model.set('friendlyId', friendlyId); }); }, afterUpdate(record) { this._updateSequence(record).then(() => { $('.message').show(); $('.message').text(this.get('i18n').t('patients.messages.savedPatient', record)); $('.message').delay(3000).fadeOut(100); }); } });
export default AbstractEditController.extend({ needs: 'inventory', adjustmentTypes: [{ name: 'Add', type: 'Adjustment (Add)' }, { name: 'Remove', type: 'Adjustment (Remove)' }, { name: 'Return To Vendor', type: 'Return To Vendor' }, { name: 'Return', type: 'Return' }, { name: 'Write Off', type: 'Write Off' }], expenseAccountList: Ember.computed.alias('controllers.inventory.expenseAccountList'), title: 'Adjustment', transactionTypeChanged: function() { Ember.run.once(this, function(){ this.get('model').validate(); }); }.observes('transactionType'), updateButtonText: function() { return this.get('transactionType'); }.property('transactionType'), updateButtonAction: 'adjust', updateCapability: 'adjust_inventory_location', actions: { cancel: function() { this.send('closeModal'); }, adjust: function() { this.send('adjustItems', this.get('model'), true); } } });
export default AbstractEditController.extend(OperativePlanStatuses, PatientSubmodule, { completedPlan: false, lookupListsToUpdate: [{ name: 'physicianList', property: 'model.surgeon', id: 'physician_list' }, { name: 'procedureList', property: 'modelProcedures', id: 'procedure_list' }], newPlan: false, updateCapability: 'add_operative_plan', patientsController: inject.controller('patients'), physicianList: alias('patientsController.physicianList'), procedureList: alias('patientsController.procedureList'), additionalButtons: computed('model.{isNew,status}', function() { let i18n = get(this, 'i18n'); let isNew = get(this, 'model.isNew'); let status = get(this, 'model.status'); if (!isNew && status !== COMPLETED_STATUS) { return [{ class: 'btn btn-primary on-white', buttonAction: 'completePlan', buttonIcon: 'octicon octicon-check', buttonText: i18n.t('operativePlan.buttons.completePlan') }]; } }), modelProcedures: computed.map('model.procedures', function(procedure) { return get(procedure, 'description'); }), afterUpdate() { let newPlan = get(this, 'newPlan'); if (newPlan) { let patient = get(this, 'model.patient'); patient.save().then(this._finishAfterUpdate.bind(this)).then(()=> { let editTitle = get(this, 'i18n').t('operativePlan.titles.editTitle'); let sectionDetails = {}; sectionDetails.currentScreenTitle = editTitle; this.send('setSectionHeader', sectionDetails); }); } else { this._finishAfterUpdate(); } }, beforeUpdate() { let model = get(this, 'model'); let isNew = get(model, 'isNew'); let status = get(model, 'status'); addProcedure(model); set(this, 'newPlan', isNew); if (status === COMPLETED_STATUS) { let changedAttributes = model.changedAttributes(); if (changedAttributes.status) { set(this, 'completedPlan', true); } } else { set(this, 'completedPlan', false); } if (isNew) { return this.saveNewDiagnoses(); } else { return RSVP.resolve(); } }, _createOperationReport() { let store = get(this, 'store'); let operativePlan = get(this, 'model'); let propertiesToCopy = operativePlan.getProperties(...PLAN_KEYS_TO_COPY); let diagnoses = get(operativePlan, 'diagnoses'); let patient = get(operativePlan, 'patient'); set(propertiesToCopy, 'operativePlan', operativePlan); set(propertiesToCopy, 'preOpDiagnosis', diagnoses); set(propertiesToCopy, 'surgeryDate', new Date()); set(propertiesToCopy, 'returnToPatient', get(patient, 'id')); let operationReport = store.createRecord('operation-report', propertiesToCopy); this.getPatientDiagnoses(patient, operationReport); operationReport.save().then((newReport) => { patient.save().then(()=> { let i18n = get(this, 'i18n'); let updateMessage = i18n.t('operativePlan.messages.planCompleted'); let updateTitle = i18n.t('operativePlan.titles.planCompleted'); this.displayAlert(updateTitle, updateMessage, 'showOperationReport', newReport, 'ok'); }); }); }, _finishAfterUpdate() { let completedPlan = get(this, 'completedPlan'); if (completedPlan) { this._createOperationReport(); } else { let i18n = get(this, 'i18n'); let updateMessage = i18n.t('operativePlan.messages.planSaved'); let updateTitle = i18n.t('operativePlan.titles.planSaved'); this.displayAlert(updateTitle, updateMessage); } }, actions: { completePlan() { let model = get(this, 'model'); set(model, 'status', COMPLETED_STATUS); this.send('update'); } } });
export default AbstractEditController.extend(PatientSubmodule, { cancelAction: 'closeModal', findPatientVisits: false, invoiceController: Ember.inject.controller('invoices'), newPayment: false, expenseAccountList: Ember.computed.alias('invoiceController.expenseAccountList'), patientList: Ember.computed.alias('invoiceController.patientList'), _finishUpdate: function(message, title) { this.send('closeModal'); this.displayAlert(title, message); }, currentPatient: function() { let type = this.get('model.paymentType'); if (type === 'Deposit') { return this.get('model.patient'); } else { return this.get('model.invoice.patient'); } }.property('model.patient', 'model.paymentType', 'model.invoice.patient'), title: function() { let isNew = this.get('model.isNew'); let type = this.get('model.paymentType'); if (isNew) { return `Add ${type}`; } else { return `Edit ${type}`; } }.property('model.isNew', 'model.paymentType'), selectPatient: function() { let isNew = this.get('model.isNew'); let type = this.get('model.paymentType'); return (isNew && type === 'Deposit'); }.property('model.isNew', 'model.paymentType'), beforeUpdate: function() { if (this.get('model.isNew')) { this.set('newPayment', true); } else { this.set('newPayment', false); } let patient = this.get('currentPatient'); this.set('model.charityPatient', patient.get('patientType') === 'Charity'); return Ember.RSVP.resolve(); }, afterUpdate: function() { this.get('model').save().then(function(record) { if (this.get('newPayment')) { let patient = this.get('currentPatient'); patient.get('payments').then(function(payments) { payments.addObject(record); patient.save().then(function() { if (record.get('paymentType') === 'Deposit') { let message = `A deposit of ${record.get('amount')} was added for patient ${patient.get('displayName')}`; this._finishUpdate(message, 'Deposit Added'); } else { let invoice = this.get('model.invoice'); invoice.addPayment(record); invoice.save().then(function() { let message = `A payment of ${record.get('amount')} was added to invoice ${invoice.get('id')}`; this._finishUpdate(message, 'Payment Added'); }.bind(this)); } }.bind(this)); }.bind(this)); } else { this.send('closeModal'); } }.bind(this)); } });
export default AbstractEditController.extend(InventoryId, InventoryLocations, InventorySelection, { doingUpdate: false, inventoryController: Ember.inject.controller('inventory'), inventoryItems: null, warehouseList: Ember.computed.alias('inventoryController.warehouseList'), aisleLocationList: Ember.computed.alias('inventoryController.aisleLocationList'), vendorList: Ember.computed.alias('inventoryController.vendorList'), purchaseAttributes: [ 'expirationDate', 'inventoryItem', 'lotNumber', 'purchaseCost', 'quantity', 'vendorItemNo' ], inventoryList: function() { var inventoryItems = this.get('inventoryItems'); if (!Ember.isEmpty(inventoryItems)) { var mappedItems = inventoryItems.map(function(item) { return item.doc; }); return mappedItems; } }.property('inventoryItems.[]'), lookupListsToUpdate: [{ name: 'aisleLocationList', // Name of property containing lookup list property: 'model.aisleLocation', // Corresponding property on model that potentially contains a new value to add to the list id: 'aisle_location_list' // Id of the lookup list to update }, { name: 'vendorList', // Name of property containing lookup list property: 'model.vendor', // Corresponding property on model that potentially contains a new value to add to the list id: 'vendor_list' // Id of the lookup list to update }, { name: 'warehouseList', // Name of property containing lookup list property: 'model.location', // Corresponding property on model that potentially contains a new value to add to the list id: 'warehouse_list' // Id of the lookup list to update }], showDistributionUnit: function() { return this._haveValidInventoryItem(); }.property('model.inventoryItemTypeAhead', 'model.inventoryItem'), showInvoiceItems: function() { var invoiceItems = this.get('model.invoiceItems'); return !Ember.isEmpty(invoiceItems); }.property('model.invoiceItems.[]'), totalReceived: function() { var invoiceItems = this.get('model.invoiceItems'), total = 0; if (!Ember.isEmpty('invoiceItems')) { total = invoiceItems.reduce(function(previousValue, item) { return previousValue + Number(item.get('purchaseCost')); }, total); } var purchaseCost = this.get('model.purchaseCost'); if (this.get('model.isValid') && !Ember.isEmpty(purchaseCost)) { total += Number(purchaseCost); } return total; }.property('model.invoiceItems.[].purchaseCost', 'model.isValid', 'model.purchaseCost'), updateButtonText: 'Save', updateCapability: 'add_inventory_item', _addNewInventoryItem: function() { this.generateId().then(function(inventoryId) { var inventoryItem = this.store.createRecord('inventory', { id: inventoryId, name: this.get('model.inventoryItemTypeAhead'), quantity: 0, // Needed for validation purposes skipSavePurchase: true }); this.send('openModal', 'inventory.quick-add', inventoryItem); }.bind(this)); }, _addInventoryItem: function() { var model = this.get('model'), inventoryItemTypeAhead = this.get('model.inventoryItemTypeAhead'), purchaseCost = this.get('model.purchaseCost'), quantity = this.get('model.quantity'); return model.validate().then(function() { if (this.get('model.isValid') && !Ember.isEmpty(inventoryItemTypeAhead) && !Ember.isEmpty(quantity) && !Ember.isEmpty(purchaseCost)) { if (this._haveValidInventoryItem()) { this._addInvoiceItem(); } else { this._addNewInventoryItem(); return true; } } else { throw Error('invalid'); } }.bind(this)).catch(function() { this.displayAlert('Warning!!!!', 'Please fill in required fields (marked with *) and correct the errors before adding.'); }.bind(this)); }, _addInvoiceItem: function() { var model = this.get('model'), invoiceItems = model.get('invoiceItems'), itemProperties = model.getProperties(this.get('purchaseAttributes')), invoiceItem = Ember.Object.create(itemProperties); invoiceItems.addObject(invoiceItem); model.set('expirationDate'); model.set('inventoryItem'); model.set('inventoryItemTypeAhead'); model.set('lotNumber'); model.set('purchaseCost'); model.set('quantity'); model.set('selectedInventoryItem'); model.set('vendorItemNo'); }, _findInventoryItem: function(purchase) { var invoiceItems = this.get('model.invoiceItems'), inventoryId = purchase.get('inventoryItem'); if (!Ember.isEmpty(inventoryId)) { var invoiceItem = invoiceItems.find(function(item) { return (item.get('inventoryItem.id') === inventoryId); }, this); if (!Ember.isEmpty(invoiceItem)) { return invoiceItem.get('inventoryItem'); } } }, _haveValidInventoryItem: function() { var inventoryItemTypeAhead = this.get('model.inventoryItemTypeAhead'), inventoryItem = this.get('model.inventoryItem'); if (Ember.isEmpty(inventoryItemTypeAhead) || Ember.isEmpty(inventoryItem)) { return false; } else { var inventoryItemName = inventoryItem.get('name'), typeAheadName = inventoryItemTypeAhead.substr(0, inventoryItemName.length); if (typeAheadName !== inventoryItemName) { return false; } else { return true; } } }, _savePurchases: function() { var model = this.get('model'), purchaseDefaults = model.getProperties([ 'dateReceived', 'vendor', 'invoiceNo', 'location', 'aisleLocation', 'giftInKind']), invoiceItems = model.get('invoiceItems'), inventoryPurchase, savePromises = []; invoiceItems.forEach(function(invoiceItem) { var inventoryItem = invoiceItem.get('inventoryItem'), quantity = invoiceItem.get('quantity'); inventoryPurchase = this.store.createRecord('inv-purchase', purchaseDefaults); inventoryPurchase.setProperties(invoiceItem.getProperties(this.get('purchaseAttributes'))); inventoryPurchase.setProperties({ distributionUnit: inventoryItem.get('distributionUnit'), currentQuantity: quantity, originalQuantity: quantity, inventoryItem: inventoryItem.get('id') }); savePromises.push(inventoryPurchase.save()); }.bind(this)); Ember.RSVP.all(savePromises).then(function(results) { var inventorySaves = [], purchasesAdded = []; results.forEach(function(newPurchase) { var inventoryItem = this._findInventoryItem(newPurchase), purchases = inventoryItem.get('purchases'); purchases.addObject(newPurchase); purchasesAdded.push(this.newPurchaseAdded(inventoryItem, newPurchase)); }.bind(this)); Ember.RSVP.all(inventorySaves).then(function() { results.forEach(function(newPurchase) { var inventoryItem = this._findInventoryItem(newPurchase); inventoryItem.updateQuantity(); inventorySaves.push(inventoryItem.save()); }.bind(this)); Ember.RSVP.all(inventorySaves).then(function() { this.updateLookupLists(); this.displayAlert('Inventory Purchases Saved', 'The inventory purchases have been successfully saved', 'allItems'); }.bind(this)); }.bind(this)); }.bind(this)); }, actions: { addInventoryItem: function() { this._addInventoryItem(); }, addedNewInventoryItem: function(inventoryItem) { this.set('model.inventoryItem', inventoryItem); this._addInvoiceItem(); this.send('closeModal'); if (this.get('doingUpdate')) { this._savePurchases(); } }, removeItem: function(removeInfo) { var invoiceItems = this.get('model.invoiceItems'), item = removeInfo.itemToRemove; invoiceItems.removeObject(item); this.send('closeModal'); }, showRemoveItem: function(item) { var message = 'Are you sure you want to remove this item from this invoice?', model = Ember.Object.create({ itemToRemove: item }), title = 'Remove Item'; this.displayConfirm(title, message, 'removeItem', model); }, /** * Update the model */ update: function() { this.set('doingUpdate', true); this._addInventoryItem().then(function(addingNewInventory) { if (!addingNewInventory) { this._savePurchases(); } }.bind(this)); } } });
export default AbstractEditController.extend(UserRoles, UserSession, { currentRole: '', disabledAction: false, hideCancelButton: true, updateCapability: 'user_roles', filteredRoles: Ember.computed.filter('userRoles', function(userRole) { return (userRole.name !== 'System Administrator'); }), availableCapabilities: [{ name: 'admin', capabilities: [ 'admin', 'load_db', 'update_config', 'user_roles' ] }, { name: 'appointments', capabilities: [ 'appointments', 'add_appointment' ] }, { name: 'billing', capabilities: [ 'billing', 'add_charge', 'add_pricing', 'add_pricing_profile', 'add_invoice', 'add_payment', 'delete_invoice', 'delete_pricing', 'delete_pricing_profile', 'edit_invoice', 'invoices', 'override_invoice', 'pricing' ] }, { name: 'patients', capabilities: [ 'patients', 'add_diagnosis', 'add_photo', 'add_patient', 'add_visit', 'add_vitals', 'admit_patient', 'delete_photo', 'delete_patient', 'delete_appointment', 'delete_diagnosis', 'delete_procedure', 'delete_socialwork', 'delete_vitals', 'delete_visit', 'discharge_patient', 'patient_reports', 'visits' ] }, { name: 'medication', capabilities: [ 'medication', 'add_medication', 'delete_medication', 'fulfill_medication' ] }, { name: 'labs', capabilities: [ 'labs', 'add_lab', 'complete_lab', 'delete_lab' ] }, { name: 'imaging', capabilities: [ 'imaging', 'add_imaging', 'complete_imaging', 'delete_imaging' ] }, { name: 'inventory', capabilities: [ 'inventory', 'add_inventory_request', 'add_inventory_item', 'add_inventory_purchase', 'adjust_inventory_location', 'delete_inventory_item', 'delete_inventory_purchase', 'fulfill_inventory' ] }], capabilitySections: Ember.computed.map('availableCapabilities', function(section) { var mappedCapabilities = []; section.capabilities.forEach((key) => { mappedCapabilities.push({ key: key, name: this.get('i18n').t('admin.roles.capability.' + key) }); }); return { name: this.get('i18n').t('admin.roles.capability.' + section.name), capabilities: mappedCapabilities }; }), actions: { selectRole(role) { var roleToUpdate = this.get('model').findBy('id', role.dasherize()); this.set('currentRole', role); this.set('roleToUpdate', roleToUpdate); if (roleToUpdate) { var capabilities = roleToUpdate.get('capabilities'); this.get('availableCapabilities').forEach((section) => { section.capabilities.forEach((capability) => { if (capabilities.contains(capability)) { this.set(capability, true); } else { this.set(capability, false); } }); }); } else { var defaultCapabilities = this.get('defaultCapabilities'); Object.keys(defaultCapabilities).forEach((capability) => { var capabilityRoles = defaultCapabilities[capability]; if (capabilityRoles.contains(role)) { this.set(capability, true); } else { this.set(capability, false); } }); } }, update() { var currentRole = this.get('currentRole'); var roleToUpdate = this.get('roleToUpdate'); if (Ember.isEmpty(roleToUpdate)) { roleToUpdate = this.get('store').createRecord('user-role', { id: currentRole.dasherize(), name: currentRole }); } var capabilitiesToSave = []; this.get('availableCapabilities').forEach((section) => { section.capabilities.forEach((capability) => { if (this.get(capability) === true) { capabilitiesToSave.push(capability); } }); }); roleToUpdate.set('capabilities', capabilitiesToSave); roleToUpdate.save().then(() => { this.displayAlert(this.get('i18n').t('admin.roles.titles.role_saved'), this.get('i18n').t('admin.roles.messages.role_saved', { roleName: currentRole })); }); } } });