How to call Recursive function for array data Using Promises in Node Js - node.js

I am trying to call the recursive function in my code. The loop executing first time, but recursive function which is called inside the function is not working.
Here is my code :
function buildDynamicMenu(elements,parentId)
{
branch =new Array();
elements.forEach(function(element){
if (element['parent_id'] == parentId) {
children = buildDynamicMenu(elements, element['menu_id']); //Recursive function not working
if (children) {
element['children'] =children;
}
branch = element;
}
});
return branch;
}
var parentId=0;
buildDynamicMenu(data); // Array data
I have added sample array which I am using for this logic, array has menu and Submenu Id, we have to call recursive function to loop through all sub array
Array
(
[0] => Array
(
[menu_id] => 1
[menu_name] => Home
[parent_id] => 0
[link] => #home
)
[1] => Array
(
[menu_id] => 2
[menu_name] => Web development
[parent_id] => 0
[link] => #web-dev
)
[2] => Array
(
[menu_id] => 3
[menu_name] => WordPress Development
[parent_id] => 2
[link] => #wp-dev
)
[3] => Array
(
[menu_id] => 4
[menu_name] => About w3school.info
[parent_id] => 2
[link] => #w3school-info
)
[4] => Array
(
[menu_id] => 7
[menu_name] => Javascript
[parent_id] => 2
[link] => #
)
[5] => Array
(
[menu_id] => 8
[menu_name] => Plugins
[parent_id] => 7
[link] => #plugin-dev
)
)

seems like this doesn't have a pointed buildDynamicMenu export. check if there is one in 'this'. try to assign the buildDynamicMenu function to some const and perform call to it.
Ok here is my demo func working very well in nodejs typescript:
function recursieve (p) {
console.log('in recursieve ', p);
if (p > 0) {
recursieve (--p);
} } recursieve (10);// rec call
So in my opinion there are two problems in your code:
1. 'this' was not pointed to the function.
2. recursieve condition, like the elements is empty, or id is no match.

Related

Bitrix24 webhook/REST API

