restforce gem save only changed attriubtes? - ruby-on-rails

I'm using restforce to interat with salesforce in Ruby on Rails.
I have this snippet of code:
client = Restforce.new
acc = client.find("Account", account_ID)
acc.firstName = "test"
acc.save
# if I use update I get the same error
acc.update
But I get the following error
[
{
"message":"Unable to create/update fields: jigsaw_clean__Sync_Status_Indicator__c, LastModifiedDate, PhotoUrl, IsDeleted, jigsaw_clean__Jigsaw_Managed_Backend__c, jigsaw_clean__Sync_Status_Summary__c, AccPwr1__c, BillingAddress, jigsaw_clean__Duplicate__c, LastActivityDate, jigsaw_clean__Automatic_Updates__c, JigsawCompanyId, CreatedById, MasterRecordId, LastViewedDate, CreatedDate, LastReferencedDate, jigsaw_clean__Additional_Information__c, jigsaw_clean__Jigsaw_Last_Sync_Locked__c, Cross_Sell_Score__c, jigsaw_clean__Jigsaw_Managed__c, ShippingAddress, LastModifiedById, IANA_Number_field__c. Please check the security settings of this field and verify that it is read/write for your profile or permission set.",
"errorCode":"INVALID_FIELD_FOR_INSERT_UPDATE",
"fields":[
"jigsaw_clean__Sync_Status_Indicator__c",
"jigsaw_clean__Jigsaw_Managed_Backend__c",
"jigsaw_clean__Sync_Status_Summary__c",
"AccPwr1__c",
"BillingAddress",
"jigsaw_clean__Duplicate__c",
"LastActivityDate",
"jigsaw_clean__Automatic_Updates__c",
"CreatedById",
"MasterRecordId",
"jigsaw_clean__Additional_Information__c",
"jigsaw_clean__Jigsaw_Last_Sync_Locked__c",
"Cross_Sell_Score__c",
"jigsaw_clean__Jigsaw_Managed__c",
]
}
]
and other fields.
I know, I can do something like:
client = Restforce.new
acc = client.find("Account", account_ID)
acc1 = {Id: acc.Id}
acc1["firstName"] = "test"
client.update("Account", acc1)
How do I do this in a more efficient way?

Please check the security settings of this field and verify that it is read/write for your profile or permission set.
Are you sure that you have permission to make updates?

The only way I can find is the instead of using find we use query with fields that we want to update.
client = Restforce.new
acc1 = client.query("SELECT ID, firstName, LastName FROM Account where ID = '#{account_ID}'").first
acc1["firstName"] = "test"
acc1.save

Related

ODOO 12 : show field of model “purchase.order” in form view of “account.invoice”

I added commission field in purchase order model and i want to show it in account invoice when i click on "create bill". below is my code but it doesn't work, I hope somebody can help me. Many thanks in advance.
class ConfirmComm(models.Model):
_inherit = "purchase.order"
commission = fields.Float(string='Commission', required='true', default=0)
#api.multi
def action_view_invoice(self, cr, uid, order, context=None):
if context is None:
context = {}
journal_id = self.pool['account.invoice'].default_get(cr, uid, ['journal_id'], context=context)['journal_id']
if not journal_id:
raise UserError(_('Error!'),
_('Please define purchase journal for this company: "%s" (id:%d).') % (
order.company_id.name, order.company_id.id))
invoice_vals = {
'name': order.partner_ref or '',
'origin': order.name,
# 'type': 'in_invoice',
# Sale order id as source_id
# 'source_id': order.id,
'reference': order.partner_ref or order.name,
'account_id': order.partner_invoice_id.property_account_receivable.id,
'partner_id': order.partner_invoice_id.id,
'journal_id': journal_id,
'commission': order.commission,
# 'invoice_line': [(6, 0, lines)],
'currency_id': order.pricelist_id.currency_id.id,
# 'comment': order.note,
'payment_term_id': order.payment_term_id or False,
'fiscal_position_id': order.fiscal_position_id,
'date_invoice': context.get('date_invoice', False),
'company_id': order.company_id.id,
'user_id': order.user_id and order.user_id.id or False,
}
_logger.info("KTR this is commissionTest $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ %d", order.commission)
invoice_vals.update(self._inv_get(cr, uid, order, context=context))
return invoice_vals
You need to add this field to model account.invoice, too, because there is no direct relation between purchase.order and account.invoice to use a related field or something fancy. To see that field in the invoice form view, you have to add it there, too (as usual).
The rest of your code should be okay, because setting the value by using in it purchase.order.action_view_invoice() would be the next important part, but you've already done that ;-)

Shopify how to create Price Rule through API

