angular.module('dc.controllers', [])
.controller('MainCtrl', function($rootScope, $scope, $location, $ionicModal, $ionicSideMenuDelegate, Session, AuthService, DesignService, PushNotificationService) {
PushNotificationService.register().then (function (response) {
$rootScope.deviceToken = response;
console.log("Success call back: " + $rootScope.deviceToken);
}, function (error) {
console.log("Error call back:", error);
});
$rootScope.isApp = ionic.Platform.isWebView();
$rootScope.isIPad = ionic.Platform.isIPad();
$rootScope.isIOS = ionic.Platform.isIOS();
$rootScope.isAndroid = ionic.Platform.isAndroid();
$rootScope.isWindowsPhone = ionic.Platform.isWindowsPhone();
$rootScope.isFileDraggable = !$rootScope.isApp && !$rootScope.isIPad && !$rootScope.isIOS && !$rootScope.isAndroid && !$rootScope.isWindowsPhone;
$rootScope.session = Session;
$rootScope.isDesignerSite = $location.host().indexOf("designer.")==0;
$rootScope.showMenu = function() {
$ionicSideMenuDelegate.toggleRight();
}
$rootScope.makePayment = function(designId) {
$rootScope.payDesignId = designId;
DesignService.getDesigns().then(function(designResponse) {
$rootScope.design = DesignService.getDesign(designId);
$rootScope.showPay();
});
}
$ionicModal.fromTemplateUrl('login.html', {
scope: $rootScope,
animation: 'slide-in-up'
}).then(function(modal) {
$rootScope.loginModal = modal;
});
$rootScope.showLogin = function(postLoginSuccessBroadcast) {
$rootScope.loginModal.show();
$rootScope.postLoginSuccessBroadcastMsg = postLoginSuccessBroadcast;
}
$rootScope.closeLogin = function() {
$rootScope.loginModal.hide();
}
$ionicModal.fromTemplateUrl('pay.html', {
id: 'payModal',
scope: $scope,
animation: 'slide-in-up'
}).then(function(modal) {
$scope.payModal = modal;
});
$rootScope.showPay = function() {
$scope.payModal.show();
}
$scope.$on('modal.shown', function(event) {
console.log('Modal is shown! '+event);
if (event.currentScope.payModal) {
$rootScope.doStripeRetryCount = 0;
$rootScope.doStripe();
}
});
$rootScope.closePay = function() {
$scope.payModal.hide();
}
$rootScope.doStripeRetryCount = 0;
$rootScope.doStripe = function() {
if (!document.getElementById('card-element')) {
if ($rootScope.doStripeRetryCount > 15) {
return;
}
setTimeout($rootScope.doStripe, 200);
$rootScope.doStripeRetryCount++;
} else {
$rootScope.doStripeRetryCount = 0;
// Create a Stripe client.
var stripe = Stripe('pk_test_FOPihhGe1tSuktchNwLWbYp9');
// Create an instance of Elements.
var elements = stripe.elements();
// Custom styling can be passed to options when creating an Element.
// (Note that this demo uses a wider set of styles than the guide below.)
var style = {
base: {
color: '#32325d',
lineHeight: '18px',
fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
fontSmoothing: 'antialiased',
fontSize: '16px',
'::placeholder': {
color: '#aab7c4'
}
},
invalid: {
color: '#fa755a',
iconColor: '#fa755a'
}
};
// Create an instance of the card Element.
var card = elements.create('card', {style: style});
// Add an instance of the card Element into the `card-element`
.
if (document.getElementById('card-element')) {
card.mount('#card-element');
}
// Handle real-time validation errors from the card Element.
card.addEventListener('change', function(event) {
var displayError = document.getElementById('card-errors');
if (event.error) {
displayError.textContent = event.error.message;
} else {
displayError.textContent = '';
}
});
// Handle form submission.
var form = document.getElementById('payment-form');
if (form) {
form.addEventListener('submit', function(event) {
event.preventDefault();
stripe.createToken(card).then(function(result) {
if (result.error) {
// Inform the user if there was an error.
var errorElement = document.getElementById('card-errors');
errorElement.textContent = result.error.message;
} else {
// Send the token to your server.
$rootScope.stripeToken = result.token;
$rootScope.$broadcast('submitStripePayment');
}
});
});
}
}
}
$ionicModal.fromTemplateUrl('register.html', {
scope: $scope,
animation: 'slide-in-up'
}).then(function(modal) {
$scope.registerModal = modal;
});
$rootScope.showRegister = function() {
$scope.registerModal.show();
}
$rootScope.closeRegister = function() {
$scope.registerModal.hide();
}
$ionicModal.fromTemplateUrl('gallery.html', {
scope: $scope,
animation: 'slide-in-up'
}).then(function(modal) {
$scope.galleryModal = modal;
});
$scope.showGallery = function() {
$scope.galleryModal.show();
}
$scope.closeGallery = function() {
$scope.galleryModal.hide();
}
$ionicModal.fromTemplateUrl('view-model.html', {
scope: $rootScope,
animation: 'slide-in-up'
}).then(function(modal) {
$rootScope.modelModal = modal;
});
$rootScope.showModel = function() {
$rootScope.modelModal.show();
}
$rootScope.closeModel = function() {
$rootScope.modelModal.hide();
}
$scope.doLogout = function() {
AuthService.logout();
}
$scope.loadDetails = function() {
AuthService.details();
}
$scope.$on('auth-details-success', function(event, args){
AuthService.balance();
});
$scope.$on('load-details', function(){
$scope.loadDetails();
});
$scope.loadDetails();
$rootScope.show3DModel = function(videoUrl) {
$rootScope.videoUrl = videoUrl;
$rootScope.showModel();
$rootScope.$broadcast('show-model');
}
})
.controller('DashCtrl', function($scope, $ionicModal) {
})
.controller('LandCtrl', function($scope, $ionicModal) {
})
.controller('PayCtrl', function($rootScope, $scope, $ionicLoading, $ionicScrollDelegate, Session, TransactionService, DesignService, CashierService, AuthService) {
$scope.resetPay = function() {
$scope.promo = new Object();
$scope.promo.promoAmount = null;
$scope.promo.promoDescription = null;
$scope.promo.promoCode = "";
$scope.payErrors = [];
$scope.paySuccessMessages = [];
}
$scope.resetPay();
$scope.applyPromo = function() {
$scope.payErrors = [];
$scope.paySuccessMessages = [];
if ($scope.promo.promoCode != "") {
$ionicLoading.show();
TransactionService.applyPromo($scope.promo.promoCode, $rootScope.design.designId).then(function(promoResponse) {
if (promoResponse.data.success) {
$scope.promo.promoAmount = promoResponse.data.promoAmount;
$scope.promo.promoDescription = promoResponse.data.promoDescription;
$scope.paySuccessMessages.push("Promo Code '"+$scope.promo.promoCode+"' applied successfully!");
} else {
$scope.payErrors.push(promoResponse.data.errorMessage);
}
$ionicScrollDelegate.scrollBottom(true);
$ionicLoading.hide();
}, function (errorResponse) {
$ionicLoading.hide();
});
} else {
$scope.payErrors.push("No promo code was entered.");
$ionicScrollDelegate.scrollBottom(true);
}
}
$scope.amountDue = function() {
var amountDue = $rootScope.design.cost - $rootScope.session.balance + ($scope.promo.promoAmount?$scope.promo.promoAmount:0)
if (amountDue < 0) amountDue = 0;
return amountDue;
}
$scope.makePayment = function() {
if ($scope.amountDue() > 0) {
// TODO deposit functionality goes here.
alert('Deposit Not Implemented Yet');
} else {
// Account is settled - proceed
TransactionService.completePurchase($rootScope.design.designId, $scope.promo.promoCode).then(function(completeResponse) {
if (completeResponse.data.success) {
$scope.resetPay();
$scope.paySuccessMessages.push("Purchase Completed.");
setTimeout(function() {$rootScope.$broadcast('open-recently-submitted'); $rootScope.closePay();}, 1200)
} else {
$scope.payErrors.push("Could not complete purchase: " + completeResponse.data.errorMessage);
}
$ionicScrollDelegate.scrollBottom(true);
});
}
}
$scope.$on('submitStripePayment', function(){
CashierService.payNow($rootScope.stripeToken, $scope.amountDue()).then(function(payNowResponse) {
if (payNowResponse.data.success) {
$scope.paySuccessMessages.push("Payment Successful - send it to the Printers using the button below!");
} else {
$scope.payErrors.push("Could not complete payment: " + payNowResponse.data.errorMessage);
}
AuthService.balance();
});
});
})
.controller('AccountCtrl', function($scope, $ionicScrollDelegate, $ionicPopup, Session, DesignService, TransactionService) {
$scope.modelDesignErrors = new Object();
$scope.resetDesigns = function() {
$scope.designsPendingDesigner = [];
$scope.designsPendingPayment = [];
$scope.designsBeingModelled = [];
$scope.designsPendingApproval = [];
$scope.designsInProduction = [];
$scope.designsCompleted = [];
$scope.designsApproved = [];
$scope.designsCancelled = [];
$scope.myTransactions = [];
}
$scope.resetDesigns();
$scope.loadDesigns = function() {
if(Session.loggedIn) {
DesignService.getDesigns().then(function(designResponse) {
if (designResponse.data.success) {
$scope.resetDesigns();
$scope.designsPendingDesigner = designResponse.data.pendingDesigner;
$scope.designsPendingPayment = designResponse.data.pendingPayment;
$scope.designsBeingModelled = designResponse.data.beingModelled;
$scope.designsPendingApproval = designResponse.data.pendingApproval;
$scope.designsInProduction = designResponse.data.inProduction;
$scope.designsCompleted = designResponse.data.completed;
$scope.designsApproved = designResponse.data.approved;
$scope.designsCancelled = designResponse.data.cancelled;
} else {
$scope.resetDesigns();
}
});
TransactionService.getMine().then(function(transactionsResponse) {
if (transactionsResponse.data.success) {
$scope.myTransactions = transactionsResponse.data.transactions
}
});
}
}
$scope.loadDesigns();
$scope.approveModel = function(designId) {
var confirmPopup = $ionicPopup.confirm({
title: 'Approve This Design?',
template: 'By approving this Design you are indicating that it is suitable and ready for 3D printing. This version will then be sent to the 3D printer and cannot be cancelled.'
});
confirmPopup.then(function(res) {
if(res) {
DesignService.approveModel(designId).then(function(designResponse) {
if (designResponse.data.success) {
// success
} else {
// fail
}
$scope.resetDesigns();
$scope.loadDesigns();
$ionicScrollDelegate.scrollTop(true);
});
} else {
console.log('You are not sure');
}
});
}
$scope.rejectModel = function(design) {
var designId = design.designId;
$scope.modelDesignErrors[designId] = "";
if (!design.rejectionReasons || design.rejectionReasons=="") {
$scope.modelDesignErrors[designId] = "You must describe what design changes you would like to see";
return;
}
var confirmPopup = $ionicPopup.confirm({
title: 'Reject This Design?',
template: 'The model will be returned to the Designer for further processing. Your reasons will be passed on to the Designer.'
});
confirmPopup.then(function(res) {
if(res) {
DesignService.rejectModel(designId, design.rejectionReasons).then(function(designResponse) {
if (designResponse.data.success) {
// success
} else {
// fail
}
$scope.resetDesigns();
$scope.loadDesigns();
$ionicScrollDelegate.scrollTop(true);
});
} else {
console.log('You are not sure');
}
});
}
$scope.$on('auth-login-success', function(){
$scope.loadDesigns();
});
$scope.$on('auth-details-success', function(){
$scope.loadDesigns();
});
$scope.$on('auth-logout-success', function(){
$scope.resetDesigns();
});
$scope.currentGroup = new Object();
$scope.currentGroup.name = 'account-details';
$scope.openGroup = function(groupName) {
if ($scope.currentGroup.name == groupName) {
$scope.currentGroup.name = 'none';
} else {
$scope.currentGroup.name = groupName;
}
$ionicScrollDelegate.scrollTop(true);
}
$scope.isGroupShown = function(groupName) {
return $scope.currentGroup.name == groupName;
}
$scope.$on('open-recently-submitted', function(){
$scope.loadDesigns();
$scope.openGroup('recently-submitted');
});
})
.controller('LoginCtrl', function($rootScope, $scope, $localStorage, AuthService) {
$scope.loginDetails = {
email : $localStorage.get('_loginEmail'),
password : $localStorage.get('_loginPassword'),
isRememberEmail : ($localStorage.get('_rememberEmail', false)==="true"?true:false),
isRememberPassword : ($localStorage.get('_rememberPassword', false)==="true"?true:false)
}
$scope.loggingIn = false;
$scope.doLogin = function() {
$scope.loggingIn = true;
$scope.loginErrors = [];
if (!$scope.loginDetails.email || $scope.loginDetails.email.length < 1) {
$scope.loginErrors.push("You must enter an email address to login");
}
if (!$scope.loginDetails.password || $scope.loginDetails.password.length < 1) {
$scope.loginErrors.push("You must enter a password to login");
}
if ($scope.loginErrors.length == 0) {
$localStorage.set('_rememberEmail', $scope.loginDetails.isRememberEmail);
$localStorage.set('_rememberPassword', $scope.loginDetails.isRememberPassword);
if ($scope.loginDetails.isRememberEmail) {
$localStorage.set('_loginEmail', $scope.loginDetails.email);
} else {
$localStorage.set('_loginEmail', '');
}
if ($scope.loginDetails.isRememberPassword) {
$localStorage.set('_loginPassword', $scope.loginDetails.password);
} else {
$localStorage.set('_loginPassword', '');
}
AuthService.login($scope.loginDetails.email, $scope.loginDetails.password, $rootScope.isDesignerSite);
} else {
$scope.loggingIn = false;
}
};
$scope.$on('auth-login-success', function(){
$scope.loggingIn = false;
setTimeout($rootScope.closeLogin, 1000);
$rootScope.$broadcast('load-details');
$scope.loggingIn = false;
$scope.$apply();
});
$scope.$on('auth-login-fail', function(event, args){
$scope.loginErrors.push(args.errorMessage.message);
$scope.loggingIn = false;
$scope.$apply();
});
})
.controller('RegisterCtrl', function($rootScope, $scope, $localStorage, AuthService) {
$scope.registerDetails = new Object();
$scope.registering = false;
$scope.doRegister = function() {
$scope.registering = true;
$scope.registerErrors = [];
if (!$scope.registerDetails.firstName || $scope.registerDetails.firstName.length < 1) {
$scope.registerErrors.push("You must choose a First Name.");
}
if (!$scope.registerDetails.lastName || $scope.registerDetails.lastName.length < 1) {
$scope.registerErrors.push("You must choose a Last Name.");
}
if (!$scope.registerDetails.email || $scope.registerDetails.email.length < 5 || !$scope.isValidEmailAddress($scope.registerDetails.email)) {
$scope.registerErrors.push("You must enter a valid Email Address.");
}
if (!$scope.registerDetails.password || $scope.registerDetails.password.length < 1) {
$scope.registerErrors.push("You must enter a password to register");
} else if(!$scope.isValidPasswordComplexEnough($scope.registerDetails.password)) {
$scope.registerErrors.push("Your password is not complex enough. Please make it longer, use upper and lower case, and/or include some non-standard characters.");
} else if ($scope.registerDetails.password != $scope.registerDetails.password2) {
$scope.registerErrors.push("Your confirmed password does not match the first one. Please re-enter them to make sure we have your correct password.");
}
if ($scope.registerErrors.length == 0) {
$localStorage.set('_loginEmail', $scope.registerDetails.email);
AuthService.register($scope.registerDetails.firstName, $scope.registerDetails.lastName, $scope.registerDetails.email, $scope.registerDetails.phoneNumber, $scope.registerDetails.password);
} else {
$scope.registering = false;
}
};
$scope.$on('auth-register-phase1-success', function(event, args){
AuthService.registerPhase2($scope.registerDetails.firstName, $scope.registerDetails.lastName, $scope.registerDetails.email, $scope.registerDetails.phoneNumber, $scope.registerDetails.password);
});
$scope.$on('auth-register-fail', function(event, args){
$scope.registerErrors.push(args.errorMessage.message);
$scope.registering = false;
$scope.$apply();
});
$scope.$on('auth-register-success', function(){
$scope.registering = false;
$scope.registerDetails.firstName = "";
$scope.registerDetails.lastName = "";
$scope.registerDetails.email = "";
$scope.registerDetails.password = "";
$scope.registerDetails.password2 = "";
setTimeout($rootScope.closeRegister, 1000);
AuthService.details();
AuthService.balance();
});
$scope.isValidPasswordComplexEnough = function() {
var pass = $scope.registerDetails.password;
var score = 0;
if (!pass) return score;
// award every unique letter until 5 repetitions
var letters = new Object();
for (var i=0; i
50;
}
$scope.isValidEmailAddress = function(theEmail) {
var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(theEmail);
};
})
.controller('StartCtrl', function($rootScope, $scope, $state, $ionicLoading, $ionicScrollDelegate, Camera, Session, DesignService) {
$scope.canTakePhotos = function() {
return (navigator && navigator.camera);
}
$scope.canPickFromGallery = function() {
return (navigator && navigator.camera);
}
$scope.myModel = null;
$scope.resetModel = function() {
$scope.myModel = new Object();
$scope.myModel.height = 10;
$scope.myModel.material = "colorSandstone";
$scope.submitErrors = [];
$scope.submittingModel = false;
}
$scope.resetModel();
$scope.makeMyModel = function() {
$scope.submittingModel = true;
if(!Session.loggedIn) {
$rootScope.showLogin('actually-make-model');
$scope.submittingModel = false;
return;
}
$scope.actuallyMakeMyModel();
}
$scope.getCost = function() {
return 15 + ($scope.myModel.height * 4);
}
$scope.actuallyMakeMyModel = function() {
$ionicLoading.show({
template: 'Submitting Model. Please wait'
});
$scope.submitErrors = [];
if (!$scope.uploadDetails.url) {
$scope.submitErrors.push("You must choose and upload a photo!!!");
}
if (!$scope.myModel.material) {
$scope.submitErrors.push("You must select a material!!!");
}
if (!$scope.myModel.name) {
$scope.submitErrors.push("You must enter a name for your model!!!");
}
if ($scope.submitErrors.length > 0) {
$ionicLoading.hide();
$ionicScrollDelegate.scrollBottom(true);
$scope.submittingModel = false;
return;
}
DesignService.submitDesign($scope.myModel.name, $scope.uploadDetails.url, ($scope.myModel.circularBase && true), ($scope.myModel.loop && true), $scope.myModel.height, $scope.myModel.material, $scope.myModel.additionalInfo, $scope.imgRotate).then(function(response) {
if (response.data.success) {
$ionicLoading.hide();
$state.go('tab.account');
setTimeout(function() {$rootScope.$broadcast('open-recently-submitted');}, 500)
setTimeout(function() {$rootScope.makePayment(response.data.id);}, 500)
$scope.resetModel();
} else {
$ionicLoading.hide();
$scope.submitErrors.push(response.data.errorMessage);
}
$scope.submittingModel = false;
}, function(response) {
$ionicLoading.hide();
$scope.submitErrors.push("System error. Please try again, and contact us if this error continues.");
$ionicScrollDelegate.scrollBottom(true);
$scope.submittingModel = false;
});
}
$scope.$on('actually-make-model', function(){
$scope.submittingModel = true;
setTimeout($scope.actuallyMakeMyModel, 2000);
});
$scope.getPhoto = function() {
Camera.getPicture().then(function(imageURI) {
$scope.photoImageUrl = imageURI;
console.log(imageURI);
}, function(err) {
console.err(err);
});
};
$scope.uploadErrors = [];
$scope.uploadDetails = {
url: null
};
$scope.imgRotate = 0;
$scope.imgHeight = null;
$scope.imgWidth = null;
$scope.rotatePicture = function() {
$scope.imgRotate += 90;
if ($scope.imgRotate == 360) $scope.imgRotate = 0;
//var imgEl = angular.element(document.querySelector('#dcUploadedImage'));
// $scope.picDimensions();
}
$scope.picDimensions = function() {
var imgEl = document.getElementById('dcUploadedImage');
if (imgEl) {
var imgBox = imgEl.getBoundingClientRect();
var imgHeight = imgBox.bottom - imgBox.top;
var imgWidth = imgBox.right - imgBox.left;
if (imgHeight > imgWidth) { // portrait
$scope.imgHeight = imgHeight;
$scope.imgWidth = imgWidth;
} else { // landscape
$scope.imgHeight = imgWidth;
$scope.imgWidth = imgHeight;
}
if ($scope.imgHeight > 400) $scope.imgHeight = 400;
if ($scope.imgWidth > 400) $scope.imgWidth = 400;
}
}
$scope.uploadFile = function(files) {
$scope.uploadErrors = [];
if (!files || files.length != 1) {
$scope.uploadErrors.push("You must upload one (and only one) image");
$scope.$apply();
return;
}
if (files[0].type.indexOf("jpeg") < 0 && files[0].type.indexOf("bmp") < 0 && files[0].type.indexOf("gif") < 0 && files[0].type.indexOf("png") < 0 && files[0].type.indexOf("tif") < 0) {
$scope.uploadErrors.push("Image must be a JPEG, BMP, GIF, TIF or PNG.");
$scope.$apply();
return;
}
if (files[0].size > 10485760) {
$scope.uploadErrors.push("Image is too big - maximum file size is 10 Megabytes.");
$scope.$apply();
return;
}
$ionicLoading.show({
template: 'Uploading your image...'
});
DesignService.uploadFile(files[0]).then(function(response) {
$ionicLoading.hide();
if (response.success) {
$scope.uploadDetails.url = response.url;
} else {
$scope.uploadErrors.push(response.errorMessage);
}
});
/*
DesignService.uploadFile(files[0]).then(function(response) {
$ionicLoading.hide();
if (response.data.success) {
$scope.uploadDetails.url = response.data.url;
} else {
$scope.uploadErrors.push(response.data.errorMessage);
}
}, function(response) {
$ionicLoading.hide();
if (response.status && response.status == 413) {
$scope.uploadErrors.push("Error - Your image was too big to upload. Please try again with a smaller file.");
} else {
$scope.uploadErrors.push("Error - Could not upload your image.");
$scope.uploadErrors.push(response.statusText);
}
$scope.$apply();
});
*/
};
$scope.fileToUpload = 'none';
angular.element(document).find('input')[0].addEventListener('change', function (e) {
var theFile = e.target.files[0];
$scope.fileToUpload = theFile.name;
// save the file object
}, false);
$scope.initialiseDropBox = function() {
//============== DRAG & DROP =============
// source for drag&drop: http://www.webappers.com/2011/09/28/drag-drop-file-upload-with-html5-javascript/
if ($rootScope.isFileDraggable) {
var dropbox = document.getElementById("dropbox");
if (!dropbox) {
setTimeout($scope.initialiseDropBox, 500);
return;
}
$scope.dropText = 'Drop files here...'
// init event handlers
function dragEnterLeave(evt) {
evt.stopPropagation()
evt.preventDefault()
$scope.$apply(function(){
$scope.dropText = 'Drop files here...'
$scope.dropClass = ''
})
}
dropbox.addEventListener("dragenter", dragEnterLeave, false)
dropbox.addEventListener("dragleave", dragEnterLeave, false)
dropbox.addEventListener("dragover", function(evt) {
evt.stopPropagation()
evt.preventDefault()
var clazz = 'not-available'
var ok = evt.dataTransfer && evt.dataTransfer.types && evt.dataTransfer.types.indexOf('Files') >= 0
$scope.$apply(function(){
$scope.dropText = ok ? 'Drop files here...' : 'Only files are allowed!'
$scope.dropClass = ok ? 'over' : 'not-available'
})
}, false)
dropbox.addEventListener("drop", function(evt) {
console.log('drop evt:', JSON.parse(JSON.stringify(evt.dataTransfer)))
evt.stopPropagation()
evt.preventDefault()
$scope.$apply(function(){
$scope.dropText = 'Drop files here...'
$scope.dropClass = ''
})
var files = evt.dataTransfer.files
if (files.length > 0) {
$scope.$apply(function(){
$scope.files = []
for (var i = 0; i < files.length; i++) {
$scope.files.push(files[i])
}
})
}
}, false)
}
}
$scope.initialiseDropBox();
//============== DRAG & DROP =============
$scope.setFiles = function(element) {
$scope.$apply(function($scope) {
console.log('files:', element.files);
// Turn the FileList object into an Array
$scope.files = []
for (var i = 0; i < element.files.length; i++) {
$scope.files.push(element.files[i])
}
$scope.photoImageUrl = element.files[0].fileName;
$scope.progressVisible = false
});
};
$scope.uploadFile2 = function() {
var fd = new FormData()
for (var i in $scope.files) {
fd.append("uploadedFile", $scope.files[i])
}
var xhr = new XMLHttpRequest()
xhr.upload.addEventListener("progress", uploadProgress, false)
xhr.addEventListener("load", uploadComplete, false)
xhr.addEventListener("error", uploadFailed, false)
xhr.addEventListener("abort", uploadCanceled, false)
xhr.open("POST", "/fileupload")
$scope.progressVisible = true
xhr.send(fd)
}
function uploadProgress(evt) {
$scope.$apply(function(){
if (evt.lengthComputable) {
$scope.progress = Math.round(evt.loaded * 100 / evt.total)
} else {
$scope.progress = 'unable to compute'
}
})
}
function uploadComplete(evt) {
/* This event is raised when the server send back a response */
alert(evt.target.responseText)
}
function uploadFailed(evt) {
alert("There was an error attempting to upload the file.")
}
function uploadCanceled(evt) {
$scope.$apply(function(){
$scope.progressVisible = false
})
alert("The upload has been canceled by the user or the browser dropped the connection.")
}
})
.controller('DesignerCtrl', function($window, $rootScope, $scope, $state, $ionicPopup, $ionicScrollDelegate, $ionicLoading, $ionicModal, Session, DesignService) {
$scope.fileToUpload = null;
$scope.designsNew = [];
$scope.designsMineToModel = [];
$scope.designsMinePendingApproval = [];
$scope.designsMineApproved = [];
$scope.designsMineToModel = [];
$scope.designsMineCompleted = [];
$scope.designsMineCancelled = [];
$scope.resetDesigns = function() {
$scope.designsNew = [];
$scope.designsMineToModel = [];
$scope.designsMinePendingApproval = [];
$scope.designsMineApproved = [];
$scope.designsMineToModel = [];
$scope.designsMineInProduction = [];
$scope.designsMineCompleted = [];
$scope.designsMineCancelled = [];
$scope.fileToUpload = null;
}
$scope.modelFilesPendingUpload = 0;
$scope.videoFilesPendingUpload = 0;
$scope.uploadErrors = [];
$scope.modelFilesToUpload = null;
$scope.setFiles = function(files) {
$scope.modelFilesToUpload = files;
$scope.$apply();
}
$scope.videoFilesToUpload = null;
$scope.setVideoFiles = function(files) {
$scope.videoFilesToUpload = files;
$scope.$apply();
}
$scope.uploadFiles = function(design) {
var designId = design.id;
var files = $scope.modelFilesToUpload;
$scope.uploadErrors = [];
$scope.fileToUpload = files;
if (files && files.length > 0) {
$ionicLoading.show({
template: 'Uploading your files...'
});
for (var i=0;i < files.length;i++) {
$scope.modelFilesPendingUpload++;
if (!files[i].name.endsWith(".zip")) {
// do something
alert("We expect a zip file!");
$ionicLoading.hide();
return;
}
DesignService.uploadModelFile(files[i], design.designId).then(function(response) {
$scope.modelFilesPendingUpload--;
if (response.success) {
design.modelUrl = response.url;
DesignService.setModelUrl(design.designId, design.modelUrl).then(function(response) {
if (response.data.success) {
alert ("Model Uploaded - thank you. Now upload the video for the customer.");
} else {
$scope.uploadErrors.push(response.errorMessage);
}
if ($scope.modelFilesPendingUpload == 0) {
$ionicLoading.hide();
$scope.resetDesigns();
$scope.loadMine();
}
});
} else {
$scope.uploadErrors.push(response.errorMessage);
if ($scope.modelFilesPendingUpload == 0) {
$ionicLoading.hide();
$scope.resetDesigns();
$scope.loadMine();
}
}
});
}
}
};
$scope.uploadVideos = function(design) {
var designId = design.id;
var files = $scope.videoFilesToUpload;
$scope.uploadErrors = [];
$scope.videoFileToUpload = files;
if (files && files.length > 0) {
$ionicLoading.show({
template: 'Uploading your files...'
});
for (var i=0;i < files.length;i++) {
$scope.videoFilesPendingUpload++;
if (!files[i].name.endsWith(".mp4") && !files[i].name.endsWith(".mov")) {
// do something
alert("We expect a mov or mp4 file!");
$ionicLoading.hide();
return;
}
DesignService.uploadVideoFile(files[i], design.designId).then(function(response) {
$scope.VideoFilesPendingUpload--;
if (response.success) {
design.videoUrl = response.url;
design.videoUrlToShow = response.url.substring(response.url.lastIndexOf("/"));
DesignService.setVideoUrl(design.designId, design.videoUrl).then(function(response) {
if (response.data.success) {
alert ("Video Uploaded - thank you. You may now submit the model for Approval.");
} else {
$scope.uploadErrors.push(response.errorMessage);
}
if ($scope.videoFilesPendingUpload == 0) {
$ionicLoading.hide();
$scope.resetDesigns();
$scope.loadMine();
}
});
} else {
$scope.uploadErrors.push(response.errorMessage);
if ($scope.videoFilesPendingUpload == 0) {
$ionicLoading.hide();
$scope.resetDesigns();
$scope.loadMine();
}
}
});
}
}
};
$scope.uploadNow = function(designId) {
DesignService.uploadFile($scope.fileToUpload[0]).then(function(response) {
if (response.data.success) {
for(var i=0; i< $scope.designsMineToModel.length; i++) {
if ($scope.designsMineToModel[i].id == designId) {
$scope.designsMineToModel[i].modelUrl = response.data.url;
$scope.show3DModel(response.data.url);
// $scope.render3DModel(designId, response.data.url);
}
}
} else {
$scope.uploadErrors.push(response.data.errorMessage);
}
});
};
$scope.loadNewDesigns = function() {
if(Session.loggedIn) {
$scope.refreshing = true;
DesignService.getNewDesigns().then(function(designResponse) {
if (designResponse.data.success) {
$scope.designsNew = designResponse.data.designs;
} else {
$scope.resetDesigns();
}
$scope.refreshing = false;
});
}
}
$scope.loadMine = function() {
if(Session.loggedIn) {
DesignService.getMineAsDesigner().then(function(designResponse) {
if (designResponse.data.success) {
$scope.designsMineToModel = [];
$scope.designsMinePendingApproval = [];
$scope.designsMineApproved = [];
$scope.designsMineToModel = [];
$scope.designsMineInProduction = [];
$scope.designsMineCompleted = [];
$scope.designsMineCancelled = [];
for (var i=0; icreate a 3D model as specified. Please try to upload the 3D model within 1 hour. If after 4 hours a 3D model has not been received, then you will receive a negative mark on your reputation and the model will be returned to the pool for others to take.
Please only continue if you agree to these terms.'
});
confirmPopup.then(function(res) {
if(res) {
DesignService.takeDesign(designId, userId).then(function(designResponse) {
if (designResponse.data.success) {
$scope.takeDesignErrors[designId] = null;
$scope.takeDesignSuccesses[designId] = true;
} else {
$scope.takeDesignErrors[designId] = designResponse.data.errorMessage;
}
$state.go('tab.designerModel');
$scope.loadNewDesigns();
$scope.loadMine();
$scope.$apply();
});
} else {
console.log('You are not sure');
}
$scope.takingDesign = false;
});
}
$scope.approve = function(designId) {
var confirmPopup = $ionicPopup.confirm({
title: 'Approve This Design?',
template: 'By approving this Design you are indicating that it is suitable and ready for 3D printing. This version will then be presented to the customer.'
});
confirmPopup.then(function(res) {
if(res) {
DesignService.requestApprovalDesign(designId).then(function(designResponse) {
if (designResponse.data.success) {
// success
} else {
// fail
}
$scope.loadMine();
$ionicScrollDelegate.scrollTop(true);
});
} else {
console.log('You are not sure');
}
});
}
$scope.markAsInProduction = function(designId) {
var confirmPopup = $ionicPopup.confirm({
title: 'In Production?',
template: 'Confirm this is successfully in production.'
});
confirmPopup.then(function(res) {
if(res) {
DesignService.markAsInProduction(designId).then(function(designResponse) {
if (designResponse.data.success) {
// success
} else {
// fail
}
$scope.loadMine();
$ionicScrollDelegate.scrollTop(true);
});
} else {
console.log('You are not sure');
}
});
}
$scope.downloadModelFiles = function(designId) {
$window.open("/api/designer/model-files/"+designId, '_blank');
}
$scope.markAsCompleted = function(designId) {
var confirmPopup = $ionicPopup.confirm({
title: 'Completed?',
template: 'Confirm this is model is Completed.'
});
confirmPopup.then(function(res) {
if(res) {
DesignService.markAsCompleted(designId).then(function(designResponse) {
if (designResponse.data.success) {
// success
} else {
// fail
}
$scope.loadMine();
$ionicScrollDelegate.scrollTop(true);
});
} else {
console.log('You are not sure');
}
});
}
$scope.$on('auth-details-success', function(){
$scope.loadNewDesigns();
$scope.loadMine();
});
$scope.currentGroup = new Object();
$scope.currentGroup.name = 'ready-for-modelling';
$scope.openGroup = function(groupName) {
if ($scope.currentGroup.name == groupName) {
$scope.currentGroup.name = 'none';
} else {
$scope.currentGroup.name = groupName;
}
$ionicScrollDelegate.scrollTop(true);
}
$scope.isGroupShown = function(groupName) {
return $scope.currentGroup.name == groupName;
}
$scope.downloadImage = function(design) {
$window.open(design.imgUrl, '_blank');
}
})
.controller('ModelCtrl', function($rootScope, $scope, Session, DesignService) {
var scene;
var camera;
var renderer;
var model;
})
;