SugarCRM Rest API set_relationship between Contacts and Documents - sugarcrm

I am trying to (link/set_relationship) between a document and a contact on SugarCRM. I am not sure how to construct the "name_value_list" specifically for this. At least that is what I believe to be wrong.
I have tried the following:
1.
'name_value_list': []
2.
'name_value_list' : [{
'name': "documents_contacts",
'value': 'Other',
}],
3.
'name_value_list': [{'table': "%s_%s" % (ModuleName, LinkedModuleName)},
{'fields': [
{"id": str(uuid.uuid1())},
{"date_modified": str(datetime.datetime.now())},
{"deleted": '0'},
{"document_id": RecordID},
{"contact_id": LinkedRecordID},
]
4.
'name_value_list':[{"%s_%s" % (ModuleName, LinkedModuleName): 'Other',
"id": str(uuid.uuid1()),
"date_modified": str(datetime.datetime.now()),
"deleted": '0',
"document_id": RecordID,
"contact_id": LinkedRecordID
}]
SugarCRM CE Version 6.5.20 (Build 1001)
SugarCRM v4_1 Rest API Documentation:
* Set a single relationship between two beans. The items are related by module name and id.
*
* #param String $session -- Session ID returned by a previous call to login.
* #param String $module_name -- name of the module that the primary record is from. This name should be the name the module was developed under (changing a tab name is studio does not affect the name that should be passed into this method)..
* #param String $module_id - The ID of the bean in the specified module_name
* #param String link_field_name -- name of the link field which relates to the other module for which the relationship needs to be generated.
* #param array related_ids -- array of related record ids for which relationships needs to be generated
* #param array $name_value_list -- The keys of the array are the SugarBean attributes, the values of the array are the values the attributes should have.
* #param integer $delete -- Optional, if the value 0 or nothing is passed then it will add the relationship for related_ids and if 1 is passed, it will delete this relationship for related_ids
* #return Array - created - integer - How many relationships has been created
* - failed - integer - How many relationsip creation failed
* - deleted - integer - How many relationships were deleted
* #exception 'SoapFault' -- The SOAP error, if any
*/
Method [ public method set_relationship ] {
- Parameters [7] {
Parameter #0 [ $session ]
Parameter #1 [ $module_name ]
Parameter #2 [ $module_id ]
Parameter #3 [ $link_field_name ]
Parameter #4 [ $related_ids ]
Parameter #5 [ $name_value_list ]
Parameter #6 [ $delete ]
}
}
Python 3.7
def SetRelationship(self, ModuleName, ModuleID, LinkFieldName, RelatedID):
method = 'set_relationship'
data = {
'session':self.SessionID,
'module_name':ModuleName,
'module_id':ModuleID,
'link_field_name':LinkFieldName,
'related_ids':[RelatedID, ]
}
response = json.loads(self.request(method, data))
SetRelationship('Documents', 'e9d22076-02fe-d95d-1abb-5d572e65dd46', 'Contacts', '2cdc28d8-763e-6232-2788-57f4e19a9ea0')
Result:
{'created': 0, 'failed': 1, 'deleted': 0}
Expected Result:
{'created': 1, 'failed': 0, 'deleted': 0}

You probably meant to call
SetRelationship('Documents', 'e9d22076-02fe-d95d-1abb-5d572e65dd46', 'contacts', '2cdc28d8-763e-6232-2788-57f4e19a9ea0')
Notice the lowercase contacts here, as the API expects the name of the link field in Documents, not the name of the module.
If that still doesn't fix the issue, check the sugarcrm.log and the php log for errors.

Related

Laravel 6 collections - Extract a single value from a record

I have the following collection:
$products = $this->productRepository->getByCompanyId(1)->get();
Illuminate\Database\Eloquent\Collection {#856 ▼
#items: array:1 [▼
0 => App\OrderItemProduct {#824 ▼
#table: "product"
...
#attributes: array:3 [▼
"available" => "5"
"product_name" => "Product X"
"product_id" => 1
]
....
}
]
}
I want to get the available value for a single record. I try the following which works if a record exists:
$available = $products->where('product_id','=', 1)->first()['available'];
However it throws an exception Trying to access array offset on value of type null if I try to retrieve the available value of a record that doesn't exist in the collection e.g trying to get for product_id 17:
$available = $products->where('product_id','=', 17)->first()['available'];
This was working in laravel v6 and earlier but no longer seems to work in laravel 6.17.1
Note in laravel 5.5 I was able to use the value method as follows but then that started throwing same errors as above in v 5.7 so I switched to the above method but now that no loger works either in the latest laravel version.
`available = $products->where('product_id','=', 17)->value('available');
Also when i try get why does it always return null even where record exists?
`available = $products->where('product_id','=', 1)->get('available');
Any ideas how to fix?