I am new to shopify. Now I want to use shopify API to create a price rule, this is my source code here
I use rails 5.1.4, shopify_app 8.1.0
shop_url = "https://api_key:secret#domain/admin"
ShopifyAPI::Base.site = shop_url
prerequisite_saved_search_ids = [53677883419]
price_rule = ShopifyAPI::PriceRule.new
price_rule.title = "demodemo"
price_rule.target_name = "line_item"
price_rule.target_selection = "all"
price_rule.allocation_method = "across"
price_rule.value_type = "fixed_amount"
price_rule.value = "-10.0"
price_rule.customer_selection = "prerequisite"
price_rule.prerequisite_saved_search_ids = prerequisite_saved_search_ids
price_rule.start_at = Time.now.iso8601
res = price_rule.save
puts res
However it always return me false. If anyone has the idea? Thanks a million!
Please check this Api to create price rule(Shopify Api). I have used this Api in php and its working fine for me.
I have created App and then use Api key and secret key to generate price rule.
Thanks
For the ones coming to this question, one could fetch Price rules as per shopify_app gem for Rails applications as:
First allow your app to access read/write permissions in initializers/shopify.rb file as:
config.scope = "read_products, write_products, read_price_rules, write_price_rules"
After that you can fetch price rules as:
#price_rules = ShopifyAPI::PriceRule.find(:all, params:{id: '4171201931'})
And can also create a price rule as:
#create_price_rule = ShopifyAPI::PriceRule.new(
price_rule: {
title: "FREESHIPPING2",
target_type: "shipping_line",
target_selection: "all",
allocation_method: "each",
value_type: "percentage",
value: "-100.0",
usage_limit: 20,
customer_selection: "all",
prerequisite_subtotal_range: {
greater_than_or_equal_to: "50.0"
},
starts_at: "2017-11-19T17:59:10Z"
}
)
#create_price_rule.save
There are validations involved. Incase you want to check the response, one may inspect it like #create_price_rule.inspect
Or even you can delete a PriceRule as:
#price_rules = ShopifyAPI::PriceRule.find(:all).first
#price_rules.destroy
#last_price_rule = ShopifyAPI::PriceRule.find(4171860875)

Rails where / find_all with multiple id same column

Hello I'm looking for a clean way (overide .where method??) to retrieve from DB multiple rows with multiples ids of the same column,
Example:
# Actual ugly mode
args = {}
args[:channel] = common_channel
args[:writer] = userA
args[:receiver] = userB
journalsA = Journal.where args
args[:writer] = userB
args[:receiver] = userA
journalsB = Journal.where args
# #journals = journalsA + journalsB
How can I make something like this: Journals.where userA: userA, userB: userB, channel:x where user(A|B) points to writer and receiver at the same time
Do I need to use a custom SQL line or exist some fancy rails way to do this.
I think you can think of what you are asking as: Can you write a OR query in Rails? The answer is yes, but with SQL fragments:
Journal.where(channel: common_channel).where('(writer = ? AND receiver = ?) OR (writer = ? AND receiver = ?)', userA, userB, userB, userA)

Friends checkins with facebook graph api and rails - APIError

I am trying to get a users friends checkins, I am using omniauth and koala gem.
When a user gets saved this method hits:
def add_friends
friends_data = facebook.get_connections("me", "friends", :fields => "id, name, link, picture, gender, checkins")
friends_data.map do |h|
friend = Friend.new
friend.uid = h["id"]
friend.name = h["name"]
friend.image = h["picture"]
friend.gender = h["gender"]
friend.urls = h["link"]
friend.user_id = self.id
friend.save!
if (!h["checkins"].blank?)
checkin = Checkin.new
checkin.checkin_id = h["id"]
checkin.user_id = h["checkins"]["data"]["from"]["id"]
checkin.user_name = h["checkins"]["data"]["from"]["name"]
checkin.tags = h["checkins"]["tags"]["data"]["name"]
checkin.place_id = h["checkins"]["place"]["id"]
checkin.place_name = h["checkins"]["place"]["name"]
checkin.message = h["checkins"]["message"]
checkin.created_time = h["checkins"]["created_time"]
checkin.friend_id = friend.id
checkin.save!
end
end
end
But I get this error:
Koala::Facebook::APIError: HTTP 500: Response body: {"error_code":1,"error_msg":"An unknown error occurred"}
I dont really know what that means, any ideas? And does anybody know how to define a limit on checkins with the koala gem?
I tried something like this:
u.facebook.get_connections("me","friends", :fields => "checkins.limit(2)")
But I got the same error!
In fields, you're requesting information about a friend, but 'checkins' isn't a profile field, it's an entirely different connection altogether.
What you must do is loop through all the friend IDs and get the checkins for each:
friend_checkins = []
friend_ids = u.facebook.get_connections("me","friends", :fields => "id")
friend_ids.each do |friend_id|
friend_checkins << u.facebook.get_connections(friend_id,"checkins")
end
Also, when doing this, it would be a great time to look into batch requests with Koala, as you could potentially be making a lot of calls to the API here..

Spring Security UI Grails only search/create/edit users for the admin?

