Hey guys agian i have a a problem with Meteor accounts api.
im trying to let only users that are logged in to change their own list, without effecting other users list here is my code:
client-side:
Meteor.subscribe('Categories');
Meteor.autosubscribe(function() {
Meteor.subscribe("listdetails",
Session.get('current_list'));
});
'keyup #add-category': function (e,t){
if (e.which === 13)
{
var catVal = String(e.target.value || "");
if (catVal)
{
lists.insert({Category:catVal,owner:this.userId});
Session.set('adding_category', false);
}
}
},
the server-side:
Meteor.startup(function () {
Meteor.publish("Categories", function() {
return lists.find({owner:Meteor.userId},{fields:{Category:1}});
});
Meteor.publish("listdetails", function(category_id){
return lists.find({_id:category_id});
});
});
both sides(client and server):
lists = new Meteor.Collection("Lists");
/*function adminUser(userId) {
var adminUser = Meteor.users.findOne({username:"boazhoch"});
return userId && adminUser && userId === adminUser._id;
} */
function adminUser(userId) {
var adminUser = Meteor.users.findOne({username:"admin"});
return (userId && adminUser && userId === adminUser._id);
}
lists.allow({
insert: function (userId, doc) {
// the user must be logged in, and the document must be owned by the user
return (adminUser(userId) || userId && doc.owner === userId);
},
update: function(userId, docs, fields, modifier){
return adminUser(userId) || _.all(docs, function(doc) {
return doc.owner === userId;
});
},
remove: function (userId, docs){
return adminUser(userId) || _.all(docs, function(doc) {
return doc.owner === userId;
});
},
fetch: ['owner']
});
you can clearly see that when logged in with admin and not logged the screens are similar (not the result i want) and notice that this.userId is "undefined" which is wired and this is why i used Meteor.userId.
Change your code to this below:
client (in the "keyup #add-category" event):
lists.insert({Category:catVal,owner:Meteor.userId()});
server (in publish Categories):
return lists.find({owner:this.userId},{fields:{Category:1}});
both sides(client and server):
lists.allow({
insert: function(userId, doc){
return adminUser(userId) || (userId && doc.owner === userId);
},
update: function(userId, doc, fields, modifier) {
return adminUser(userId) || doc.owner === userId;
},
remove: function (userId, doc){
return adminUser(userId) || doc.owner === userId;
},
fetch: ['owner']
});
On the client you should use Meteor.userId() and on the server this.userId, but only in a publish function:
Meteor.publish("Categories", function() {
return lists.find({owner:this.userId},{fields:{Category:1}});
});
And when you insert it, on the client:
lists.insert({Category:catVal,owner:Meteor.userId()});
You also need to make sure you remove autopublish, which automatically publishes everything, before you start meteor
meteor remove autopublish
full client code:
Meteor.subscribe('Categories');
Meteor.autosubscribe(function() {
Meteor.subscribe("listdetails",
Session.get('current_list'));
});
Template.categories.lists = function () {
return lists.find({},{sort: {Category: 1}});
};
Session.set('adding_category', false);
Template.categories.new_cat = function () {
return Session.equals('adding_category',true);
};
Template.categories.events({
'click #btnNewCat': function (e, t) {
Session.set('adding_category', true);
Meteor.flush();
focusText(t.find("#add-category"));
},
'keyup #add-category': function (e,t){
if (e.which === 13)
{
var catVal = String(e.target.value || "");
if (catVal)
{
lists.insert({Category:catVal,owner:Meteor.userId});
Session.set('adding_category', false);
}
}
},
'focusout #add-category': function(e,t){
Session.set('adding_category',false);
},
'click .category': selectCategory
});
/////Generic Helper Functions/////
//this function puts our cursor where it needs to be.
function focusText(i,val) {
i.focus();
i.value = val ? val : "";
i.select();
};//< -----This is the end tag for focusText() -----
function selectCategory(e,t){
Session.set('current_list',this._id);
}
function addItem(list_id,item_name){
if (!item_name&&!list_id)
return;
lists.update({_id:list_id},
{$addToSet:{items:{Name:item_name}}});
}
function removeItem(list_id,item_name){
if (!item_name&&!list_id)
return;
lists.update({_id:list_id},
{$pull:{items:{Name:item_name}}});
}
function updateLendee(list_id,item_name,lendee_name){
var l = lists.findOne({"_id":list_id ,
"items.Name":item_name});
if (l&&l.items)
{
for (var i = 0; i<l.items.length; i++)
{
if (l.items[i].Name === item_name)
{
l.items[i].LentTo = lendee_name;
}
}
lists.update({"_id":list_id},{$set:{"items":l.items}});
}
};
Template.list.items = function () {
if (Session.equals('current_list',null)) return null;
else
{
var cats = lists.findOne({_id:Session.get('current_list')});
if (cats&&cats.items)
{
for(var i = 0; i<cats.items.length;i++) {
var d = cats.items[i]; d.Lendee = d.LentTo ? d.LentTo :
"free"; d.LendClass = d.LentTo ?
"label-important" : "label-success";
}
return cats.items;
}
}
};// < ---- ending bracket for Template.list.items function ----
Template.list.list_selected = function() {
return ((Session.get('current_list')!=null) &&
(!Session.equals('current_list',null)));
};
Template.categories.list_status = function(){
if (Session.equals('current_list',this._id))
return "";
else
return " btn-inverse";
};
Template.list.list_adding = function(){
return (Session.equals('list_adding',true));
};
Template.list.lendee_editing = function(){
return (Session.equals('lendee_input',this.Name));
};
Template.list.events({
'click #btnAddItem': function (e,t){
Session.set('list_adding',true);
Meteor.flush();
focusText(t.find("#item_to_add"));
},
'keyup #item_to_add': function (e,t){
if (e.which === 13)
{
addItem(Session.get('current_list'),e.target.value);
Session.set('list_adding',false);
}
},
'focusout #item_to_add': function(e,t){
Session.set('list_adding',false);
},
'click .delete_item': function(e,t){
removeItem(Session.get('current_list'),e.target.id);
},
'click .lendee' : function(e,t){
Session.set('lendee_input',this.Name);
Meteor.flush();
focusText(t.find("#edit_lendee"),this.LentTo);
},
'keyup #edit_lendee': function (e,t){
if (e.which === 13)
{
updateLendee(Session.get('current_list'),this.Name,
e.target.value);
Session.set('lendee_input',null);
}
if (e.which === 27)
{
Session.set('lendee_input',null);
}
}
});
Accounts.ui.config({
passwordSignupFields: 'USERNAME_AND_OPTIONAL_EMAIL'
});
Related
I created a live pool app where you can create, view and delete questions from the table pools from the rethinkdb database.
The delete is the problem. When I use a DELETE request with POSTMAN, it works, the table is deleted. But when I click on the delete button in Angular, it doesn't do anything. How do I create a DELETE http request ?
This is my delete code that works in the database:
deletePolls(pollData,callback) {
async.waterfall([
function(callback) {
var pollObject = new db();
pollObject.connectToDb(function(err,connection) {
if(err) {
return callback(true,"Error connecting to database");
}
callback(null,connection);
});
},
function(connection,callback) {
//THIS DELETES THE TABLE FROM THE DATABASE
rethinkdb.table('poll').delete().run(connection,function(err,result) {
connection.close();
if(err) {
return callback(true,"Error happens while deleting polls");
}
callback(null,result);
});
}
],function(err,data) {
callback(err === null ? false : true,data);
});
}
This is the button in my index.html, that calls the function delete():
<md-button ng-submit="delete()">Delete the table</md-button>
This is the function that should delete:
$scope.delete = function() {
$http.delete("/polls",data).success(function(response) {
if(response.responseCode === 0) {
console.log("Success");
console.log("IvanUspeh");
$scope.hiddenrows.push(index);
} else {
console.log("error");
}
});
};
Here is the full app.js, the javascript that angular works with:
var app = angular.module('starterApp', ['ngMaterial','ngRoute','ngMessages']);
app.factory('socket',function(){
var socket = io.connect('http://localhost:3000');
return socket;
});
app.config(function($routeProvider){
$routeProvider
.when('/',{
templateUrl: 'home.html'
})
.when('/create',{
templateUrl: 'create.html'
})
.when('/view',{
templateUrl: 'view.html'
})
.when('/delete',{ //IGNORE THIS, THIS JUST OPENS AN EMPTY HTML
templateUrl: 'delete.html'
})
;
});
app.controller('pollingController',function($scope,$mdDialog,$http,socket) {
$scope.pollData = [];
$scope.formData = {};
$scope.voteData = {};
$scope.hiddenrows = [];
getPollData();
function getPollData() {
$http.get("/polls").success(function(response){
$scope.pollData = response.data;
});
}
$scope.submitPoll = function(ev) {
var data = {
"question" : $scope.formData.pollQuestion,
"polls" : [{
"option" : $scope.formData.pollOption1, "vote" : 0
},{
"option" : $scope.formData.pollOption2, "vote" : 0
},{
"option" : $scope.formData.pollOption3, "vote" : 0
}]
};
var message = {"title" : "", "message" : ""};
$http.post('/polls',data).success(function(response) {
if(response.responseCode === 0) {
message.title = "Uspeh !";
message.message = "Anketa je uspešno napravljena.";
data["id"] = response.data.generated_keys[0];
$scope.pollData.push(data);
} else {
message.title = "Greška !";
message.message = "Greška u toku pravljenja ankete.";
}
$mdDialog.show(
$mdDialog.alert()
.parent(angular.element(document.querySelector('#popupContainer')))
.clickOutsideToClose(true)
.title(message.title)
.textContent(message.message)
.ok('Got it!')
.targetEvent(ev)
);
});
}
$scope.updateVote = function(index) {
var data = {
"id" : $scope.pollData[index].id,
"option" : $scope.pollData[index].selected
};
$http.put("/polls",data).success(function(response) {
if(response.responseCode === 0) {
console.log("Success");
$scope.hiddenrows.push(index);
} else {
console.log("error");
}
});
}
$scope.delete = function() {
$http.delete("/polls",data).success(function(response) {
if(response.responseCode === 0) {
console.log("Success");
console.log("IvanUspeh");
$scope.hiddenrows.push(index);
} else {
console.log("error");
}
});
};
socket.on('changeFeed',function(data) {
for(var pollCounter = 0 ;pollCounter < $scope.pollData.length; pollCounter++) {
if($scope.pollData[pollCounter].id === data.id) {
$scope.pollData[pollCounter].polls = data.polls;
$scope.$apply();
}
}
});
});
So, when I push the button with the function delete(), I want it to delete everything in the table like in POSTMAN, like a http request. What am I doing wrong ?
This is not much of a solution , rather a suggestion on how to debug
You are capturing only the success from the http call but not the error . You can write the function like below to more detail on where its failing.
$scope.delete = function() {
console.log("delete function called");
$http.delete("/polls",data).success(function(response) {
if(response.responseCode === 0) {
console.log("Success");
console.log("IvanUspeh");
$scope.hiddenrows.push(index);
} else {
console.log("error");
}
})
.error(function (data, status, header, config) {console.log(status)});
};
Somehow I am not able to get my data from the factory method to the controller. I am using javascript remoting and factory is given below
function userRecordFetchFactory($rootScope) {
var custRec = {};
return {
checkRecordType : function(urlObject) {
function loadRecordType(err, records, event) {
if (err) {
displayReadingInformationErrorView();
} else if (records != null && records.length == 0) {
displayReadingInformationErrorView();
} else {
custRec = {
Name : records[0].get('Name'),
lat : records[0].get('Latitude__c'),
lon : records[0].get('Longitude__c'),
SiteStreet : records[0]
.get('SiteStreet__c'),
SiteCity : records[0].get('SiteCity__c'),
SiteCountryCode : records[0]
.get('SiteCountryCode__c'),
SitePostalCode : records[0]
.get('SitePostalCode__c'),
AddressID : records[0].get('AddressID__c'),
loaded : true
};
}
}
if (urlObject && urlObject.aid
&& urlObject.aid.startsWith(accPrefix)) {
objModel = new RemoteObjectModel.Account();
}
if (urlObject && urlObject.aid
&& urlObject.aid.startsWith(leadPrefix)) {
objModel = new RemoteObjectModel.Lead();
}
if (objModel) {
objModel.retrieve({
where : {
Id : {
eq : urlObject.aid
}
}
}, loadRecordType);
}
return custRec;
}
};
}
and my controller is given below to access the data
function LocatorInitController($document, $scope,
userRecordFetchFactory) {
console.log("inside the controller"+urlParams);
$scope.CustomerSite = {};
userRecordFetchFactory.checkRecordType(urlParams)
.then(function successData(data){
$scope.CustomerSite = data.data;
execGeoCoding();
});
I get an error cannot read property success of undefined. In the factory the method checkRecordType has a retrieve function which is a javascript remoting call and that finction has a callback to loadrecordtype.
Suggest you write your factory in a simpler way to read it. All your nesting is causing you not to see the whole thing easily
Put all the accessible members up top
// pass functions as references to object properties
// can easily see the whole factory object at top of the file
var custRec = {
checkRecordType : checkRecordType,
subscribe : subscribe
};
return custRec;
// move function declarations to the bottom and out of the way
function checkRecordType(){
/// do stuff
return stuff;
}
function loadRecordType(err, records, event) {
/// do stuff
return stuff;
}
function subscribe(scope, callback){
/// do stuff
return stuff;
}
See John Papa Angular STyle Guide
Why don't you try rewriting your factory like so:
function Factory() {
var custRec = {
subscribe: function(scope, callback) {
var handler = $rootScope.$on(
'fire-event-accountservice-retrieve',
function(
event, data) {
callback(data);
scope.$apply();
});
scope.$on('$destroy', handler);
},
checkRecordType: function(urlObject) {
var custRec;
if (urlObject.aid == null && urlObject.addr == null) {
displayCurrentLocation();
}
if (urlObject && urlObject.aid &&
urlObject.aid.startsWith(accPrefix)) {
objModel = new RemoteObjectModel.Account();
}
if (urlObject && urlObject.aid &&
urlObject.aid.startsWith(leadPrefix)) {
objModel = new RemoteObjectModel.Lead();
}
if (objModel == null && urlObject.aid != null && urlObject.addr == null) {
displayReadingInformationErrorView();
}
if (objModel) {
objModel.retrieve({
where: {
Id: {
eq: urlObject.aid
}
}
}, loadRecordType);
} else if ((urlObject.addr != null || urlObject.addr != '') && (typeof urlObject.addr != "undefined")) {
displayLocationBasedOnAddress(urlObject.addr);
}
function loadRecordType(err, records, event) {
if (err) {
displayReadingInformationErrorView();
} else if (records != null && records.length == 0) {
displayReadingInformationErrorView();
} else {
custRec = {
Name: records[0].get('Name'),
lat: records[0].get('Latitude__c'),
lon: records[0].get('Longitude__c'),
SiteStreet: records[0]
.get('SiteStreet__c'),
SiteCity: records[0].get('SiteCity__c'),
SiteCountryCode: records[0]
.get('SiteCountryCode__c'),
SitePostalCode: records[0]
.get('SitePostalCode__c'),
AddressID: records[0].get('AddressID__c'),
loaded: true
};
/* $rootScope.$emit(
'fire-event-accountservice-retrieve',
custRec); */
}
}
}
}
return custRec;
}
Looks like you're returning your factory object the wrong way.
function userRecordFetchFactory($rootScope) {
var custRec = {};
custRec.checkRecordType = function (urlObject) {
function loadRecordType(err, records, event) {
if (err) {
displayReadingInformationErrorView();
} else if (records != null && records.length == 0) {
displayReadingInformationErrorView();
} else {
custRec = {
Name: records[0].get('Name'),
lat: records[0].get('Latitude__c'),
lon: records[0].get('Longitude__c'),
SiteStreet: records[0]
.get('SiteStreet__c'),
SiteCity: records[0].get('SiteCity__c'),
SiteCountryCode: records[0]
.get('SiteCountryCode__c'),
SitePostalCode: records[0]
.get('SitePostalCode__c'),
AddressID: records[0].get('AddressID__c'),
loaded: true
};
}
}
if (urlObject && urlObject.aid
&& urlObject.aid.startsWith(accPrefix)) {
objModel = new RemoteObjectModel.Account();
}
if (urlObject && urlObject.aid
&& urlObject.aid.startsWith(leadPrefix)) {
objModel = new RemoteObjectModel.Lead();
}
if (objModel) {
objModel.retrieve({
where: {
Id: {
eq: urlObject.aid
}
}
},
return custRec;
}
I want to run this code without having to click on the chrome.browserAction.onClicked.addListener. How do I do this?
This is the code:
var ToggleJSApplication = {
triggerWin: null,
urlPattern: 'http://*',
init: function() {
var self = this;
self.updateIcon(function() {
chrome.browserAction.onClicked.addListener(self.toggleState.bind(self));
chrome.windows.onFocusChanged.addListener(self.onWinFocusChanged.bind(self));
});
},
getState: function(incognito, callback) {
var self = this,
data = {
'primaryUrl': self.urlPattern,
'incognito': incognito || false
};
chrome.contentSettings.javascript.get(data, function(state) {
state.enabled = (state.setting === 'allow');
if (typeof callback === 'function') callback(state);
});
},
setState: function(incognito, enabled, callback) {
var self = this,
data = {
'primaryPattern': '<all_urls>',
'setting': (enabled) ? 'allow' : 'block',
'scope': (incognito === true) ? 'incognito_session_only' : 'regular'
};
chrome.contentSettings.javascript.set(data, function() {
self.updateIcon();
if (typeof callback === 'function') callback();
});
},
toggleState: function() {
var self = this;
chrome.windows.getCurrent(function(win) {
self.triggerWin = win;
self.getState(win.incognito, function(state) {
self.setState(win.incognito, !state.enabled, function() {
self.reloadCurrentTab();
});
});
});
},
onWinFocusChanged: function() {
var self = this;
chrome.windows.getCurrent(function(win) {
self.triggerWin = win;
self.updateIcon();
});
},
reloadCurrentTab: function() {
chrome.tabs.query({currentWindow: true, active: true}, function(tabs) {
var tab = tabs[0];
chrome.tabs.duplicate(tab.id);
chrome.tabs.remove(tab.id);
});
},
updateIcon: function(callback) {
var self = this,
incognito = (self.triggerWin && self.triggerWin.incognito) || false;
self.getState(incognito, function(state) {
if (state.enabled) {
chrome.browserAction.setIcon({path: 'icons/38-on.png'});
chrome.browserAction.setTitle({title: 'JavaScript is enabled'});
}
else {
chrome.browserAction.setIcon({path: 'icons/38-off.png'});
chrome.browserAction.setTitle({title: 'JavaScript is disabled'});
}
if (typeof callback === 'function') callback();
});
}
};
ToggleJSApplication.init();
I already tried using context menu's but I failed. Is there any workaround?
You mentioned that you want to use a button click in the existing webpage to trigger your script. In order to interact with the webpage, you need to use a content script, which must interact with the background script via message passing. The content script can be as simple as:
document.getElementById('buttonId').addEventListener('click',sendMessage);
// or $('#buttonId').click(sendMessage);
function sendMessage() {
chrome.runtime.sendMessage({'message':'buttonClicked'});
}
Then in your background script, you can add:
chrome.runtime.onMessage.addListener(messageListener);
function messageListener(request) {
if ( request.message === 'buttonClicked' ) {
ToggleJSApplication.toggleState();
}
}
i have phpbb 3.1 forum.
i have a- jquery.collapse.js.
i want that the defult will be collapsed insted of open.
wheat parameter do i need to change to do it?
and can o make it that in default only 1 is open and not close?
the default will be the 1st category to be open, and when i open the next one, the open one will close automatically.
the code-
(function($, exports) {
// Constructor
function Collapse (el, options) {
options = options || {};
var _this = this,
query = options.query || "> :even";
$.extend(_this, {
$el: el,
options : options,
sections: [],
isAccordion : options.accordion || false,
db : options.persist ? jQueryCollapseStorage(el.get(0).id) : false
});
// Figure out what sections are open if storage is used
_this.states = _this.db ? _this.db.read() : [];
// For every pair of elements in given
// element, create a section
_this.$el.find(query).each(function() {
new jQueryCollapseSection($(this), _this);
});
// Capute ALL the clicks!
(function(scope) {
_this.$el.on("click", "[data-collapse-summary] " + (scope.options.clickQuery || ""),
$.proxy(_this.handleClick, scope));
_this.$el.bind("toggle close open",
$.proxy(_this.handleEvent, scope));
}(_this));
}
Collapse.prototype = {
handleClick: function(e, state) {
e.preventDefault();
state = state || "toggle";
var sections = this.sections,
l = sections.length;
while(l--) {
if($.contains(sections[l].$summary[0], e.target)) {
sections[l][state]();
break;
}
}
},
handleEvent: function(e) {
if(e.target == this.$el.get(0)) return this[e.type]();
this.handleClick(e, e.type);
},
open: function(eq) {
this._change("open", eq);
},
close: function(eq) {
this._change("close", eq);
},
toggle: function(eq) {
this._change("toggle", eq);
},
_change: function(action, eq) {
if(isFinite(eq)) return this.sections[eq][action]();
$.each(this.sections, function(i, section) {
section[action]();
});
}
};
// Section constructor
function Section($el, parent) {
if(!parent.options.clickQuery) $el.wrapInner('<a href="#"/>');
$.extend(this, {
isOpen : false,
$summary : $el.attr("data-collapse-summary",""),
$details : $el.next(),
options: parent.options,
parent: parent
});
parent.sections.push(this);
// Check current state of section
var state = parent.states[this._index()];
if(state === 0) {
this.close(true);
}
else if(this.$summary.is(".open") || state === 1) {
this.open(true);
} else {
this.close(true);
}
}
Section.prototype = {
toggle : function() {
this.isOpen ? this.close() : this.open();
},
close: function(bypass) {
this._changeState("close", bypass);
},
open: function(bypass) {
var _this = this;
if(_this.options.accordion && !bypass) {
$.each(_this.parent.sections, function(i, section) {
section.close();
});
}
_this._changeState("open", bypass);
},
_index: function() {
return $.inArray(this, this.parent.sections);
},
_changeState: function(state, bypass) {
var _this = this;
_this.isOpen = state == "open";
if($.isFunction(_this.options[state]) && !bypass) {
_this.options[state].apply(_this.$details);
} else {
_this.$details[_this.isOpen ? "show" : "hide"]();
}
_this.$summary.toggleClass("open", state !== "close");
_this.$details.attr("aria-hidden", state === "close");
_this.$summary.attr("aria-expanded", state === "open");
_this.$summary.trigger(state === "open" ? "opened" : "closed", _this);
if(_this.parent.db) {
_this.parent.db.write(_this._index(), _this.isOpen);
}
}
};
// Expose in jQuery API
$.fn.extend({
collapse: function(options, scan) {
var nodes = (scan) ? $("body").find("[data-collapse]") : $(this);
return nodes.each(function() {
var settings = (scan) ? {} : options,
values = $(this).attr("data-collapse") || "";
$.each(values.split(" "), function(i,v) {
if(v) settings[v] = true;
});
new Collapse($(this), settings);
});
}
});
//jQuery DOM Ready
$(function() {
$.fn.collapse(false, true);
});
// Expose constructor to
// global namespace
exports.jQueryCollapse = Collapse;
exports.jQueryCollapseSection = Section;
})(window.jQuery, window);
the forum- limodim.com/1
thank you.
I have a controller that works fine on initial load. It calls user [0] data and everything processes fine. When I change dropdown, I want to call the same function, but I cannot get the entire controller to reload. It starts from the function call and leaves undefined in places where it pulls correct information (linkToken, etc) on initial load. Is there a way I can get it to reload all data from the controller instead of just from the function?
After calling the testchange() from the view to pass in the new data, I get :
TypeError: Cannot read property 'locations' of undefined
at h.$scope.updateLocations (refillController.js:261)
at refillController.js:73
But, when I call the original getRefills() that is ran on the initial page load I get the same error. How can I define these so the load after the onchange(0)?
angular.module('FinalApp.Controllers').controller('refillController', function ($rootScope, $scope, $location, $modal, userService, dependentsService, accountService, sharedCollections, configurationService, refillsService) {
$scope.user = userService.GetUserInformation();
$scope.userInfoArr = [];
//$scope.tests.push({'Name':$scope.user.FirstName, 'LinkToken':$scope.user.LinkToken});
$scope.userInfoArr = $scope.user.Dependants.map(function(item){return {'Name':item.FirstName, 'LinkToken':item.LinkToken}});
$scope.userInfoArr.splice(0, 0, {'Name': $scope.user.FirstName, 'LinkToken': $scope.user.LinkToken});
console.log($scope.userInfoArr);
$scope.finUserInfoArr = $scope.userInfoArr[0].LinkToken;
$scope.billingInfo = null;
$rootScope.showNavbar = true;
$scope.selectedMethod = null;
$scope.location = null;
$scope.payment = null;
$scope.refills = [];
$scope.deliverTypes = [];
$scope.locations = [];
$scope.payments = [];
$scope.allSelected = false;
$scope.loadingBillingInfo = false;
$scope.isMailOrder = false;
//Detect Mobile Switch Refill List To Grid
if(window.innerWidth <= 800) {
$scope.view = "Grid";
} else {
$scope.view = "List";
}
$scope.changeViewToList = function () {
$scope.view = "List";
};
$scope.changeViewToGrid = function () {
$scope.view = "Grid";
};
$scope.testchange = function(selectedTest) {
$scope.getRefills(selectedTest);
console.log(selectedTest);
};
$scope.getRefills = function (linkToken) {
$scope.allSelected = false;
$scope.loading = true;
refillsService.GetRefills(
linkToken,
$scope.selectedMethod,
$scope.location,
$scope.payment
).then(function (data) {
$scope.refills = [];
_.each(data.Prescriptions, function (item) {
fillRefills(item);
});
fillDeliverTypes(data.DeliveryTypes);
if (!$scope.selectedMethod)
$scope.selectedMethod = data.DeliveryTypeId;
if (!$scope.location)
$scope.location = data.PickupLocationId;
if (!$scope.payment)
$scope.payment = data.PaymentTypeId;
$scope.loading = false;
$scope.updateLocations();
})["catch"](function (error) {
console.log(error);
$scope.loading = false;
alertify.alert(configurationService.ErrorMessage("getting your refills", error.Message));
});
};
var fillRefills = function (item) {
//TODO-CallDoc temp fix
if (item.RefillClass == "CALL_DOCTOR") {
item.NextRefillDate = '1900-01-01T00:00:00'
}
var parsedDate = checkDate(moment(item.NextRefillDate).format('L'));
var lastrefill = checkDate(moment(item.LastDispenseDate).format('L'));
var expireDate = checkDate(moment(item.ExpirationDate).format('L'));
var status = (item.RefillStatus.indexOf("After") == -1) ? item.RefillStatus : "Refill " + item.RefillStatus;
$scope.refills.push({
selected: false,
rx: item.ScriptNo,
name: item.DrugName,
dose: item.UnitsPerDose,
dir: item.Instructions,
nextfill: parsedDate,
lastfill: lastrefill,
refillsLeft: item.NumRefillsLeft,
status: status,
msg: item.RefillMessage,
canSelect: item.IsRefillable,
refillClass: item.RefillClass,
lastDispenseQty: item.LastDispenseQty,
DaysSupply: item.DaysSupply,
expireDate: expireDate,
copayAmt: item.CopayAmt,
drFirstName: item.DoctorFirstName,
drLastName: item.DoctorLastName,
writtenQty: item.WrittenQty
});
};
var checkDate = function (date) {
if (date == "01/01/1900") return "N/A";
if (date == "Invalid Date") return "";
return date;
};
var fillDeliverTypes = function (deliverTypes) {
$scope.deliverTypes = [];
_.each(deliverTypes, function (item) {
$scope.deliverTypes.push({
id: item.DeliveryTypeId,
name: item.DeliveryTypeName,
locations: item.PickupLocations,
payments: item.PaymentTypes
});
});
};
var getBillingInfo = function () {
$scope.loadingBillingInfo = true;
accountService.GetCreditCardInfo().then(function (data) {
$scope.billingInfo = data;
$scope.loadingBillingInfo = false;
})["catch"](function (error) {
$scope.loadingBillingInfo = false;
alertify.alert(configurationService.ErrorMessage("getting account information", error.Message));
});
};
var getAccountInfo = function () {
accountService.GetAccountInfo().then(function (data) {
if (data.StatusCode == "SUCCESS") {
$scope.user = data;
userService.SaveUserInformation(data);
if ($scope.user.IsLinked) {
$rootScope.enableMyRefills = true;
$rootScope.enableMyReports = true;
window.location.hash = "#/refills";
} else {
$rootScope.enableMyRefills = false;
$rootScope.enableMyReports = true;
}
} else {
alertify.alert(configurationService.ErrorMessage("getting account information", data.StatusMessage));
}
})["catch"](function (error) {
alertify.alert(configurationService.ErrorMessage("getting account information", error.Message));
});
};
var openModal = function (viewUrl, controllerUrl, size, payload) {
var modalInstance = $modal.open({
templateUrl: viewUrl,
controller: controllerUrl,
size: size,
resolve: {
data: function () {
return payload;
}
}
});
return modalInstance;
};
$scope.toggleRxSelection = function(rx) {
if (rx.canSelect) {
rx.selected = !rx.selected;
$scope.evaluateAllSelected();
}
};
$scope.selectAll = function (data) {
// $scope.allSelected = allSelected;
_.each($scope.refills, function (x) {
if (x.canSelect) x.selected = data;
});
};
$scope.evaluateAllSelected = function () {
var count = _.countBy(_.where($scope.refills, {canSelect:true}), function(refill) {
return refill.selected ? 'selected' : 'not';
});
$scope.allSelected = (count.not === undefined);
};
$scope.openEditCreditCardInfo = function () {
var payload = ($scope.billingInfo != null && $scope.billingInfo != undefined)
&& $scope.billingInfo.CardNumber != "" ? $scope.billingInfo : {};
if (payload != {}) {
payload.ExpMonth = {id: parseInt(payload.ExpMonth)};
payload.ExpYear = {id: parseInt(payload.ExpYear)};
}
openModal('app/views/editAccount/billingInformation.html', "billingInformationController", "xlg", payload).result.then(function () {
getAccountInfo();
getBillingInfo();
}, function () {
getBillingInfo();
});
};
$scope.openConfirmOrder = function () {
var refillsSelected = _.where($scope.refills, {selected: true});
var location = _.findWhere($scope.locations, {PickupLocationId: $scope.location});
var payment = _.findWhere($scope.payments, {PaymentTypeId: $scope.payment});
var deliver = _.findWhere($scope.deliverTypes, {id: $scope.selectedMethod});
if (refillsSelected.length == 0) {
alertify.error("You need to select at least one refill");
return;
}
if (deliver.id == 10001 && !$scope.user.IsCreditCardOnFile) {
alertify.error("Need credit card on file for mail order");
return;
}
sharedCollections.setRefills(refillsSelected);
sharedCollections.setLocation(location);
sharedCollections.setPayment(payment);
sharedCollections.setDeliver(deliver);
openModal('app/views/refills/confirmOrder.html', "confirmOrderController", "xlg").result.then(function () {
$scope.billingInfo = accountService.GetCreditCardInfo();
$scope.getRefills();
}, function () {
//$scope.billingInfo = accountService.GetCreditCardInfo();
//getRefills();
});
};
$scope.showRefill = function (rx) {
var data = {rx: rx, refills: $scope.refills};
openModal('app/views/refills/showRefills.html', "refillsCarrousel", "xlg", data).result.then(function () {
$scope.evaluateAllSelected();
}, function () {
$scope.evaluateAllSelected();
});
};
$scope.updateLocations = function () {
$scope.locations = _.findWhere($scope.deliverTypes, {id: $scope.selectedMethod}).locations;
$scope.payments = _.findWhere($scope.deliverTypes, {id: $scope.selectedMethod}).payments;
setLocationAndPayment();
};
var setLocationAndPayment = function () {
if ($scope.locations.length == 1) {
$scope.location = $scope.locations[0].PickupLocationId;
}
if ($scope.payments.length == 1) {
$scope.payment = $scope.payments[0].PaymentTypeId;
}
//check for mail order
($scope.selectedMethod == 10001 && !$scope.payment) ? $scope.isMailOrder = true : $scope.isMailOrder = false;
};
$scope.getRefills($scope.finUserInfoArr);
getBillingInfo();
});
Check if your refillsService returns correct data, it could be that $scope.refills remains empty array.