Get the groups of a customeruser in otrs

I am extending OTRS with an app and need to get the groups a customeruser is in. I want to do this by communicating with the SessionGet-Endpoint (https://doc.otrs.com/doc/api/otrs/6.0/Perl/Kernel/GenericInterface/Operation/Session/SessionGet.pm.html)
The Endpoint for SessionGet returns a lot of information about the user but not the groups he is in. I am not talking about agents who can login to the backend of otrs but customerusers.
I am using OTRS 6 because it was the only one available in docker. I created the REST-endpoints in the backend and everything works well. There is a new functionality why I need to get the information about the groups.
Had a look at the otrs system-config but could not figure out if it is possible to include this information in the response.
Although I am a programmer, I did not want to write perl because of ... reasons.
I had a look at the file which handles the incoming request at /opt/otrs/Kernel/GenericInterface/Operation/Session/SessionGet.pm and traced the calls to the actual file where the information is collected from the database in /opt/otrs/Kernel/System/AuthSession/DB.pm. In line 169 the SQL-statement is written so it came to my mind that I just can extend this to also get the information of the groups, because, as I said, I did not want to write perl...
A typical response from this endpoint looks like this:
{
"SessionData": [
{
"Value": "2",
"Key": "ChangeBy"
},
{
"Value": "2019-06-26 13:43:18",
"Key": "ChangeTime"
},
{
"Value": "2",
"Key": "CreateBy"
},
{
"Value": "2019-06-26 13:43:18",
"Key": "CreateTime"
},
{
"Value": "XXX",
"Key": "CustomerCompanyCity"
},
{
"Value": "",
"Key": "CustomerCompanyComment"
}
...
}
A good thing would be to just insert another Value-Key-pair with the IDs of the groups. The SQL-statement queries only one table $Self->{SessionTable} mostly called otrs.sessions.
I used the following resources to create a SQL-statement which extends the existing SQL-statement with the needed information. You can find it here:
$DBObject->Prepare(
SQL => "
(
SELECT id, data_key, data_value, serialized FROM $Self->{SessionTable} WHERE session_id = ? ORDER BY id ASC
)
UNION ALL
(
SELECT
(
SELECT MAX(id) FROM $Self->{SessionTable} WHERE session_id = ?
) +1
AS id,
'UserGroupsID' AS data_key,
(
SELECT GROUP_CONCAT(DISTINCT group_id SEPARATOR ', ')
FROM otrs.group_customer_user
WHERE user_id =
(
SELECT data_value
FROM $Self->{SessionTable}
WHERE session_id = ?
AND data_key = 'UserID'
ORDER BY id ASC
)
)
AS data_value,
0 AS serialized
)",
Bind => [ \$Param{SessionID}, \$Param{SessionID}, \$Param{SessionID} ],
);
Whoever needs to get the groups of a customeruser can replace the existing code with the one provided. At least in my case it works very well. Now, I get the expected key-value-pair:
{
"Value": "10, 11, 6, 7, 8, 9",
"Key": "UserGroupsID"
},
I used the following resources:
Adding the results of multiple SQL selects?
Can I concatenate multiple MySQL rows into one field?
Add row to query result using select
Happy coding,
Nico

Symfony 4 argument has no type-hint, you should configure its value explicitly

Symfony 4.2.3
Recently upgraded from version 3.4 to 4.2.3 and got my project working, but
when setting autoconfigure in services.yaml to true, I will receive this error message:
Cannot autowire service "App\EventListener\RedirectToLocaleActiveListener": argument "$localeActive" of method "__construct()" has no type-hint, you should configure its value explicitly.
My services.yaml
parameters:
locale: de
locale_active: de
app_locales: de|en
uploads_directory_name: uploads
uploads_profile_directory_name: profiles
uploads_directory: '%kernel.root_dir%/../public/%uploads_directory_name%'
profile_directory: '%kernel.root_dir%/../public/%uploads_directory_name%/%uploads_profile_directory_name%'
google_recaptcha_site_key: '%env(GOOGLE_RECAPTCHA_SITE_KEY)%'
services:
_defaults:
autowire: true
autoconfigure: true
App\:
resource: '../src/*'
exclude: '../src/{DependencyInjection,Entity,Migrations,Tests,Kernel.php}'
App\Controller\:
resource: ../src/Controller
tags:
- controller.service_arguments
locales:
class: App\Util\Locales
arguments:
- '%locale_active%'
- '%app_locales%'
- '#session'
app.locale:
class: App\EventListener\LocaleListener
tags:
- {name: kernel.event_subscriber}
app.redirect_to_locale_active:
class: App\EventListener\RedirectToLocaleActiveListener
arguments:
- '#router'
- '%locale_active%'
tags:
- {name: kernel.event_subscriber}
My RedirectToLocaleActiveListener.php
<?php
namespace App\EventListener;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
/**
* Class RedirectToLocaleActiveListener
* When a user enters to the homepage without the parameter locale,
* the subscriber redirects the user to the main locale.
*
* #package App\EventListener
*/
class RedirectToLocaleActiveListener implements EventSubscriberInterface
{
/**
* #var UrlGeneratorInterface
*/
private $urlGenerator;
/**
* #var string
*/
private $localeActive;
/**
* #param UrlGeneratorInterface $urlGenerator
* #param $localeActive
*/
public function __construct(UrlGeneratorInterface $urlGenerator, $localeActive)
{
$this->urlGenerator = $urlGenerator;
$this->localeActive = $localeActive;
}
public static function getSubscribedEvents()
{
return [
KernelEvents::REQUEST => 'onKernelRequest',
];
}
/**
* #param GetResponseEvent $event
*/
public function onKernelRequest(GetResponseEvent $event)
{
$request = $event->getRequest();
if ('/' == $request->getPathInfo()) {
$route = $this->urlGenerator->generate('app_index', ['_locale' => $this->localeActive]);
$response = new RedirectResponse($route);
$event->setResponse($response);
}
}
}
What I've tried:
adding 'string' to $localActive in __construct of RedirectToLocaleActiveListener
Result:
Cannot autowire service "App\EventListener\RedirectToLocaleActiveListener": argument "$localeActive" of method "__construct()" is type-hinted "string", you should configure its value explicitly.
arguments of scalar type cannot be auto-wired. You need to wire them manually.
You can try wiring the argument explicitly in the service definition:
App\EventListener\RedirectToLocaleActiveListener
arguments:
$urlGenerator: '#router'
$localeActive: '%locale_active%'
tags:
- {name: kernel.event_subscriber}
Documentation:
https://symfony.com/doc/current/service_container.html#manually-wiring-arguments
Or you can make use of the local service binding feature to bind a parameter to a scalar argument:
services:
_defaults:
bind:
$localeActive: '%locale_active%'
Documentation:
https://symfony.com/blog/new-in-symfony-3-4-local-service-binding
If your service name is not equal to fqcn, such as:
app.ext.telegram_bot_api:
class: 'App\Ext\TelegramBot\Bot'
and somewhere your using automatic services resolution like this:
# makes classes in src/ available to be used as services
# this creates a service per class whose id is the fully-qualified class name
App\:
resource: '../src/*'
exclude: '../src/{Entity,Document,Migrations,Tests,Kernel.php}'
your should create alias between your service name and fqcn like that:
'App\Ext\TelegramBot\Bot': '#app.ext.telegram_bot_api'
so your automatic services resolution should know about your service extra configuration.

How use values mode in Orion?

Reading FIWARE-NGSI v2 Specification (http://telefonicaid.github.io/fiware-orion/api/v2/latest/)
In section Simplified Entity Representation
I couldn't test values mode as recomend. My test fail:
values mode. This mode represents the entity as an array of attribute
values. Information about id and type is left out. See example below.
The order of the attributes in the array is specified by the attrs URI
param (e.g. attrs=branch,colour,engine). If attrs is not used, the
order is arbitrary.
[ 'Ford', 'black', 78.3 ]
Where and how I referenced an entityID?
POST /v2/entities/Room1?options=values&attrs=branch,colour,engine
payload:
[ 'Ford', 'black', 78.3 ]
Answer:
{
"error": "MethodNotAllowed",
"description": "method not allowed"
}
POST /v2/entities?options=values
payload:
[ 'Ford', 'black', 78.3 ]
Answer:
{
"error": "ParseError",
"description": "Errors found in incoming JSON buffer"
}
Version:
GET /version
{
"orion": {
"version": "1.10.0-next",
"uptime": "0 d, 0 h, 1 m, 34 s",
"git_hash": "0f92803495a8b6c145547e19f35e8f633dec92e0",
"compile_time": "Fri Feb 2 09:45:41 UTC 2018",
"compiled_by": "root",
"compiled_in": "77ff7f334a88",
"release_date": "Fri Feb 2 09:45:41 UTC 2018",
"doc": "https://fiware-orion.readthedocs.org/en/master/"
}
}
"options=values" is a representation format for querying data not for posting new entity data for obvious reasons, when you are creating new entities you have to specify the entity id and the entity type and with the values representation format you can't ...

BSON::InvalidDocument: Cannot serialize an object into BSON

I'm trying to follow along with http://mongotips.com/b/array-keys-allow-for-modeling-simplicity/
I have a Story document and a Rating document. The user will rate a story, so I wanted to create a many relationship to ratings by users as such:
class StoryRating
include MongoMapper::Document
# key <name>, <type>
key :user_id, ObjectId
key :rating, Integer
timestamps!
end
class Story
include MongoMapper::Document
# key <name>, <type>
timestamps!
key :title, String
key :ratings, Array, :index => true
many :story_ratings, :in => :ratings
end
Then
irb(main):006:0> s = Story.create
irb(main):008:0> s.ratings.push(Rating.new(user_id: '0923ksjdfkjas'))
irb(main):009:0> s.ratings.last.save
=> true
irb(main):010:0> s.save
BSON::InvalidDocument: Cannot serialize an object of class StoryRating into BSON.
from /usr/local/lib/ruby/gems/1.9.1/gems/bson-1.6.2/lib/bson/bson_c.rb:24:in `serialize' (...)
Why?
You should be using the association "story_rating" method for your push/append rather than the internal "rating" Array.push to get what you want to follow John Nunemaker's "Array Keys Allow For Modeling Simplicity" discussion. The difference is that with the association method, MongoMapper will insert the BSON::ObjectId reference into the array, with the latter you are pushing a Ruby StoryRating object into the Array, and the underlying driver driver cant serialize it.
Here's a test that works for me, that shows the difference. Hope that this helps.
Test
require 'test_helper'
class Object
def to_pretty_json
JSON.pretty_generate(JSON.parse(self.to_json))
end
end
class StoryTest < ActiveSupport::TestCase
def setup
User.delete_all
Story.delete_all
StoryRating.delete_all
#stories_coll = Mongo::Connection.new['free11513_mongomapper_bson_test']['stories']
end
test "Array Keys" do
user = User.create(:name => 'Gary')
story = Story.create(:title => 'A Tale of Two Cities')
rating = StoryRating.create(:user_id => user.id, :rating => 5)
assert_equal(1, StoryRating.count)
story.ratings.push(rating)
p story.ratings
assert_raise(BSON::InvalidDocument) { story.save }
story.ratings.pop
story.story_ratings.push(rating) # note story.story_ratings, NOT story.ratings
p story.ratings
assert_nothing_raised(BSON::InvalidDocument) { story.save }
assert_equal(1, Story.count)
puts Story.all(:ratings => rating.id).to_pretty_json
end
end
Result
Run options: --name=test_Array_Keys
# Running tests:
[#<StoryRating _id: BSON::ObjectId('4fa98c25e4d30b9765000003'), created_at: Tue, 08 May 2012 21:12:05 UTC +00:00, rating: 5, updated_at: Tue, 08 May 2012 21:12:05 UTC +00:00, user_id: BSON::ObjectId('4fa98c25e4d30b9765000001')>]
[BSON::ObjectId('4fa98c25e4d30b9765000003')]
[
{
"created_at": "2012-05-08T21:12:05Z",
"id": "4fa98c25e4d30b9765000002",
"ratings": [
"4fa98c25e4d30b9765000003"
],
"title": "A Tale of Two Cities",
"updated_at": "2012-05-08T21:12:05Z"
}
]
.
Finished tests in 0.023377s, 42.7771 tests/s, 171.1084 assertions/s.
1 tests, 4 assertions, 0 failures, 0 errors, 0 skips