I am currently working on a solution in Grails and I have installed the following security plugins:
Spring Security Core
Spring Security UI
I will basically have a solution with the following security structure:
Super Users
Admins(For different business areas)
Users (within the different business areas)
So basically I installed the Spring Security UI in order to allow the various Business Area Admins manage their own areas, they should be able to use the UI in order to allow them to search only for users in thier own area, create users in their own area and edit users only in their own area. However the spring security UI gives people who have access blanket access do anything.
I have added an extra field to the spring security domain model which is "Area", so I was thinking when the admin is searching for users they would only see users in the same area as them, when they create a user they can only do so for their own area and they can only edit users in their own area.
Below is some code that the spring security UI uses to search for the users, can I modify this in order to only return the users that are in the same area as the admin who is currently logged in? or is there a better way?
def userSearch = {
boolean useOffset = params.containsKey('offset')
setIfMissing 'max', 10, 100
setIfMissing 'offset', 0
def hql = new StringBuilder('FROM ').append(lookupUserClassName()).append(' u WHERE 1=1 ')
def queryParams = [:]
def userLookup = SpringSecurityUtils.securityConfig.userLookup
String usernameFieldName = userLookup.usernamePropertyName
for (name in [username: usernameFieldName]) {
if (params[name.key]) {
hql.append " AND LOWER(u.${name.value}) LIKE :${name.key}"
queryParams[name.key] = params[name.key].toLowerCase() + '%'
}
}
String enabledPropertyName = userLookup.enabledPropertyName
String accountExpiredPropertyName = userLookup.accountExpiredPropertyName
String accountLockedPropertyName = userLookup.accountLockedPropertyName
String passwordExpiredPropertyName = userLookup.passwordExpiredPropertyName
for (name in [enabled: enabledPropertyName,
accountExpired: accountExpiredPropertyName,
accountLocked: accountLockedPropertyName,
passwordExpired: passwordExpiredPropertyName]) {
Integer value = params.int(name.key)
if (value) {
hql.append " AND u.${name.value}=:${name.key}"
queryParams[name.key] = value == 1
}
}
int totalCount = lookupUserClass().executeQuery("SELECT COUNT(DISTINCT u) $hql", queryParams)[0]
Integer max = params.int('max')
Integer offset = params.int('offset')
String orderBy = ''
if (params.sort) {
orderBy = " ORDER BY u.$params.sort ${params.order ?: 'ASC'}"
}
def results = lookupUserClass().executeQuery(
"SELECT DISTINCT u $hql $orderBy",
queryParams, [max: max, offset: offset])
def model = [results: results, totalCount: totalCount, searched: true]
// add query params to model for paging
for (name in ['username', 'enabled', 'accountExpired', 'accountLocked',
'passwordExpired', 'sort', 'order']) {
model[name] = params[name]
}
render view: 'search', model: model
}
EDIT....
I believe it may have something to do with the code below:
def results = lookupUserClass().executeQuery(
"SELECT DISTINCT u $hql $orderBy",
queryParams, [max: max, offset: offset])
I think I just need to alter this statement so that it looks for the list of users where the currently logged in users "Area" is equal to the same area as the users. Can anyone please help me with this??
EDIT 2.....
I have now looked into this and have been able to obtain the users Area and now alls I need to do is to modify the query to the database to look for the users that have the same Area as the admin searching. I have tried the following with no luck, can someone please help me with this as I know this must be simple just cant seem to get there :-S
def user = springSecurityService.currentUser
def userArea = user.area
def hql = new StringBuilder('FROM ').append(lookupUserClassName()).append(' u WHERE 1=1 AND u.area = userArea')
EDIT 3.......
Thanks so much half of my problem is solved lol, now just the Ajax piece:
I have tried the below code in order to modify the search for the Ajax function to only return results where the Area of the user is the same as the currently logged in user:
String username = params.term
String usernameFieldName = SpringSecurityUtils.securityConfig.userLookup.usernamePropertyName
def user = springSecurityService.currentUser
setIfMissing 'max', 10, 100
def results = lookupUserClass().executeQuery(
"SELECT DISTINCT u.$usernameFieldName " +
"FROM ${lookupUserClassName()} u " +
"WHERE LOWER(u.$usernameFieldName) LIKE :name AND LOWER(u.area) = :area " +
"ORDER BY u.$usernameFieldName",
[name: "${username.toLowerCase()}%"],
[area: "user.area"],
[max: params.max])
Also tried changing the param as below:
[area: user.area]
The controller is building an HQL query, so you can't just say "WHERE u.area = userArea", you'll need to use a named parameter and put the value in the queryParams map
def user = springSecurityService.currentUser
def hql = new StringBuilder('FROM ').append(lookupUserClassName()).append(
' u WHERE u.area = :userArea ')
def queryParams = [userArea:user.area]
For the second part of the problem (the Ajax bit), I doubt you need the LOWER conversion, and also you need to put all your query parameters into one map (the second map parameter is just for the pagination settings):
def results = lookupUserClass().executeQuery(
"SELECT DISTINCT u.$usernameFieldName " +
"FROM ${lookupUserClassName()} u " +
"WHERE LOWER(u.$usernameFieldName) LIKE :name AND u.area = :area " +
"ORDER BY u.$usernameFieldName",
[name: "${username.toLowerCase()}%", area:user.area],
[max: params.max])
If you really do want the area check to be case-insensitive then leave it as LOWER(u.area) = :area but then you also need to convert the value you are testing against to lower case:
[name: "${username.toLowerCase()}%", area:user.area.toLowerCase()],

Resources