We are using bookshelf.js with MySQL.
We have a Table: Contact(id, name, email_Id, updated_Contact_At)
bookshelf Query :
new Contact({id: 1}).save(
{name: 'Jhon Snow', email_Id: 'jhonsnow42#gmail.com', birthdate:'1998-10-21'},
{patch: true, default: false, require: true, method: 'update'}
);
which translates to :
Update Contact set name = "Jhon Snow",
email_Id = 'jhonsnow1212#gmail.com',
birthdate = '1998-10-21',
updated_Contact_At = 020-06-08T09:18:10.513Z
where id = 1;
after executing above query bookshelf fetches the same record:
select Contact.* from Contact where Contact.id = 1 limit 1
Is there any way in bookshelf.js to stop fetch call after updating record?
You can use autoRefresh = false while updating record
new Contact({id: 1}).save(
{name: 'Jhon Snow', email_Id: 'jhonsnow42#gmail.com', birthdate:'1998-10-21'},
{patch: true, default: false, require: true, method: 'update', autoRefresh : false}
);
use Bookshelf.js version: ^1.2.0
Related
i am using stripe on my ruby on rails 5 website for my payment gateway plans. I am using the api in the client-side just as it appears in this link. I need to add a coupon to my plan, I could create it in the stripe dashboard in the testmode like the plan but adding the id to the code doesn't redirect me to the stripe checkout page. this is my javascript code:
<script src="https://js.stripe.com/v3"></script>
<script type="text/javascript">
$(document).ready(function() {
var stripe = Stripe('<%= Rails.configuration.stripe[:publishable_key] %>');
$('.payment-action').on('click', function() {
const data = $(this).data();
const user_email = '<%= current_user ? current_user.email : ""%>'
const user = '<%= current_user.id%>'
stripe.redirectToCheckout({
lineItems: [{
// Define the product and price in the Dashboard first, and use the price
// ID in your client-side code. You may also pass a SKU id into the `price`
// field
price: data['plankey'],
quantity: 1
}],
customerEmail: user_email,
mode: 'subscription',
subscriptionData: {
coupon: 'WaS5wFHC'
},
successUrl: 'https://www.my_web.network/success_payment?session_id={CHECKOUT_SESSION_ID}&p_i='+data['plan']+'&us='+user,
cancelUrl: 'https://www.my_web.network/update_plan'
});
});
});
</script>
I've been trying to get it to appear on this page using subscription_data or subscriptionData but it still doesn't work, what could I be missing?
<script type="text/javascript">
$(document).ready(function() {
var stripe = Stripe('<%= Rails.configuration.stripe[:publishable_key] %>');
$('.payment-action').on('click', function() {
const data = $(this).data();
const user_email = '<%= current_user ? current_user.email : ""%>'
const user = '<%= current_user.id%>'
stripe.redirectToCheckout({
lineItems: [{
// Define the product and price in the Dashboard first, and use the price
// ID in your client-side code. You may also pass a SKU id into the `price`
// field
price: data['plankey'],
quantity: 1
}],
customerEmail: user_email,
mode: 'subscription',
subscription_data: {
coupon: 'WaS5wFHC'
},
successUrl: 'https://www.my_web.network/success_payment?session_id={CHECKOUT_SESSION_ID}&p_i='+data['plan']+'&us='+user,
cancelUrl: 'https://www.my_web.network/update_plan'
});
});
});
</script>
It's not possible to use coupons for subscriptions in client-side only Checkout. You'd have to create a Checkout Session on your server where you pass in your coupon ID: https://stripe.com/docs/api/checkout/sessions/create#create_checkout_session-subscription_data-coupon
I'm trying to add an sms api to Wordpress which sends an order confirmation message using Woocommerce hooks. After some research, I found the following code here which works the same way.
add_action('woocommerce_payment_complete', 'custom_process_order', 10, 1);
function custom_process_order($order_id) {
//Lets get data about the order made
$order = new WC_Order( $order_id );
//Now will fetch customer/buyer id here
$customer_id = $order->user_id;
//now finally we fetch phone number
$billing_phone = get_user_meta( $customer_id, 'billing_phone', true );
// Now put your HTTP SMS API URL . I PUT WHICH WE ARE USING
$jsonurl = "http://tsms.thirdeyegoa.com/api/sendmsg.php?user=USERNAME&pass=PASSWORD&sender=MYSENDERID&phone=".$billing_phone."&priority=ndnd&stype=normal&text=MY MESSAGE TO CUSTOMER.";
// NOW WILL CALL FUNCTION CURL
$json = curl($jsonurl);
return $order_id;
}
The Api Code my sms gateway provided is
// Include provided Java Script
<script language="javascript" src="https://domainapi.js" type="text/javascript"> </script>
<script language="javascript">
// Replace your API key at below line
var apikey = 'ABCDEFGH1234567890abcdefghQWERTY123=';
// Form your data object
var mail_details = { email : 'John.Doe#foo.com', msgid : '82', listname : '', prefix : '', firstname : 'John', middlename : '', lastname : 'Doe', telephone : '', address : '', city : '', state : '', pincode : '', country : '', mobile : '9999999999', designation : '', company : '', companyphone : '', birthdate : '', anniversary : '', extra1 : '', extra2 : '' }
call_api(apikey, 'sendSingleSMS', mail_details, function(response) { document.getElementById('show').innerHTML=response; });</script>
Please tell me how to integrate this API in the above script for Wordpress.
Presumably, you are trying to blend your API's script into the "WordPress way" and load some data from WooCommerce's order. First, you'd want to register your scripts in your main plugin file:
add_action( 'wp_enqueue_scripts', 'so_38554614_enqueue_scripts' );
function so_38554614_enqueue_scripts(){
wp_register_script( 'your-api', 'https://domainapi.js', array(), '1.0', true );
wp_register_script( 'your-script', 'path-to-your-script.js', array('your-api'), '1.0', true );
}
And then you'll want to load them on the payment complete page. You will also want to take advantage of wp_localize_script() to pass some variables to the script.
add_action('woocommerce_payment_complete', 'custom_process_order', 10, 1);
function custom_process_order($order_id) {
//Lets get data about the order made
$order = new WC_Order( $order_id );
wp_enqueue_script('your-api');
wp_enqueue_script('your-script');
$l18n = array( 'mail_details'=>
array(
email' => $order->billing_email,
'msgid' => 82,
'listname' => '',
'firstname' => $order->billing_first_name,
'middlename' => '',
'lastname' => $order->billing_last_name,
'telephone' => $order->billing_phone,
'address'= >$order->billing_address_1 . ' ' . $order->billing_address_2,
'city' => $order->billing_city,
'state' => $order->billing_state,
'pincode' => '',
'country' => $order->billing_country,
'mobile' => $order->billing_phone
'designation' => '',
'company' => $order->billing_company,
'companyphone' => '',
'birthdate' => '',
'anniversary' => '',
'extra1' => '',
'extra2' => ''
),
'apikey' => 'ABCDEFGH1234567890abcdefghQWERTY123=' );
wp_localize_script( 'your-script', 'Your_JS_Object', $l18n );
wp_localize_script()
return $order_id;
}
And finally, your javascript file, stored somewhere in your plugin. It takes advantage of the javascript object Your_JS_Object which was created by wp_localize_script():
// Java Script path-to-your-script.js
call_api( Your_JS_Object.apikey, 'sendSingleSMS', Your_JS_Object.mail_details, function(response) { document.getElementById('show').innerHTML=response; });
When start a new meanjs project (mongoose, angular etc.) using the generator and add a CRUD-module i get methods like this:
$scope.findOne = function() {
$scope.income = Incomes.get({
incomeId: $stateParams.incomeId
});
In my income server model is shown below, it has some different attributes and some different object types on these attributes, for example, number, date and string.
When i get data in my $scope.income after the promise "$scope.findOne" has succeded all my data are strings. Do i need to cast each and every one of them to their proper type?
In my front end i want to present the different types in the input elements of my "update" view. For example:
<label class="control-label" for="date">Date of transaction</label>
<div class="list-group-item">
<div class="controls">
<input type="date" data-ng-model="income.date" id="date" class="form-control" placeholder="Date" required>
</div>
This does not work since the object $scope.income.date consists of a string. Changing the input type to string makes it show up. But I want to use a date picker here.
Should I write something like:
$scope.findOne = function() {
Incomes.get({
incomeId: $stateParams.incomeId
}).then(function(data){
var dateVar=new Date(data.date);
var amountVar =Number(data.amount)
$scope.income ={date: dateVar, name: data.name, amount:amountVar}()
);
What is best practise here?
Model I am using:
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
/**
* Income Schema
*/
var IncomeSchema = new Schema({
name: {
type: String,
default: '',
required: 'Please fill Income name',
trim: true
},
amount: {
type: String,
default: '',
required: 'Please fill Income amount',
trim: true
},
date: {
type: Date,
default: '',
required: 'Please fill Income date',
trim: true
},
monthly: {
type: Boolean,
default: '',
required: 'Please fill whether income is recurring monthly',
trim: true
},
yearly: {
type: Boolean,
default: '',
required: 'Please fill whether income is recurring yearly',
trim: true
},
account: {
type: Schema.ObjectId,
ref: 'Account',
required: 'Please select account'
},
created: {
type: Date,
default: Date.now
},
user: {
type: Schema.ObjectId,
ref: 'User'
}
});
mongoose.model('Income', IncomeSchema);
First I had to get a hold of the promise, than I easily could build more complex objects from the Incomes.get response. The data is sent over the network as JSON and there fore it is just text, so I needed to instantiate it to the proper types using f ex. Date and Number:
Incomes.get({
incomeId: $stateParams.incomeId
}).$promise.then(function(data){
var dateVar=new Date(data.date);
var amountVar =Number(data.amount)
$scope.income ={date: dateVar, name: data.name, amount:amountVar}()
);
To make the resources function for remove work properly "this" needed to be used, dont forget that the promise is in another namespace so "that=this" is needed.
var that=this;
Incomes.get({
incomeId: $stateParams.incomeId
}).$promise.then(function(income){
income.date= new Date(income.date);
var recurringVar;
if(income.monthly===true){
recurringVar = 'monthly';
} else if( income.yearly===true){
recurringVar = 'yearly';
}
income.recurring=recurringVar;
that.income=income;
});
I'm attempting to create a Mongo document then update the document form a form to have additional properties, one of which has an array of objects.
I'm able to save everything except objects to the address array.
The following code snippets show my current attempt to save an object to the address array. I feel like I'm missing a push or shift which I've tried and can't seem to get syntax correct.
Mongoose Schema:
var UserSchema = new mongoose.Schema({
username: { type: String, lowercase: true }
, password: { type: String }
, email: { type: String, lowercase: true }
, phone: { type: String }
, newsletter: Boolean
, created: { type: Date, default: Date.now }
, address: [{
nickname: { type: String }
, streetAddress: { type: String }
, streetAddress2: { type: String }
, state: { type: String }
, zip: { type: String }
}]
});
Model Methods:
First I create an account. The form only asks for username, email, password then redirects to the jade file where users can fill out the rest of the form.
module.exports = exports = function(){
//create account
this.createAndSave = function (req, res ) {
new User({
username: req.body.username
, password: req.body.password
, email: req.body.email
, phone: req.body.phone
, address: [{
nickname: req.body.nickname
, streetAddress: req.body.streetAddress
, streetAddress2: req.body.streetAddress2
, state: req.body.state
, zip: req.body.zip
}]
}).save(function (err, user){
if (err) throw err;
req.session.isLoggedIn = true;
req.session.user = user.username;
res.redirect('/account/' + user.username)
})
}
//update account
this.updateRequest = function (req, res) {
User.update({username: req.user.username}, {
username: req.body.username
, email: req.body.email
, phone: req.body.phone
, newsletter: req.body.newsletter
, address: [{
nickname: req.body.nickname
, streetAddress: req.body.streetAddress
, streetAddress2: req.body.streetAddress2
, state: req.body.state
, zip: req.body.zip
}]
}, function (err) {
res.redirect("/account/" + req.body.username);
});
}
Jade Template: (I'm sure this could be cleaner)
h1 Edit User
#{user}
form(method="POST", action="/account/#{user.username}")
input(type="hidden", name="_method", value="PUT")
.form-group
label(for="username") Name
input#name.form-control(type="text", name="username", value= user.username )
.form-group
label(for="email") Email
input#email.form-control(type="email", name="email", value= user.email )
.form-group
label Phone
input#phone.form-control(type="text", name="phone", value= user.phone )
.form-group
label Newsletter Opt In/Out
input#newsletter(type="checkbox", name="newsletter", checked=(true===false ? "checked" : undefined))
if(user.address.length > 0)
for (var i = 0; i < user.shippingAddresses.length; i++) {}>)
.form-group
label Street Address
input#address.form-control(type="text", name="streetAddress", value= user.shippingAddresses[i].streetAddress )
.form-group
label Address Continued
input#address2.form-control(type="text", name="streetAddress2", value= user.shippingAddresses[i].streetAddress2 )
.form-group
label Zip Code
input#zip.form-control(type="text", name="zip", value= user.shippingAddresses[i].zip )
else
.form-group
label Location Nick Name
input#address.form-control(type="text", name="nickname", value= )
.form-group
label Street Address
input#address.form-control(type="text", name="streetAddress", value= )
.form-group
label Address Cont.
input#address2.form-control(type="text", name="streetAddress2", value= )
.form-group
label State
input#state.form-control(type="text", name="state", value= )
.form-group
label Zip Code
input#zip.form-control(type="text", name="zip", value= )
button(type="submit") Update Account
Additionally there is another address only form which is why the address is an array.
Any direction would be very helpful as I may go unhinged at any moment. If you any further code let me know.
Something else to note, I'm not able to get any of the updated data from the update function to save to mongo.
Thanks!
Here is the solution I came up with. I find the document to update and push an object to the property that stores the array.
Example method:
this.addAddress = function (req, res) {
var newAddress = {
nickname: req.body.nickname,
streetAddress: req.body.streetAddress,
streetAddress2: req.body.streetAddress2,
state: req.body.state,
zip: req.body.zip
}
User.update({username: req.session.user}, { $push : {
address: newAddress
}}, {upsert: true}, function ( err ) {
if(err){
console.log(err);
}else{
console.log("Successfully added");
}
})
}
app.Model.BrandModel = Backbone.Model.extend({
idAttribute: 'brandId',
defaults: {
name : '',
description : '',
brandImage : '',
user : '',
showPro : false,
proDescription : ''
},
url : function(){
return '/rest/brands/' + brandId;
}
});
I can see from firebug that my my server is returning the following JSON response.Also the request is successful.
brandId "fc692c70-4096-11e3-a0f2-3c970e02b4ec"
name "Galeria"
user "940ee800-4090-11e3-80c0-3c970e02b4ec"
description "This is galeria"
brandImage "/brand-images/fc692c70-...3-a0f2-3c970e02b4ec.jpg"
proDescription ""
showPro false
I am calling like this.
var brandModel = new app.Model.BrandModel();
brandModel.fetch();
but my model is not getting populated and the values are still default one.
my controller
#RequestMapping(value = "/rest/brands/{brandId}",
method = RequestMethod.GET,
produces = "application/json")
#ResponseBody
public Brand getBrand(#PathVariable("brandId") String brandId, HttpServletResponse response) {
I don't see where you are telling your code WHICH brandId to fetch... Have you tried this?
var brandModel = new app.Model.BrandModel({brandId: "fc692c70-4096-11e3-a0f2-3c970e02b4ec"});
brandModel.fetch();
More information: How do I fetch a single model in Backbone?
fetch performs an asynchronous HTTP (Ajax) request, so I passeed fetch a success callback and now i am seeing the modal values.
brandModel.fetch({
success: function(){
console.log(brandModel.toJSON());
}
});
Should be:
app.Model.BrandModel = Backbone.Model.extend({
idAttribute: 'brandId',
urlRoot : '/rest/brands/',
defaults: {
name : '',
description : '',
brandImage : '',
user : '',
showPro : false,
proDescription : ''
}
});
Then like #David mentioned:
var brandModel = new app.Model.BrandModel({brandId: "fc692c70-4096-11e3-a0f2-3c970e02b4ec"});
brandModel.fetch();
Also return '/rest/brands/' + brandId; probably should be return '/rest/brands/' + this.get("brandId");