Sails.js cannot update display gallery for updating into mongoDB - javascript

I am trying to update a program for updating and inserting into mongodb, but I keep getting an error. Let me paste the relevant code here, and I hope to get some help.
PosProductVariant.js
module.exports = {
schema : true,
attributes: {
// unique name identifier
name : { type: 'text', unique : true , required : true },
product : { model : 'PosCustomProduct' },
additionalPrice : { type : 'integer', defaultsTo: 0 },
// assets
display : { model : 'CmsProductVariant' },
// store referrer
store : { model : 'SystemStore' }
}
};
CmsProductVariant.js
module.exports = {
schema : true,
attributes: {
// custom product variant reference
product : { model : 'PosProductVariant' },
// custom title
title : { type : 'string' },
gallery : { type : 'array' , defaultsTo : [] }, // main gallery
}
};
PosProductController.js
module.exports = {
updatePricing : function(req,res,next){
// get pricing parameters
var pricing = req.allParams(),
query = {};
// parameters violation
if(!pricing.additionalPrice)
return res.badRequest();
// compose query
for(var attr in pricing){
if(attr !== 'additionalPrice' && _.isArray(pricing[attr])){
query[attr] = pricing[attr];
}
}
sails.log.verbose('pricing parameter');
sails.log.verbose(pricing);
sails.log.verbose('update query');
sails.log.verbose(query);
PosProductVariant.update(query,{
additionalPrice : pricing.additionalPrice,
display : pricing.display.gallery
})
.then(function(_variant){
if(!_variant) throw 'Cant update Variant';
res.ok();
})
.catch(function(error){
sails.log.error(error);
res.serverError(error);
});
}
};
pricing.html
<form class="grid-fluid grid-parent" name="pricingForm" ng-if="isDefined(product)"
ng-disabled="isProcessing" ng-submit="updatePricing()" novalidate>
<div class="form-group grid-50" ng-repeat="(attr, options) in product.attributes">
<label>{{attr}}</label>
<select multiple ng-model="pricing[attr]" class="form-control" ng-options="option for option in options" required></select>
</div>
<div class="form-group grid-100">
<label>add price</label>
<input type="number" class="form-control" ng-model="pricing.additionalPrice" placeholder="add price" required />
</div>
<div class="form-group grid-100">
<carousel class="bg-dark">
<slide ng-repeat="slide in pricing.display.gallery" active="slide.active" index="$index">
<img ng-src="{{slide.gallery}}" style="margin:auto;">
<div class="carousel-caption">
<a class="button button-error button-labeled"
ng-click="removeItem(pricing.display.gallery,$index)">
<span class="button-label"><i class="icon icon-trash-a"></i></span>
delete image
</a>
</div>
</slide>
</carousel>
<hr/>
<div class="form-group">
<label>tambahan galeri</label>
<file-uploader class="form-control"
image-width="{{galleryConfigs.width}}"
image-height="{{galleryConfigs.height}}"
image-crop-width="{{galleryConfigs.width}}"
image-crop-height="{{galleryConfigs.height}}"
max-size="5000"
allowed-extensions="png,jpeg,jpg"
result-model="addGallery">
</file-uploader>
</div>
</div>
<!-- action -->
<div class="form-group grid-100">
<hr/>
<button type="submit" class="button button-primary button-labeled"
ng-disabled="pricingForm.$invalid || pricingForm.$pristine || isProcessing" >
<span class="button-label"><i class="icon icon-paper-airplane"></i></span>
Update Pricing
</button>
<button class="button button-default button-labeled pull-right" role="action"
ng-click="goBack()" ng-disabled="isProcessing">
<span class="button-label"><i class="icon icon-android-close"></i></span>
Back
</button>
</div>
</form>
And controller pricing.js
var store = {},
id = $stateParams.modelId,
filter = {};
// get current active store
store = authService.getCurrentStore($scope);
if(!store){
// session expired
$scope.$emit(GLOBAL_EVENTS.SYSTEM.STORE.SESSION_TIMEOUT);
return;
}
// init scope
$scope.product = {};
$scope.pricing = {
display: {
gallery: []
}
};
moduleConfigResolver.syncStoreConfig(store.id)
.then(function(STORE_CONFIG){
// get gallery image size configs
$scope.galleryConfigs = {
height : [STORE_CONFIG.POS_PRODUCT_ZOOM_HEIGHT,
STORE_CONFIG.POS_PRODUCT_GALLERY_HEIGHT,
STORE_CONFIG.POS_PRODUCT_THUMBNAIL_HEIGHT],
width : [STORE_CONFIG.POS_PRODUCT_ZOOM_WIDTH,
STORE_CONFIG.POS_PRODUCT_GALLERY_WIDTH,
STORE_CONFIG.POS_PRODUCT_THUMBNAIL_WIDTH]
};
});
// add gallery image
$scope.addGallery = function(imageSrc){
if(!angular.isArray(imageSrc) || imageSrc.length < 3)
return;
$scope.pricing.display.gallery.push({
zoom : imageSrc[0],
gallery : imageSrc[1],
thumbnail : imageSrc[2]
});
};
// if has url params
if(id){
dataProvider.CustomProduct.get({'id':id}).$promise
.then(function(_product_customize){
$scope.product = angular.copy(_product_customize);
})
.catch(function(error){
$log.error(error);
});
It looks to me that the form does not submit data gallery, as the parameters are printed as undefined/null in my posproductcontroller and get an error.
{
"error": "E_VALIDATION",
"status": 400,
"summary": "1 attribute is invalid",
"model": "CmsProductVariant",
"invalidAttributes": {
"hashedPassword": [
{
"display": CmsProductVariant,
"message": "`undefined` should be a string (instead of \"null\", which is a object)"
}
]
}
}
what is my problem with my code? Help me please Sir?

Related

Pass parameters via GET to return filter

I want to return a data query via GET to return me values according to what is selected in the v-model.
I would like to know how to get the v-model values from the input and make the request to get by parameter
My filter (the components are already returning object as your id according to what I select)
<div class="row gutter-sm">
<div class="col-md-12">
<q-card class="full-width bg-white q-pa-md q-card-flex">
<div class="col-md-2">
<situacao-select multiple v-model="situacao" :stackLabel="'Situação OS'" style="height:50px;" :clearable="true" />
</div>
<div class="col-md-2">
<input-holder label="Help Desk" style="height:50px;">
<pessoa-funcao-select :funcao="'Help Desk'" :clearable="true" />
</input-holder>
</div>
<div class="col-md-2">
<input-holder label="Supervisor" style="height:50px;">
<pessoa-funcao-select :funcao="'Supervisor'" :clearable="true" />
</input-holder>
</div>
<div class="col-auto">
<q-btn
color="primary"
style="margin-left: auto; margin-right: auto;"
#click="search = false"
>FILTER</q-btn>
</div>
</div>
</q-card>
Request the API (I know it is wrong, I would like to know how to request with the parameter according to what the GET requests)
mounted() {
this.refresh()
},
methods: {
refresh () {
this.$axios.get()
this.$axios.get("/Operacional/GetRelatorio").then(res => {
this.prazos = res.data
this.$refs.chart1.updateSeries([{
name: 'NO PRAZO',
data: [this.prazos.noPrazo, this.prazos.emDia, this.prazos.atrasadas]
}])
})
this.$axios.get("/Operacional/GetAprovadas").then(res => {
this.os = res.data
})
this.$axios.get("/Operacional/GetPendenciasOS").then(res => {
this.os = res.data
this.$refs.chart4.updateSeries([{
name: 'EM DIA',
data: [ this.os.emdiaPendencia, this.os.emdiaSPendencia],
},{
name: 'ATRASADAS',
data: [ this.os.atrasadasPendencia, this.os.atrasadasSPendencia],
}
])
})
This is how you get that value you selected, let's say you want to use 'situacao'.
and pass that value to your backend via GET parameters:
refresh () {
this.$axios.get()
var selectedSituacao = this.situacao;
var url = "/Operacional/GetRelatorio?ID=" + selectedSituacao;
this.$axios.get(url).then(res => { .... })
// or you could do this:
var axiosParams = {
params: {
ID: selectedSituacao
}
}
this.$axios.get("/Operacional/GetRelatorio", axiosParams).then(res => { .... })
edit: Updated url get parameter situacao to ID as requested.

Save uploaded resume using javascript?

I'm exploring an API, but I'm stuck on how to upload a resume and save it using javascript/jQuery
Here is a link to the API, if you want to take a look.
The end goal is to have the resume loaded in an object. I only care about loading the uploaded file/resume
Here is the expected output:
let payload = {
"fields": [{
"key" : "resume", "value": {
"encoded_data" : "aGVsbG8gd29ybGQ=",
"file_name" : "resume.txt"
}
}],
"source" : "new website"
}
Here is the structure of the HTML file
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container" id="json-response">
<div class="form-container">
<div class="header">
<h1>Application form</h1>
</div>
<form action="#" class="applicantForm">
<div class="form-group">
<div class="input-group">
<label for="Resume">Resume <span>*</span></label>
<input class="form-control" type="file" name="Resume">
</div>
</div>
<button class="submit" type="submit">Apply Now</button>
</form>
</div>
</div>
Here is the javascript so far:
$(document).ready(function() {
const ApplyOpeningPayloadBuilder = function() {
let payload = {
"fields": [],
"source" : "new website"
};
return {
withKeyValue: function(key, value) {
let param = {};
param.key = key;
param.value = value;
payload.fields.push(param);
return this;
},
withFile: function(key, encoded_data, filename) {
let value = {};
value.encoded_data = encoded_data;
value.file_name = filename;
this.withKeyValue(key, value);
return this;
},
build: function() {
return payload;
}
}
}
let encoded_file = "aGVsbG8gd29ybGQ=";
$('.applicantForm').on('submit', function(e) {
e.preventDefault();
let apply_for_an_opening_payload_builder = new ApplyOpeningPayloadBuilder();
apply_for_an_opening_payload_builder.withFile("resume", encoded_file, this.value);
let payload = apply_for_an_opening_payload_builder.build();
console.log("Log uploaded resume:", payload);
});
})

Vue 1 class binding returning always false

I am working on this Laravel Social Network Script and it uses Vue 1.0.26.
My objetive is to bind the class connected or disconnected according to the user status which is true or false. I created a Laravel API to get the user status:
Controller (Laravel):
// $id = User id - https://www.mysite.uy/api/v1/status/{userid}
public function getUserStatus($id)
{
$active = false;
$open_session = \App\OpenSession::where('user_id', $id)->first();
if($open_session) {
if(Carbon::parse($open_session->created_at)->diffInSeconds(Carbon::parse($open_session->expires)) < 86400 && $open_session->active > 0) {
$active = true;
}
}
return response()->json($active);
}
This works fine from the URL, it returns true or false, but then here is some view.blade.php:
<li class="list-group-item" v-for="conversation in conversations.data" v-if="conversation.user"> <!-- Conversaciones -->
<a href="#" #click.prevent="showChatBox(conversation)">
<div class="media">
<div class="media-left">
<img v-bind:src="conversation.user.avatar" alt="images">
</div>
<div class="media-body">
<h4 class="media-heading">
#{{ conversation.user.name }}
<i v-bind:class="getUserStatus(conversation.user.id)"></i> <!-- <-- look at here -->
</h4>
<span class="pull-right active-ago" v-if="message">
<time class="microtime" datetime="#{{ message.created_at }}" title="#{{ message.created_at }}">
#{{ message.created_at }}
</time>
</span>
</div>
</div>
</a>
</li>
This block is being displayed as <i></i> on the HTML when using the getUserStatus() method on computed:
<h4 class="media-heading">
#{{ conversation.user.name }}
<i v-bind:class="getUserStatus(conversation.user.id)"></i> <!-- <-- look at here -->
</h4>
And this displays <i class="status disconnected"></i> even when the response.data is true and I check it with console.log(response.data == true):
<h4 class="media-heading">
#{{ conversation.user.name }}
<i v-bind:class="['status', getUserStatus(conversation.user.id) ? 'connected' : 'disconnected' ]"></i>
</h4>
And here is the Vue stuff:
data: {
status: {
on: 'connected',
off: 'disconnected'
},
},
created: {
...
},
methods: {
getUserStatus: function(userid)
{
this.$http.post(base_url + 'api/v1/status/' + userid).then(function(response) {
if(response.data == 'true') {
return true;
} else {
return false;
}
});
},
},
computed: {
/*getUserStatus: function(userid)
{
this.$http.post(base_url + 'api/v1/status/' + userid).then(function(response) {
return {
status: true,
connected: response.data == 'true',
disconnected: response.data == 'false'
}
});
}*/
}
I only have one of the methods "working", but I switch them. I am reading this guide but I get this is for Vue 2.
Ok, I made it work by adding a default variable in data and changing it later:
data: {
...
userStatus: {},
}
And in the method. As you can see I made some irrelevant changes on the Controller side.
methods: {
getUserStatus: function(userid)
{
var userStatus = this.$http.post(base_url + 'api/v1/status/' + userid).then(function(response) {
this.userStatus = JSON.parse(response.data);
});
return this.userStatus.status;
},
...
}
And in the HTML side I use:
<h4 class="media-heading">
#{{ conversation.user.name }}
<i class="status connected" v-bind:class="[ 'status', getUserStatus(conversation.user.id) ? 'connected' : 'disconnected' ]"></i>
</h4>
Now I have a different issue: The function seems to run repeteadly so the status are constantly changing. All the other functions runs once.

How to manage .json response data from custom REST in jhipster

I'm creating a new custom RESTful web service (managed with Spring framework) on a Jhipster app that search on objects Request containing a text that I give in input.
I tested the REST call from html and Angular.js and it works fine. The only one problem is that I don't know how could I parse the result in a html page instead of .json format.
My html code (located in "src/main/webapp/app/layouts/navbar/navbar.html") that call REST is this:
<form class="navbar" method="GET" action="/api/search">
<input style="margin-top: 2.8%; margin-right:2px;" class="btn" type="text" name="content" placeholder="Search requests..." />
<input style="margin-top: 2.8%; margin-right:5px;" class="btn btn-primary" type="submit" text="Search" value="Search">
</form>
My "navbarController.js" is this:
(function () {
'use strict';
angular
.module('businessRequestApp')
.controller('NavbarController', NavbarController);
NavbarController.$inject = ['$state', 'Auth', 'Principal', 'ProfileService', 'LoginService', 'Request'];
function NavbarController($state, Auth, Principal, ProfileService, LoginService, Request) {
var vm = this;
vm.isNavbarCollapsed = true;
vm.isAuthenticated = Principal.isAuthenticated;
ProfileService.getProfileInfo().then(function (response) {
vm.inProduction = response.inProduction;
vm.swaggerEnabled = response.swaggerEnabled;
});
vm.login = login;
vm.logout = logout;
vm.toggleNavbar = toggleNavbar;
vm.collapseNavbar = collapseNavbar;
vm.$state = $state;
vm.requests = [];
loadAll();
function loadAll() {
Request.query(function (result) {
vm.requests = result;
vm.searchQuery = null;
});
}
function login() {
collapseNavbar();
LoginService.open();
}
function logout() {
collapseNavbar();
Auth.logout();
$state.go('home');
}
function toggleNavbar() {
vm.isNavbarCollapsed = !vm.isNavbarCollapsed;
}
function collapseNavbar() {
vm.isNavbarCollapsed = true;
}
}
})();
My java REST ("RequestResource.java") is this:
#GetMapping("/search")
#Timed
public ResponseEntity<List<Request>> searchRequest(#RequestParam String content) {
log.debug("REST request to get Request : {}", content);
List<Request> requestsFounded = findByContentContaining(content);
return ResponseUtil.wrapOrNotFound(Optional.ofNullable(requestsFounded));
}
When I click the button I receive this .json (that is a list of matching Request that I searched for - based on parameter content give in input):
[ {
"id" : 13,
"requestTitle" : "Titolo",
"content" : "Richiesta",
"creationDate" : "2017-06-23",
"authorUsername" : "admin",
"author" : null,
"referencedTable" : {
"id" : 3,
"usersOnIt" : "",
"name" : "Tavolo 1"
}
}, {
"id" : 14,
"requestTitle" : "Voglio vedere Tiziano Ferro",
"content" : "Mi piacerebbe vedere tiziano per fare ...",
"creationDate" : "2017-06-25",
"authorUsername" : "admin",
"author" : null,
"referencedTable" : {
"id" : 4,
"usersOnIt" : "alfa",
"name" : "Tavolo 3"
}
}, {
"id" : 19,
"requestTitle" : "Titolo",
"content" : "Voglio vedere Marco",
"creationDate" : "2017-06-26",
"authorUsername" : "user",
"author" : null,
"referencedTable" : null
} ]
So, my final question is: how could I translate that .json objects list into an html table?
I've been searching a lot on the web but I found nothing, I hope someone will help me.
Thanks in advice for your time,
Manuel.
You can call a function on form submit and get the json in your vm instance inside your function
HTML
<form class="navbar" ng-submit="vm.getJson()">
<input style="margin-top: 2.8%; margin-right:2px;" class="btn" type="text" name="content" ng-model="vm.content" placeholder="Search requests..." />
<input style="margin-top: 2.8%; margin-right:5px;" class="btn btn-primary" type="submit" text="Search" value="Search">
</form>
<tr ng-repeat="value in json"><td>{{value }}</td></tr>
JS:
vm.getJson=function(){
$http.get("YourUrl",vm.content).then(function(response){
vm.json=response.data;
console.log(response);
})
}

ng-click(parameters) open a popup window with dropdown,then selected item and parameters sent to the service

I'm new to Angular-js. I'm using JSP for front end and passing values from UI to controller.Now I need to open a new popup list where user can select an option, then pass all parameters to service ..
ng-click="rewardRetry(singleWinner)"
controller --->
$scope.retryRewardDTO = {
"mobile_number" : null,
"draw_id" : 0,
"lottery_ticket_id" : 0,
"prize" : 0,
"reward_method" :null
};
(mobile_number,draw_id,lottery_ticket_id,prize) I can assign like this
$scope.rewardRetry = rewardRetry;
function rewardRetry(rewardRetryDTO) {
$scope.retryRewardDTO.draw_id=rewardRetryDTO.draw_id;
$scope.retryRewardDTO.lottery_ticket_id=rewardRetryDTO.lottery_ticket_id;
$scope.retryRewardDTO.prize=rewardRetryDTO.prize;
$scope.retryRewardDTO.mobile_number=rewardRetryDTO.mobile_number;
//$scope.retryRewardDTO.reward_method=rewardRetryDTO.reward_method;
}
But here retryRewardDTO.reward_method -->user should be select in popup option. (wallet,m_cash,reload,,, ....etc)
calling to service
winnerService.winnerService.rewardRetry(
$scope.retryRewardDTO,
function(data, headers) {
winnerSearch();
}, function() {
});
I'm trying do something like below link.but couldn't get a proper output.please some helps to me...
visit :AngularJS Modal Popup
Finally I found the answer and here implemented new rewardService
$scope.rewardRetry = rewardRetry;
function rewardRetry(rewardRetryDTO) {
$scope.retryRewardDTO.draw_id=rewardRetryDTO.draw_id;
$scope.retryRewardDTO.lottery_ticket_id=rewardRetryDTO.lottery_ticket_id;
$scope.retryRewardDTO.prize=rewardRetryDTO.prize;
$scope.retryRewardDTO.mobile_number=rewardRetryDTO.mobile_number;
//$scope.retryRewardDTO.reward_method=rewardRetryDTO.reward_method;
var modalOptions = {
bodyText : 'Are you sure you want to retry '+$scope.retryRewardDTO.prize+'/= reward for 0'+ $scope.retryRewardDTO.mobile_number+' ? Please select a reward method first and confirm'
};
rewardService.showModal({}, modalOptions).then(
function(result) {
$scope.retryRewardDTO.reward_method = result;
$('#retry-'+rewardRetryDTO.draw_id+'-'+rewardRetryDTO.lottery_ticket_id).hide();
$timeout(function() {
winnerService.winnerService.rewardRetry(
$scope.retryRewardDTO,
function(data, headers) {
winnerSearch();
}, function() {
});
});
});
}
;
My reward_option.jsp file
<%# taglib prefix="sec"
uri="http://www.springframework.org/security/tags"%>
<div class="option">
<div class="pull-right"></div>
<div>Copyright © Lucky889 2016</div>
<input type="hidden" value="<sec:authentication property="principal.userType" />" id="user_type" />
<input type="hidden" value="<sec:authentication property="principal.operator" />" id="user_operator" />
</div>
<script type="text/ng-template" id="rewardModalContent.html">
<div class="modal-header">
<h3>{{modalOptions.headerText}}</h3>
</div>
<div class="modal-body">
<p>{{modalOptions.bodyText}}</p>
<div class="modal-body">
<%-- <p ng-repeat="(key,singleReward) in modalOptions.rewardList">{{key}}----{{singleReward}}</p> --%>
<div class="form-group">
<label class="control-label" for="reward">Reward
Method</label><select name="reward" id="reward"
ng-model="reward_method" class="form-control">
<option ng-repeat="(key,singleReward) in modalOptions.rewardList"
value="{{key}}">{{singleReward}}</option>
</select>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-primary"
data-ng-click="modalOptions.confirm(reward_method)">{{modalOptions.actionButtonText}}</button>
<button type="button" class="btn"
data-ng-click="modalOptions.cancel()">{{modalOptions.closeButtonText}}</button>
</div>
</script>
Here is my rewardService
angular.module("zmessengerRewardApp.service", []).service(
'rewardService',
function(toastr, $uibModal, $log) {
var showHeaderErrorMessage = function(header) {
toastr.clear();
toastr.error(header['lms-message'],
header['lms-root-cause-message']);
};
var showHeaderSuccessMessage = function(header) {
toastr.clear();
toastr.success(header['lms-message'],
header['lms-root-cause-message']);
};
var modalDefaults = {
backdrop : true,
keyboard : true,
modalFade : true,
templateUrl : 'rewardModalContent.html'
};
var modalOptions = {
closeButtonText : 'Cancel',
actionButtonText : 'Confirm',
headerText : 'Confirmation',
bodyText : 'Perform this action?',
rewardList : {reload:'Auto Reload',manual_reload:'Manual Reload',ez_cash:'Ezcash',mcash:'MCash',wallet:'Wallet',bank:'Bank Transfer'}
};
function showModal(customModalDefaults, customModalOptions) {
if (!customModalDefaults)
customModalDefaults = {};
customModalDefaults.backdrop = 'static';
return show(customModalDefaults, customModalOptions);
};
function show(customModalDefaults, customModalOptions) {
// Create temp objects to work with since we're in a singleton
// service
var tempModalDefaults = {};
var tempModalOptions = {};
// Map angular-ui modal custom defaults to modal defaults
// defined in service
angular.extend(tempModalDefaults, modalDefaults,
customModalDefaults);
// Map modal.html $scope custom properties to defaults defined
// in service
angular.extend(tempModalOptions, modalOptions,
customModalOptions);
if (!tempModalDefaults.controller) {
tempModalDefaults.controller = function($scope,
$uibModalInstance) {
$scope.modalOptions = tempModalOptions;
$scope.modalOptions.confirm = function(result) {
$uibModalInstance.close(result);
};
$scope.modalOptions.cancel = function(result) {
$uibModalInstance.dismiss('cancel');
};
}
}
return $uibModal.open(tempModalDefaults).result;
};
return {
showHeaderErrorMessage : showHeaderErrorMessage,
showHeaderSuccessMessage : showHeaderSuccessMessage,
showModal : showModal,
};
});

Categories

Resources