I'd like to create TASK in bitrix24 with webhook URL. Almost everything is fine (task name, description, responsible, deadline etc...) the only problem is with field with several users (Observers and Participants). I don't know how to add these parameters to the URL :( The documentation is incomplete.
The solution is easy, I didn't see your code but per the API doc, you need to encode the JSON array of fields as parameters into the GET request: this will help you: How should I put json in GET request?
A better approach would be using POST to submit data instead of GET, this way you don't need to do the above, you can send the array as it.
This is the API doc you need to follow:
https://training.bitrix24.com/rest_help/tasks/task/tasks/tasks_task_add.php
Here is the array of fields you can set as the "fields" parameter when creating a task:
https://training.bitrix24.com/rest_help/tasks/fields.php
Example of an array of fields:
Array
(
[TITLE] => Process lead: +19196299012 - Outgoing call (set from business process)
[STAGE_ID] => 0
[DESCRIPTION] => Process lead: +19196299012 - Outgoing call
[DEADLINE] =>
[START_DATE_PLAN] =>
[END_DATE_PLAN] =>
[PRIORITY] => 0
[ACCOMPLICES] => Array
(
)
[AUDITORS] => Array
(
)
[TAGS] => Array
(
)
[ALLOW_CHANGE_DEADLINE] => Y
[ALLOW_CHANGE_DEADLINE_COUNT] =>
[ALLOW_CHANGE_DEADLINE_COUNT_VALUE] =>
[ALLOW_CHANGE_DEADLINE_MAXTIME] =>
[ALLOW_CHANGE_DEADLINE_MAXTIME_VALUE] =>
[TASK_CONTROL] => Y
[PARENT_ID] =>
[DEPENDS_ON] => Array
(
)
[GROUP_ID] => 0
[RESPONSIBLE_ID] => 1
[TIME_ESTIMATE] => 0
[ID] => 130
[CREATED_BY] => 1
[DESCRIPTION_IN_BBCODE] => Y
[DECLINE_REASON] =>
[REAL_STATUS] => 2
[STATUS] => 2
[RESPONSIBLE_NAME] => Mohamed Ali
[RESPONSIBLE_LAST_NAME] => Ouled Ameur
[RESPONSIBLE_SECOND_NAME] =>
[DATE_START] =>
[DURATION_FACT] =>
[DURATION_PLAN] =>
[DURATION_TYPE] => days
[CREATED_BY_NAME] => Mohamed Ali
[CREATED_BY_LAST_NAME] => Ouled Ameur
[CREATED_BY_SECOND_NAME] =>
[CREATED_DATE] => 2021-06-26T08:12:39+03:00
[CHANGED_BY] => 1
[CHANGED_DATE] => 2021-06-26T08:12:39+03:00
[STATUS_CHANGED_BY] => 1
[STATUS_CHANGED_DATE] => 2021-06-26T08:12:39+03:00
[CLOSED_BY] =>
[CLOSED_DATE] =>
[ACTIVITY_DATE] => 2021-06-26T08:12:39+03:00
[GUID] => {bcd84631-6c08-4124-8db2-7cfe90628dc1}
[MARK] =>
[VIEWED_DATE] => 2021-06-28T09:09:17+03:00
[TIME_SPENT_IN_LOGS] =>
[FAVORITE] => N
[ALLOW_TIME_TRACKING] => N
[MATCH_WORK_TIME] => N
[ADD_IN_REPORT] => Y
[FORUM_ID] =>
[FORUM_TOPIC_ID] =>
[COMMENTS_COUNT] =>
[SITE_ID] => s1
[SUBORDINATE] => Y
[FORKED_BY_TEMPLATE_ID] =>
[MULTITASK] => N
[UF_CRM_TASK] => Array
(
[0] => L_38
[1] => L_38
)
[UF_MAIL_MESSAGE] =>
[UF_TASK_WEBDAV_FILES] =>
)
to set more then one, you can use this. In the array every usernumber
$accomplice = ['1','2'];
$createTask = CRest::call('tasks.task.add',
...
'ACCOMPLICES' => $accomplice,
...

Codeigniter 4 Query Builder loses SELECT and WHERE condition while executing once more

I am using Codeigniter 4 Query Builder.
Following is code to retrieve data from the database
public function get_data()
{
$where = [
'username' => 'admin'
];
$this->_builder = $this->_db->table('pf_user_master s');
$this->_builder->join('pf_role_master r', 'r.role_id = s.role_id');
$this->_builder->select('username, first_name, last_name, mobile, email, r.role_name, s.status');
if (is_array($where) && !empty($where)) {
$this->_builder->where($where);
}
$first= $this->_builder->get()->getResultArray();
print_r($first);
$second= $this->_builder->get()->getResultArray();
print_r($second);
exit;
}
I am getting the following output:
In variable $first I am getting output as expected
Array
(
[0] => Array
(
[username] => admin
[first_name] => Fisrt
[last_name] => Last
[mobile] =>
[email] => first.last#gmail.com
[role_name] => Admin
[status] => 1
)
)
But in variable $second it Query Builder loses SELECT, WHERE condition and also JOIN.
And prints the output as follows:
Array
(
[0] => Array
(
[user_id] => 1
[username] => admin
[password] => 21232f297a57a5a743894a0e4a801fc3
[first_name] => First
[last_name] => Last
[mobile] =>
[email] => first.last#gmail.com
[role_id] => 1
[status] => 1
[created_by] =>
[created_date] => 2020-09-08 19:30:52
[updated_by] =>
[updated_date] => 2020-09-08 19:32:42
)
[1] => Array
(
[user_id] => 2
[username] => superadmin
[password] => 21232f297a57a5a743894a0e4a801fc3
[first_name] => NewFirst
[last_name] => NewLast
[mobile] =>
[email] => new.new#gmail.com
[role_id] => 1
[status] => 1
[created_by] =>
[created_date] => 2020-09-08 21:51:42
[updated_by] =>
[updated_date] =>
)
)
I've not tested this and it comes from reading the documentation only.
In the CodeIgniter documentation get() has the following parameters
get([$limit = NULL[, $offset = NULL[, $reset = TRUE]]]])
Reference: https://codeigniter.com/user_guide/database/query_builder.html#get
If you were to use
$first= $this->_builder->get(NULL,NULL,FALSE)->getResultArray();
Then your code would become:
public function get_data()
{
$where = [
'username' => 'admin'
];
$this->_builder = $this->_db->table('pf_user_master s');
$this->_builder->join('pf_role_master r', 'r.role_id = s.role_id');
$this->_builder->select('username, first_name, last_name, mobile, email, r.role_name, s.status');
if (is_array($where) && !empty($where)) {
$this->_builder->where($where);
}
$first= $this->_builder->get(NULL,NULL,FALSE)->getResultArray();
print_r($first);
$second= $this->_builder->get()->getResultArray();
print_r($second);
exit;
}
Of course if you were to perform this a 3rd time, the 2nd instance should cause a reset.
The Code is the Documentation ( in most cases ) so we have
In CodeIgniter 4.04 - /system/Database/BaseBuilder.php - Line 1824
The code is
/**
* Get
*
* Compiles the select statement based on the other functions called
* and runs the query
*
* #param integer $limit The limit clause
* #param integer $offset The offset clause
* #param boolean $reset Are we want to clear query builder values?
*
* #return ResultInterface
*/
public function get(int $limit = null, int $offset = 0, bool $reset = true)
{
if (! is_null($limit))
{
$this->limit($limit, $offset);
}
$result = $this->testMode
? $this->getCompiledSelect($reset)
: $this->db->query($this->compileSelect(), $this->binds, false);
if ($reset === true)
{
$this->resetSelect();
// Clear our binds so we don't eat up memory
$this->binds = [];
}
return $result;
}
So the default for $reset, will "clear" what you have observed.
As mentioned by TimBrownlaw
I changed
$first= $this->_builder->get()->getResultArray();
to
$first= $this->_builder->get(NULL, 0 , false)->getResultArray();
and it worked for me as it didn't reset the query as third parameter of get() is for resetting the query

How to export data of array to excel with each element from an array storing in single row

I am trying to export data to excel using Fast excel. This is easy for straight forward export. However, I have data as follows:
Illuminate\Support\Collection Object
(
[items:protected] => Array
(
[0] => stdClass Object
(
[id] => 1
[name] => name1
[multiple_units] => ["80","103","126","7","10","13"]
)
[1] => stdClass Object
(
[id] => 2
[name] => name2
[multiple_units] => ["30","23","26","7","25","33"]
)
)
)
Where multiple_units is a text column with json_decode. So, now when I try to export data with following code:
public function exportTest()
{
$reviews = DB::table('test_db')->get();
$file_name = 'Review - '.date('Y_m_d').'.xlsx';
return (new FastExcel($reviews))->download($file_name,function($review){
$unit_lists = '';
if($review->multiple_units != NULL){
$unit_ids = json_decode($review->multiple_units, true);
foreach($unit_ids as $uk => $uv){
return [
'Name' => $review->name,
'Units' => $uv
];
}
}
});
}
It export to excel file like as:
Name Units
name1 80
name2 30
However, I want to export with each unit being in a single row. For instance,
Name Units
name1 80
name1 103
name1 126
name1 7
name1 10
name1 13
...
...
...
...
As far as I can see, Fast Excel does not allow changing the number of rows in the callback function.
The solution is to manipulate the data before passing it to Fast Excel:
public function exportTest()
{
$reviews = DB::table('test_db')->get()->flatMap(function ($review) {
$items = [];
if ($review->multiple_units != NULL) {
$unit_ids = json_decode($review->multiple_units, true);
foreach ($unit_ids as $uk => $uv) {
$items[] = [
'Name' => $review->name,
'Units' => $uv
];
}
}
return $items;
});
$file_name = 'Review - '.date('Y_m_d').'.xlsx';
return (new FastExcel($reviews))->download($file_name);
}
This will map over each review return an array containing name and units for each unit. Then the array is flattened and passed to Fast Excel.
Note: This will ignore any reviews where review->multiple_units == NULL (which includes an empty string)
public function exportTest() {
$reviews = DB::table('test_db')->orderBy('name')->get();
$file_name = 'Review - '.date('Y_m_d').'.xlsx';
return (new FastExcel($reviews))->download($file_name,function($reviews) {
foreach ($reviews as $review) {
# code...
if(!empty($review->multiple_units)) {
$unit_ids = json_decode($review->multiple_units, true);
foreach($unit_ids as $uk => $uv){
return [
'Name' => $review->name,
'Units' => $uv
];
}
}
}
});
}

add customerGroup to article with PUT call

Im trying to update my articles and add a excluded CustomerGroup.
Since the documentation is pretty bad for that part I try to find some more help here.
I put this [] Object to shopware for example
[data] => Array
(
[id] => 1460
[mainDetailId] => 1460
[supplierId] => 1
[taxId] => 1
[filterGroupId] => 1
[name] => XXX
[added] => 2018-01-26T00:00:00+0100
[active] => 1
[pseudoSales] => 0
[changed] => 2018-02-09T15:22:35+0100
[lastStock] => 1
[mode] => 0
[mainDetail] => Array
(
[id] => 1460
[articleId] => 1460
[...] => ...
)
[customerGroups] => Array
(
[0] => Array
(
[customerGroupKey] => EK
)
)
)
The important part is the [customerGroups] array which i add and which doesnt work for me.
You should create a customer group before you use the "groupKey", use "CustomerGroup" api resource for this (see /engine/Shopware/Components/Api/Resource/CustomerGroup.php).

laravel excel get headers and maatwebsite

I want to get only my excel first column that will be column name.
I am using this code
Excel::load($request->file, function ($reader) use($request) {
$torarray=$reader->toArray();
$line0 = $torarray[0];
$headers = array_keys($line0);
$excel_header=$headers;
});
Sometimes it works but some times not work. when not work with some files the i write below that and works
$torarray=$reader->toArray();
$line0 = $torarray[0][0];
$headers = array_keys($line0);
$excel_header=$headers;
});
I cant understand whats the correct solution.
Thank you #mahmoud-zalt
Just wanted to share how I use it in Laravel 5.5:
$reader = Excel::load(storage_path() . '/uploads/tracking-number/' . $fileName)->get();
$headerRow = $reader->first()->keys()->toArray();
JSON:
["date","reference_no","tracking_notrace_webhttpwww.17track.com_for_eub_and_httpwww.cacesapostal.com_for_swiss_post","destination_country","receiver","tel","state","city","post_code","address","weightkg","quantity","valueusd","description","parcelquantity",0]
var_export:
array (
0 => 'date',
1 => 'reference_no',
2 => 'tracking_notrace_webhttpwww.17track.com_for_eub_and_httpwww.cacesapostal.com_for_swiss_post',
3 => 'destination_country',
4 => 'receiver',
5 => 'tel',
6 => 'state',
7 => 'city',
8 => 'post_code',
9 => 'address',
10 => 'weightkg',
11 => 'quantity',
12 => 'valueusd',
13 => 'description',
14 => 'parcelquantity',
15 => 0,
)
print_r
Array
(
[0] => date
[1] => reference_no
[2] => tracking_notrace_webhttpwww.17track.com_for_eub_and_httpwww.cacesapostal.com_for_swiss_post
[3] => destination_country
[4] => receiver
[5] => tel
[6] => state
[7] => city
[8] => post_code
[9] => address
[10] => weightkg
[11] => quantity
[12] => valueusd
[13] => description
[14] => parcelquantity
[15] => 0
)
This code worked for me:
$results = Excel::selectSheetsByIndex(0)->load($file)->get();
echo "<pre>";
var_dump($results->getHeading());
echo "</pre>";
For version 3 of maatwebsite excel you can get the headings by the following approach:
use Maatwebsite\Excel\HeadingRowImport;
$headings = (new HeadingRowImport)->toArray(file);
Insert your file path in place of the file keyword.
Try this:
/**
* #param \SplFileInfo $file
*
* #return Array
*/
public function run(SplFileInfo $file)
{
$excelFile = Excel::load($file);
$excelData = $excelFile->all();
return (($excelData->first())->keys())->toArray();
}
Just wanted to share a bit more optimized approach (this is v2.1 solution):
Excel::load($file->path(), function (LaravelExcelReader $reader) {
/** #var RowCollection $singleRow */
$singleRow = $reader->takeRows(1)->get(); // no need to parse whole sheet for the headings
$headings = $singleRow->getHeading();
// Do validation. Throw exception.
$reader->takeRows(false); // set the limit back to unlimited
})->get();

Resources