Solving conflicts updating with last changes in develop branch

This commit is contained in:
Julio Cesar Laura Avendaño
2020-12-03 20:19:49 +00:00
66 changed files with 3721 additions and 1224 deletions

View File

@@ -0,0 +1,14 @@
<?php
namespace App\Jobs;
class TaskScheduler extends QueuedClosure
{
/**
* The number of times the job may be attempted.
*
* @var int
*/
public $tries = 1;
}

View File

@@ -62,6 +62,14 @@ return [
'days' => $app->make('config')->get('app.log_max_files', 60), 'days' => $app->make('config')->get('app.log_max_files', 60),
], ],
'taskScheduler' => [
'driver' => 'daily',
'tap' => [App\Logging\CustomizeFormatter::class],
'path' => storage_path('logs/taskScheduler.log'),
'level' => 'debug',
'days' => $app->make('config')->get('app.log_max_files', 60),
],
'slack' => [ 'slack' => [
'driver' => 'slack', 'driver' => 'slack',
'url' => env('LOG_SLACK_WEBHOOK_URL'), 'url' => env('LOG_SLACK_WEBHOOK_URL'),

View File

@@ -0,0 +1,12 @@
<?php
use Faker\Generator as Faker;
$factory->define(\ProcessMaker\Model\AppTimeoutAction::class, function (Faker $faker) {
$index = $faker->unique()->numberBetween(20);
return [
'APP_UID' => G::generateUniqueID(),
'DEL_INDEX' => $index,
'EXECUTION_DATE' => $faker->dateTime()
];
});

View File

@@ -5,21 +5,21 @@ use Faker\Generator as Faker;
$factory->define(\ProcessMaker\Model\Application::class, function(Faker $faker) { $factory->define(\ProcessMaker\Model\Application::class, function(Faker $faker) {
$user = factory(\ProcessMaker\Model\User::class)->create(); $user = factory(\ProcessMaker\Model\User::class)->create();
$appNumber = $faker->unique()->numberBetween(1000); $appNumber = $faker->unique()->numberBetween(1000);
// APP_TITLE field is used in 'MYSQL: MATCH() AGAINST()' function, string size should not be less than 3.
//APP_TITLE field is used in 'MYSQL: MATCH() AGAINST()' function, string size should not be less than 3.
$appTitle = $faker->lexify(str_repeat('?', rand(3, 5)) . ' ' . str_repeat('?', rand(3, 5))); $appTitle = $faker->lexify(str_repeat('?', rand(3, 5)) . ' ' . str_repeat('?', rand(3, 5)));
//APP_STATUS must start in TO_DO because all tests require this state.
return [ return [
'APP_UID' => G::generateUniqueID(), 'APP_UID' => G::generateUniqueID(),
'APP_TITLE' => $appTitle, 'APP_TITLE' => $appTitle,
'APP_DESCRIPTION' => $faker->text,
'APP_NUMBER' => $appNumber, 'APP_NUMBER' => $appNumber,
'APP_STATUS' => 'TO_DO', 'APP_STATUS' => 'TO_DO',
'APP_STATUS_ID' => 2, 'APP_STATUS_ID' => 2,
'PRO_UID' => function() { 'PRO_UID' => function() {
return factory(\ProcessMaker\Model\Process::class)->create()->PRO_UID; return factory(\ProcessMaker\Model\Process::class)->create()->PRO_UID;
}, },
'APP_PROC_STATUS' => '',
'APP_PROC_CODE' => '',
'APP_PARALLEL' => 'N', 'APP_PARALLEL' => 'N',
'APP_INIT_USER' => $user->USR_UID, 'APP_INIT_USER' => $user->USR_UID,
'APP_CUR_USER' => $user->USR_UID, 'APP_CUR_USER' => $user->USR_UID,
@@ -38,18 +38,22 @@ $factory->state(\ProcessMaker\Model\Application::class, 'foreign_keys', function
$user = factory(\ProcessMaker\Model\User::class)->create(); $user = factory(\ProcessMaker\Model\User::class)->create();
$appNumber = $faker->unique()->numberBetween(1000); $appNumber = $faker->unique()->numberBetween(1000);
//APP_TITLE field is used in 'MYSQL: MATCH() AGAINST()' function, string size should not be less than 3. // APP_TITLE field is used in 'MYSQL: MATCH() AGAINST()' function, string size should not be less than 3.
$appTitle = $faker->lexify(str_repeat('?', rand(3, 5)) . ' ' . str_repeat('?', rand(3, 5))); $appTitle = $faker->lexify(str_repeat('?', rand(3, 5)) . ' ' . str_repeat('?', rand(3, 5)));
//APP_STATUS must start in TO_DO because all tests require this state. $statuses = ['DRAFT', 'TO_DO', 'COMPLETED', 'CANCELLED'];
$status = $faker->randomElement($statuses);
$statusId = array_search($status, $statuses) + 1;
return [ return [
'APP_UID' => G::generateUniqueID(), 'APP_UID' => G::generateUniqueID(),
'APP_TITLE' => $appTitle, 'APP_TITLE' => $appTitle,
'APP_NUMBER' => $appNumber, 'APP_NUMBER' => $appNumber,
'APP_STATUS' => 'TO_DO', 'APP_STATUS' => $status,
'APP_STATUS_ID' => 2, 'APP_STATUS_ID' => $statusId,
'PRO_UID' => $process->PRO_UID, 'PRO_UID' => $process->PRO_UID,
'APP_PROC_STATUS' => '',
'APP_PROC_CODE' => '',
'APP_PARALLEL' => 'N', 'APP_PARALLEL' => 'N',
'APP_INIT_USER' => $user->USR_UID, 'APP_INIT_USER' => $user->USR_UID,
'APP_CUR_USER' => $user->USR_UID, 'APP_CUR_USER' => $user->USR_UID,

View File

@@ -18,3 +18,4 @@ $factory->define(\ProcessMaker\Model\BpmnProcess::class, function(Faker $faker)
'PRO_IS_SUBPROCESS' => 0, 'PRO_IS_SUBPROCESS' => 0,
]; ];
}); });

View File

@@ -3,17 +3,22 @@
use Faker\Generator as Faker; use Faker\Generator as Faker;
$factory->define(\ProcessMaker\Model\BpmnProject::class, function (Faker $faker) { $factory->define(\ProcessMaker\Model\BpmnProject::class, function (Faker $faker) {
// Create user
$user = factory(\ProcessMaker\Model\User::class)->create();
// Create process
$process = factory(\ProcessMaker\Model\Process::class)->create();
return [ return [
'PRJ_UID' => G::generateUniqueID(), 'PRJ_UID' => G::generateUniqueID(),
'PRJ_NAME' => '', 'PRJ_NAME' => $faker->sentence(5),
'PRJ_DESCRIPTION' => $faker->text, 'PRJ_DESCRIPTION' => $faker->text,
'PRJ_EXPRESION_LANGUAGE' => '', 'PRJ_EXPRESION_LANGUAGE' => '',
'PRJ_TYPE_LANGUAGE' => '', 'PRJ_TYPE_LANGUAGE' => '',
'PRJ_EXPORTER' => '', 'PRJ_EXPORTER' => '',
'PRJ_EXPORTER_VERSION' => '', 'PRJ_EXPORTER_VERSION' => '',
'PRJ_CREATE_DATE' => new \Carbon\Carbon(2030, 1, 1), 'PRJ_CREATE_DATE' => $faker->dateTime(),
'PRJ_UPDATE_DATE' => new \Carbon\Carbon(2030, 1, 1), 'PRJ_UPDATE_DATE' => $faker->dateTime(),
'PRJ_AUTHOR' => '', 'PRJ_AUTHOR' => $user->USR_UID,
'PRJ_AUTHOR_VERSION' => '', 'PRJ_AUTHOR_VERSION' => '',
'PRJ_ORIGINAL_SOURCE' => '', 'PRJ_ORIGINAL_SOURCE' => '',
]; ];

View File

@@ -5,20 +5,25 @@
use Faker\Generator as Faker; use Faker\Generator as Faker;
$factory->define(\ProcessMaker\Model\Process::class, function(Faker $faker) { $factory->define(\ProcessMaker\Model\Process::class, function(Faker $faker) {
// Return with default values
//The incremental fields of the tables must not be specified in the creation list.
return [ return [
'PRO_UID' => G::generateUniqueID(), 'PRO_UID' => G::generateUniqueID(),
'PRO_ID' => $faker->unique()->numberBetween(1000),
'PRO_TITLE' => $faker->sentence(3), 'PRO_TITLE' => $faker->sentence(3),
'PRO_DESCRIPTION' => $faker->paragraph(3), 'PRO_DESCRIPTION' => $faker->paragraph(3),
'PRO_CREATE_USER' => '00000000000000000000000000000001', 'PRO_PARENT' => G::generateUniqueID(),
'PRO_DYNAFORMS' => '',
'PRO_ITEE' => 1,
'PRO_STATUS' => 'ACTIVE', 'PRO_STATUS' => 'ACTIVE',
'PRO_STATUS_ID' => 1, 'PRO_STATUS_ID' => 1,
'PRO_TYPE' => 'NORMAL',
'PRO_ASSIGNMENT' => 'FALSE',
'PRO_TYPE_PROCESS' => 'PUBLIC', 'PRO_TYPE_PROCESS' => 'PUBLIC',
'PRO_UPDATE_DATE' => $faker->dateTime(), 'PRO_UPDATE_DATE' => $faker->dateTime(),
'PRO_CREATE_DATE' => $faker->dateTime(), 'PRO_CREATE_DATE' => $faker->dateTime(),
'PRO_CREATE_USER' => '00000000000000000000000000000001',
'PRO_DEBUG' => 0,
'PRO_DYNAFORMS' => serialize([]),
'PRO_ITEE' => 1,
'PRO_ACTION_DONE' => serialize([]),
'PRO_CATEGORY' => function() { 'PRO_CATEGORY' => function() {
return factory(\ProcessMaker\Model\ProcessCategory::class)->create()->CATEGORY_UID; return factory(\ProcessMaker\Model\ProcessCategory::class)->create()->CATEGORY_UID;
}, },
@@ -27,45 +32,29 @@ $factory->define(\ProcessMaker\Model\Process::class, function(Faker $faker) {
// Create a process with the foreign keys // Create a process with the foreign keys
$factory->state(\ProcessMaker\Model\Process::class, 'foreign_keys', function (Faker $faker) { $factory->state(\ProcessMaker\Model\Process::class, 'foreign_keys', function (Faker $faker) {
// Create user
$user = factory(\ProcessMaker\Model\User::class)->create(); $user = factory(\ProcessMaker\Model\User::class)->create();
return [ return [
'PRO_UID' => G::generateUniqueID(), 'PRO_UID' => G::generateUniqueID(),
'PRO_ID' => $faker->unique()->numberBetween(1000),
'PRO_TITLE' => $faker->sentence(3), 'PRO_TITLE' => $faker->sentence(3),
'PRO_DESCRIPTION' => $faker->paragraph(3), 'PRO_DESCRIPTION' => $faker->paragraph(3),
'PRO_CREATE_USER' => $user->USR_UID, 'PRO_PARENT' => G::generateUniqueID(),
'PRO_DYNAFORMS' => '',
'PRO_ITEE' => 1,
'PRO_STATUS' => 'ACTIVE', 'PRO_STATUS' => 'ACTIVE',
'PRO_STATUS_ID' => 1, 'PRO_STATUS_ID' => 1,
'PRO_TYPE' => 'NORMAL',
'PRO_ASSIGNMENT' => 'FALSE',
'PRO_TYPE_PROCESS' => 'PUBLIC', 'PRO_TYPE_PROCESS' => 'PUBLIC',
'PRO_UPDATE_DATE' => $faker->dateTime(), 'PRO_UPDATE_DATE' => $faker->dateTime(),
'PRO_CREATE_DATE' => $faker->dateTime(), 'PRO_CREATE_DATE' => $faker->dateTime(),
'PRO_CATEGORY' => '',
];
});
// Create a process related to the flow designer
$factory->state(\ProcessMaker\Model\Process::class, 'flow', function (Faker $faker) {
// Create values in the foreign key relations
$user = factory(\ProcessMaker\Model\User::class)->create();
$process = [
'PRO_UID' => G::generateUniqueID(),
'PRO_TITLE' => $faker->sentence(3),
'PRO_DESCRIPTION' => $faker->paragraph(3),
'PRO_CREATE_USER' => $user->USR_UID, 'PRO_CREATE_USER' => $user->USR_UID,
'PRO_DYNAFORMS' => '', 'PRO_DEBUG' => 0,
'PRO_DYNAFORMS' => serialize([]),
'PRO_ITEE' => 1, 'PRO_ITEE' => 1,
'PRO_STATUS' => 'ACTIVE', 'PRO_ACTION_DONE' => serialize([]),
'PRO_STATUS_ID' => 1, 'PRO_CATEGORY' => function() {
'PRO_TYPE_PROCESS' => 'PUBLIC', return factory(\ProcessMaker\Model\ProcessCategory::class)->create()->CATEGORY_UID;
'PRO_UPDATE_DATE' => $faker->dateTime(), },
'PRO_CREATE_DATE' => $faker->dateTime(),
'PRO_CATEGORY' => '',
]; ];
// Create a task related to this process
$task = factory(\ProcessMaker\Model\Task::class)->create([
'PRO_UID' => $process->PRO_UID,
'PRO_ID' => $process->PRO_ID,
]);
}); });

View File

@@ -29,10 +29,11 @@ $factory->define(\ProcessMaker\Model\Task::class, function(Faker $faker) {
'TAS_OWNER_APP' => 'FALSE', 'TAS_OWNER_APP' => 'FALSE',
'TAS_CAN_SEND_MESSAGE' => 'FALSE', 'TAS_CAN_SEND_MESSAGE' => 'FALSE',
'TAS_SEND_LAST_EMAIL' => 'FALSE', 'TAS_SEND_LAST_EMAIL' => 'FALSE',
'TAS_SELFSERVICE_TIMEOUT' => 0,
]; ];
}); });
// Create a delegation with the foreign keys // Create a task with the foreign keys
$factory->state(\ProcessMaker\Model\Task::class, 'foreign_keys', function (Faker $faker) { $factory->state(\ProcessMaker\Model\Task::class, 'foreign_keys', function (Faker $faker) {
$process = factory(\ProcessMaker\Model\Process::class)->create(); $process = factory(\ProcessMaker\Model\Process::class)->create();
return [ return [
@@ -57,5 +58,29 @@ $factory->state(\ProcessMaker\Model\Task::class, 'foreign_keys', function (Faker
'TAS_OWNER_APP' => 'FALSE', 'TAS_OWNER_APP' => 'FALSE',
'TAS_CAN_SEND_MESSAGE' => 'FALSE', 'TAS_CAN_SEND_MESSAGE' => 'FALSE',
'TAS_SEND_LAST_EMAIL' => 'FALSE', 'TAS_SEND_LAST_EMAIL' => 'FALSE',
'TAS_SELFSERVICE_TIMEOUT' => 0,
];
});
// Create a task related with the self-service timeout execution
$factory->state(\ProcessMaker\Model\Task::class, 'sef_service_timeout', function (Faker $faker) {
$timeUnit = $faker->randomElement(['MINUTES', 'HOURS', 'DAYS']);
$execution = $faker->randomElement(['EVERY_TIME', 'ONCE']);
return [
'TAS_UID' => G::generateUniqueID(),
'TAS_ID' => $faker->unique()->numberBetween(1, 200000),
'TAS_TITLE' => $faker->sentence(2),
'TAS_TYPE' => 'NORMAL',
'TAS_TYPE_DAY' => 1,
'TAS_DURATION' => 1,
'TAS_ASSIGN_TYPE' => 'SELF_SERVICE',
'TAS_ASSIGN_VARIABLE' => '@@SYS_NEXT_USER_TO_BE_ASSIGNED',
'TAS_SELFSERVICE_TIMEOUT' => 1,
'TAS_SELFSERVICE_TIME' => $faker->unique()->numberBetween(1, 24),
'TAS_SELFSERVICE_TIME_UNIT' => $timeUnit,
'TAS_SELFSERVICE_TRIGGER_UID' => function() {
return $trigger = factory(\ProcessMaker\Model\Triggers::class)->create()->TRI_UID;
},
'TAS_SELFSERVICE_EXECUTION' => $execution,
]; ];
}); });

View File

@@ -12,7 +12,7 @@ $factory->define(Triggers::class, function (Faker $faker) {
return factory(\ProcessMaker\Model\Process::class)->create()->PRO_UID; return factory(\ProcessMaker\Model\Process::class)->create()->PRO_UID;
}, },
'TRI_TYPE' => 'SCRIPT', 'TRI_TYPE' => 'SCRIPT',
'TRI_WEBBOT' => $faker->text, 'TRI_WEBBOT' => '$var = 1;',
'TRI_PARAM' => '', 'TRI_PARAM' => '',
]; ];
}); });

View File

@@ -3,6 +3,7 @@
use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Request; use Illuminate\Support\Facades\Request;
use ProcessMaker\Core\System; use ProcessMaker\Core\System;
use ProcessMaker\Log\AuditLog;
use ProcessMaker\Plugins\PluginRegistry; use ProcessMaker\Plugins\PluginRegistry;
use ProcessMaker\Services\OAuth2\Server; use ProcessMaker\Services\OAuth2\Server;
use ProcessMaker\Validation\ValidationUploadedFiles; use ProcessMaker\Validation\ValidationUploadedFiles;

View File

@@ -876,8 +876,6 @@ EOREGEX;
} }
break; break;
} }
$shouldItContinue = false;
switch ($upper) { switch ($upper) {
case 'AS': case 'AS':
$token_count ++; $token_count ++;
@@ -888,7 +886,6 @@ EOREGEX;
++ $n; ++ $n;
} }
$shouldItContinue = true;
break; break;
case 'INDEX': case 'INDEX':
if ($token_category == 'CREATE') { if ($token_category == 'CREATE') {
@@ -910,12 +907,10 @@ EOREGEX;
case 'OUTER': case 'OUTER':
# $expression .= $token; # $expression .= $token;
$token_count ++; $token_count ++;
$shouldItContinue = true;
break; break;
case 'FOR': case 'FOR':
$token_count ++; $token_count ++;
$skip_next = true; $skip_next = true;
$shouldItContinue = true;
break; break;
case 'LEFT': case 'LEFT':
case 'RIGHT': case 'RIGHT':
@@ -971,7 +966,6 @@ EOREGEX;
break; break;
default: default:
if ($token === false || empty( $token ) || $token === "") { if ($token === false || empty( $token ) || $token === "") {
$shouldItContinue = true;
break; break;
} }
@@ -985,9 +979,6 @@ EOREGEX;
$token_count ++; $token_count ++;
break; break;
} }
if ($shouldItContinue === true) {
continue;
}
++ $i; ++ $i;
} }
if (substr( trim( $table ), 0, 1 ) == '(') { if (substr( trim( $table ), 0, 1 ) == '(') {

View File

@@ -0,0 +1,50 @@
<?php
namespace Tests\unit\workflow\engine\classes;
use Tests\TestCase;
use WorkspaceTools;
class WorkflowToolsTest extends TestCase
{
private $workspaceTools;
/**
* Method set up.
*/
public function setUp()
{
parent::setUp();
$this->workspaceTools = new WorkspaceTools('workflow');
}
/**
* Method tear down.
*/
public function tearDown()
{
parent::tearDown();
}
/**
* This test the addAsyncOptionToSchedulerCommands method.
* @test
* @covers \WorkspaceTools::addAsyncOptionToSchedulerCommands()
*/
public function it_should_test_addAsyncOptionToSchedulerCommands_method()
{
//method "WorkspaceTools::initPropel(true)" crashes all connections
$message = "WorkspaceTools::initPropel(true) crashes all connections";
$this->markTestIncomplete($message);
ob_start();
$this->workspaceTools->addAsyncOptionToSchedulerCommands(false);
$string = ob_get_clean();
$this->assertRegExp("/This was previously updated/", $string);
ob_start();
$this->workspaceTools->addAsyncOptionToSchedulerCommands(true);
$string = ob_get_clean();
$this->assertRegExp("/Adding \+async option/", $string);
}
}

View File

@@ -4,22 +4,26 @@ namespace ProcessMaker\BusinessModel;
use Exception; use Exception;
use G; use G;
use ProcessMaker\BusinessModel\Cases; use Illuminate\Support\Facades\DB;
use ProcessMaker\Model\Application; use ProcessMaker\Model\Application;
use ProcessMaker\Model\Delegation; use ProcessMaker\Model\Delegation;
use ProcessMaker\Model\Documents; use ProcessMaker\Model\Documents;
use ProcessMaker\Model\ListUnassigned;
use ProcessMaker\Model\Process;
use ProcessMaker\Model\Step;
use ProcessMaker\Model\Task;
use ProcessMaker\Model\Triggers;
use ProcessMaker\Model\User; use ProcessMaker\Model\User;
use RBAC; use RBAC;
use Tests\TestCase; use Tests\TestCase;
/** /**
* Class DelegationTest * Class CasesTest
* *
* @coversDefaultClass \ProcessMaker\BusinessModel\Cases * @coversDefaultClass \ProcessMaker\BusinessModel\Cases
*/ */
class CasesTest extends TestCase class CasesTest extends TestCase
{ {
/** /**
* Set up method. * Set up method.
*/ */
@@ -233,4 +237,144 @@ class CasesTest extends TestCase
// Call the uploadFiles method // Call the uploadFiles method
$case->uploadFiles($user->USR_UID, $application->APP_UID, $varName, -1, null, $delegation->DEL_INDEX); $case->uploadFiles($user->USR_UID, $application->APP_UID, $varName, -1, null, $delegation->DEL_INDEX);
} }
/**
* This test the execution of trigger from cases related to the self services timeout
*
* @covers \ProcessMaker\BusinessModel\Cases::executeSelfServiceTimeout()
* @test
*/
public function it_execute_trigger_from_cases_with_self_service_timeout_every_time()
{
ListUnassigned::truncate();
// Define the Execute Trigger = EVERY_TIME
$application = factory(Application::class)->states('foreign_keys')->create();
// Create a trigger
$trigger = factory(Triggers::class)->create([
'PRO_UID' => $application->PRO_UID,
'TRI_WEBBOT' => 'echo(1);'
]);
// Create a task with the configuration trigger execution
$task = factory(Task::class)->states('sef_service_timeout')->create([
'PRO_UID' => $application->PRO_UID,
'TAS_SELFSERVICE_EXECUTION' => 'EVERY_TIME',
'TAS_SELFSERVICE_TRIGGER_UID' => $trigger->TRI_UID
]);
// Create a unassigned cases
factory(ListUnassigned::class)->create([
'TAS_UID' => $task->TAS_UID,
'TAS_ID' => $task->TAS_ID,
'APP_NUMBER' => $application->APP_NUMBER,
'APP_UID' => $application->APP_UID,
'PRO_UID' => $application->PRO_UID
]);
// Define the session
$_SESSION["PROCESS"] = $application->PRO_UID;
// todo: the function Cases::loadCase is using propel we need to change this
DB::commit();
$casesExecuted = Cases::executeSelfServiceTimeout();
$this->assertTrue(is_array($casesExecuted));
}
/**
* This test the execution of trigger from cases related to the self services timeout
*
* @covers \ProcessMaker\BusinessModel\Cases::executeSelfServiceTimeout()
* @test
*/
public function it_execute_trigger_from_cases_with_self_service_timeout_once()
{
ListUnassigned::truncate();
// Define the Execute Trigger = ONCE
$application = factory(Application::class)->states('foreign_keys')->create();
// Create a trigger
$trigger = factory(Triggers::class)->create([
'PRO_UID' => $application->PRO_UID,
'TRI_WEBBOT' => 'echo(1);'
]);
// Create a task with the configuration trigger execution
$task = factory(Task::class)->states('sef_service_timeout')->create([
'PRO_UID' => $application->PRO_UID,
'TAS_SELFSERVICE_EXECUTION' => 'ONCE',
'TAS_SELFSERVICE_TRIGGER_UID' => $trigger->TRI_UID
]);
// Create a unassigned cases
factory(ListUnassigned::class)->create([
'TAS_UID' => $task->TAS_UID,
'TAS_ID' => $task->TAS_ID,
'APP_NUMBER' => $application->APP_NUMBER,
'APP_UID' => $application->APP_UID,
'PRO_UID' => $application->PRO_UID
]);
// Define the session
$_SESSION["PROCESS"] = $application->PRO_UID;
// todo: the function Cases::loadCase is using propel we need to change this
DB::commit();
$casesExecuted = Cases::executeSelfServiceTimeout();
$this->assertTrue(is_array($casesExecuted));
}
/**
* It test get assigned DynaForms as steps by application Uid
*
* @covers \ProcessMaker\BusinessModel\Cases::dynaFormsByApplication()
* @test
*/
public function it_should_test_get_dynaforms_by_application()
{
// Create a process
$process = factory(Process::class)->create();
// Create a task related to the process
$task1 = factory(Task::class)->create([
'PRO_UID' => $process->PRO_UID
]);
// Created another task related to the process
$task2 = factory(Task::class)->create([
'PRO_UID' => $process->PRO_UID
]);
// Created a step related to the first task
factory(Step::class)->create([
'PRO_UID' => $process->PRO_UID,
'TAS_UID' => $task1->TAS_UID,
'STEP_TYPE_OBJ' => 'DYNAFORM',
'STEP_UID_OBJ' => G::generateUniqueID(),
'STEP_POSITION' => 1
]);
// Created a step related to the second task and with a specific DynaForm Uid
$dynUid = G::generateUniqueID();
factory(Step::class)->create([
'PRO_UID' => $process->PRO_UID,
'TAS_UID' => $task2->TAS_UID,
'STEP_TYPE_OBJ' => 'DYNAFORM',
'STEP_UID_OBJ' => $dynUid,
'STEP_POSITION' => 1
]);
// Create an application related to the process in draft status
$application = factory(Application::class)->create([
'PRO_UID' => $process->PRO_UID,
'APP_STATUS' => 'DRAFT'
]);
// Get all DynaForms assigned as steps
self::assertCount(2, Cases::dynaFormsByApplication($application->APP_UID));
// Get DynaForms assigned as steps for the first task
self::assertCount(1, Cases::dynaFormsByApplication($application->APP_UID, $task1->TAS_UID));
// Get DynaForms assigned as steps sending a specific DynaForm Uid
self::assertCount(1, Cases::dynaFormsByApplication($application->APP_UID, '', $dynUid));
// Get DynaForms assigned as steps for the second task when the application status is DRAFT
self::assertCount(1, Cases::dynaFormsByApplication($application->APP_UID, $task2->TAS_UID, '', 'TO_DO'));
// Get DynaForms assigned as steps for the second task when the application status is COMPLETED
self::assertCount(2, Cases::dynaFormsByApplication($application->APP_UID, $task2->TAS_UID, '', 'COMPLETED'));
}
} }

View File

@@ -0,0 +1,120 @@
<?php
namespace Tests\unit\workflow\engine\src\ProcessMaker\Model;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use ProcessMaker\Model\AppTimeoutAction;
use Tests\TestCase;
/**
* Class DelegationTest
*
* @coversDefaultClass \ProcessMaker\Model\AppTimeoutAction
*/
class AppTimeoutActionTest extends TestCase
{
use DatabaseTransactions;
/**
* Test set and get the caseUid property
*
* @covers \ProcessMaker\Model\AppTimeoutAction::setCaseUid()
* @covers \ProcessMaker\Model\AppTimeoutAction::getCaseUid()
* @test
*/
public function it_set_get_case_uid()
{
factory(AppTimeoutAction::class)->create();
$timeout = factory(AppTimeoutAction::class)->create();
$timeout->setCaseUid($timeout->APP_UID);
$this->assertEquals($timeout->getCaseUid(), $timeout->APP_UID);
}
/**
* Test set and get the index property
*
* @covers \ProcessMaker\Model\AppTimeoutAction::setIndex()
* @covers \ProcessMaker\Model\AppTimeoutAction::getIndex()
* @test
*/
public function it_set_get_index()
{
factory(AppTimeoutAction::class)->create();
$timeout = factory(AppTimeoutAction::class)->create();
$timeout->setIndex($timeout->DEL_INDEX);
$this->assertEquals($timeout->getIndex(), $timeout->DEL_INDEX);
}
/**
* Test a query to only include a specific case
*
* @covers \ProcessMaker\Model\AppTimeoutAction::scopeCase()
* @test
*/
public function it_filter_a_specific_case()
{
factory(AppTimeoutAction::class)->create();
$timeout = factory(AppTimeoutAction::class)->create();
$this->assertCount(1, $timeout->case($timeout->APP_UID)->get());
}
/**
* Test scope a query to only include a specific case
*
* @covers \ProcessMaker\Model\AppTimeoutAction::scopeIndex()
* @test
*/
public function it_filter_a_specific_index()
{
factory(AppTimeoutAction::class)->create();
$timeout = factory(AppTimeoutAction::class)->create();
$this->assertCount(1, $timeout->case($timeout->APP_UID)->index($timeout->DEL_INDEX)->get());
}
/**
* This checks it returns information about the self service timeout in a sequential thread
*
* @covers \ProcessMaker\Model\AppTimeoutAction::cases()
* @test
*/
public function it_return_the_case_executed_once_one_thread()
{
$records = factory(AppTimeoutAction::class, 5)->create();
foreach ($records as $row) {
$appUid = $row->APP_UID;
$delIndex = $row->DEL_INDEX;
}
$appTimeout = new AppTimeoutAction();
$appTimeout->setCaseUid($appUid);
$appTimeout->setIndex($delIndex);
$caseExecuted = $appTimeout->cases();
$this->assertNotEmpty($caseExecuted);
}
/**
* This checks it returns information about the self service timeout in a parallel thread
*
* @covers \ProcessMaker\Model\AppTimeoutAction::cases()
* @test
*/
public function it_return_the_case_executed_once_more_than_one_thread()
{
$records = factory(AppTimeoutAction::class, 5)->create();
foreach ($records as $row) {
$appUid = $row->APP_UID;
$delIndex = $row->DEL_INDEX;
}
// Create other thread in the same case
factory(AppTimeoutAction::class)->create([
'APP_UID' => $appUid,
'DEL_INDEX' => $delIndex + 1,
]);
$appTimeout = new AppTimeoutAction();
$appTimeout->setCaseUid($appUid);
$appTimeout->setIndex($delIndex);
$caseExecuted = $appTimeout->cases();
$this->assertNotEmpty($caseExecuted);
}
}

View File

@@ -300,5 +300,25 @@ class ListUnassignedTest extends TestCase
$result = ListUnassigned::loadList($user->USR_UID, $filters); $result = ListUnassigned::loadList($user->USR_UID, $filters);
$this->assertCount(2, $result); $this->assertCount(2, $result);
} }
/**
* This checks the self-service timeout cases
*
* @covers \ProcessMaker\Model\ListUnassigned::selfServiceTimeout()
* @test
*/
public function it_should_return_cases_configured_self_service_timeout()
{
// Create some cases configured the self service timeout
for ($x = 1; $x <= 5; $x++) {
$task = factory(Task::class)->states('sef_service_timeout')->create();
factory(ListUnassigned::class)->create([
'TAS_UID' => $task->TAS_UID,
'TAS_ID' => $task->TAS_ID
]);
}
$results = ListUnassigned::selfServiceTimeout();
$this->assertCount(5, $results);
}
} }

View File

@@ -19,6 +19,15 @@ class ProcessTest extends TestCase
{ {
use DatabaseTransactions; use DatabaseTransactions;
/**
* Call the setUp parent method
*/
public function setUp()
{
parent::setUp();
Process::query()->delete();
}
/** /**
* Test belongs to PRO_ID * Test belongs to PRO_ID
* *
@@ -215,9 +224,9 @@ class ProcessTest extends TestCase
} }
/** /**
* It tests the convertPrivateProcessesToPublic method * It tests the convertPrivateProcessesToPublicAndUpdateUser method
* *
* @covers \ProcessMaker\Model\Process::convertPrivateProcessesToPublic() * @covers \ProcessMaker\Model\Process::convertPrivateProcessesToPublicAndUpdateUser()
* @test * @test
*/ */
public function it_should_test_the_convert_private_processes_to_public_method() public function it_should_test_the_convert_private_processes_to_public_method()
@@ -236,12 +245,100 @@ class ProcessTest extends TestCase
//Create a Process object //Create a Process object
$process = new Process(); $process = new Process();
//Call the convertPrivateProcessesToPublic() method //Call the convertPrivateProcessesToPublicAndUpdateUser() method
$process->convertPrivateProcessesToPublic($p); $process->convertPrivateProcessesToPublicAndUpdateUser($p, $pro->PRO_CREATE_USER);
$p = Process::where('PRO_UID', $pro->PRO_UID)->get()->values(); $p = Process::where('PRO_UID', $pro->PRO_UID)->get()->values();
// This asserts the process was converted from private to public // This asserts the process was converted from private to public
$this->assertEquals('PUBLIC', $p[0]->PRO_TYPE_PROCESS); $this->assertEquals('PUBLIC', $p[0]->PRO_TYPE_PROCESS);
} }
/**
* It tests the process list
*
* @covers \ProcessMaker\Model\Process::getProcessesFilter()
* @covers \ProcessMaker\Model\Process::scopeNoStatus()
* @covers \ProcessMaker\Model\Process::scopeSubProcess()
* @test
*/
public function it_should_test_process_without_filter()
{
$process = factory(Process::class)->create();
$result = Process::getProcessesFilter(
null,
null,
null,
$process->PRO_CREATE_USER
);
$this->assertEquals($process->PRO_CREATE_USER, $result[0]['USR_UID']);
}
/**
* It tests the process list with specific category
*
* @covers \ProcessMaker\Model\Process::getProcessesFilter()
* @covers \ProcessMaker\Model\Process::scopeCategory()
* @test
*/
public function it_should_test_process_with_category_filter()
{
$process = factory(Process::class)->create([
'PRO_CATEGORY' => function () {
return factory(ProcessCategory::class)->create()->CATEGORY_UID;
}
]);
$result = Process::getProcessesFilter(
$process->PRO_CATEGORY
);
$this->assertEquals($process->PRO_CATEGORY, $result[0]['PRO_CATEGORY']);
}
/**
* It tests the process list with specific process
*
* @covers \ProcessMaker\Model\Process::getProcessesFilter()
* @covers \ProcessMaker\Model\Process::scopeProcess()
* @test
*/
public function it_should_test_process_with_process_filter()
{
$process = factory(Process::class)->create();
$result = Process::getProcessesFilter(
null,
$process->PRO_UID
);
$this->assertEquals($process->PRO_UID, $result[0]['PRO_UID']);
}
/**
* It tests the process list with specific process title
*
* @covers \ProcessMaker\Model\Process::getProcessesFilter()
* @covers \ProcessMaker\Model\Process::scopeTitle()
* @test
*/
public function it_should_test_process_with_title_filter()
{
$process = factory(Process::class)->create();
$result = Process::getProcessesFilter(
null,
null,
$process->PRO_TITLE
);
$this->assertEquals($process->PRO_TITLE, $result[0]['PRO_TITLE']);
}
/**
* It tests the count process
*
* @covers \ProcessMaker\Model\Process::getCounter()
* @test
*/
public function it_should_test_count_process()
{
$process = factory(Process::class)->create();
$total = Process::getCounter($process->PRO_CREATE_USER);
$this->assertEquals(1, $total);
}
} }

View File

@@ -2,14 +2,40 @@
namespace Tests\unit\workflow\engine\src\ProcessMaker\Model; namespace Tests\unit\workflow\engine\src\ProcessMaker\Model;
use G;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use ProcessMaker\Model\Process; use ProcessMaker\Model\Process;
use ProcessMaker\Model\Triggers; use ProcessMaker\Model\Triggers;
use Tests\TestCase; use Tests\TestCase;
/**
* Class DelegationTest
*
* @coversDefaultClass \ProcessMaker\Model\Triggers
*/
class TriggersTest extends TestCase class TriggersTest extends TestCase
{ {
use DatabaseTransactions;
/**
* Test set and get the trigger property
*
* @covers \ProcessMaker\Model\Triggers::setTrigger()
* @covers \ProcessMaker\Model\Triggers::getTrigger()
* @test
*/
public function it_set_get_trigger()
{
factory(Triggers::class)->create();
$trigger = factory(Triggers::class)->create();
$trigger->setTrigger($trigger->TRI_UID);
$this->assertEquals($trigger->getTrigger(), $trigger->TRI_UID);
}
/** /**
* It tests the process scope in the trigger model * It tests the process scope in the trigger model
*
* @covers \ProcessMaker\Model\Triggers::scopeProcess()
* @test * @test
*/ */
public function it_should_test_process_scope_in_trigger_model() public function it_should_test_process_scope_in_trigger_model()
@@ -74,4 +100,48 @@ class TriggersTest extends TestCase
$this->assertEquals($process[2]['PRO_UID'], $result[0]['PRO_UID']); $this->assertEquals($process[2]['PRO_UID'], $result[0]['PRO_UID']);
$this->assertEquals($process[2]['PRO_UID'], $result[1]['PRO_UID']); $this->assertEquals($process[2]['PRO_UID'], $result[1]['PRO_UID']);
} }
/**
* Test scope a query to only include a specific case
*
* @covers \ProcessMaker\Model\Triggers::scopeTrigger()
* @test
*/
public function it_filter_specific_tasks()
{
factory(Triggers::class)->create();
$trigger = factory(Triggers::class)->create();
$this->assertCount(1, $trigger->trigger($trigger->TRI_UID)->get());
}
/**
* This checks it returns information about the trigger
*
* @covers \ProcessMaker\Model\Triggers::triggers()
* @test
*/
public function it_return_specific_trigger_information()
{
$triggers = factory(Triggers::class, 5)->create();
$trigger = new Triggers();
$trigger->setTrigger($triggers[0]->TRI_UID);
$triggersList = $trigger->triggers();
$this->assertCount(1, $triggersList);
$this->assertEquals($triggers[0]->TRI_TITLE , $triggersList[0]['TRI_TITLE']);
}
/**
* This checks it returns empty when the trigger does not exist
*
* @covers \ProcessMaker\Model\Triggers::triggers()
* @test
*/
public function it_return_empty_when_the_trigger_not_exist()
{
factory(Triggers::class)->create();
$trigger = new Triggers();
$trigger->setTrigger(G::generateUniqueID());
$triggersList = $trigger->triggers();
$this->assertEmpty($triggersList);
}
} }

View File

@@ -0,0 +1,560 @@
<?php
namespace Tests\unit\workflow\engine\src\ProcessMaker\TaskScheduler;
use App\Jobs\TaskScheduler;
use Faker\Factory;
use Illuminate\Support\Facades\Queue;
use ProcessMaker\Model\Application;
use ProcessMaker\Model\AppThread;
use ProcessMaker\Model\Delegation;
use ProcessMaker\TaskScheduler\Task;
use Tests\TestCase;
/**
* Class TaskTest
*
* @coversDefaultClass \ProcessMaker\TaskScheduler\Task
*/
class TaskTest extends TestCase
{
private $faker;
/**
* Method setUp.
*/
protected function setUp()
{
parent::setUp();
$this->faker = Factory::create();
Delegation::truncate();
AppThread::truncate();
Application::truncate();
}
/**
* Method tearDown.
*/
protected function tearDown()
{
parent::tearDown();
}
/**
* Test synchronous asynchronous cases.
*/
public function asynchronousCases()
{
return [
[true],
[false]
];
}
/**
* This test verify the setExecutionMessage method.
* @test
* @covers ProcessMaker\TaskScheduler\Task::runTask()
* @covers ProcessMaker\TaskScheduler\Task::setExecutionMessage()
* @dataProvider asynchronousCases
*/
public function it_should_test_setExecutionMessage_method($asynchronous)
{
$task = new Task($asynchronous, '');
$message = $this->faker->paragraph;
ob_start();
$task->setExecutionMessage($message);
$printing = ob_get_clean();
//assert if message is contained in output buffer
if ($asynchronous === false) {
$this->assertRegExp("/{$message}/", $printing);
}
//assert if not showing message
if ($asynchronous === true) {
$this->assertEmpty($printing);
}
}
/**
* This test verify the setExecutionResultMessage method.
* @test
* @covers ProcessMaker\TaskScheduler\Task::runTask()
* @covers ProcessMaker\TaskScheduler\Task::setExecutionResultMessage()
* @dataProvider asynchronousCases
*/
public function it_should_test_setExecutionResultMessage_method($asynchronous)
{
$task = new Task($asynchronous, '');
$message = $this->faker->paragraph;
ob_start();
$task->setExecutionResultMessage($message, 'error');
$printing = ob_get_clean();
//assert if message is contained in output buffer
if ($asynchronous === false) {
$this->assertRegExp("/{$message}/", $printing);
}
//assert if not showing message
if ($asynchronous === true) {
$this->assertEmpty($printing);
}
ob_start();
$task->setExecutionResultMessage($message, 'info');
$printing = ob_get_clean();
//assert if message is contained in output buffer
if ($asynchronous === false) {
$this->assertRegExp("/{$message}/", $printing);
}
//assert if not showing message
if ($asynchronous === true) {
$this->assertEmpty($printing);
}
ob_start();
$task->setExecutionResultMessage($message, 'warning');
$printing = ob_get_clean();
//assert if message is contained in output buffer
if ($asynchronous === false) {
$this->assertRegExp("/{$message}/", $printing);
}
//assert if not showing message
if ($asynchronous === true) {
$this->assertEmpty($printing);
}
}
/**
* This test verify the saveLog method.
* @test
* @covers ProcessMaker\TaskScheduler\Task::runTask()
* @covers ProcessMaker\TaskScheduler\Task::saveLog()
* @dataProvider asynchronousCases
*/
public function it_should_test_saveLog_method($asynchronous)
{
$task = new Task(false, '');
$task->saveLog('', '', $this->faker->paragraph);
$file = PATH_DATA . "log/cron.log";
$this->assertFileExists($file);
if ($asynchronous === false) {
$description = $this->faker->paragraph;
$task = new Task($asynchronous, '');
$task->saveLog('', '', $description);
$contentLog = file_get_contents($file);
$this->assertRegExp("/{$description}/", $contentLog);
}
if ($asynchronous === true) {
$description = $this->faker->paragraph;
$task = new Task($asynchronous, '');
$task->saveLog('', '', $description);
$contentLog = file_get_contents($file);
$this->assertNotRegExp("/{$description}/", $contentLog);
}
}
/**
* This test verify the resendEmails activity method for synchronous and asynchronous execution.
* @test
* @covers ProcessMaker\TaskScheduler\Task::runTask()
* @covers ProcessMaker\TaskScheduler\Task::resendEmails()
* @dataProvider asynchronousCases
*/
public function it_should_test_resendEmails_method($asynchronous)
{
$task = new Task($asynchronous, '');
$dateSystem = $this->faker->date();
//assert synchronous for cron file
if ($asynchronous === false) {
ob_start();
$task->resendEmails('', $dateSystem);
$printing = ob_get_clean();
$this->assertRegExp("/DONE/", $printing);
}
//assert asynchronous for job process
if ($asynchronous === true) {
Queue::fake();
Queue::assertNothingPushed();
$task->resendEmails('', $dateSystem);
Queue::assertPushed(TaskScheduler::class);
}
}
/**
* This test verify the unpauseApplications activity method for synchronous and asynchronous execution.
* @test
* @covers ProcessMaker\TaskScheduler\Task::runTask()
* @covers ProcessMaker\TaskScheduler\Task::unpauseApplications()
* @dataProvider asynchronousCases
*/
public function it_should_test_unpauseApplications_method($asynchronous)
{
$task = new Task($asynchronous, '');
//assert synchronous for cron file
if ($asynchronous === false) {
ob_start();
$task->unpauseApplications('');
$printing = ob_get_clean();
$this->assertRegExp("/DONE/", $printing);
}
//assert asynchronous for job process
if ($asynchronous === true) {
Queue::fake();
Queue::assertNothingPushed();
$task->unpauseApplications('');
Queue::assertPushed(TaskScheduler::class);
}
}
/**
* This test verify the calculateDuration activity method for synchronous and asynchronous execution.
* @test
* @covers ProcessMaker\TaskScheduler\Task::runTask()
* @covers ProcessMaker\TaskScheduler\Task::calculateDuration()
* @dataProvider asynchronousCases
*/
public function it_should_test_calculateDuration_method($asynchronous)
{
$task = new Task($asynchronous, '');
//assert synchronous for cron file
if ($asynchronous === false) {
ob_start();
$task->calculateDuration();
$printing = ob_get_clean();
$this->assertRegExp("/DONE/", $printing);
}
//assert asynchronous for job process
if ($asynchronous === true) {
Queue::fake();
Queue::assertNothingPushed();
$task->calculateDuration();
Queue::assertPushed(TaskScheduler::class);
}
}
/**
* This test verify the calculateDuration activity method for synchronous and asynchronous execution.
* @covers ProcessMaker\TaskScheduler\Task::executeCaseSelfService()
* @test
* @dataProvider asynchronousCases
*/
public function it_should_test_unassignedcase($asynchronous)
{
$task = new Task($asynchronous, '');
// Assert synchronous for cron file
if ($asynchronous === false) {
ob_start();
$task->executeCaseSelfService();
$printing = ob_get_clean();
$this->assertRegExp("/Unassigned case/", $printing);
}
// Assert asynchronous for job process
if ($asynchronous === true) {
Queue::fake();
Queue::assertNothingPushed();
$task->executeCaseSelfService();
Queue::assertPushed(TaskScheduler::class);
}
}
/**
* This test verify the calculateAppDuration activity method for synchronous and asynchronous execution.
* @test
* @covers ProcessMaker\TaskScheduler\Task::runTask()
* @covers ProcessMaker\TaskScheduler\Task::calculateAppDuration()
* @dataProvider asynchronousCases
*/
public function it_should_test_calculateAppDuration_method($asynchronous)
{
$task = new Task($asynchronous, '');
//assert synchronous for cron file
if ($asynchronous === false) {
ob_start();
$task->calculateAppDuration();
$printing = ob_get_clean();
$this->assertRegExp("/DONE/", $printing);
}
//assert asynchronous for job process
if ($asynchronous === true) {
Queue::fake();
Queue::assertNothingPushed();
$task->calculateAppDuration();
Queue::assertPushed(TaskScheduler::class);
}
}
/**
* This test verify the cleanSelfServiceTables activity method for synchronous and asynchronous execution.
* @test
* @covers ProcessMaker\TaskScheduler\Task::runTask()
* @covers ProcessMaker\TaskScheduler\Task::cleanSelfServiceTables()
* @dataProvider asynchronousCases
*/
public function it_should_test_cleanSelfServiceTables_method($asynchronous)
{
$task = new Task($asynchronous, '');
//assert synchronous for cron file
if ($asynchronous === false) {
ob_start();
$task->cleanSelfServiceTables();
$printing = ob_get_clean();
$this->assertRegExp("/DONE/", $printing);
}
//assert asynchronous for job process
if ($asynchronous === true) {
Queue::fake();
Queue::assertNothingPushed();
$task->cleanSelfServiceTables();
Queue::assertPushed(TaskScheduler::class);
}
}
/**
* This test verify the executePlugins activity method for synchronous and asynchronous execution.
* @test
* @covers ProcessMaker\TaskScheduler\Task::runTask()
* @covers ProcessMaker\TaskScheduler\Task::executePlugins()
* @dataProvider asynchronousCases
*/
public function it_should_test_executePlugins_method($asynchronous)
{
$task = new Task($asynchronous, '');
//assert synchronous for cron file
if ($asynchronous === false) {
ob_start();
$task->executePlugins();
$printing = ob_get_clean();
$this->assertRegExp("/plugins/", $printing);
}
//assert asynchronous for job process
if ($asynchronous === true) {
Queue::fake();
Queue::assertNothingPushed();
$task->executePlugins();
Queue::assertPushed(TaskScheduler::class);
}
}
/**
* This test verify the fillReportByUser activity method for synchronous and asynchronous execution.
* @test
* @covers ProcessMaker\TaskScheduler\Task::runTask()
* @covers ProcessMaker\TaskScheduler\Task::fillReportByUser()
* @dataProvider asynchronousCases
*/
public function it_should_test_fillReportByUser_method($asynchronous)
{
$task = new Task($asynchronous, '');
$dateInit = $this->faker->dateTime;
$dateFinish = $this->faker->dateTime;
//assert synchronous for cron file
if ($asynchronous === false) {
ob_start();
$task->fillReportByUser($dateInit, $dateFinish);
$printing = ob_get_clean();
$this->assertRegExp("/User Reporting/", $printing);
}
//assert asynchronous for job process
if ($asynchronous === true) {
Queue::fake();
Queue::assertNothingPushed();
$task->fillReportByUser($dateInit, $dateFinish);
Queue::assertPushed(TaskScheduler::class);
}
}
/**
* This test verify the fillReportByProcess activity method for synchronous and asynchronous execution.
* @test
* @covers ProcessMaker\TaskScheduler\Task::runTask()
* @covers ProcessMaker\TaskScheduler\Task::fillReportByProcess()
* @dataProvider asynchronousCases
*/
public function it_should_test_fillReportByProcess_method($asynchronous)
{
$task = new Task($asynchronous, '');
$dateInit = $this->faker->dateTime;
$dateFinish = $this->faker->dateTime;
//assert synchronous for cron file
if ($asynchronous === false) {
ob_start();
$task->fillReportByProcess($dateInit, $dateFinish);
$printing = ob_get_clean();
$this->assertRegExp("/Process Reporting/", $printing);
}
//assert asynchronous for job process
if ($asynchronous === true) {
Queue::fake();
Queue::assertNothingPushed();
$task->fillReportByProcess($dateInit, $dateFinish);
Queue::assertPushed(TaskScheduler::class);
}
}
/**
* This test verify the ldapcron activity method for synchronous and asynchronous execution.
* @test
* @covers ProcessMaker\TaskScheduler\Task::runTask()
* @covers ProcessMaker\TaskScheduler\Task::ldapcron()
* @dataProvider asynchronousCases
*/
public function it_should_test_ldapcron_method($asynchronous)
{
$task = new Task($asynchronous, '');
//assert synchronous for cron file
if ($asynchronous === false) {
ob_start();
$task->ldapcron(false);
$printing = ob_get_clean();
$this->assertRegExp("/\+---/", $printing);
}
//assert asynchronous for job process
if ($asynchronous === true) {
Queue::fake();
Queue::assertNothingPushed();
$task->ldapcron(false);
Queue::assertPushed(TaskScheduler::class);
}
}
/**
* This test verify the sendNotifications activity method for synchronous and asynchronous execution.
* @test
* @covers ProcessMaker\TaskScheduler\Task::runTask()
* @covers ProcessMaker\TaskScheduler\Task::sendNotifications()
* @dataProvider asynchronousCases
*/
public function it_should_test_sendNotifications_method($asynchronous)
{
$task = new Task($asynchronous, '');
//assert synchronous for cron file
if ($asynchronous === false) {
ob_start();
$task->sendNotifications();
$printing = ob_get_clean();
$this->assertRegExp("/Resending Notifications/", $printing);
}
//assert asynchronous for job process
if ($asynchronous === true) {
Queue::fake();
Queue::assertNothingPushed();
$task->sendNotifications();
Queue::assertPushed(TaskScheduler::class);
}
}
/**
* This test verify the actionsByEmailResponse activity method for synchronous and asynchronous execution.
* @test
* @covers ProcessMaker\TaskScheduler\Task::runTask()
* @covers ProcessMaker\TaskScheduler\Task::actionsByEmailResponse()
* @dataProvider asynchronousCases
*/
public function it_should_test_actionsByEmailResponse_method($asynchronous)
{
$task = new Task($asynchronous, '');
//assert synchronous for cron file
if ($asynchronous === false) {
ob_start();
$task->actionsByEmailResponse();
$printing = ob_get_clean();
$this->assertEmpty($printing);
}
//assert asynchronous for job process
if ($asynchronous === true) {
Queue::fake();
Queue::assertNothingPushed();
$task->actionsByEmailResponse();
Queue::assertPushed(TaskScheduler::class);
}
}
/**
* This test verify the messageeventcron activity method for synchronous and asynchronous execution.
* @test
* @covers ProcessMaker\TaskScheduler\Task::runTask()
* @covers ProcessMaker\TaskScheduler\Task::messageeventcron()
* @dataProvider asynchronousCases
*/
public function it_should_test_messageeventcron_method($asynchronous)
{
$task = new Task($asynchronous, '');
//assert synchronous for cron file
if ($asynchronous === false) {
ob_start();
$task->messageeventcron();
$printing = ob_get_clean();
$this->assertRegExp("/Message-Events/", $printing);
}
//assert asynchronous for job process
if ($asynchronous === true) {
Queue::fake();
Queue::assertNothingPushed();
$task->messageeventcron();
Queue::assertPushed(TaskScheduler::class);
}
}
/**
* Tests the timerEventCron method with jobs in the task scheduler
*
* @test
* @covers ProcessMaker\TaskScheduler\Task::timerEventCron()
* @dataProvider asynchronousCases
*/
public function it_should_test_the_timer_event_cron_method($asynchronous)
{
//Creates a new task
$task = new Task($asynchronous, '');
//Sets the currect date
$date = date('Y-m-d H:i:s');
//assert synchronous for cron file
if ($asynchronous === false) {
ob_start();
//Calls the timerEventCron method
$task->timerEventCron($date, true);
//Gets the result
$printing = ob_get_clean();
//Asserts the result is printing that there is no exisiting records to continue a case in the determined date
$this->assertRegExp('/No existing records to continue a case, on date "' . $date . '/', $printing);
}
//assert asynchronous for job process
if ($asynchronous === true) {
Queue::fake();
Queue::assertNothingPushed();
$task->timerEventCron($date, true);
Queue::assertPushed(TaskScheduler::class);
}
}
}

View File

@@ -0,0 +1,44 @@
<?php
namespace Tests\unit\workflow\engine\src\ProcessMaker\Util\Helpers;
use Tests\TestCase;
class CalculateDateTest extends TestCase
{
/**
* It tests the addition of days
*
* @test
*/
public function it_test_adding_days()
{
$iniDate = '2019-10-04 12:07:40';
$newDate = calculateDate($iniDate, 'DAYS', 1);
$this->assertEquals('2019-10-05 12:07:40', $newDate);
}
/**
* It tests the addition of hours
*
* @test
*/
public function it_test_adding_hours()
{
$iniDate = '2019-10-04 12:07:40';
$newDate = calculateDate($iniDate, 'HOURS', 1);
$this->assertEquals('2019-10-04 13:07:40', $newDate);
}
/**
* It tests the addition of minutes
*
* @test
*/
public function it_test_adding_minutes()
{
$iniDate = '2019-10-04 12:07:40';
$newDate = calculateDate($iniDate, 'MINUTES', 10);
$this->assertEquals('2019-10-04 12:17:40', $newDate);
}
}

View File

@@ -4,7 +4,7 @@ namespace Tests\unit\workflow\src\ProcessMaker\Util\Helpers;
use Tests\TestCase; use Tests\TestCase;
class ChangeAbbreviationOfDirectives extends TestCase class ChangeAbbreviationOfDirectivesTest extends TestCase
{ {
/** /**
* Provider to define different types of configurations in the php.ini and the result expected * Provider to define different types of configurations in the php.ini and the result expected

View File

@@ -17,11 +17,12 @@ try {
'ldapcron' => ['title' => 'LDAP Advanced CRON'], 'ldapcron' => ['title' => 'LDAP Advanced CRON'],
'messageeventcron' => ['title' => 'Message-Event CRON'], 'messageeventcron' => ['title' => 'Message-Event CRON'],
'timereventcron' => ['title' => 'Timer-Event CRON'], 'timereventcron' => ['title' => 'Timer-Event CRON'],
'sendnotificationscron' => ['title' => 'Send-Notifications CRON'] 'sendnotificationscron' => ['title' => 'Send-Notifications CRON'],
'webentriescron' => ['title' => 'Web Entries CRON']
]; ];
//Define constants //Define constants
define('PATH_SEP', ($osIsLinux)? '/' : '\\'); define('PATH_SEP', ($osIsLinux) ? '/' : '\\');
$arrayPathToCron = []; $arrayPathToCron = [];
$flagPathToCron = false; $flagPathToCron = false;
@@ -86,12 +87,12 @@ try {
$arraySystemConfiguration = System::getSystemConfiguration(); $arraySystemConfiguration = System::getSystemConfiguration();
$e_all = (defined('E_DEPRECATED'))? E_ALL & ~E_DEPRECATED : E_ALL; $e_all = (defined('E_DEPRECATED')) ? E_ALL & ~E_DEPRECATED : E_ALL;
$e_all = (defined('E_STRICT'))? $e_all & ~E_STRICT : $e_all; $e_all = (defined('E_STRICT')) ? $e_all & ~E_STRICT : $e_all;
$e_all = ($arraySystemConfiguration['debug'])? $e_all : $e_all & ~E_NOTICE; $e_all = ($arraySystemConfiguration['debug']) ? $e_all : $e_all & ~E_NOTICE;
//In community version the default value is 0 //In community version the default value is 0
$systemUtcTimeZone = (int)($arraySystemConfiguration['system_utc_time_zone']) == 1; $systemUtcTimeZone = (int) ($arraySystemConfiguration['system_utc_time_zone']) == 1;
app()->useStoragePath(realpath(PATH_DATA)); app()->useStoragePath(realpath(PATH_DATA));
app()->make(Kernel::class)->bootstrap(); app()->make(Kernel::class)->bootstrap();
@@ -128,7 +129,8 @@ try {
if (in_array($arrayCommandOption['force'], $argv)) { if (in_array($arrayCommandOption['force'], $argv)) {
unset($argv[array_search($arrayCommandOption['force'], $argv)]); unset($argv[array_search($arrayCommandOption['force'], $argv)]);
//reindex keys
$argv = array_values($argv);
$force = true; $force = true;
} }
@@ -137,8 +139,8 @@ try {
//Get data of CRON file //Get data of CRON file
$arrayCron = unserialize(trim(file_get_contents(PATH_DATA . $cronName))); $arrayCron = unserialize(trim(file_get_contents(PATH_DATA . $cronName)));
$flagIsRunning = (bool)((isset($arrayCron['flagIsRunning']))? $arrayCron['flagIsRunning'] : $arrayCron['bCronIsRunning']); $flagIsRunning = (bool) ((isset($arrayCron['flagIsRunning'])) ? $arrayCron['flagIsRunning'] : $arrayCron['bCronIsRunning']);
$lastExecution = (isset($arrayCron['lastExecution']))? $arrayCron['lastExecution'] : $arrayCron['sLastExecution']; $lastExecution = (isset($arrayCron['lastExecution'])) ? $arrayCron['lastExecution'] : $arrayCron['sLastExecution'];
} }
if (!$force && $osIsLinux) { if (!$force && $osIsLinux) {
@@ -189,7 +191,7 @@ try {
} }
if (!$flagDate) { if (!$flagDate) {
$argvx = $argvx . (($argvx != '')? ' ' : '') . $argv[$i]; $argvx = $argvx . (($argvx != '') ? ' ' : '') . $argv[$i];
} }
} }
} }
@@ -208,8 +210,8 @@ try {
if (is_dir(PATH_DB . $entry)) { if (is_dir(PATH_DB . $entry)) {
if (file_exists(PATH_DB . $entry . PATH_SEP . 'db.php')) { if (file_exists(PATH_DB . $entry . PATH_SEP . 'db.php')) {
$counterw++; $counterw++;
$command = 'php -f "' . $cronSinglePath . '" "' . base64_encode(PATH_HOME) . '" "' . base64_encode(PATH_TRUNK) . '" "' . base64_encode(PATH_OUTTRUNK) . '" ' . $cronName . ' ' . $entry . ' "' . $date . '" ' . $argvx;
passthru('php -f "' . $cronSinglePath . '" "' . base64_encode(PATH_HOME) . '" "' . base64_encode(PATH_TRUNK) . '" "' . base64_encode(PATH_OUTTRUNK) . '" ' . $cronName . ' ' . $entry . ' "' . $date . '" ' . $argvx); passthru($command);
} }
} }
} }
@@ -220,8 +222,8 @@ try {
} }
$counterw++; $counterw++;
$command = 'php -f "' . $cronSinglePath . '" "' . base64_encode(PATH_HOME) . '" "' . base64_encode(PATH_TRUNK) . '" "' . base64_encode(PATH_OUTTRUNK) . '" ' . $cronName . ' ' . $workspace . ' "' . $date . '" ' . $argvx;
passthru('php -f "' . $cronSinglePath . '" "' . base64_encode(PATH_HOME) . '" "' . base64_encode(PATH_TRUNK) . '" "' . base64_encode(PATH_OUTTRUNK) . '" ' . $cronName . ' ' . $workspace . ' "' . $date . '" ' . $argvx); passthru($command);
} }
eprintln('Finished ' . $counterw . ' workspaces processed'); eprintln('Finished ' . $counterw . ' workspaces processed');
@@ -234,13 +236,13 @@ try {
file_put_contents(PATH_DATA . $cronName, serialize($arrayCron)); file_put_contents(PATH_DATA . $cronName, serialize($arrayCron));
} else { } else {
eprintln('The ' . $arrayCronConfig[$cronName]['title'] . ' is running, please wait for it to finish' . "\n" . 'Started in ' . $lastExecution); eprintln('The ' . $arrayCronConfig[$cronName]['title'] . ' is running, please wait for it to finish' . "\n" . 'Started in ' . $lastExecution);
eprintln('If do you want force the execution use the option "' . $arrayCommandOption['force'] . '", example: php -f ' . $cronName . '.php +wworkflow ' . $arrayCommandOption['force'] ,'green'); eprintln('If do you want force the execution use the option "' . $arrayCommandOption['force'] . '", example: php -f ' . $cronName . '.php +wworkflow ' . $arrayCommandOption['force'], 'green');
} }
echo 'Done!' . "\n"; echo 'Done!' . "\n";
} catch (Exception $e) { } catch (Exception $e) {
$token = strtotime("now"); $token = strtotime("now");
PMException::registerErrorLog($e, $token); PMException::registerErrorLog($e, $token);
G::outRes( G::LoadTranslation("ID_EXCEPTION_LOG_INTERFAZ", array($token)) . "\n" ); G::outRes(G::LoadTranslation("ID_EXCEPTION_LOG_INTERFAZ", [$token]) . "\n");
} }

View File

@@ -4,27 +4,27 @@
* cron_single.php * cron_single.php
* *
* @see workflow/engine/bin/cron.php * @see workflow/engine/bin/cron.php
* @see workflow/engine/bin/messageeventcron.php
* @see workflow/engine/bin/timereventcron.php * @see workflow/engine/bin/timereventcron.php
* @see workflow/engine/bin/ldapcron.php * @see workflow/engine/bin/ldapcron.php
* @see workflow/engine/bin/sendnotificationscron.php * @see workflow/engine/bin/sendnotificationscron.php
* @see workflow/engine/bin/webentriescron.php
* @see workflow/engine/methods/setup/cron.php * @see workflow/engine/methods/setup/cron.php
* *
* @link https://wiki.processmaker.com/3.2/Executing_cron.php * @link https://wiki.processmaker.com/3.2/Executing_cron.php
*/ */
use Illuminate\Foundation\Http\Kernel; use Illuminate\Foundation\Http\Kernel;
/*----------------------------------********---------------------------------*/ use ProcessMaker\BusinessModel\Cases;
use ProcessMaker\BusinessModel\ActionsByEmail\ResponseReader;
/*----------------------------------********---------------------------------*/
require_once __DIR__ . '/../../../gulliver/system/class.g.php'; require_once __DIR__ . '/../../../gulliver/system/class.g.php';
require_once __DIR__ . '/../../../bootstrap/autoload.php'; require_once __DIR__ . '/../../../bootstrap/autoload.php';
require_once __DIR__ . '/../../../bootstrap/app.php'; require_once __DIR__ . '/../../../bootstrap/app.php';
use ProcessMaker\BusinessModel\WebEntry;
use ProcessMaker\Core\JobsManager; use ProcessMaker\Core\JobsManager;
use ProcessMaker\Core\System; use ProcessMaker\Core\System;
use ProcessMaker\Plugins\PluginRegistry; use ProcessMaker\Plugins\PluginRegistry;
use ProcessMaker\TaskScheduler\Task;
register_shutdown_function(function () { register_shutdown_function(function () {
if (class_exists("Propel")) { if (class_exists("Propel")) {
@@ -55,6 +55,14 @@ try {
$cronName = $argv[4]; $cronName = $argv[4];
$workspace = $argv[5]; $workspace = $argv[5];
$now = $argv[6]; //date $now = $argv[6]; //date
//asynchronous flag
$asynchronous = false;
$result = array_search('+async', $argv);
if ($result !== false && is_int($result)) {
$asynchronous = true;
unset($argv[$result]);
$argv = array_values($argv);
}
//Defines constants //Defines constants
define('PATH_SEP', ($osIsLinux) ? '/' : '\\'); define('PATH_SEP', ($osIsLinux) ? '/' : '\\');
@@ -280,31 +288,75 @@ try {
try { try {
switch ($cronName) { switch ($cronName) {
case 'cron': case 'cron':
processWorkspace(); try {
$task = new Task($asynchronous, $sObject);
if (empty($argvx) || strpos($argvx, "emails") !== false) {
$task->resendEmails($now, $dateSystem);
}
if (empty($argvx) || strpos($argvx, "unpause") !== false) {
$task->unpauseApplications($now);
}
if (empty($argvx) || strpos($argvx, "calculate") !== false) {
$task->calculateDuration();
}
/*----------------------------------********---------------------------------*/
if (empty($argvx) || strpos($argvx, "calculateapp") !== false) {
$task->calculateAppDuration();
}
/*----------------------------------********---------------------------------*/
executeEvents();
executeScheduledCases();
executeUpdateAppTitle();
if (empty($argvx) || strpos($argvx, "unassigned-case") !== false) {
$task->executeCaseSelfService();
}
if (empty($argvx) || strpos($argvx, "clean-self-service-tables") !== false) {
$task->cleanSelfServiceTables();
}
if (empty($argvx) || strpos($argvx, "plugins") !== false) {
$task->executePlugins();
}
/*----------------------------------********---------------------------------*/
if (strpos($argvx, "report_by_user") !== false) {
$task->fillReportByUser($dateInit, $dateFinish);
}
if (strpos($argvx, "report_by_process") !== false) {
$task->fillReportByProcess($dateInit, $dateFinish);
}
synchronizeDrive();
synchronizeGmailLabels();
/*----------------------------------********---------------------------------*/
} catch (Exception $oError) {
saveLog("main", "error", "Error processing workspace : " . $oError->getMessage() . "\n");
}
break; break;
case 'ldapcron': case 'ldapcron':
require_once(PATH_HOME . 'engine' . PATH_SEP . 'methods' . PATH_SEP . 'services' . PATH_SEP . 'ldapadvanced.php'); $task = new Task($asynchronous, $sObject);
$task->ldapcron(in_array('+debug', $argv));
$ldapadvancedClassCron = new ldapadvancedClassCron();
$ldapadvancedClassCron->executeCron(in_array('+debug', $argv));
break; break;
case 'messageeventcron': case 'messageeventcron':
$messageApplication = new \ProcessMaker\BusinessModel\MessageApplication(); $task = new Task($asynchronous, $sObject);
$task->messageeventcron();
$messageApplication->catchMessageEvent(true);
break; break;
case 'timereventcron': case 'timereventcron':
$timerEvent = new \ProcessMaker\BusinessModel\TimerEvent(); $task = new Task($asynchronous, $sObject);
$task->timerEventCron($now, true);
$timerEvent->startContinueCaseByTimerEvent($now, true);
break; break;
case 'sendnotificationscron': case 'sendnotificationscron':
sendNotifications(); if (empty($argvx) || strpos($argvx, "send-notifications") !== false) {
$task = new Task($asynchronous, $sObject);
$task->sendNotifications();
}
break;
case 'webentriescron':
setExecutionMessage('Deleting web entry cases created one week ago or more');
WebEntry::deleteOldWebEntries();
setExecutionResultMessage('FINISHED');
break; break;
/*----------------------------------********---------------------------------*/ /*----------------------------------********---------------------------------*/
case 'actionsByEmailEmailResponse': case 'actionsByEmailEmailResponse':
(new ResponseReader)->actionsByEmailEmailResponse(); $task = new Task($asynchronous, $sObject);
$task->actionsByEmailResponse();
break; break;
/*----------------------------------********---------------------------------*/ /*----------------------------------********---------------------------------*/
} }
@@ -328,250 +380,9 @@ try {
G::outRes(G::LoadTranslation("ID_EXCEPTION_LOG_INTERFAZ", array($token)) . "\n"); G::outRes(G::LoadTranslation("ID_EXCEPTION_LOG_INTERFAZ", array($token)) . "\n");
} }
//Functions function executeEvents()
function processWorkspace()
{ {
try {
global $sObject;
global $sLastExecution; global $sLastExecution;
resendEmails();
unpauseApplications();
calculateDuration();
/*----------------------------------********---------------------------------*/
calculateAppDuration();
/*----------------------------------********---------------------------------*/
executeEvents($sLastExecution);
executeScheduledCases();
executeUpdateAppTitle();
executeCaseSelfService();
cleanSelfServiceTables();
executePlugins();
/*----------------------------------********---------------------------------*/
fillReportByUser();
fillReportByProcess();
synchronizeDrive();
synchronizeGmailLabels();
/*----------------------------------********---------------------------------*/
} catch (Exception $oError) {
saveLog("main", "error", "Error processing workspace : " . $oError->getMessage() . "\n");
}
}
function resendEmails()
{
global $argvx;
global $now;
global $dateSystem;
if ($argvx != "" && strpos($argvx, "emails") === false) {
return false;
}
setExecutionMessage("Resending emails");
try {
$dateResend = $now;
if ($now == $dateSystem) {
$arrayDateSystem = getdate(strtotime($dateSystem));
$mktDateSystem = mktime(
$arrayDateSystem["hours"],
$arrayDateSystem["minutes"],
$arrayDateSystem["seconds"],
$arrayDateSystem["mon"],
$arrayDateSystem["mday"],
$arrayDateSystem["year"]
);
$dateResend = date("Y-m-d H:i:s", $mktDateSystem - (7 * 24 * 60 * 60));
}
$oSpool = new SpoolRun();
$oSpool->resendEmails($dateResend, 1);
saveLog("resendEmails", "action", "Resending Emails", "c");
$aSpoolWarnings = $oSpool->getWarnings();
if ($aSpoolWarnings !== false) {
foreach ($aSpoolWarnings as $sWarning) {
print("MAIL SPOOL WARNING: " . $sWarning . "\n");
saveLog("resendEmails", "warning", "MAIL SPOOL WARNING: " . $sWarning);
}
}
setExecutionResultMessage("DONE");
} catch (Exception $e) {
$c = new Criteria("workflow");
$c->clearSelectColumns();
$c->addSelectColumn(ConfigurationPeer::CFG_UID);
$c->add(ConfigurationPeer::CFG_UID, "Emails");
$result = ConfigurationPeer::doSelectRS($c);
$result->setFetchmode(ResultSet::FETCHMODE_ASSOC);
if ($result->next()) {
setExecutionResultMessage("WARNING", "warning");
$message = "Emails won't be sent, but the cron will continue its execution";
eprintln(" '-" . $message, "yellow");
} else {
setExecutionResultMessage("WITH ERRORS", "error");
eprintln(" '-" . $e->getMessage(), "red");
}
saveLog("resendEmails", "error", "Error Resending Emails: " . $e->getMessage());
}
}
function unpauseApplications()
{
global $argvx;
global $now;
if ($argvx != "" && strpos($argvx, "unpause") === false) {
return false;
}
setExecutionMessage("Unpausing applications");
try {
$oCases = new Cases();
$oCases->ThrowUnpauseDaemon($now, 1);
setExecutionResultMessage('DONE');
saveLog('unpauseApplications', 'action', 'Unpausing Applications');
} catch (Exception $oError) {
setExecutionResultMessage('WITH ERRORS', 'error');
eprintln(" '-" . $oError->getMessage(), 'red');
saveLog('unpauseApplications', 'error', 'Error Unpausing Applications: ' . $oError->getMessage());
}
}
function executePlugins()
{
global $argvx;
if ($argvx != "" && strpos($argvx, "plugins") === false) {
return false;
}
$pathCronPlugins = PATH_CORE . 'bin' . PATH_SEP . 'plugins' . PATH_SEP;
// Executing cron files in bin/plugins directory
if (!is_dir($pathCronPlugins)) {
return false;
}
if ($handle = opendir($pathCronPlugins)) {
setExecutionMessage('Executing cron files in bin/plugins directory in Workspace: ' . config("system.workspace"));
while (false !== ($file = readdir($handle))) {
if (strpos($file, '.php', 1) && is_file($pathCronPlugins . $file)) {
$filename = str_replace('.php', '', $file);
$className = $filename . 'ClassCron';
// Execute custom cron function
executeCustomCronFunction($pathCronPlugins . $file, $className);
}
}
}
// Executing registered cron files
// -> Get registered cron files
$oPluginRegistry = PluginRegistry::loadSingleton();
$cronFiles = $oPluginRegistry->getCronFiles();
// -> Execute functions
if (!empty($cronFiles)) {
setExecutionMessage('Executing registered cron files for Workspace: ' . config('system.workspace'));
/**
* @var \ProcessMaker\Plugins\Interfaces\CronFile $cronFile
*/
foreach ($cronFiles as $cronFile) {
$path = PATH_PLUGINS . $cronFile->getNamespace() . PATH_SEP . 'bin' . PATH_SEP . $cronFile->getCronFile() . '.php';
if (file_exists($path)) {
executeCustomCronFunction($path, $cronFile->getCronFile());
} else {
setExecutionMessage('File ' . $cronFile->getCronFile() . '.php ' . 'does not exist.');
}
}
}
}
function executeCustomCronFunction($pathFile, $className)
{
include_once $pathFile;
$oPlugin = new $className();
if (method_exists($oPlugin, 'executeCron')) {
$arrayCron = unserialize(trim(@file_get_contents(PATH_DATA . "cron")));
$arrayCron["processcTimeProcess"] = 60; //Minutes
$arrayCron["processcTimeStart"] = time();
@file_put_contents(PATH_DATA . "cron", serialize($arrayCron));
//Try to execute Plugin Cron. If there is an error then continue with the next file
setExecutionMessage("\n--- Executing cron file: $pathFile");
try {
$oPlugin->executeCron();
setExecutionResultMessage('DONE');
} catch (Exception $e) {
setExecutionResultMessage('FAILED', 'error');
eprintln(" '-" . $e->getMessage(), 'red');
saveLog('executePlugins', 'error', 'Error executing cron file: ' . $pathFile . ' - ' . $e->getMessage());
}
}
}
function calculateDuration()
{
global $argvx;
if ($argvx != "" && strpos($argvx, "calculate") === false) {
return false;
}
setExecutionMessage("Calculating Duration");
try {
$oAppDelegation = new AppDelegation();
$oAppDelegation->calculateDuration(1);
setExecutionResultMessage('DONE');
saveLog('calculateDuration', 'action', 'Calculating Duration');
} catch (Exception $oError) {
setExecutionResultMessage('WITH ERRORS', 'error');
eprintln(" '-" . $oError->getMessage(), 'red');
saveLog('calculateDuration', 'error', 'Error Calculating Duration: ' . $oError->getMessage());
}
}
/*----------------------------------********---------------------------------*/
function calculateAppDuration()
{
global $argvx;
if ($argvx != "" && strpos($argvx, "calculateapp") === false) {
return false;
}
setExecutionMessage("Calculating Duration by Application");
try {
$oApplication = new Application();
$oApplication->calculateAppDuration(1);
setExecutionResultMessage('DONE');
saveLog('calculateDurationByApp', 'action', 'Calculating Duration by Application');
} catch (Exception $oError) {
setExecutionResultMessage('WITH ERRORS', 'error');
eprintln(" '-" . $oError->getMessage(), 'red');
saveLog('calculateDurationByApp', 'error', 'Error Calculating Duration: ' . $oError->getMessage());
}
}
/*----------------------------------********---------------------------------*/
function executeEvents($sLastExecution, $now = null)
{
global $argvx; global $argvx;
global $now; global $now;
@@ -689,176 +500,14 @@ function executeUpdateAppTitle()
} }
} }
function executeCaseSelfService() /**
{ * @deprecated This function is only used in this file and must be deleted.
try { * @global string $sObject
global $argvx; * @global string $isDebug
* @param string $sSource
if ($argvx != "" && strpos($argvx, "unassigned-case") === false) { * @param string $sType
return false; * @param string $sDescription
} */
$criteria = new Criteria("workflow");
//SELECT
$criteria->addSelectColumn(AppCacheViewPeer::APP_UID);
$criteria->addSelectColumn(AppCacheViewPeer::DEL_INDEX);
$criteria->addSelectColumn(AppCacheViewPeer::DEL_DELEGATE_DATE);
$criteria->addSelectColumn(AppCacheViewPeer::APP_NUMBER);
$criteria->addSelectColumn(AppCacheViewPeer::PRO_UID);
$criteria->addSelectColumn(TaskPeer::TAS_UID);
$criteria->addSelectColumn(TaskPeer::TAS_SELFSERVICE_TIME);
$criteria->addSelectColumn(TaskPeer::TAS_SELFSERVICE_TIME_UNIT);
$criteria->addSelectColumn(TaskPeer::TAS_SELFSERVICE_TRIGGER_UID);
/*----------------------------------********---------------------------------*/
$criteria->addSelectColumn(TaskPeer::TAS_SELFSERVICE_EXECUTION);
/*----------------------------------********---------------------------------*/
//FROM
$condition = array();
$condition[] = array(AppCacheViewPeer::TAS_UID, TaskPeer::TAS_UID);
$condition[] = array(TaskPeer::TAS_SELFSERVICE_TIMEOUT, 1);
$criteria->addJoinMC($condition, Criteria::LEFT_JOIN);
//WHERE
$criteria->add(AppCacheViewPeer::USR_UID, "");
$criteria->add(AppCacheViewPeer::DEL_THREAD_STATUS, "OPEN");
//QUERY
$rsCriteria = AppCacheViewPeer::doSelectRS($criteria);
$rsCriteria->setFetchmode(ResultSet::FETCHMODE_ASSOC);
setExecutionMessage("Unassigned case");
saveLog("unassignedCase", "action", "Unassigned case", "c");
$calendar = new Calendar();
while ($rsCriteria->next()) {
$row = $rsCriteria->getRow();
$flag = false;
$appcacheAppUid = $row["APP_UID"];
$appcacheDelIndex = $row["DEL_INDEX"];
$appcacheDelDelegateDate = $row["DEL_DELEGATE_DATE"];
$appcacheAppNumber = $row["APP_NUMBER"];
$appcacheProUid = $row["PRO_UID"];
$taskUid = $row["TAS_UID"];
$taskSelfServiceTime = intval($row["TAS_SELFSERVICE_TIME"]);
$taskSelfServiceTimeUnit = $row["TAS_SELFSERVICE_TIME_UNIT"];
$taskSelfServiceTriggerUid = $row["TAS_SELFSERVICE_TRIGGER_UID"];
/*----------------------------------********---------------------------------*/
$taskSelfServiceJustOneExecution = $row["TAS_SELFSERVICE_EXECUTION"];
if ($taskSelfServiceJustOneExecution == 'ONCE') {
$criteriaSelfService = new Criteria("workflow");
$criteriaSelfService->add(AppTimeoutActionExecutedPeer::APP_UID, $appcacheAppUid);
$criteriaSelfService->add(AppTimeoutActionExecutedPeer::DEL_INDEX, $appcacheDelIndex);
$querySelfService = AppTimeoutActionExecutedPeer::doSelectRS($criteriaSelfService);
$querySelfService->setFetchmode(ResultSet::FETCHMODE_ASSOC);
if ($querySelfService->next()) {
$row = $querySelfService->getRow();
$flag = true; //already executed
}
}
/*----------------------------------********---------------------------------*/
if ($calendar->pmCalendarUid == '') {
$calendar->getCalendar(null, $appcacheProUid, $taskUid);
$calendar->getCalendarData();
}
$dueDate = $calendar->calculateDate(
$appcacheDelDelegateDate,
$taskSelfServiceTime,
$taskSelfServiceTimeUnit //HOURS|DAYS|MINUTES
//1
);
if (time() > $dueDate["DUE_DATE_SECONDS"] && $flag == false) {
$sessProcess = null;
$sessProcessSw = 0;
//Load data
$case = new Cases();
$appFields = $case->loadCase($appcacheAppUid);
$appFields["APP_DATA"]["APPLICATION"] = $appcacheAppUid;
if (isset($_SESSION["PROCESS"])) {
$sessProcess = $_SESSION["PROCESS"];
$sessProcessSw = 1;
}
$_SESSION["PROCESS"] = $appFields["PRO_UID"];
//Execute trigger
$criteriaTgr = new Criteria();
$criteriaTgr->add(TriggersPeer::TRI_UID, $taskSelfServiceTriggerUid);
$rsCriteriaTgr = TriggersPeer::doSelectRS($criteriaTgr);
$rsCriteriaTgr->setFetchmode(ResultSet::FETCHMODE_ASSOC);
if ($rsCriteriaTgr->next()) {
$row = $rsCriteriaTgr->getRow();
if (is_array($row) && $row["TRI_TYPE"] == "SCRIPT") {
$arrayCron = unserialize(trim(@file_get_contents(PATH_DATA . "cron")));
$arrayCron["processcTimeProcess"] = 60; //Minutes
$arrayCron["processcTimeStart"] = time();
@file_put_contents(PATH_DATA . "cron", serialize($arrayCron));
//Trigger
global $oPMScript;
$oPMScript = new PMScript();
$oPMScript->setDataTrigger($row);
$oPMScript->setFields($appFields["APP_DATA"]);
$oPMScript->setScript($row["TRI_WEBBOT"]);
$oPMScript->setExecutedOn(PMScript::SELF_SERVICE_TIMEOUT);
$oPMScript->execute();
/*----------------------------------********---------------------------------*/
//saving the case`s data if the 'Execution' is set in ONCE.
if ($taskSelfServiceJustOneExecution == "ONCE") {
$oAppTimeoutActionExecuted = new AppTimeoutActionExecuted();
$dataSelf = array();
$dataSelf["APP_UID"] = $appcacheAppUid;
$dataSelf["DEL_INDEX"] = $appcacheDelIndex;
$dataSelf["EXECUTION_DATE"] = time();
$oAppTimeoutActionExecuted->create($dataSelf);
}
/*----------------------------------********---------------------------------*/
$appFields["APP_DATA"] = array_merge($appFields["APP_DATA"], $oPMScript->aFields);
unset($appFields['APP_STATUS']);
unset($appFields['APP_PROC_STATUS']);
unset($appFields['APP_PROC_CODE']);
unset($appFields['APP_PIN']);
$case->updateCase($appFields["APP_UID"], $appFields);
saveLog("unassignedCase", "action", "OK Executed trigger to the case $appcacheAppNumber");
}
}
unset($_SESSION["PROCESS"]);
if ($sessProcessSw == 1) {
$_SESSION["PROCESS"] = $sessProcess;
}
}
}
setExecutionResultMessage("DONE");
} catch (Exception $e) {
setExecutionResultMessage("WITH ERRORS", "error");
eprintln(" '-" . $e->getMessage(), "red");
saveLog("unassignedCase", "error", "Error in unassigned case: " . $e->getMessage());
}
}
function saveLog($sSource, $sType, $sDescription) function saveLog($sSource, $sType, $sDescription)
{ {
try { try {
@@ -876,6 +525,10 @@ function saveLog($sSource, $sType, $sDescription)
} }
} }
/**
* @deprecated This function is only used in this file and must be deleted.
* @param string $m
*/
function setExecutionMessage($m) function setExecutionMessage($m)
{ {
$len = strlen($m); $len = strlen($m);
@@ -889,6 +542,11 @@ function setExecutionMessage($m)
} }
} }
/**
* @deprecated This function is only used in this file and must be deleted.
* @param string $m
* @param string $t
*/
function setExecutionResultMessage($m, $t = '') function setExecutionResultMessage($m, $t = '')
{ {
$c = 'green'; $c = 'green';
@@ -909,67 +567,6 @@ function setExecutionResultMessage($m, $t = '')
} }
/*----------------------------------********---------------------------------*/ /*----------------------------------********---------------------------------*/
function fillReportByUser()
{
try {
global $argvx;
global $dateInit;
global $dateFinish;
if (strpos($argvx, "report_by_user") === false) {
return false;
}
if ($dateInit == null) {
eprintln("You must enter the starting date.", "red");
eprintln('Example: +init-date"YYYY-MM-DD HH:MM:SS" +finish-date"YYYY-MM-DD HH:MM:SS"', "red");
return false;
}
$dateFinish = ($dateFinish != null) ? $dateFinish : date("Y-m-d H:i:s");
$appcv = new AppCacheView();
$appcv->setPathToAppCacheFiles(PATH_METHODS . 'setup' . PATH_SEP . 'setupSchemas' . PATH_SEP);
setExecutionMessage("Calculating data to fill the 'User Reporting'...");
$appcv->fillReportByUser($dateInit, $dateFinish);
setExecutionResultMessage("DONE");
} catch (Exception $e) {
setExecutionResultMessage("WITH ERRORS", "error");
eprintln(" '-" . $e->getMessage(), "red");
saveLog("fillReportByUser", "error", "Error in fill report by user: " . $e->getMessage());
}
}
function fillReportByProcess()
{
try {
global $argvx;
global $dateInit;
global $dateFinish;
if (strpos($argvx, "report_by_process") === false) {
return false;
}
if ($dateInit == null) {
eprintln("You must enter the starting date.", "red");
eprintln('Example: +init-date"YYYY-MM-DD HH:MM:SS" +finish-date"YYYY-MM-DD HH:MM:SS"', "red");
return false;
}
$dateFinish = ($dateFinish != null) ? $dateFinish : date("Y-m-d H:i:s");
$appcv = new AppCacheView();
$appcv->setPathToAppCacheFiles(PATH_METHODS . 'setup' . PATH_SEP . 'setupSchemas' . PATH_SEP);
setExecutionMessage("Calculating data to fill the 'Process Reporting'...");
$appcv->fillReportByProcess($dateInit, $dateFinish);
setExecutionResultMessage("DONE");
} catch (Exception $e) {
setExecutionResultMessage("WITH ERRORS", "error");
eprintln(" '-" . $e->getMessage(), "red");
saveLog("fillReportByProcess", "error", "Error in fill report by process: " . $e->getMessage());
}
}
function synchronizeDrive() function synchronizeDrive()
{ {
try { try {
@@ -1027,94 +624,3 @@ function synchronizeGmailLabels()
} }
} }
/*----------------------------------********---------------------------------*/ /*----------------------------------********---------------------------------*/
function sendNotifications()
{
try {
global $argvx;
if ($argvx != "" && strpos($argvx, "send-notifications") === false) {
return false;
}
setExecutionMessage("Resending Notifications");
setExecutionResultMessage("PROCESSING");
$notQueue = new \NotificationQueue();
$notQueue->checkIfCasesOpenForResendingNotification();
$notificationsAndroid = $notQueue->loadStatusDeviceType('pending', 'android');
if ($notificationsAndroid) {
setExecutionMessage("|-- Send Android's Notifications");
$n = 0;
foreach ($notificationsAndroid as $key => $item) {
$oNotification = new \ProcessMaker\BusinessModel\Light\PushMessageAndroid();
$oNotification->setSettingNotification();
$oNotification->setDevices(unserialize($item['DEV_UID']));
$response['android'] = $oNotification->send($item['NOT_MSG'], unserialize($item['NOT_DATA']));
$notQueue = new \NotificationQueue();
$notQueue->changeStatusSent($item['NOT_UID']);
$n += $oNotification->getNumberDevices();
}
setExecutionResultMessage("Processed $n");
}
$notificationsApple = $notQueue->loadStatusDeviceType('pending', 'apple');
if ($notificationsApple) {
setExecutionMessage("|-- Send Apple Notifications");
$n = 0;
foreach ($notificationsApple as $key => $item) {
$oNotification = new \ProcessMaker\BusinessModel\Light\PushMessageIOS();
$oNotification->setSettingNotification();
$oNotification->setDevices(unserialize($item['DEV_UID']));
$response['apple'] = $oNotification->send($item['NOT_MSG'], unserialize($item['NOT_DATA']));
$notQueue = new \NotificationQueue();
$notQueue->changeStatusSent($item['NOT_UID']);
$n += $oNotification->getNumberDevices();
}
setExecutionResultMessage("Processed $n");
}
} catch (Exception $e) {
setExecutionResultMessage("WITH ERRORS", "error");
eprintln(" '-" . $e->getMessage(), "red");
saveLog("ExecuteSendNotifications", "error", "Error when sending notifications " . $e->getMessage());
}
}
/**
* Clean unused records in tables related to the Self-Service Value Based feature
*
* @see processWorkspace()
*
* @link https://wiki.processmaker.com/3.2/Executing_cron.php#Syntax_of_cron.php_Options
*/
function cleanSelfServiceTables()
{
try {
global $argvx;
// Check if the action can be executed
if ($argvx !== "" && strpos($argvx, "clean-self-service-tables") === false) {
return false;
}
// Start message
setExecutionMessage("Clean unused records for Self-Service Value Based feature");
// Get Propel connection
$cnn = Propel::getConnection(AppAssignSelfServiceValueGroupPeer::DATABASE_NAME);
// Delete related rows and missing relations, criteria don't execute delete with joins
$cnn->begin();
$stmt = $cnn->createStatement();
$stmt->executeQuery("DELETE " . AppAssignSelfServiceValueGroupPeer::TABLE_NAME . "
FROM " . AppAssignSelfServiceValueGroupPeer::TABLE_NAME . "
LEFT JOIN " . AppAssignSelfServiceValuePeer::TABLE_NAME . "
ON (" . AppAssignSelfServiceValueGroupPeer::ID . " = " . AppAssignSelfServiceValuePeer::ID . ")
WHERE " . AppAssignSelfServiceValuePeer::ID . " IS NULL");
$cnn->commit();
// Success message
setExecutionResultMessage("DONE");
} catch (Exception $e) {
$cnn->rollback();
setExecutionResultMessage("WITH ERRORS", "error");
eprintln(" '-" . $e->getMessage(), "red");
saveLog("ExecuteCleanSelfServiceTables", "error", "Error when try to clean self-service tables " . $e->getMessage());
}
}

View File

@@ -1,5 +1,6 @@
<?php <?php
use ProcessMaker\BusinessModel\WebEntry;
use ProcessMaker\Core\JobsManager; use ProcessMaker\Core\JobsManager;
use ProcessMaker\Model\Process; use ProcessMaker\Model\Process;
use ProcessMaker\Validation\MySQL57; use ProcessMaker\Validation\MySQL57;
@@ -428,6 +429,27 @@ EOT
CLI::taskArg('fontFileName', false); CLI::taskArg('fontFileName', false);
CLI::taskRun('documents_remove_font'); CLI::taskRun('documents_remove_font');
/**
* Add +async option to scheduler commands in table SCHEDULER.
*/
CLI::taskName('add-async-option-to-scheduler-commands');
CLI::taskDescription(<<<EOT
Add +async option to scheduler commands in table SCHEDULER.
EOT
);
CLI::taskArg('workspace');
CLI::taskRun('add_async_option_to_scheduler_commands');
/**
* Convert Web Entries v1.0 to v2.0 for BPMN processes in order to deprecate the old version.
*/
CLI::taskName('convert-old-web-entries');
CLI::taskDescription(<<<EOT
Convert Web Entries v1.0 to v2.0 for BPMN processes in order to deprecate the old version.
EOT
);
CLI::taskRun('convert_old_web_entries');
/** /**
* Function run_info * Function run_info
* *
@@ -1606,3 +1628,64 @@ function documents_remove_font($args)
CLI::logging($e->getMessage() . PHP_EOL . PHP_EOL); CLI::logging($e->getMessage() . PHP_EOL . PHP_EOL);
} }
} }
/**
* Add +async option to scheduler commands in table SCHEDULER.
* @param array $args
* @param string $opts
*/
function add_async_option_to_scheduler_commands($args, $opts)
{
if (count($args) === 1) {
Bootstrap::setConstantsRelatedWs($args[0]);
$workspaceTools = new WorkspaceTools($args[0]);
CLI::logging("> Adding +async option to scheduler commands...\n");
$start = microtime(true);
$workspaceTools->addAsyncOptionToSchedulerCommands(true);
CLI::logging("<*> Adding +async option to scheduler commands took " . (microtime(true) - $start) . " seconds.\n");
} else {
$workspaces = get_workspaces_from_args($args);
foreach ($workspaces as $workspace) {
passthru(PHP_BINARY . ' processmaker add-async-option-to-scheduler-commands ' . $workspace->name);
}
}
}
/**
* Convert Web Entries v1.0 to v2.0 for BPMN processes in order to deprecate the old version.
*
* @param array $args
*/
function convert_old_web_entries($args)
{
try {
if (!empty($args)) {
// Print initial message
$start = microtime(true);
CLI::logging("> Converting Web Entries v1.0 to v2.0 for BPMN processes...\n");
// Set workspace constants and initialize DB connection
Bootstrap::setConstantsRelatedWs($args[0]);
Propel::init(PATH_CONFIG . 'databases.php');
// Convert Web Entries
WebEntry::convertFromV1ToV2();
// Print last message
$stop = microtime(true);
CLI::logging("<*> Converting Web Entries v1.0 to v2.0 for BPMN processes data took " . ($stop - $start) . " seconds.\n");
} else {
// If a workspace is not specified, get all available workspaces in the server
$workspaces = get_workspaces_from_args($args);
// Execute the command for each workspace
foreach ($workspaces as $workspace) {
passthru(PHP_BINARY . ' processmaker convert-old-web-entries ' . $workspace->name);
}
}
} catch (Exception $e) {
// Display the error message
CLI::logging($e->getMessage() . PHP_EOL . PHP_EOL);
}
}

View File

@@ -0,0 +1,3 @@
<?php
require_once 'cron.php';

View File

@@ -1,6 +1,7 @@
<?php <?php
use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Log;
use ProcessMaker\BusinessModel\Cases as BusinessModelCases;
use ProcessMaker\BusinessModel\Task as BusinessModelTask; use ProcessMaker\BusinessModel\Task as BusinessModelTask;
use ProcessMaker\BusinessModel\User as BusinessModelUser; use ProcessMaker\BusinessModel\User as BusinessModelUser;
use ProcessMaker\BusinessModel\WebEntryEvent; use ProcessMaker\BusinessModel\WebEntryEvent;
@@ -983,7 +984,8 @@ class Cases
/** Update case*/ /** Update case*/
$app->update($Fields); $app->update($Fields);
//Update the reportTables and tables related to the case //Update the reportTables and tables related to the case, only for applications with positive application number
if ($appFields['APP_NUMBER'] > 0) {
require_once 'classes/model/AdditionalTables.php'; require_once 'classes/model/AdditionalTables.php';
$reportTables = new ReportTables(); $reportTables = new ReportTables();
$additionalTables = new additionalTables(); $additionalTables = new additionalTables();
@@ -999,6 +1001,7 @@ class Cases
$additionalTables->updateReportTables( $additionalTables->updateReportTables(
$appFields['PRO_UID'], $appUid, $Fields['APP_NUMBER'], $appData, $Fields['APP_STATUS'] $appFields['PRO_UID'], $appUid, $Fields['APP_NUMBER'], $appData, $Fields['APP_STATUS']
); );
}
//Update the priority related to the task //Update the priority related to the task
$delIndex = isset($Fields['DEL_INDEX']) ? trim($Fields['DEL_INDEX']) : ''; $delIndex = isset($Fields['DEL_INDEX']) ? trim($Fields['DEL_INDEX']) : '';
@@ -2105,199 +2108,201 @@ class Cases
* This function start a case using the task for the user $sUsrUid * This function start a case using the task for the user $sUsrUid
* With this function we can Start a case * With this function we can Start a case
* *
* @name startCase * @param string $taskUid
* @param string $sTasUid * @param string $userUid
* @param string $sUsrUid * @param bool $isSubProcess
* @return Fields * @param array $dataPreviousApplication
* @param bool $isSelfService
* @param string $sequenceType
* @return array
* @throws Exception
*/ */
public function startCase($sTasUid, $sUsrUid, $isSubprocess = false, $dataPreviusApplication = array(), $isSelfService = false) public function startCase($taskUid, $userUid, $isSubProcess = false, $dataPreviousApplication = [], $isSelfService = false, $sequenceType = AppSequence::APP_TYPE_NORMAL)
{ {
if ($sTasUid != '') { if ($taskUid != '') {
try { try {
$task = TaskPeer::retrieveByPK($sTasUid); $task = TaskPeer::retrieveByPK($taskUid);
$user = UsersPeer::retrieveByPK($sUsrUid); $user = UsersPeer::retrieveByPK($userUid);
if (is_null($task)) { if (is_null($task)) {
throw new Exception(G::LoadTranslation("ID_TASK_NOT_EXIST", array("TAS_UID", $sTasUid))); throw new Exception(G::LoadTranslation("ID_TASK_NOT_EXIST", ["TAS_UID", $taskUid]));
} }
//To allow Self Service as the first task // To allow Self Service as the first task
$arrayTaskTypeToExclude = array("START-TIMER-EVENT"); $arrayTaskTypeToExclude = ["START-TIMER-EVENT"];
if (!is_null($task) && !in_array($task->getTasType(), $arrayTaskTypeToExclude) && $task->getTasAssignType() != "SELF_SERVICE" && $sUsrUid == "") { if (!is_null($task) && !in_array($task->getTasType(), $arrayTaskTypeToExclude) && $task->getTasAssignType() != "SELF_SERVICE" && $userUid == "") {
throw (new Exception('You tried to start a new case without send the USER UID!')); throw (new Exception('You tried to start a new case without send the USER UID!'));
} }
//Process // Process
$sProUid = $task->getProUid(); $processUid = $task->getProUid();
$this->Process = new Process; $this->Process = new Process;
$proFields = $this->Process->Load($sProUid); $proFields = $this->Process->Load($processUid);
//application // Application
$Application = new Application; $application = new Application;
$sAppUid = $Application->create($sProUid, $sUsrUid); $appUid = $application->create($processUid, $userUid, $sequenceType);
//appDelegation // AppDelegation
$AppDelegation = new AppDelegation; $appDelegation = new AppDelegation;
$iAppThreadIndex = 1; // Start Thread $appThreadIndex = 1; // Start Thread
$iAppDelPrio = 3; // Priority $appDelPriority = 3; // Priority
$iDelIndex = $AppDelegation->createAppDelegation( $delIndex = $appDelegation->createAppDelegation(
$sProUid, $processUid,
$sAppUid, $appUid,
$sTasUid, $taskUid,
$sUsrUid, $userUid,
$iAppThreadIndex, $appThreadIndex,
$iAppDelPrio, $appDelPriority,
$isSubprocess, $isSubProcess,
-1, -1,
null, null,
false, false,
false, false,
0, 0,
$Application->getAppNumber(), $application->getAppNumber(),
$task->getTasId(), $task->getTasId(),
(empty($user)) ? 0 : $user->getUsrId(), (empty($user)) ? 0 : $user->getUsrId(),
$this->Process->getProId() $this->Process->getProId()
); );
//appThread // AppThread
$AppThread = new AppThread; $appThread = new AppThread;
$iAppThreadIndex = $AppThread->createAppThread($sAppUid, $iDelIndex, 0); $appThreadIndex = $appThread->createAppThread($appUid, $delIndex, 0);
$oDerivation = new Derivation(); $derivation = new Derivation();
//Multiple Instance // Multiple Instance
$aUserFields = array(); $usersFields = [];
$taskAssignType = $task->getTasAssignType(); $taskAssignType = $task->getTasAssignType();
$nextTaskAssignVariable = $task->getTasAssignVariable(); $nextTaskAssignVariable = $task->getTasAssignVariable();
if ($taskAssignType == "MULTIPLE_INSTANCE" || $taskAssignType == "MULTIPLE_INSTANCE_VALUE_BASED") { if ($taskAssignType == "MULTIPLE_INSTANCE" || $taskAssignType == "MULTIPLE_INSTANCE_VALUE_BASED") {
switch ($taskAssignType) { switch ($taskAssignType) {
case 'MULTIPLE_INSTANCE': case 'MULTIPLE_INSTANCE':
$userFields = $oDerivation->getUsersFullNameFromArray($oDerivation->getAllUsersFromAnyTask($sTasUid)); $userFields = $derivation->getUsersFullNameFromArray($derivation->getAllUsersFromAnyTask($taskUid));
break; break;
default: default:
throw (new Exception('Invalid Task Assignment method')); throw (new Exception('Invalid Task Assignment method'));
break; break;
} }
$userFields = $oDerivation->getUsersFullNameFromArray($oDerivation->getAllUsersFromAnyTask($sTasUid)); $userFields = $derivation->getUsersFullNameFromArray($derivation->getAllUsersFromAnyTask($taskUid));
$count = 0; $count = 0;
foreach ($userFields as $rowUser) { foreach ($userFields as $rowUser) {
if ($rowUser["USR_UID"] != $sUsrUid) { if ($rowUser["USR_UID"] != $userUid) {
//appDelegation // AppDelegation
$AppDelegation = new AppDelegation; $appDelegation = new AppDelegation;
$iAppThreadIndex ++; // Start Thread $appThreadIndex ++; // Start Thread
$iAppDelPrio = 3; // Priority $appDelPriority = 3; // Priority
$user = UsersPeer::retrieveByPK($rowUser["USR_UID"]); $user = UsersPeer::retrieveByPK($rowUser["USR_UID"]);
$iDelIndex1 = $AppDelegation->createAppDelegation( $delIndex1 = $appDelegation->createAppDelegation(
$sProUid, $processUid,
$sAppUid, $appUid,
$sTasUid, $taskUid,
$rowUser["USR_UID"], $rowUser["USR_UID"],
$iAppThreadIndex, $appThreadIndex,
$iAppDelPrio, $appDelPriority,
$isSubprocess, $isSubProcess,
-1, -1,
null, null,
false, false,
false, false,
0, 0,
$Application->getAppNumber(), $application->getAppNumber(),
$task->getTasId(), $task->getTasId(),
(empty($user)) ? 0 : $user->getUsrId(), (empty($user)) ? 0 : $user->getUsrId(),
$this->Process->getProId() $this->Process->getProId()
); );
//appThread // AppThread
$AppThread = new AppThread; $appThread = new AppThread;
$iAppThreadIndex = $AppThread->createAppThread($sAppUid, $iDelIndex1, 0); $appThreadIndex = $appThread->createAppThread($appUid, $delIndex1, 0);
//Save Information // Save Information
$aUserFields[$count] = $rowUser; $usersFields[$count] = $rowUser;
$aUserFields[$count]["DEL_INDEX"] = $iDelIndex1; $usersFields[$count]["DEL_INDEX"] = $delIndex1;
$count++; $count++;
} }
} }
} }
//DONE: Al ya existir un delegation, se puede "calcular" el caseTitle. $fields = $application->toArray(BasePeer::TYPE_FIELDNAME);
$Fields = $Application->toArray(BasePeer::TYPE_FIELDNAME); $applicationFields = $fields['APP_DATA'];
$aApplicationFields = $Fields['APP_DATA']; $fields['DEL_INDEX'] = $delIndex;
$Fields['DEL_INDEX'] = $iDelIndex; $newValues = $this->newRefreshCaseTitleAndDescription($appUid, $fields, $applicationFields);
$newValues = $this->newRefreshCaseTitleAndDescription($sAppUid, $Fields, $aApplicationFields);
if (!isset($newValues['APP_TITLE'])) { if (!isset($newValues['APP_TITLE'])) {
$newValues['APP_TITLE'] = ''; $newValues['APP_TITLE'] = '';
} }
$caseNumber = $Fields['APP_NUMBER']; $caseNumber = $fields['APP_NUMBER'];
$Application->update($Fields); $application->update($fields);
//Update the task last assigned (for web entry and web services) // Update the task last assigned (for web entry and web services)
$oDerivation->setTasLastAssigned($sTasUid, $sUsrUid); $derivation->setTasLastAssigned($taskUid, $userUid);
// Execute Events // Execute Events
require_once 'classes/model/Event.php';
$event = new Event(); $event = new Event();
$event->createAppEvents($sProUid, $sAppUid, $iDelIndex, $sTasUid); $event->createAppEvents($processUid, $appUid, $delIndex, $taskUid);
//update searchindex // Update search index
if ($this->appSolr != null) { if ($this->appSolr != null) {
$this->appSolr->updateApplicationSearchIndex($sAppUid); $this->appSolr->updateApplicationSearchIndex($appUid);
} }
/*----------------------------------********---------------------------------*/ /*----------------------------------********---------------------------------*/
$Fields['TAS_UID'] = $sTasUid; $fields['TAS_UID'] = $taskUid;
$Fields['USR_UID'] = $sUsrUid; $fields['USR_UID'] = $userUid;
$Fields['DEL_INDEX'] = $iDelIndex; $fields['DEL_INDEX'] = $delIndex;
$Fields['APP_STATUS'] = 'TO_DO'; $fields['APP_STATUS'] = 'TO_DO';
$Fields['DEL_DELEGATE_DATE'] = $Fields['APP_INIT_DATE']; $fields['DEL_DELEGATE_DATE'] = $fields['APP_INIT_DATE'];
if (!$isSubprocess) { if (!$isSubProcess) {
$Fields['APP_STATUS'] = 'DRAFT'; $fields['APP_STATUS'] = 'DRAFT';
} else { } else {
$Fields['APP_INIT_DATE'] = null; $fields['APP_INIT_DATE'] = null;
} }
$inbox = new ListInbox(); $inbox = new ListInbox();
$inbox->newRow($Fields, $sUsrUid, $isSelfService); $inbox->newRow($fields, $userUid, $isSelfService);
//Multiple Instance // Multiple Instance
foreach ($aUserFields as $rowUser) { foreach ($usersFields as $rowUser) {
$Fields["USR_UID"] = $rowUser["USR_UID"]; $fields["USR_UID"] = $rowUser["USR_UID"];
$Fields["DEL_INDEX"] = $rowUser["DEL_INDEX"]; $fields["DEL_INDEX"] = $rowUser["DEL_INDEX"];
$inbox = new ListInbox(); $inbox = new ListInbox();
$inbox->newRow($Fields, $sUsrUid, $isSelfService); $inbox->newRow($fields, $userUid, $isSelfService);
} }
/*----------------------------------********---------------------------------*/ /*----------------------------------********---------------------------------*/
} catch (exception $e) { } catch (Exception $e) {
throw ($e); throw ($e);
} }
} else { } else {
throw (new Exception('You tried to start a new case without send the USER UID or TASK UID!')); throw (new Exception('You tried to start a new case without send the USER UID or TASK UID!'));
} }
//Log // Log
$message = 'Create case'; $message = 'Create case';
$context = $data = [ $context = $data = [
"appUid" => $sAppUid, "appUid" => $appUid,
"usrUid" => $sUsrUid, "usrUid" => $userUid,
"tasUid" => $sTasUid, "tasUid" => $taskUid,
"isSubprocess" => $isSubprocess, "isSubProcess" => $isSubProcess,
"appNumber" => $caseNumber, "appNumber" => $caseNumber,
"delIndex" => $iDelIndex, "delIndex" => $delIndex,
"appInitDate" => $Fields['APP_INIT_DATE'] "appInitDate" => $fields['APP_INIT_DATE']
]; ];
Log::channel(':CreateCase')->info($message, Bootstrap::context($context)); Log::channel(':CreateCase')->info($message, Bootstrap::context($context));
//call plugin // Call plugin
if (class_exists('folderData')) { if (class_exists('folderData')) {
$folderData = new folderData($sProUid, $proFields['PRO_TITLE'], $sAppUid, $newValues['APP_TITLE'], $sUsrUid); $folderData = new folderData($processUid, $proFields['PRO_TITLE'], $appUid, $newValues['APP_TITLE'], $userUid);
$oPluginRegistry = PluginRegistry::loadSingleton(); $pluginRegistry = PluginRegistry::loadSingleton();
$oPluginRegistry->executeTriggers(PM_CREATE_CASE, $folderData); $pluginRegistry->executeTriggers(PM_CREATE_CASE, $folderData);
} }
$this->getExecuteTriggerProcess($sAppUid, 'CREATE'); $this->getExecuteTriggerProcess($appUid, 'CREATE');
//end plugin // End plugin
return array( return [
'APPLICATION' => $sAppUid, 'APPLICATION' => $appUid,
'INDEX' => $iDelIndex, 'INDEX' => $delIndex,
'PROCESS' => $sProUid, 'PROCESS' => $processUid,
'CASE_NUMBER' => $caseNumber 'CASE_NUMBER' => $caseNumber
); ];
} }
/** /**
@@ -6089,7 +6094,7 @@ class Cases
switch ($opType) { switch ($opType) {
case 'ANY': case 'ANY':
//For dynaforms //For dynaforms
$listDynaform = $objectPermission->objectPermissionByDynaform( $listDynaform = BusinessModelCases::dynaFormsByApplication(
$appUid, $appUid,
$opTaskSource, $opTaskSource,
$opObjUid, $opObjUid,
@@ -6149,7 +6154,7 @@ class Cases
$resultMessages = array_merge($resultMessages, $listMessage); $resultMessages = array_merge($resultMessages, $listMessage);
break; break;
case 'DYNAFORM': case 'DYNAFORM':
$listDynaform = $objectPermission->objectPermissionByDynaform( $listDynaform = BusinessModelCases::dynaFormsByApplication(
$appUid, $appUid,
$opTaskSource, $opTaskSource,
$opObjUid, $opObjUid,

View File

@@ -7,6 +7,7 @@ use ProcessMaker\BusinessModel\Process as BmProcess;
/*----------------------------------********---------------------------------*/ /*----------------------------------********---------------------------------*/
use ProcessMaker\ChangeLog\ChangeLog; use ProcessMaker\ChangeLog\ChangeLog;
/*----------------------------------********---------------------------------*/ /*----------------------------------********---------------------------------*/
use ProcessMaker\BusinessModel\WebEntry;
use ProcessMaker\Core\Installer; use ProcessMaker\Core\Installer;
use ProcessMaker\Core\ProcessesManager; use ProcessMaker\Core\ProcessesManager;
use ProcessMaker\Core\System; use ProcessMaker\Core\System;
@@ -364,6 +365,18 @@ class WorkspaceTools
$start = microtime(true); $start = microtime(true);
$this->updateTriggers(true, $lang); $this->updateTriggers(true, $lang);
CLI::logging("* End updating MySQL triggers...(" . (microtime(true) - $start) . " seconds)\n"); CLI::logging("* End updating MySQL triggers...(" . (microtime(true) - $start) . " seconds)\n");
CLI::logging("* Start adding +async option to scheduler commands...\n");
$start = microtime(true);
$this->addAsyncOptionToSchedulerCommands(true);
CLI::logging("* End adding +async option to scheduler commands...(Completed on " . (microtime(true) - $start) . " seconds)\n");
CLI::logging("* Start Converting Web Entries v1.0 to v2.0 for BPMN processes...\n");
$start = microtime(true);
Bootstrap::setConstantsRelatedWs($workspace);
Propel::init(PATH_CONFIG . 'databases.php');
WebEntry::convertFromV1ToV2();
CLI::logging("* End converting Web Entries v1.0 to v2.0 for BPMN processes...(" . (microtime(true) - $start) . " seconds)\n");
} }
/** /**
@@ -1243,12 +1256,15 @@ class WorkspaceTools
if ($action == 'ADD') { if ($action == 'ADD') {
$tablesToAddColumns[$tableName] = $actionData; $tablesToAddColumns[$tableName] = $actionData;
// In a very old schema the primary key for table "LOGIN_LOG" was changed and we need to delete the // In a very old schema the primary key for tables "LOGIN_LOG" and "APP_SEQUENCE" were changed and we need to delete the
// primary index to avoid errors in the database upgrade // primary index to avoid errors in the database upgrade
// TO DO: The change of a Primary Key in a table should be generic // TO DO: The change of a Primary Key in a table should be generic
if ($tableName == 'LOGIN_LOG' && array_key_exists('LOG_ID', $actionData)) { if ($tableName == 'LOGIN_LOG' && array_key_exists('LOG_ID', $actionData)) {
$database->executeQuery('DROP INDEX `PRIMARY` ON LOGIN_LOG;'); $database->executeQuery('DROP INDEX `PRIMARY` ON LOGIN_LOG;');
} }
if ($tableName == 'APP_SEQUENCE' && array_key_exists('APP_TYPE', $actionData)) {
$database->executeQuery('DROP INDEX `PRIMARY` ON APP_SEQUENCE;');
}
} else { } else {
foreach ($actionData as $columnName => $meta) { foreach ($actionData as $columnName => $meta) {
switch ($action) { switch ($action) {
@@ -2206,6 +2222,18 @@ class WorkspaceTools
$start = microtime(true); $start = microtime(true);
$workspace->updateTriggers(true, $lang); $workspace->updateTriggers(true, $lang);
CLI::logging("* End updating MySQL triggers...(" . (microtime(true) - $start) . " seconds)\n"); CLI::logging("* End updating MySQL triggers...(" . (microtime(true) - $start) . " seconds)\n");
CLI::logging("* Start adding +async option to scheduler commands...\n");
$start = microtime(true);
$workspace->addAsyncOptionToSchedulerCommands(false);
CLI::logging("* End adding +async option to scheduler commands...(Completed on " . (microtime(true) - $start) . " seconds)\n");
CLI::logging("* Start Converting Web Entries v1.0 to v2.0 for BPMN processes...\n");
$start = microtime(true);
Bootstrap::setConstantsRelatedWs($workspace);
Propel::init(PATH_CONFIG . 'databases.php');
WebEntry::convertFromV1ToV2();
CLI::logging("* End converting Web Entries v1.0 to v2.0 for BPMN processes...(" . (microtime(true) - $start) . " seconds)\n");
} }
CLI::logging("> Start To Verify License Enterprise...\n"); CLI::logging("> Start To Verify License Enterprise...\n");
@@ -3285,22 +3313,46 @@ class WorkspaceTools
} }
} }
/**
* Add sequence numbers
*/
public function checkSequenceNumber() public function checkSequenceNumber()
{ {
$criteria = new Criteria("workflow"); // Instance required class
$appSequenceInstance = new AppSequence();
// Get a record from APP_SEQUENCE table
$criteria = new Criteria('workflow');
$rsCriteria = AppSequencePeer::doSelectRS($criteria); $rsCriteria = AppSequencePeer::doSelectRS($criteria);
$rsCriteria->setFetchmode(ResultSet::FETCHMODE_ASSOC); $rsCriteria->setFetchmode(ResultSet::FETCHMODE_ASSOC);
$rsCriteria->next(); $rsCriteria->next();
$appSequenceRow = $rsCriteria->getRow(); $appSequenceRow = $rsCriteria->getRow();
// If table APP_SEQUENCE is empty, insert two records
if (empty($appSequenceRow)) { if (empty($appSequenceRow)) {
$sequenceInstance = SequencesPeer::retrieveByPK("APP_NUMBER"); // Check if exist a value in old table SEQUENCES
$appSequenceInstance = new AppSequence(); $sequenceInstance = SequencesPeer::retrieveByPK('APP_NUMBER');
if (!is_null($sequenceInstance)) { if (!is_null($sequenceInstance)) {
// If exists a value in SEQUENCE table, copy the same to APP_SEQUENCES table
$sequenceFields = $sequenceInstance->toArray(BasePeer::TYPE_FIELDNAME); $sequenceFields = $sequenceInstance->toArray(BasePeer::TYPE_FIELDNAME);
$appSequenceInstance->updateSequenceNumber($sequenceFields['SEQ_VALUE']); $appSequenceInstance->updateSequenceNumber($sequenceFields['SEQ_VALUE']);
} else { } else {
// If not exists a value in SEQUENCE table, insert a initial value
$appSequenceInstance->updateSequenceNumber(0); $appSequenceInstance->updateSequenceNumber(0);
} }
// Insert a initial value for the web entries
$appSequenceInstance->updateSequenceNumber(0, AppSequence::APP_TYPE_WEB_ENTRY);
} else {
// Create a new instance of Criteria class
$criteria = new Criteria('workflow');
$criteria->add(AppSequencePeer::APP_TYPE, AppSequence::APP_TYPE_WEB_ENTRY);
// Check if exists a record for the web entries, if not exist insert the initial value
if (AppSequencePeer::doCount($criteria) === 0) {
$appSequenceInstance->updateSequenceNumber(0, AppSequence::APP_TYPE_WEB_ENTRY);
}
} }
} }
@@ -4939,7 +4991,9 @@ class WorkspaceTools
$case = new Cases(); $case = new Cases();
//select cases for this Process, ordered by APP_NUMBER //select cases for this Process, ordered by APP_NUMBER
$applications = Application::where('PRO_UID', '=', $processUid) $applications = Application::query()
->where('PRO_UID', '=', $processUid)
->where('APP_NUMBER', '>', 0)
->orderBy('APP_NUMBER', 'asc') ->orderBy('APP_NUMBER', 'asc')
->offset($start) ->offset($start)
->limit($limit) ->limit($limit)
@@ -5040,4 +5094,37 @@ class WorkspaceTools
$database = $this->getDatabase($rbac); $database = $this->getDatabase($rbac);
$database->executeQuery($query, true); $database->executeQuery($query, true);
} }
/**
* Add +async option to scheduler commands in table SCHEDULER.
* @param boolean $force
*/
public function addAsyncOptionToSchedulerCommands($force = false)
{
//read update status
$this->initPropel(true);
$conf = new Configurations();
$exist = $conf->exists('ADDED_ASYNC_OPTION_TO_SCHEDULER', 'scheduler');
if ($exist === true && $force === false) {
$config = (object) $conf->load('ADDED_ASYNC_OPTION_TO_SCHEDULER', 'scheduler');
if ($config->updated) {
CLI::logging("-> This was previously updated.\n");
return;
}
}
//update process
$updateQuery = ""
. "UPDATE {$this->dbName}.SCHEDULER SET body = REPLACE(body, '+force\"', '+force +async\"') "
. "WHERE body NOT LIKE '%+async%'"
. "";
$con = Propel::getConnection("workflow");
$stmt = $con->createStatement();
$stmt->executeQuery($updateQuery);
CLI::logging("-> Adding +async option to scheduler commands in table {$this->dbName}.SCHEDULER\n");
//save update status
$conf->aConfig = ['updated' => true];
$conf->saveConfig('ADDED_ASYNC_OPTION_TO_SCHEDULER', 'scheduler');
}
} }

View File

@@ -302,6 +302,9 @@ class PMScript
case 'SCRIPT_TASK': case 'SCRIPT_TASK':
$executedOn = self::SCRIPT_TASK; $executedOn = self::SCRIPT_TASK;
break; break;
case 'SELF_SERVICE_TIMEOUT':
$executedOn = self::SELF_SERVICE_TIMEOUT;
break;
default: default:
$executedOn = self::UNDEFINED_ORIGIN; $executedOn = self::UNDEFINED_ORIGIN;
break; break;

View File

@@ -314,6 +314,8 @@ class AppFolder extends BaseAppFolder
$oCriteria->addSelectColumn( AppDocumentPeer::APP_DOC_STATUS_DATE); $oCriteria->addSelectColumn( AppDocumentPeer::APP_DOC_STATUS_DATE);
$oCriteria->addSelectColumn( AppDocumentPeer::APP_DOC_FIELDNAME); $oCriteria->addSelectColumn( AppDocumentPeer::APP_DOC_FIELDNAME);
$oCriteria->addSelectColumn(AppDocumentPeer::APP_DOC_DRIVE_DOWNLOAD); $oCriteria->addSelectColumn(AppDocumentPeer::APP_DOC_DRIVE_DOWNLOAD);
$oCriteria->addJoin(AppDocumentPeer::APP_UID, ApplicationPeer::APP_UID);
$oCriteria->add(ApplicationPeer::APP_NUMBER, 0, Criteria::GREATER_THAN);
if ((is_array( $docIdFilter )) && (count( $docIdFilter ) > 0)) { if ((is_array( $docIdFilter )) && (count( $docIdFilter ) > 0)) {
//Search by App Doc UID no matter what Folder it is //Search by App Doc UID no matter what Folder it is

View File

@@ -16,27 +16,34 @@ require_once 'classes/model/om/BaseAppSequence.php';
*/ */
class AppSequence extends BaseAppSequence { class AppSequence extends BaseAppSequence {
const APP_TYPE_NORMAL = 'NORMAL';
const APP_TYPE_WEB_ENTRY = 'WEB_ENTRY';
/** /**
* Get an Set new sequence number * Get an Set new sequence number
* *
* @param string $sequenceType
* @return mixed * @return mixed
* @throws Exception * @throws Exception
*/ */
public function sequenceNumber() public function sequenceNumber($sequenceType)
{ {
try { try {
$con = Propel::getConnection('workflow'); $con = Propel::getConnection('workflow');
$stmt = $con->createStatement(); $stmt = $con->createStatement();
//UPDATE SEQUENCES SET SEQ_VALUE = LAST_INSERT_ID(SEQ_VALUE + 1); $sql = "UPDATE APP_SEQUENCE SET ID=LAST_INSERT_ID(ID+1) WHERE APP_TYPE = '{$sequenceType}'";
$sql = "UPDATE APP_SEQUENCE SET ID=LAST_INSERT_ID(ID+1)";
$stmt->executeQuery($sql, ResultSet::FETCHMODE_ASSOC); $stmt->executeQuery($sql, ResultSet::FETCHMODE_ASSOC);
//SELECT LAST_INSERT_ID()
$sql = "SELECT LAST_INSERT_ID()"; $sql = "SELECT LAST_INSERT_ID()";
$rs = $stmt->executeQuery($sql, ResultSet::FETCHMODE_ASSOC); $rs = $stmt->executeQuery($sql, ResultSet::FETCHMODE_ASSOC);
$rs->next(); $rs->next();
$row = $rs->getRow(); $row = $rs->getRow();
$result = $row['LAST_INSERT_ID()']; $result = $row['LAST_INSERT_ID()'];
} catch (\Exception $e) {
// If the type is WEB_ENTRY, we need to change to negative
if ($sequenceType === 'WEB_ENTRY') {
$result *= -1;
}
} catch (Exception $e) {
throw ($e); throw ($e);
} }
return $result; return $result;
@@ -46,26 +53,36 @@ class AppSequence extends BaseAppSequence {
/** /**
* Update sequence number * Update sequence number
* *
* @return mixed * @param int $number
* @param string $sequenceType
*
* @throws Exception * @throws Exception
*/ */
public function updateSequenceNumber($number) public function updateSequenceNumber($number, $sequenceType = AppSequence::APP_TYPE_NORMAL)
{ {
try { try {
$con = Propel::getConnection('workflow'); // Get the current connection
$stmt = $con->createStatement(); $connection = Propel::getConnection('workflow');
$c = new Criteria();
$rs = AppSequencePeer::doSelectRS($c); // Create a statement instance
$rs->setFetchmode(ResultSet::FETCHMODE_ASSOC); $statement = $connection->createStatement();
$rs->next();
$row = $rs->getRow(); // Get the record according to the sequence type
$criteria = new Criteria();
$criteria->add(AppSequencePeer::APP_TYPE, $sequenceType);
$rsCriteria = AppSequencePeer::doSelectRS($criteria);
$rsCriteria->setFetchmode(ResultSet::FETCHMODE_ASSOC);
$rsCriteria->next();
$row = $rsCriteria->getRow();
// Insert/Update sequence table with the number sent
if ($row) { if ($row) {
$sql = "UPDATE APP_SEQUENCE SET ID=LAST_INSERT_ID('$number')"; $sql = "UPDATE APP_SEQUENCE SET ID=LAST_INSERT_ID('{$number}') WHERE APP_TYPE = '{$sequenceType}'";
} else { } else {
$sql = "INSERT INTO APP_SEQUENCE (ID) VALUES ('$number');"; $sql = "INSERT INTO APP_SEQUENCE (ID, APP_TYPE) VALUES ('{$number}', '{$sequenceType}')";
} }
$stmt->executeQuery($sql, ResultSet::FETCHMODE_ASSOC); $statement->executeQuery($sql, ResultSet::FETCHMODE_ASSOC);
} catch (\Exception $e) { } catch (Exception $e) {
throw ($e); throw ($e);
} }
} }

View File

@@ -207,30 +207,31 @@ class Application extends BaseApplication
} }
/** /**
* Creates the Application * Creates an Application
* *
* @param * @param string $processUid
* $sProUid the process id * @param string $userUid
* $sUsrUid the userid * @param string $sequenceType
* @return void * @throws PropelException
* @throws Exception
* @return string
*/ */
public function create($sProUid, $sUsrUid) public function create($processUid, $userUid, $sequenceType)
{ {
require_once ("classes/model/AppSequence.php");
$con = Propel::getConnection('workflow'); $con = Propel::getConnection('workflow');
try { try {
//fill the default values for new application row // Fill the default values for new application row
$this->setAppUid(G::generateUniqueID()); $this->setAppUid(G::generateUniqueID());
$this->setAppParent(''); $this->setAppParent('');
$this->setAppStatus('DRAFT'); $this->setAppStatus('DRAFT');
$this->setAppStatusId(1); $this->setAppStatusId(1);
$this->setProUid($sProUid); $this->setProUid($processUid);
$this->setAppProcStatus(''); $this->setAppProcStatus('');
$this->setAppProcCode(''); $this->setAppProcCode('');
$this->setAppParallel('N'); $this->setAppParallel('N');
$this->setAppInitUser($sUsrUid); $this->setAppInitUser($userUid);
$this->setAppCurUser($sUsrUid); $this->setAppCurUser($userUid);
$this->setAppCreateDate('now'); $this->setAppCreateDate('now');
$this->setAppInitDate('now'); $this->setAppInitDate('now');
$this->setAppUpdateDate('now'); $this->setAppUpdateDate('now');
@@ -241,8 +242,8 @@ class Application extends BaseApplication
$c = new Criteria(); $c = new Criteria();
$c->clearSelectColumns(); $c->clearSelectColumns();
$oAppSequence = new AppSequence(); $appSequence = new AppSequence();
$maxNumber = $oAppSequence->sequenceNumber(); $maxNumber = $appSequence->sequenceNumber($sequenceType);
$this->setAppNumber($maxNumber); $this->setAppNumber($maxNumber);
$this->setAppData(serialize(['APP_NUMBER' => $maxNumber, 'PIN' => $pin])); $this->setAppData(serialize(['APP_NUMBER' => $maxNumber, 'PIN' => $pin]));
@@ -253,9 +254,7 @@ class Application extends BaseApplication
$con->begin(); $con->begin();
$this->setAppTitleContent('#' . $maxNumber); $this->setAppTitleContent('#' . $maxNumber);
$this->setAppDescriptionContent(''); $this->setAppDescriptionContent('');
//to do: ID_CASE in translation $this->setAppTitle(G::LoadTranslation('ID_CASE') . $maxNumber); $this->save();
//Content::insertContent('APP_PROC_CODE', '', $this->getAppUid(), $lang, '');
$res = $this->save();
$con->commit(); $con->commit();
return $this->getAppUid(); return $this->getAppUid();

View File

@@ -65,7 +65,9 @@ class AppSequenceMapBuilder
$tMap->setUseIdGenerator(false); $tMap->setUseIdGenerator(false);
$tMap->addPrimaryKey('ID', 'Id', 'int', CreoleTypes::INTEGER, true, null); $tMap->addColumn('ID', 'Id', 'int', CreoleTypes::INTEGER, true, null);
$tMap->addColumn('APP_TYPE', 'AppType', 'string', CreoleTypes::VARCHAR, true, 20);
} // doBuild() } // doBuild()

View File

@@ -67,7 +67,7 @@ class AppTimeoutActionExecutedMapBuilder
$tMap->addPrimaryKey('APP_UID', 'AppUid', 'string', CreoleTypes::VARCHAR, true, 32); $tMap->addPrimaryKey('APP_UID', 'AppUid', 'string', CreoleTypes::VARCHAR, true, 32);
$tMap->addColumn('DEL_INDEX', 'DelIndex', 'int', CreoleTypes::INTEGER, true, null); $tMap->addPrimaryKey('DEL_INDEX', 'DelIndex', 'int', CreoleTypes::INTEGER, true, null);
$tMap->addColumn('EXECUTION_DATE', 'ExecutionDate', 'int', CreoleTypes::TIMESTAMP, false, null); $tMap->addColumn('EXECUTION_DATE', 'ExecutionDate', 'int', CreoleTypes::TIMESTAMP, false, null);

View File

@@ -33,6 +33,12 @@ abstract class BaseAppSequence extends BaseObject implements Persistent
*/ */
protected $id; protected $id;
/**
* The value for the app_type field.
* @var string
*/
protected $app_type = 'NORMAL';
/** /**
* Flag to prevent endless save loop, if this object is referenced * Flag to prevent endless save loop, if this object is referenced
* by another object which falls in this transaction. * by another object which falls in this transaction.
@@ -58,6 +64,17 @@ abstract class BaseAppSequence extends BaseObject implements Persistent
return $this->id; return $this->id;
} }
/**
* Get the [app_type] column value.
*
* @return string
*/
public function getAppType()
{
return $this->app_type;
}
/** /**
* Set the value of [id] column. * Set the value of [id] column.
* *
@@ -80,6 +97,28 @@ abstract class BaseAppSequence extends BaseObject implements Persistent
} // setId() } // setId()
/**
* Set the value of [app_type] column.
*
* @param string $v new value
* @return void
*/
public function setAppType($v)
{
// Since the native PHP type for this column is string,
// we will cast the input to a string (if it is not).
if ($v !== null && !is_string($v)) {
$v = (string) $v;
}
if ($this->app_type !== $v || $v === 'NORMAL') {
$this->app_type = $v;
$this->modifiedColumns[] = AppSequencePeer::APP_TYPE;
}
} // setAppType()
/** /**
* Hydrates (populates) the object variables with values from the database resultset. * Hydrates (populates) the object variables with values from the database resultset.
* *
@@ -99,12 +138,14 @@ abstract class BaseAppSequence extends BaseObject implements Persistent
$this->id = $rs->getInt($startcol + 0); $this->id = $rs->getInt($startcol + 0);
$this->app_type = $rs->getString($startcol + 1);
$this->resetModified(); $this->resetModified();
$this->setNew(false); $this->setNew(false);
// FIXME - using NUM_COLUMNS may be clearer. // FIXME - using NUM_COLUMNS may be clearer.
return $startcol + 1; // 1 = AppSequencePeer::NUM_COLUMNS - AppSequencePeer::NUM_LAZY_LOAD_COLUMNS). return $startcol + 2; // 2 = AppSequencePeer::NUM_COLUMNS - AppSequencePeer::NUM_LAZY_LOAD_COLUMNS).
} catch (Exception $e) { } catch (Exception $e) {
throw new PropelException("Error populating AppSequence object", $e); throw new PropelException("Error populating AppSequence object", $e);
@@ -311,6 +352,9 @@ abstract class BaseAppSequence extends BaseObject implements Persistent
case 0: case 0:
return $this->getId(); return $this->getId();
break; break;
case 1:
return $this->getAppType();
break;
default: default:
return null; return null;
break; break;
@@ -332,6 +376,7 @@ abstract class BaseAppSequence extends BaseObject implements Persistent
$keys = AppSequencePeer::getFieldNames($keyType); $keys = AppSequencePeer::getFieldNames($keyType);
$result = array( $result = array(
$keys[0] => $this->getId(), $keys[0] => $this->getId(),
$keys[1] => $this->getAppType(),
); );
return $result; return $result;
} }
@@ -366,6 +411,9 @@ abstract class BaseAppSequence extends BaseObject implements Persistent
case 0: case 0:
$this->setId($value); $this->setId($value);
break; break;
case 1:
$this->setAppType($value);
break;
} // switch() } // switch()
} }
@@ -393,6 +441,10 @@ abstract class BaseAppSequence extends BaseObject implements Persistent
$this->setId($arr[$keys[0]]); $this->setId($arr[$keys[0]]);
} }
if (array_key_exists($keys[1], $arr)) {
$this->setAppType($arr[$keys[1]]);
}
} }
/** /**
@@ -408,6 +460,10 @@ abstract class BaseAppSequence extends BaseObject implements Persistent
$criteria->add(AppSequencePeer::ID, $this->id); $criteria->add(AppSequencePeer::ID, $this->id);
} }
if ($this->isColumnModified(AppSequencePeer::APP_TYPE)) {
$criteria->add(AppSequencePeer::APP_TYPE, $this->app_type);
}
return $criteria; return $criteria;
} }
@@ -424,29 +480,32 @@ abstract class BaseAppSequence extends BaseObject implements Persistent
{ {
$criteria = new Criteria(AppSequencePeer::DATABASE_NAME); $criteria = new Criteria(AppSequencePeer::DATABASE_NAME);
$criteria->add(AppSequencePeer::ID, $this->id);
return $criteria; return $criteria;
} }
/** /**
* Returns the primary key for this object (row). * Returns NULL since this table doesn't have a primary key.
* @return int * This method exists only for BC and is deprecated!
* @return null
*/ */
public function getPrimaryKey() public function getPrimaryKey()
{ {
return $this->getId(); return null;
} }
/** /**
* Generic method to set the primary key (id column). * Dummy primary key setter.
* *
* @param int $key Primary key. * This function only exists to preserve backwards compatibility. It is no longer
* @return void * needed or required by the Persistent interface. It will be removed in next BC-breaking
* release of Propel.
*
* @deprecated
*/ */
public function setPrimaryKey($key) public function setPrimaryKey($pk)
{ {
$this->setId($key); // do nothing, because this object doesn't have any primary keys
} }
/** /**
@@ -462,11 +521,13 @@ abstract class BaseAppSequence extends BaseObject implements Persistent
public function copyInto($copyObj, $deepCopy = false) public function copyInto($copyObj, $deepCopy = false)
{ {
$copyObj->setId($this->id);
$copyObj->setAppType($this->app_type);
$copyObj->setNew(true); $copyObj->setNew(true);
$copyObj->setId(NULL); // this is a pkey column, so set to default value
} }
/** /**

View File

@@ -25,7 +25,7 @@ abstract class BaseAppSequencePeer
const CLASS_DEFAULT = 'classes.model.AppSequence'; const CLASS_DEFAULT = 'classes.model.AppSequence';
/** The total number of columns. */ /** The total number of columns. */
const NUM_COLUMNS = 1; const NUM_COLUMNS = 2;
/** The number of lazy-loaded columns. */ /** The number of lazy-loaded columns. */
const NUM_LAZY_LOAD_COLUMNS = 0; const NUM_LAZY_LOAD_COLUMNS = 0;
@@ -34,6 +34,9 @@ abstract class BaseAppSequencePeer
/** the column name for the ID field */ /** the column name for the ID field */
const ID = 'APP_SEQUENCE.ID'; const ID = 'APP_SEQUENCE.ID';
/** the column name for the APP_TYPE field */
const APP_TYPE = 'APP_SEQUENCE.APP_TYPE';
/** The PHP to DB Name Mapping */ /** The PHP to DB Name Mapping */
private static $phpNameMap = null; private static $phpNameMap = null;
@@ -45,10 +48,10 @@ abstract class BaseAppSequencePeer
* e.g. self::$fieldNames[self::TYPE_PHPNAME][0] = 'Id' * e.g. self::$fieldNames[self::TYPE_PHPNAME][0] = 'Id'
*/ */
private static $fieldNames = array ( private static $fieldNames = array (
BasePeer::TYPE_PHPNAME => array ('Id', ), BasePeer::TYPE_PHPNAME => array ('Id', 'AppType', ),
BasePeer::TYPE_COLNAME => array (AppSequencePeer::ID, ), BasePeer::TYPE_COLNAME => array (AppSequencePeer::ID, AppSequencePeer::APP_TYPE, ),
BasePeer::TYPE_FIELDNAME => array ('ID', ), BasePeer::TYPE_FIELDNAME => array ('ID', 'APP_TYPE', ),
BasePeer::TYPE_NUM => array (0, ) BasePeer::TYPE_NUM => array (0, 1, )
); );
/** /**
@@ -58,10 +61,10 @@ abstract class BaseAppSequencePeer
* e.g. self::$fieldNames[BasePeer::TYPE_PHPNAME]['Id'] = 0 * e.g. self::$fieldNames[BasePeer::TYPE_PHPNAME]['Id'] = 0
*/ */
private static $fieldKeys = array ( private static $fieldKeys = array (
BasePeer::TYPE_PHPNAME => array ('Id' => 0, ), BasePeer::TYPE_PHPNAME => array ('Id' => 0, 'AppType' => 1, ),
BasePeer::TYPE_COLNAME => array (AppSequencePeer::ID => 0, ), BasePeer::TYPE_COLNAME => array (AppSequencePeer::ID => 0, AppSequencePeer::APP_TYPE => 1, ),
BasePeer::TYPE_FIELDNAME => array ('ID' => 0, ), BasePeer::TYPE_FIELDNAME => array ('ID' => 0, 'APP_TYPE' => 1, ),
BasePeer::TYPE_NUM => array (0, ) BasePeer::TYPE_NUM => array (0, 1, )
); );
/** /**
@@ -164,10 +167,12 @@ abstract class BaseAppSequencePeer
$criteria->addSelectColumn(AppSequencePeer::ID); $criteria->addSelectColumn(AppSequencePeer::ID);
$criteria->addSelectColumn(AppSequencePeer::APP_TYPE);
} }
const COUNT = 'COUNT(APP_SEQUENCE.ID)'; const COUNT = 'COUNT(*)';
const COUNT_DISTINCT = 'COUNT(DISTINCT APP_SEQUENCE.ID)'; const COUNT_DISTINCT = 'COUNT(DISTINCT *)';
/** /**
* Returns the number of rows matching criteria. * Returns the number of rows matching criteria.
@@ -376,9 +381,6 @@ abstract class BaseAppSequencePeer
if ($values instanceof Criteria) { if ($values instanceof Criteria) {
$criteria = clone $values; // rename for clarity $criteria = clone $values; // rename for clarity
$comparison = $criteria->getComparison(AppSequencePeer::ID);
$selectCriteria->add(AppSequencePeer::ID, $criteria->remove(AppSequencePeer::ID), $comparison);
} else { } else {
$criteria = $values->buildCriteria(); // gets full criteria $criteria = $values->buildCriteria(); // gets full criteria
$selectCriteria = $values->buildPkeyCriteria(); // gets criteria w/ primary key(s) $selectCriteria = $values->buildPkeyCriteria(); // gets criteria w/ primary key(s)
@@ -436,11 +438,22 @@ abstract class BaseAppSequencePeer
$criteria = clone $values; // rename for clarity $criteria = clone $values; // rename for clarity
} elseif ($values instanceof AppSequence) { } elseif ($values instanceof AppSequence) {
$criteria = $values->buildPkeyCriteria(); $criteria = $values->buildCriteria();
} else { } else {
// it must be the primary key // it must be the primary key
$criteria = new Criteria(self::DATABASE_NAME); $criteria = new Criteria(self::DATABASE_NAME);
$criteria->add(AppSequencePeer::ID, (array) $values, Criteria::IN); // primary key is composite; we therefore, expect
// the primary key passed to be an array of pkey
// values
if (count($values) == count($values, COUNT_RECURSIVE)) {
// array is not multi-dimensional
$values = array($values);
}
$vals = array();
foreach ($values as $value) {
}
} }
// Set the correct dbName // Set the correct dbName
@@ -498,54 +511,6 @@ abstract class BaseAppSequencePeer
return BasePeer::doValidate(AppSequencePeer::DATABASE_NAME, AppSequencePeer::TABLE_NAME, $columns); return BasePeer::doValidate(AppSequencePeer::DATABASE_NAME, AppSequencePeer::TABLE_NAME, $columns);
} }
/**
* Retrieve a single object by pkey.
*
* @param mixed $pk the primary key.
* @param Connection $con the connection to use
* @return AppSequence
*/
public static function retrieveByPK($pk, $con = null)
{
if ($con === null) {
$con = Propel::getConnection(self::DATABASE_NAME);
}
$criteria = new Criteria(AppSequencePeer::DATABASE_NAME);
$criteria->add(AppSequencePeer::ID, $pk);
$v = AppSequencePeer::doSelect($criteria, $con);
return !empty($v) > 0 ? $v[0] : null;
}
/**
* Retrieve multiple objects by pkey.
*
* @param array $pks List of primary keys
* @param Connection $con the connection to use
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function retrieveByPKs($pks, $con = null)
{
if ($con === null) {
$con = Propel::getConnection(self::DATABASE_NAME);
}
$objs = null;
if (empty($pks)) {
$objs = array();
} else {
$criteria = new Criteria();
$criteria->add(AppSequencePeer::ID, $pks, Criteria::IN);
$objs = AppSequencePeer::doSelect($criteria, $con);
}
return $objs;
}
} }

View File

@@ -565,28 +565,40 @@ abstract class BaseAppTimeoutActionExecuted extends BaseObject implements Persis
$criteria = new Criteria(AppTimeoutActionExecutedPeer::DATABASE_NAME); $criteria = new Criteria(AppTimeoutActionExecutedPeer::DATABASE_NAME);
$criteria->add(AppTimeoutActionExecutedPeer::APP_UID, $this->app_uid); $criteria->add(AppTimeoutActionExecutedPeer::APP_UID, $this->app_uid);
$criteria->add(AppTimeoutActionExecutedPeer::DEL_INDEX, $this->del_index);
return $criteria; return $criteria;
} }
/** /**
* Returns the primary key for this object (row). * Returns the composite primary key for this object.
* @return string * The array elements will be in same order as specified in XML.
* @return array
*/ */
public function getPrimaryKey() public function getPrimaryKey()
{ {
return $this->getAppUid(); $pks = array();
$pks[0] = $this->getAppUid();
$pks[1] = $this->getDelIndex();
return $pks;
} }
/** /**
* Generic method to set the primary key (app_uid column). * Set the [composite] primary key.
* *
* @param string $key Primary key. * @param array $keys The elements of the composite key (order must match the order in XML file).
* @return void * @return void
*/ */
public function setPrimaryKey($key) public function setPrimaryKey($keys)
{ {
$this->setAppUid($key);
$this->setAppUid($keys[0]);
$this->setDelIndex($keys[1]);
} }
/** /**
@@ -602,8 +614,6 @@ abstract class BaseAppTimeoutActionExecuted extends BaseObject implements Persis
public function copyInto($copyObj, $deepCopy = false) public function copyInto($copyObj, $deepCopy = false)
{ {
$copyObj->setDelIndex($this->del_index);
$copyObj->setExecutionDate($this->execution_date); $copyObj->setExecutionDate($this->execution_date);
@@ -611,6 +621,8 @@ abstract class BaseAppTimeoutActionExecuted extends BaseObject implements Persis
$copyObj->setAppUid(''); // this is a pkey column, so set to default value $copyObj->setAppUid(''); // this is a pkey column, so set to default value
$copyObj->setDelIndex('0'); // this is a pkey column, so set to default value
} }
/** /**

View File

@@ -389,6 +389,9 @@ abstract class BaseAppTimeoutActionExecutedPeer
$comparison = $criteria->getComparison(AppTimeoutActionExecutedPeer::APP_UID); $comparison = $criteria->getComparison(AppTimeoutActionExecutedPeer::APP_UID);
$selectCriteria->add(AppTimeoutActionExecutedPeer::APP_UID, $criteria->remove(AppTimeoutActionExecutedPeer::APP_UID), $comparison); $selectCriteria->add(AppTimeoutActionExecutedPeer::APP_UID, $criteria->remove(AppTimeoutActionExecutedPeer::APP_UID), $comparison);
$comparison = $criteria->getComparison(AppTimeoutActionExecutedPeer::DEL_INDEX);
$selectCriteria->add(AppTimeoutActionExecutedPeer::DEL_INDEX, $criteria->remove(AppTimeoutActionExecutedPeer::DEL_INDEX), $comparison);
} else { } else {
$criteria = $values->buildCriteria(); // gets full criteria $criteria = $values->buildCriteria(); // gets full criteria
$selectCriteria = $values->buildPkeyCriteria(); // gets criteria w/ primary key(s) $selectCriteria = $values->buildPkeyCriteria(); // gets criteria w/ primary key(s)
@@ -450,7 +453,22 @@ abstract class BaseAppTimeoutActionExecutedPeer
} else { } else {
// it must be the primary key // it must be the primary key
$criteria = new Criteria(self::DATABASE_NAME); $criteria = new Criteria(self::DATABASE_NAME);
$criteria->add(AppTimeoutActionExecutedPeer::APP_UID, (array) $values, Criteria::IN); // primary key is composite; we therefore, expect
// the primary key passed to be an array of pkey
// values
if (count($values) == count($values, COUNT_RECURSIVE)) {
// array is not multi-dimensional
$values = array($values);
}
$vals = array();
foreach ($values as $value) {
$vals[0][] = $value[0];
$vals[1][] = $value[1];
}
$criteria->add(AppTimeoutActionExecutedPeer::APP_UID, $vals[0], Criteria::IN);
$criteria->add(AppTimeoutActionExecutedPeer::DEL_INDEX, $vals[1], Criteria::IN);
} }
// Set the correct dbName // Set the correct dbName
@@ -510,51 +528,23 @@ abstract class BaseAppTimeoutActionExecutedPeer
} }
/** /**
* Retrieve a single object by pkey. * Retrieve object using using composite pkey values.
* * @param string $app_uid
* @param mixed $pk the primary key. * @param int $del_index
* @param Connection $con the connection to use * @param Connection $con
* @return AppTimeoutActionExecuted * @return AppTimeoutActionExecuted
*/ */
public static function retrieveByPK($pk, $con = null) public static function retrieveByPK($app_uid, $del_index, $con = null)
{ {
if ($con === null) { if ($con === null) {
$con = Propel::getConnection(self::DATABASE_NAME); $con = Propel::getConnection(self::DATABASE_NAME);
} }
$criteria = new Criteria();
$criteria = new Criteria(AppTimeoutActionExecutedPeer::DATABASE_NAME); $criteria->add(AppTimeoutActionExecutedPeer::APP_UID, $app_uid);
$criteria->add(AppTimeoutActionExecutedPeer::DEL_INDEX, $del_index);
$criteria->add(AppTimeoutActionExecutedPeer::APP_UID, $pk);
$v = AppTimeoutActionExecutedPeer::doSelect($criteria, $con); $v = AppTimeoutActionExecutedPeer::doSelect($criteria, $con);
return !empty($v) > 0 ? $v[0] : null; return !empty($v) ? $v[0] : null;
}
/**
* Retrieve multiple objects by pkey.
*
* @param array $pks List of primary keys
* @param Connection $con the connection to use
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function retrieveByPKs($pks, $con = null)
{
if ($con === null) {
$con = Propel::getConnection(self::DATABASE_NAME);
}
$objs = null;
if (empty($pks)) {
$objs = array();
} else {
$criteria = new Criteria();
$criteria->add(AppTimeoutActionExecutedPeer::APP_UID, $pks, Criteria::IN);
$objs = AppTimeoutActionExecutedPeer::doSelect($criteria, $con);
}
return $objs;
} }
} }

View File

@@ -117,7 +117,8 @@
</unique> </unique>
</table> </table>
<table name="APP_SEQUENCE" idMethod="native"> <table name="APP_SEQUENCE" idMethod="native">
<column name="ID" type="INTEGER" required="true" primaryKey="true"/> <column name="ID" type="INTEGER" required="true"/>
<column name="APP_TYPE" type="VARCHAR" size="20" required="true" default="NORMAL"/>
</table> </table>
<table name="APP_DELEGATION" idMethod="native"> <table name="APP_DELEGATION" idMethod="native">
<vendor type="mysql"> <vendor type="mysql">
@@ -4303,7 +4304,7 @@
<table name="APP_TIMEOUT_ACTION_EXECUTED"> <table name="APP_TIMEOUT_ACTION_EXECUTED">
<column name="APP_UID" type="VARCHAR" size="32" required="true" default="" primaryKey="true"/> <column name="APP_UID" type="VARCHAR" size="32" required="true" default="" primaryKey="true"/>
<column name="DEL_INDEX" type="INTEGER" required="true" default="0"/> <column name="DEL_INDEX" type="INTEGER" required="true" default="0" primaryKey="true"/>
<column name="EXECUTION_DATE" type="TIMESTAMP" required="false"/> <column name="EXECUTION_DATE" type="TIMESTAMP" required="false"/>
</table> </table>

File diff suppressed because one or more lines are too long

View File

@@ -10931,6 +10931,12 @@ msgstr "Case Scheduler Log"
msgid "Log Information" msgid "Log Information"
msgstr "Log Information" msgstr "Log Information"
# TRANSLATION
# LABEL/ID_MAFE_TRANSLATION_DIRECTORY
#: LABEL/ID_MAFE_TRANSLATION_DIRECTORY
msgid "MAFE Translation Directory"
msgstr "MAFE Translation Directory"
# TRANSLATION # TRANSLATION
# LABEL/ID_MAFE_0015b7e51c1ca4293041c429985ca323 # LABEL/ID_MAFE_0015b7e51c1ca4293041c429985ca323
#: LABEL/ID_MAFE_0015b7e51c1ca4293041c429985ca323 #: LABEL/ID_MAFE_0015b7e51c1ca4293041c429985ca323
@@ -22085,6 +22091,12 @@ msgstr "The report table '{0}' is related to a process not present in the worksp
msgid "[LABEL/ID_PROCESS_NO_CATEGORY] No Category" msgid "[LABEL/ID_PROCESS_NO_CATEGORY] No Category"
msgstr "No Category" msgstr "No Category"
# TRANSLATION
# LABEL/ID_PROCESS_NONE_CATEGORY
#: LABEL/ID_PROCESS_NONE_CATEGORY
msgid "- No Category -"
msgstr "- No Category -"
# TRANSLATION # TRANSLATION
# LABEL/ID_PROCESS_NO_EXIST # LABEL/ID_PROCESS_NO_EXIST
#: LABEL/ID_PROCESS_NO_EXIST #: LABEL/ID_PROCESS_NO_EXIST
@@ -25499,6 +25511,18 @@ msgstr "Thu"
msgid "Timer event" msgid "Timer event"
msgstr "Timer event" msgstr "Timer event"
# TRANSLATION
# LABEL/ID_CLEAN_WEBENTRIES
#: LABEL/ID_CLEAN_WEBENTRIES
msgid "Clean web-entries"
msgstr "Clean web-entries"
# TRANSLATION
# LABEL/ID_CLEAN_WEBENTRIES_DESC
#: LABEL/ID_CLEAN_WEBENTRIES_DESC
msgid "Clean web-entries"
msgstr "Clean web-entries"
# TRANSLATION # TRANSLATION
# LABEL/ID_TIMER_EVENT_DESC # LABEL/ID_TIMER_EVENT_DESC
#: LABEL/ID_TIMER_EVENT_DESC #: LABEL/ID_TIMER_EVENT_DESC
@@ -51939,6 +51963,18 @@ msgstr "Reporting"
msgid "Every hour" msgid "Every hour"
msgstr "Every hour" msgstr "Every hour"
# TRANSLATION
# LABEL/ID_ONCE_PER_DAY
#: LABEL/ID_ONCE_PER_DAY
msgid "Once per day"
msgstr "Once per day"
# TRANSLATION
# LABEL/ID_TWICE_PER_DAY
#: LABEL/ID_TWICE_PER_DAY
msgid "Twice per day"
msgstr "Twice per day"
# TRANSLATION # TRANSLATION
# LABEL/ID_TASK_SCHEDULER_REPORT_USERS # LABEL/ID_TASK_SCHEDULER_REPORT_USERS
#: LABEL/ID_TASK_SCHEDULER_REPORT_USERS #: LABEL/ID_TASK_SCHEDULER_REPORT_USERS

View File

@@ -1,5 +1,7 @@
<?php <?php
use ProcessMaker\Model\ProcessCategory as ModelCategories;
class ProcessProxy extends HttpProxyController class ProcessProxy extends HttpProxyController
{ {
@@ -9,15 +11,29 @@ class ProcessProxy extends HttpProxyController
$RBAC->allows(basename(__FILE__), $name); $RBAC->allows(basename(__FILE__), $name);
parent::call($name); parent::call($name);
} }
/**
* get Process Categories List with defailt value (empty option) and -All- aoption
*/
public function categoriesList ()
{
$data = $this->getCategoriesList();
$defaultOption[] = Array ('CATEGORY_UID' => '<reset>','CATEGORY_NAME' => G::LoadTranslation( 'ID_ALL' ));
return array_merge( $defaultOption, $data ); /**
* Get Categories list with default values
*
* @link https://wiki.processmaker.com/3.2/Processes#Designer_Menu
*/
public function categoriesList()
{
$defaultOption = [];
// Add the option All categories
$defaultOption[] = [
'CATEGORY_UID' => '',
'CATEGORY_NAME' => G::LoadTranslation('ID_ALL')
];
// Add the option Without categories
$defaultOption[] = [
'CATEGORY_UID' => 'NONE',
'CATEGORY_NAME' => G::LoadTranslation('ID_PROCESS_NO_CATEGORY')
];
$listCategories = ModelCategories::getCategories();
return array_merge($defaultOption, $listCategories);
} }
/** /**

View File

@@ -57529,6 +57529,8 @@ INSERT INTO TRANSLATION (TRN_CATEGORY,TRN_ID,TRN_LANG,TRN_VALUE,TRN_UPDATE_DATE
( 'LABEL','ID_CLASS_ALREADY_EXISTS','en','Class already exists','2014-01-15') , ( 'LABEL','ID_CLASS_ALREADY_EXISTS','en','Class already exists','2014-01-15') ,
( 'LABEL','ID_CLASS_TABLE_DOESNT_EXIST','en','This Class Table doesn''t exist!','2014-01-15') , ( 'LABEL','ID_CLASS_TABLE_DOESNT_EXIST','en','This Class Table doesn''t exist!','2014-01-15') ,
( 'LABEL','ID_CLEAR','en','Clear','2014-01-15') , ( 'LABEL','ID_CLEAR','en','Clear','2014-01-15') ,
( 'LABEL','ID_CLEAN_WEBENTRIES','en','Clean web-entries','2020-11-10') ,
( 'LABEL','ID_CLEAN_WEBENTRIES_DESC','en','Clean web-entries','2020-11-10') ,
( 'LABEL','ID_CLEAR_CACHE','en','Clear Cache','2014-01-15') , ( 'LABEL','ID_CLEAR_CACHE','en','Clear Cache','2014-01-15') ,
( 'LABEL','ID_CLEAR_CACHE_CONFIRM1','en','Clear all cache files now?','2014-01-15') , ( 'LABEL','ID_CLEAR_CACHE_CONFIRM1','en','Clear all cache files now?','2014-01-15') ,
( 'LABEL','ID_CLEAR_CACHE_MSG1','en','All cache data was deleted','2014-01-15') , ( 'LABEL','ID_CLEAR_CACHE_MSG1','en','All cache data was deleted','2014-01-15') ,
@@ -58675,6 +58677,7 @@ INSERT INTO TRANSLATION (TRN_CATEGORY,TRN_ID,TRN_LANG,TRN_VALUE,TRN_UPDATE_DATE
( 'LABEL','ID_LOG_AGAIN','en','Please login again to apply the changes.','2014-01-15') , ( 'LABEL','ID_LOG_AGAIN','en','Please login again to apply the changes.','2014-01-15') ,
( 'LABEL','ID_LOG_CASE_SCHEDULER','en','Case Scheduler Log','2014-01-15') , ( 'LABEL','ID_LOG_CASE_SCHEDULER','en','Case Scheduler Log','2014-01-15') ,
( 'LABEL','ID_LOG_INFO','en','Log Information','2014-01-15') , ( 'LABEL','ID_LOG_INFO','en','Log Information','2014-01-15') ,
( 'LABEL','ID_MAFE_TRANSLATION_DIRECTORY','en','MAFE Translation Directory','2014-01-15') ,
( 'LABEL','ID_MAFE_0015b7e51c1ca4293041c429985ca323','en','The specified subform could not be found in the process.', NOW()) , ( 'LABEL','ID_MAFE_0015b7e51c1ca4293041c429985ca323','en','The specified subform could not be found in the process.', NOW()) ,
( 'LABEL','ID_MAFE_0025301679e9722c3abd5914cfbc7dd7','en','Database connection edited successfully', NOW()) , ( 'LABEL','ID_MAFE_0025301679e9722c3abd5914cfbc7dd7','en','Database connection edited successfully', NOW()) ,
( 'LABEL','ID_MAFE_004d33be4d12eb8c0ae00703e7c70f61','en','Pick Second', NOW()) , ( 'LABEL','ID_MAFE_004d33be4d12eb8c0ae00703e7c70f61','en','Pick Second', NOW()) ,
@@ -60266,6 +60269,7 @@ INSERT INTO TRANSLATION (TRN_CATEGORY,TRN_ID,TRN_LANG,TRN_VALUE,TRN_UPDATE_DATE
( 'LABEL','ID_OLD_VERSION','en','old version','2014-01-15') , ( 'LABEL','ID_OLD_VERSION','en','old version','2014-01-15') ,
( 'LABEL','ID_ON','en','On','2014-01-15') , ( 'LABEL','ID_ON','en','On','2014-01-15') ,
( 'LABEL','ID_ON_TIME','en','On Time','2014-01-15') , ( 'LABEL','ID_ON_TIME','en','On Time','2014-01-15') ,
( 'LABEL','ID_ONCE_PER_DAY','en','Once per day','2015-03-10') ,
( 'LABEL','ID_OPEN','en','Open','2014-01-15') , ( 'LABEL','ID_OPEN','en','Open','2014-01-15') ,
( 'LABEL','ID_OPENSSL_OPTIONAL','en','OpenSSL is optional.','2014-01-15') , ( 'LABEL','ID_OPENSSL_OPTIONAL','en','OpenSSL is optional.','2014-01-15') ,
( 'LABEL','ID_OPEN_CASE','en','Open Case','2014-01-15') , ( 'LABEL','ID_OPEN_CASE','en','Open Case','2014-01-15') ,
@@ -60576,6 +60580,7 @@ INSERT INTO TRANSLATION (TRN_CATEGORY,TRN_ID,TRN_LANG,TRN_VALUE,TRN_UPDATE_DATE
( 'LABEL','ID_PROCESS_NOCATEGORY','en','No Category','2014-01-15') , ( 'LABEL','ID_PROCESS_NOCATEGORY','en','No Category','2014-01-15') ,
( 'LABEL','ID_PROCESS_NOT_EXIST','en','The report table ''{0}'' is related to a process not present in the workspace, import the related process first. To relate the report table to other process, open the process in the designer and import from there. The report table can''t be imported.','2016-03-08') , ( 'LABEL','ID_PROCESS_NOT_EXIST','en','The report table ''{0}'' is related to a process not present in the workspace, import the related process first. To relate the report table to other process, open the process in the designer and import from there. The report table can''t be imported.','2016-03-08') ,
( 'LABEL','ID_PROCESS_NO_CATEGORY','en','No Category','2014-01-15') , ( 'LABEL','ID_PROCESS_NO_CATEGORY','en','No Category','2014-01-15') ,
( 'LABEL','ID_PROCESS_NONE_CATEGORY','en','- No Category -','2020-10-23') ,
( 'LABEL','ID_PROCESS_NO_EXIST','en','Process doesn''t exist!','2014-01-15') , ( 'LABEL','ID_PROCESS_NO_EXIST','en','Process doesn''t exist!','2014-01-15') ,
( 'LABEL','ID_PROCESS_PERMISSIONS','en','Process Permissions','2014-01-15') , ( 'LABEL','ID_PROCESS_PERMISSIONS','en','Process Permissions','2014-01-15') ,
( 'LABEL','ID_PROCESS_PERMISSIONS_CREATE','en','Process Permission created successfully','2014-01-15') , ( 'LABEL','ID_PROCESS_PERMISSIONS_CREATE','en','Process Permission created successfully','2014-01-15') ,
@@ -61287,6 +61292,7 @@ INSERT INTO TRANSLATION (TRN_CATEGORY,TRN_ID,TRN_LANG,TRN_VALUE,TRN_UPDATE_DATE
( 'LABEL','ID_TUE','en','Tue','2014-01-15') , ( 'LABEL','ID_TUE','en','Tue','2014-01-15') ,
( 'LABEL','ID_TYPE','en','Type','2014-01-15') , ( 'LABEL','ID_TYPE','en','Type','2014-01-15') ,
( 'LABEL','ID_TYPE_PROCESS','en','Process Type','2014-10-22') , ( 'LABEL','ID_TYPE_PROCESS','en','Process Type','2014-10-22') ,
( 'LABEL','ID_TWICE_PER_DAY','en','Twice per day','2014-10-22') ,
( 'LABEL','ID_UID','en','UID','2014-01-15') , ( 'LABEL','ID_UID','en','UID','2014-01-15') ,
( 'LABEL','ID_UNABLE_GET_DASHBOARDS','en','Unable to get Dashboards','2014-01-15') , ( 'LABEL','ID_UNABLE_GET_DASHBOARDS','en','Unable to get Dashboards','2014-01-15') ,
( 'LABEL','ID_UNABLE_START_CASE','en','Unable to start a case','2014-01-15') , ( 'LABEL','ID_UNABLE_START_CASE','en','Unable to start a case','2014-01-15') ,
@@ -61789,6 +61795,7 @@ INSERT INTO ADDONS_MANAGER (ADDON_DESCRIPTION,ADDON_ID,ADDON_NAME,ADDON_NICK,ADD
('User-based Time Zone Management.','userBasedTimeZone','userBasedTimeZone','userBasedTimeZone','Colosa','localRegistry','ready','','00000000000000000000000000010014','features','','','0'), ('User-based Time Zone Management.','userBasedTimeZone','userBasedTimeZone','userBasedTimeZone','Colosa','localRegistry','ready','','00000000000000000000000000010014','features','','','0'),
('SSO with an LDAP provider.','windowsSSO','windowsSSO','windowsSSO','Colosa','localRegistry','ready','','00000000000000000000000000010011','features','','','0'); ('SSO with an LDAP provider.','windowsSSO','windowsSSO','windowsSSO','Colosa','localRegistry','ready','','00000000000000000000000000010011','features','','','0');
INSERT INTO APP_SEQUENCE (ID) VALUES INSERT INTO APP_SEQUENCE (ID, APP_TYPE) VALUES
('0'); (0, 'NORMAL'),
(0, 'WEB_ENTRY');

View File

@@ -54,7 +54,7 @@ DROP TABLE IF EXISTS `APP_SEQUENCE`;
CREATE TABLE `APP_SEQUENCE` CREATE TABLE `APP_SEQUENCE`
( (
`ID` INTEGER NOT NULL, `ID` INTEGER NOT NULL,
PRIMARY KEY (`ID`) `APP_TYPE` VARCHAR(20) default 'NORMAL' NOT NULL
)ENGINE=InnoDB ; )ENGINE=InnoDB ;
#----------------------------------------------------------------------------- #-----------------------------------------------------------------------------
#-- APP_DELEGATION #-- APP_DELEGATION
@@ -2314,7 +2314,7 @@ CREATE TABLE `APP_TIMEOUT_ACTION_EXECUTED`
`APP_UID` VARCHAR(32) default '' NOT NULL, `APP_UID` VARCHAR(32) default '' NOT NULL,
`DEL_INDEX` INTEGER default 0 NOT NULL, `DEL_INDEX` INTEGER default 0 NOT NULL,
`EXECUTION_DATE` DATETIME, `EXECUTION_DATE` DATETIME,
PRIMARY KEY (`APP_UID`) PRIMARY KEY (`APP_UID`,`DEL_INDEX`)
)ENGINE=InnoDB ; )ENGINE=InnoDB ;
#----------------------------------------------------------------------------- #-----------------------------------------------------------------------------
#-- ADDONS_STORE #-- ADDONS_STORE

View File

@@ -6,6 +6,7 @@
* This page define some functions used in the start new case * This page define some functions used in the start new case
* *
* @link https://wiki.processmaker.com/3.1/Cases#New_Case * @link https://wiki.processmaker.com/3.1/Cases#New_Case
* @link https://wiki.processmaker.com/3.2/Web_Entry
*/ */
use ProcessMaker\Plugins\PluginRegistry; use ProcessMaker\Plugins\PluginRegistry;
@@ -179,61 +180,68 @@ function lookinginforContentProcess ($sproUid)
} }
function startCase () /**
* Start a case and get the next step
*/
function startCase()
{ {
$filter = new InputFilter(); $filter = new InputFilter();
$_POST = $filter->xssFilterHard($_POST); $_POST = $filter->xssFilterHard($_POST);
$_REQUEST = $filter->xssFilterHard($_REQUEST); $_REQUEST = $filter->xssFilterHard($_REQUEST);
/* GET , POST & $_SESSION Vars */ // Unset any variable, because we are starting a new case
/* unset any variable, because we are starting a new case */ if (isset($_SESSION['APPLICATION'])) {
if (isset( $_SESSION['APPLICATION'] )) { unset($_SESSION['APPLICATION']);
unset( $_SESSION['APPLICATION'] );
} }
if (isset( $_SESSION['PROCESS'] )) { if (isset($_SESSION['PROCESS'])) {
unset( $_SESSION['PROCESS'] ); unset($_SESSION['PROCESS']);
} }
if (isset( $_SESSION['TASK'] )) { if (isset($_SESSION['TASK'])) {
unset( $_SESSION['TASK'] ); unset($_SESSION['TASK']);
} }
if (isset( $_SESSION['INDEX'] )) { if (isset($_SESSION['INDEX'])) {
unset( $_SESSION['INDEX'] ); unset($_SESSION['INDEX']);
} }
if (isset( $_SESSION['STEP_POSITION'] )) { if (isset($_SESSION['STEP_POSITION'])) {
unset( $_SESSION['STEP_POSITION'] ); unset($_SESSION['STEP_POSITION']);
} }
/* Process */
try { try {
$oCase = new Cases(); // Initializing variables
$sequenceType = (!empty($_REQUEST['actionFrom']) && $_REQUEST['actionFrom'] === 'webEntry') ? AppSequence::APP_TYPE_WEB_ENTRY : AppSequence::APP_TYPE_NORMAL;
lookinginforContentProcess( $_POST['processId'] ); // Update CONTENT table
lookinginforContentProcess($_POST['processId']);
$aData = $oCase->startCase( $_REQUEST['taskId'], $_SESSION['USER_LOGGED'] ); // Create the new case
$aData = $filter->xssFilterHard($aData); $casesInstance = new Cases();
$newCase = $casesInstance->startCase($_REQUEST['taskId'], $_SESSION['USER_LOGGED'], false, [], false, $sequenceType);
$_SESSION['APPLICATION'] = $aData['APPLICATION']; // Set session variables
$_SESSION['INDEX'] = $aData['INDEX']; $_SESSION['APPLICATION'] = $newCase['APPLICATION'];
$_SESSION['PROCESS'] = $aData['PROCESS']; $_SESSION['INDEX'] = $newCase['INDEX'];
$_SESSION['PROCESS'] = $newCase['PROCESS'];
$_SESSION['TASK'] = $_REQUEST['taskId']; $_SESSION['TASK'] = $_REQUEST['taskId'];
$_SESSION['STEP_POSITION'] = 0; $_SESSION['STEP_POSITION'] = 0;
$_SESSION['CASES_REFRESH'] = true; $_SESSION['CASES_REFRESH'] = true;
$oCase = new Cases(); // Get the first step for the new case
$aNextStep = $oCase->getNextStep( $_SESSION['PROCESS'], $_SESSION['APPLICATION'], $_SESSION['INDEX'], $_SESSION['STEP_POSITION'] ); $casesInstance = new Cases();
$nextStep = $casesInstance->getNextStep($_SESSION['PROCESS'], $_SESSION['APPLICATION'], $_SESSION['INDEX'],
$_SESSION['STEP_POSITION']);
$nextStep['PAGE'] = 'open?APP_UID=' . $newCase['APPLICATION'] . '&DEL_INDEX=' . $newCase['INDEX'] . '&action=draft';
$_SESSION['BREAKSTEP']['NEXT_STEP'] = $nextStep;
$aNextStep['PAGE'] = 'open?APP_UID=' . $aData['APPLICATION'] . '&DEL_INDEX=' . $aData['INDEX'] . '&action=draft'; // Complete required information
$newCase['openCase'] = $nextStep;
$newCase['status'] = 'success';
$_SESSION['BREAKSTEP']['NEXT_STEP'] = $aNextStep; // Print JSON response
$aData['openCase'] = $aNextStep; print (G::json_encode($newCase));
$aData['status'] = 'success';
print (G::json_encode( $aData )) ;
} catch (Exception $e) { } catch (Exception $e) {
$aData['status'] = 'failure'; $newCase['status'] = 'failure';
$aData['message'] = $e->getMessage(); $newCase['message'] = $e->getMessage();
print_r( G::json_encode( $aData ) ); print_r(G::json_encode($newCase));
} }
} }

View File

@@ -1061,6 +1061,9 @@ try {
$tplFile = 'webentry/cases_ScreenDerivation'; $tplFile = 'webentry/cases_ScreenDerivation';
$caseId = $currentTask['APP_UID']; $caseId = $currentTask['APP_UID'];
$delIndex = $currentTask['DEL_INDEX']; $delIndex = $currentTask['DEL_INDEX'];
// Swap temporary APP_NUMBER
$newAppNumber = $bmWebEntry->swapTemporaryAppNumber($caseId);
$Fields['APP_NUMBER'] = $Fields['APP_DATA']['APP_NUMBER'] = $newAppNumber;
$derivationResponse = PMFDerivateCase($caseId, $delIndex, true); $derivationResponse = PMFDerivateCase($caseId, $delIndex, true);
if ($derivationResponse) { if ($derivationResponse) {
$webEntryUrl = $bmWebEntry->getCallbackUrlByTask($currentTask['TAS_UID']); $webEntryUrl = $bmWebEntry->getCallbackUrlByTask($currentTask['TAS_UID']);

View File

@@ -1,63 +1,63 @@
<?php <?php
/**
* processesList.php
*
* Get an overview information about the all the processes
*
* @link https://wiki.processmaker.com/3.2/Processes
*/
use ProcessMaker\Model\Process;
use ProcessMaker\Util\DateTime;
require_once 'classes/model/Process.php'; require_once 'classes/model/Process.php';
$start = isset($_POST['start']) ? $_POST['start'] : 0; $start = isset($_POST['start']) ? $_POST['start'] : 0;
$limit = isset($_POST['limit']) ? $_POST['limit'] : ''; $limit = isset($_POST['limit']) ? $_POST['limit'] : 25;
$dir = isset($_POST['dir']) ? $_POST['dir'] : 'ASC'; $dir = isset($_POST['dir']) ? $_POST['dir'] : 'ASC';
$sort = isset($_POST['sort']) ? $_POST['sort'] : ''; $sort = isset($_POST['sort']) ? $_POST['sort'] : 'PRO_CREATE_DATE';
switch ($sort) {
$oProcess = new Process(); case 'PRO_DEBUG_LABEL':
$oProcess->dir = $dir; $sort = 'PRO_DEBUG';
$oProcess->sort = $sort; break;
case 'PRO_CREATE_USER_LABEL':
$memkey = 'no memcache'; $sort = 'USR_UID';
$memcacheUsed = 'not used'; break;
$totalCount = 0; case 'PRO_STATUS_LABEL':
if (isset($_POST['category']) && $_POST['category'] !== '<reset>') { $sort = 'PRO_STATUS';
if (isset($_POST['processName'])) { break;
$proData = $oProcess->getAllProcesses($start, $limit, $_POST['category'], $_POST['processName'], true, false, $_SESSION["USER_LOGGED"]); case 'PROJECT_TYPE':
} else { $sort = 'PRO_TYPE';
$proData = $oProcess->getAllProcesses($start, $limit, $_POST['category'], null, true, false, $_SESSION["USER_LOGGED"]); break;
} case 'PRO_CATEGORY_LABEL':
} else { $sort = 'PRO_CATEGORY';
if (isset($_POST['processName'])) { break;
$memkey = 'processList-' . $start . '-' . $limit . '-' . $_POST['processName']; default:
$memcacheUsed = 'yes'; // keep the sort value
$proData = $memcache->get($memkey);
if ($proData === false) {
$proData = $oProcess->getAllProcesses($start, $limit, null, $_POST['processName'], true, false, $_SESSION["USER_LOGGED"]);
$memcache->set($memkey, $proData, PMmemcached::ONE_HOUR);
$totalCount = count($proData);
$proData = array_splice($proData, $start, $limit);
$memcacheUsed = 'no';
} else {
$proData = $oProcess->orderMemcache($proData, $start, $limit);
$totalCount = $proData->totalCount;
$proData = $proData->dataMemcache;
}
} else {
$memkey = 'processList-allProcesses-' . $start . '-' . $limit;
$memkeyTotal = $memkey . '-total';
$memcacheUsed = 'yes';
if (($proData = $memcache->get($memkey)) === false || ($totalCount = $memcache->get($memkeyTotal)) === false) {
$proData = $oProcess->getAllProcesses($start, $limit, null, null, true, false, $_SESSION["USER_LOGGED"]);
$totalCount = count($proData);
$proData = array_splice($proData, $start, $limit);
$memcache->set($memkey, $proData, PMmemcached::ONE_HOUR);
$memcache->set($memkeyTotal, $totalCount, PMmemcached::ONE_HOUR);
$memcacheUsed = 'no';
} else {
$proData = $oProcess->orderMemcache($proData, $start, $limit);
$totalCount = $proData->totalCount;
$proData = $proData->dataMemcache;
}
}
} }
$r = new stdclass(); $totalCount = 0;
$r->memkey = htmlspecialchars($memkey);
$r->memcache = $memcacheUsed; // Get the category uid to search
$r->data = \ProcessMaker\Util\DateTime::convertUtcToTimeZone($proData); $catUid = !empty($_POST['category']) ? $_POST['category'] : null;
$r->totalCount = $totalCount;
// Get the process name to search
$process = !empty($_POST['processName']) ? $_POST['processName'] : null;
$usrUid = $_SESSION["USER_LOGGED"];
$proData = Process::getProcessesFilter(
$catUid,
null,
$process,
$usrUid,
$start,
$limit,
$dir,
$sort
);
$response = new stdclass();
$response->data = DateTime::convertUtcToTimeZone($proData);
$response->totalCount = Process::getCounter($usrUid);
echo G::json_encode($response);
echo G::json_encode($r);

View File

@@ -1,6 +1,6 @@
<?php <?php
use ProcessMaker\AuditLog\AuditLog; use ProcessMaker\Log\AuditLog;
global $RBAC; global $RBAC;

View File

@@ -1,6 +1,6 @@
<?php <?php
use ProcessMaker\AuditLog\AuditLog; use ProcessMaker\Log\AuditLog;
$auditLog = new AuditLog(); $auditLog = new AuditLog();
$auditLog->setUserLogged($_SESSION["USER_LOGGED"]); $auditLog->setUserLogged($_SESSION["USER_LOGGED"]);

View File

@@ -117,8 +117,8 @@ try {
echo $response; echo $response;
break; break;
case 'deleteUser': case 'deleteUser':
Process::convertPrivateProcessesToPublic(json_decode($_POST['private_processes']));
$usrUid = $_POST['USR_UID']; $usrUid = $_POST['USR_UID'];
Process::convertPrivateProcessesToPublicAndUpdateUser(json_decode($_POST['private_processes']), $usrUid);
//Check if the user was defined in a process permissions //Check if the user was defined in a process permissions
$oObjectPermission = new ObjectPermission(); $oObjectPermission = new ObjectPermission();
$aProcess = $oObjectPermission->objectPermissionPerUser($usrUid, 1); $aProcess = $oObjectPermission->objectPermissionPerUser($usrUid, 1);

View File

@@ -355,7 +355,8 @@ $webEntryModel = \WebEntryPeer::retrieveByPK($weUid);
data: { data: {
action: 'startCase', action: 'startCase',
processId: processUid, processId: processUid,
taskId: tasUid taskId: tasUid,
actionFrom: 'webEntry'
}, },
success: function (data) { success: function (data) {
data.TAS_UID = tasUid; data.TAS_UID = tasUid;

View File

@@ -59,7 +59,7 @@ class ResponseReader
try { try {
if (!extension_loaded('imap')) { if (!extension_loaded('imap')) {
G::outRes(G::LoadTranslation("ID_EXCEPTION_LOG_INTERFAZ", ['php_imap']) . "\n"); G::outRes(G::LoadTranslation("ID_EXCEPTION_LOG_INTERFAZ", ['php_imap']) . "\n");
exit; return;
} }
if (PMLicensedFeatures if (PMLicensedFeatures
::getSingleton() ::getSingleton()
@@ -145,6 +145,7 @@ class ResponseReader
$emailSetup['MESS_ACCOUNT'], $emailSetup['MESS_ACCOUNT'],
$this->decryptPassword($emailSetup) $this->decryptPassword($emailSetup)
); );
Log::channel(':' . $this->channel)->debug("Open mailbox", Bootstrap::context($emailSetup));
// Read all messages into an array // Read all messages into an array
$mailsIds = $mailbox->searchMailbox('UNSEEN'); $mailsIds = $mailbox->searchMailbox('UNSEEN');
@@ -153,6 +154,7 @@ class ResponseReader
foreach ($mailsIds as $key => $mailId) { foreach ($mailsIds as $key => $mailId) {
/** @var IncomingMail $mail */ /** @var IncomingMail $mail */
$mail = $mailbox->getMail($mailId, false); $mail = $mailbox->getMail($mailId, false);
Log::channel(':' . $this->channel)->debug("Get mail", Bootstrap::context(['mailId' => $mailId]));
if (!empty($mail->textPlain)) { if (!empty($mail->textPlain)) {
preg_match("/{(.*)}/", $mail->textPlain, $matches); preg_match("/{(.*)}/", $mail->textPlain, $matches);
if ($matches) { if ($matches) {

View File

@@ -17,6 +17,7 @@ use Applications;
use AppNotes; use AppNotes;
use AppNotesPeer; use AppNotesPeer;
use AppSolr; use AppSolr;
use AppTimeoutActionExecuted;
use BasePeer; use BasePeer;
use Bootstrap; use Bootstrap;
use BpmnEngineServicesSearchIndex; use BpmnEngineServicesSearchIndex;
@@ -25,12 +26,14 @@ use CasesPeer;
use Configurations; use Configurations;
use CreoleTypes; use CreoleTypes;
use Criteria; use Criteria;
use DateTime;
use DBAdapter; use DBAdapter;
use EntitySolrRequestData; use EntitySolrRequestData;
use Exception; use Exception;
use G; use G;
use Groups; use Groups;
use GroupUserPeer; use GroupUserPeer;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Log;
use InputDocument; use InputDocument;
use InvalidIndexSearchTextException; use InvalidIndexSearchTextException;
@@ -44,8 +47,11 @@ use ProcessMaker\Exception\UploadException;
use ProcessMaker\Exception\CaseNoteUploadFile; use ProcessMaker\Exception\CaseNoteUploadFile;
use ProcessMaker\Model\Application as ModelApplication; use ProcessMaker\Model\Application as ModelApplication;
use ProcessMaker\Model\AppNotes as Notes; use ProcessMaker\Model\AppNotes as Notes;
use ProcessMaker\Model\AppTimeoutAction;
use ProcessMaker\Model\Delegation; use ProcessMaker\Model\Delegation;
use ProcessMaker\Model\Documents; use ProcessMaker\Model\Documents;
use ProcessMaker\Model\ListUnassigned;
use ProcessMaker\Model\Triggers;
use ProcessMaker\Plugins\PluginRegistry; use ProcessMaker\Plugins\PluginRegistry;
use ProcessMaker\Services\OAuth2\Server; use ProcessMaker\Services\OAuth2\Server;
use ProcessMaker\Util\DateTime as UtilDateTime; use ProcessMaker\Util\DateTime as UtilDateTime;
@@ -4107,4 +4113,171 @@ class Cases
return true; return true;
} }
/**
* Get the cases related to the self services timeout that needs to execute the trigger related
*
* @return array
* @throws Exception
*/
public static function executeSelfServiceTimeout()
{
try {
$casesSelfService = ListUnassigned::selfServiceTimeout();
$casesExecuted = [];
foreach ($casesSelfService as $row) {
$appUid = $row["APP_UID"];
$appNumber = $row["APP_NUMBER"];
$delIndex = $row["DEL_INDEX"];
$delegateDate = $row["DEL_DELEGATE_DATE"];
$proUid = $row["PRO_UID"];
$taskUid = $row["TAS_UID"];
$taskSelfServiceTime = intval($row["TAS_SELFSERVICE_TIME"]);
$taskSelfServiceTimeUnit = $row["TAS_SELFSERVICE_TIME_UNIT"];
$triggerUid = $row["TAS_SELFSERVICE_TRIGGER_UID"];
/*----------------------------------********---------------------------------*/
$typeOfExecution = $row["TAS_SELFSERVICE_EXECUTION"];
$flagExecuteOnce = true;
// This option will be executed just once, can check if was executed before
if ($typeOfExecution == 'ONCE') {
$appTimeout = new AppTimeoutAction();
$appTimeout->setCaseUid($appUid);
$appTimeout->setIndex($delIndex);
$caseExecuted = $appTimeout->cases();
$flagExecuteOnce = !empty($caseExecuted) ? false : true;
}
/*----------------------------------********---------------------------------*/
// Add the time in the corresponding unit to the delegation date
$delegateDate = calculateDate($delegateDate, $taskSelfServiceTimeUnit, $taskSelfServiceTime);
// Define the current time
$datetime = new DateTime('now');
$currentDate = $datetime->format('Y-m-d H:i:s');
// Check if the triggers to be executed
if ($currentDate >= $delegateDate && $flagExecuteOnce) {
// Review if the session process is defined
$sessProcess = null;
$sessProcessSw = false;
if (isset($_SESSION["PROCESS"])) {
$sessProcess = $_SESSION["PROCESS"];
$sessProcessSw = true;
}
// Load case data
$case = new ClassesCases();
$appFields = $case->loadCase($appUid);
$appFields["APP_DATA"]["APPLICATION"] = $appUid;
// Set the process defined in the case related
$_SESSION["PROCESS"] = $appFields["PRO_UID"];
// Get the trigger related and execute
$triggersList = [];
if (!empty($triggerUid)) {
$trigger = new Triggers();
$trigger->setTrigger($triggerUid);
$triggersList = $trigger->triggers();
}
// If the trigger exist, let's to execute
if (!empty($triggersList)) {
// Execute the trigger defined in the self service timeout
$fieldsCase['APP_DATA'] = $case->executeTriggerFromList(
$triggersList,
$appFields['APP_DATA'],
'SELF_SERVICE_TIMEOUT',
'',
'',
'',
false
);
// Update the case
$case->updateCase($appUid, $fieldsCase);
/*----------------------------------********---------------------------------*/
if ($typeOfExecution == 'ONCE') {
// Saving the case`s data if the 'Execution' is set in ONCE.
$appTimeoutActionExecuted = new AppTimeoutActionExecuted();
$dataSelf = [];
$dataSelf["APP_UID"] = $appUid;
$dataSelf["DEL_INDEX"] = $delIndex;
$dataSelf["EXECUTION_DATE"] = time();
$appTimeoutActionExecuted->create($dataSelf);
}
/*----------------------------------********---------------------------------*/
array_push($casesExecuted, $appNumber); // Register the cases executed
// Logging this action
$context = [
'appUid' => $appUid,
'appNumber' => $appNumber,
'triUid' => $triggerUid,
'proUid' => $proUid,
'tasUid' => $taskUid,
'selfServiceTime' => $taskSelfServiceTime,
'selfServiceTimeUnit' => $taskSelfServiceTimeUnit,
];
Log::channel(':TriggerExecution')->info('Timeout trigger execution', Bootstrap::context($context));
}
unset($_SESSION["PROCESS"]);
if ($sessProcessSw) {
$_SESSION["PROCESS"] = $sessProcess;
}
}
}
return $casesExecuted;
} catch (Exception $e) {
throw $e;
}
}
/**
* Get DynaForms Uids assigned as steps in the related process by application Uid
*
* @param string $appUid
* @param int $sourceTask
* @param string $dynUid
* @param string $caseStatus
* @return array
*/
public static function dynaFormsByApplication($appUid, $sourceTask = 0, $dynUid = '', $caseStatus = '')
{
// Select distinct DYN_UID
$query = ModelApplication::query()->select('STEP.STEP_UID_OBJ AS DYN_UID')->distinct();
// Join with STEP table
$query->join('STEP', function ($join) {
$join->on('APPLICATION.PRO_UID', '=', 'STEP.PRO_UID');
$join->on('STEP.STEP_TYPE_OBJ', '=', DB::raw("'DYNAFORM'"));
});
// Filter by application Uid
$query->where('APPLICATION.APP_UID', '=', $appUid);
// Filter by source task
if ($caseStatus != 'COMPLETED' && $sourceTask != '' && (int)$sourceTask != 0) {
$query->where('STEP.TAS_UID', '=', $sourceTask);
}
// Filter by DynaForm Uid
if ($dynUid != '' && $dynUid != '0') {
$query->where('STEP.STEP_UID_OBJ', '=', $dynUid);
}
// Get results
$dynaForms = [];
$items = $query->get();
$items->each(function ($item) use (&$dynaForms) {
$dynaForms[] = $item->DYN_UID;
});
// Return results
return $dynaForms;
}
} }

View File

@@ -42,84 +42,94 @@ class FilesManager
/** /**
* Return the Process Files Manager Path * Return the Process Files Manager Path
* *
* @param string $sProcessUID {@min 32} {@max 32} * @param string $processUid
* @param string $path * @param string $path
* @param boolean $getContent
* *
* return array * @return array
* @throws Exception
* *
* @access public * @access public
*/ */
public function getProcessFilesManagerPath($sProcessUID, $path, $getContent = true) public function getProcessFilesManagerPath($processUid, $path, $getContent = true)
{ {
try { try {
$checkPath = substr($path, -1); $checkPath = substr($path, -1);
if ($checkPath == '/') { if ($checkPath == '/') {
$path = substr($path, 0, -1); $path = substr($path, 0, -1);
} }
$sMainDirectory = current(explode("/", $path)); $mainDirectory = current(explode('/', $path));
if (strstr($path,'/')) { if (strstr($path,'/')) {
$sSubDirectory = substr($path, strpos($path, "/")+1). PATH_SEP ; $subDirectory = substr($path, strpos($path, '/') + 1) . PATH_SEP;
} else { } else {
$sSubDirectory = ''; $subDirectory = '';
} }
switch ($sMainDirectory) { switch ($mainDirectory) {
case 'templates': case 'templates':
$sDirectory = PATH_DATA_MAILTEMPLATES . $sProcessUID . PATH_SEP . $sSubDirectory; $currentDirectory = PATH_DATA_MAILTEMPLATES . $processUid . PATH_SEP . $subDirectory;
break; break;
case 'public': case 'public':
$sDirectory = PATH_DATA_PUBLIC . $sProcessUID . PATH_SEP . $sSubDirectory; $currentDirectory = PATH_DATA_PUBLIC . $processUid . PATH_SEP . $subDirectory;
break; break;
default: default:
throw new \Exception(\G::LoadTranslation("ID_INVALID_VALUE_FOR", array('path'))); throw new Exception(G::LoadTranslation('ID_INVALID_VALUE_FOR', ['path']));
break; break;
} }
\G::verifyPath($sDirectory, true); G::verifyPath($currentDirectory, true);
$aTheFiles = array(); $filesToList = [];
$aFiles = array(); $files = [];
$oDirectory = dir($sDirectory); $directory = dir($currentDirectory);
while ($sObject = $oDirectory->read()) { while ($object = $directory->read()) {
if (($sObject !== '.') && ($sObject !== '..')) { if (($object !== '.') && ($object !== '..')) {
$sPath = $sDirectory . $sObject; // Skip files related to web entries
if (is_dir($sPath)) { if ($object === 'wsClient.php' || WebEntry::isWebEntry($processUid, $object)) {
$aTheFiles[] = array('prf_name' => $sObject, continue;
'prf_type' => "folder", }
'prf_path' => $sMainDirectory); $path = $currentDirectory . $object;
if (is_dir($path)) {
$filesToList[] = [
'prf_name' => $object,
'prf_type' => 'folder',
'prf_path' => $mainDirectory
];
} else { } else {
$aAux = pathinfo($sPath); $aux = pathinfo($path);
$aAux['extension'] = (isset($aAux['extension'])?$aAux['extension']:''); $aux['extension'] = (isset($aux['extension']) ? $aux['extension'] : '');
$aFiles[] = array('FILE' => $sObject, 'EXT' => $aAux['extension'] ); $files[] = ['FILE' => $object, 'EXT' => $aux['extension']];
} }
} }
} }
foreach ($aFiles as $aFile) { foreach ($files as $file) {
$arrayFileUid = $this->getFileManagerUid($sDirectory.$aFile['FILE'], $aFile['FILE']); $arrayFileUid = $this->getFileManagerUid($currentDirectory.$file['FILE'], $file['FILE']);
$fcontent = ""; $content = '';
if ($getContent === true) { if ($getContent === true) {
$fcontent = file_get_contents($sDirectory . $aFile['FILE']); $content = file_get_contents($currentDirectory . $file['FILE']);
} }
$fileUid = isset($arrayFileUid["PRF_UID"]) ? $arrayFileUid["PRF_UID"] : ''; $fileUid = isset($arrayFileUid['PRF_UID']) ? $arrayFileUid['PRF_UID'] : '';
$derivationScreen = isset($arrayFileUid["DERIVATION_SCREEN_TPL"]) ? true : false; $derivationScreen = isset($arrayFileUid['DERIVATION_SCREEN_TPL']) ? true : false;
if ($fileUid != null) { if ($fileUid != null) {
$oProcessFiles = \ProcessFilesPeer::retrieveByPK($fileUid); $processFiles = ProcessFilesPeer::retrieveByPK($fileUid);
$editable = $oProcessFiles->getPrfEditable(); $editable = $processFiles->getPrfEditable();
if ($editable == '1') { if ($editable == '1') {
$editable = 'true'; $editable = 'true';
} else { } else {
$editable = 'false'; $editable = 'false';
} }
$aTheFiles[] = array( 'prf_uid' => $oProcessFiles->getPrfUid(), $filesToList[] = [
'prf_filename' => $aFile['FILE'], 'prf_uid' => $processFiles->getPrfUid(),
'usr_uid' => $oProcessFiles->getUsrUid(), 'prf_filename' => $file['FILE'],
'prf_update_usr_uid' => $oProcessFiles->getPrfUpdateUsrUid(), 'usr_uid' => $processFiles->getUsrUid(),
'prf_path' => $sMainDirectory. PATH_SEP .$sSubDirectory, 'prf_update_usr_uid' => $processFiles->getPrfUpdateUsrUid(),
'prf_type' => $oProcessFiles->getPrfType(), 'prf_path' => $mainDirectory. PATH_SEP .$subDirectory,
'prf_type' => $processFiles->getPrfType(),
'prf_editable' => $editable, 'prf_editable' => $editable,
'prf_create_date' => $oProcessFiles->getPrfCreateDate(), 'prf_create_date' => $processFiles->getPrfCreateDate(),
'prf_update_date' => $oProcessFiles->getPrfUpdateDate(), 'prf_update_date' => $processFiles->getPrfUpdateDate(),
'prf_content' => $fcontent, 'prf_content' => $content,
'prf_derivation_screen' => $derivationScreen); 'prf_derivation_screen' => $derivationScreen
];
} else { } else {
$explodeExt = explode(".", $aFile['FILE']); $explodeExt = explode('.', $file['FILE']);
$extension = end($explodeExt); $extension = end($explodeExt);
if ($extension == 'docx' || $extension == 'doc' || $extension == 'html' || $extension == 'php' || $extension == 'jsp' if ($extension == 'docx' || $extension == 'doc' || $extension == 'html' || $extension == 'php' || $extension == 'jsp'
|| $extension == 'xlsx' || $extension == 'xls' || $extension == 'js' || $extension == 'css' || $extension == 'txt') { || $extension == 'xlsx' || $extension == 'xls' || $extension == 'js' || $extension == 'css' || $extension == 'txt') {
@@ -127,21 +137,23 @@ class FilesManager
} else { } else {
$editable = 'false'; $editable = 'false';
} }
$aTheFiles[] = array('prf_uid' => '', $filesToList[] = [
'prf_filename' => $aFile['FILE'], 'prf_uid' => '',
'prf_filename' => $file['FILE'],
'usr_uid' => '', 'usr_uid' => '',
'prf_update_usr_uid' => '', 'prf_update_usr_uid' => '',
'prf_path' => $sMainDirectory. PATH_SEP .$sSubDirectory, 'prf_path' => $mainDirectory. PATH_SEP .$subDirectory,
'prf_type' => 'file', 'prf_type' => 'file',
'prf_editable' => $editable, 'prf_editable' => $editable,
'prf_create_date' => '', 'prf_create_date' => '',
'prf_update_date' => '', 'prf_update_date' => '',
'prf_content' => $fcontent, 'prf_content' => $content,
'prf_derivation_screen' => false); 'prf_derivation_screen' => false
];
} }
} }
return $aTheFiles; return $filesToList;
} catch (\Exception $e) { } catch (Exception $e) {
throw $e; throw $e;
} }
} }

View File

@@ -6,6 +6,7 @@ use G;
use Criteria; use Criteria;
use PMLicensedFeatures; use PMLicensedFeatures;
use ProcessMaker\Model\Delegation; use ProcessMaker\Model\Delegation;
use ProcessMaker\Model\User;
use UsersPeer; use UsersPeer;
/** /**
@@ -213,30 +214,51 @@ class Lists
$result = $list->loadList($userUid, $filters); $result = $list->loadList($userUid, $filters);
if (!empty($result)) { if (!empty($result)) {
foreach ($result as &$value) { foreach ($result as &$value) {
// For backward compatibility with "light" endpoints, we need to cast to string
$value['APP_NUMBER'] = (string)$value['APP_NUMBER'];
$value['DEL_INDEX'] = (string)$value['DEL_INDEX'];
if (isset($value['DEL_PREVIOUS_USR_UID'])) { if (isset($value['DEL_PREVIOUS_USR_UID'])) {
$value['PREVIOUS_USR_UID'] = $value['DEL_PREVIOUS_USR_UID']; $value['PREVIOUS_USR_UID'] = $value['DEL_PREVIOUS_USR_UID'];
$value['PREVIOUS_USR_USERNAME'] = $value['DEL_PREVIOUS_USR_USERNAME']; $value['PREVIOUS_USR_USERNAME'] = $value['DEL_PREVIOUS_USR_USERNAME'];
$value['PREVIOUS_USR_FIRSTNAME'] = $value['DEL_PREVIOUS_USR_FIRSTNAME']; $value['PREVIOUS_USR_FIRSTNAME'] = $value['DEL_PREVIOUS_USR_FIRSTNAME'];
$value['PREVIOUS_USR_LASTNAME'] = $value['DEL_PREVIOUS_USR_LASTNAME']; $value['PREVIOUS_USR_LASTNAME'] = $value['DEL_PREVIOUS_USR_LASTNAME'];
} elseif (!empty($value["USR_ID"])) {
$user = User::where("USR_ID", $value["USR_ID"])->first();
$value["PREVIOUS_USR_UID"] = $value["DEL_PREVIOUS_USR_UID"] = $user->USR_UID;
$value["PREVIOUS_USR_USERNAME"] = $value["DEL_PREVIOUS_USR_USERNAME"] = $user->USR_USERNAME;
$value["PREVIOUS_USR_FIRSTNAME"] = $value["DEL_PREVIOUS_USR_FIRSTNAME"] = $user->USR_FIRSTNAME;
$value["PREVIOUS_USR_LASTNAME"] = $value["DEL_PREVIOUS_USR_LASTNAME"] = $user->USR_LASTNAME;
} }
if (isset($value['DEL_DUE_DATE'])) { if (isset($value['DEL_DUE_DATE'])) {
$value['DEL_TASK_DUE_DATE'] = $value['DEL_DUE_DATE']; $value['DEL_TASK_DUE_DATE'] = $value['DEL_DUE_DATE'];
} }
if (isset($value['APP_PAUSED_DATE'])) { if (isset($value['APP_PAUSED_DATE'])) {
$value['APP_UPDATE_DATE'] = $value['APP_PAUSED_DATE']; $value['APP_UPDATE_DATE'] = $value['APP_PAUSED_DATE'];
} }
if (isset($value['DEL_CURRENT_USR_USERNAME'])) { if (isset($value['DEL_CURRENT_USR_USERNAME'])) {
$value['USR_USERNAME'] = $value['DEL_CURRENT_USR_USERNAME']; $value['USR_USERNAME'] = $value['DEL_CURRENT_USR_USERNAME'];
$value['USR_FIRSTNAME'] = $value['DEL_CURRENT_USR_FIRSTNAME']; $value['USR_FIRSTNAME'] = $value['DEL_CURRENT_USR_FIRSTNAME'];
$value['USR_LASTNAME'] = $value['DEL_CURRENT_USR_LASTNAME']; $value['USR_LASTNAME'] = $value['DEL_CURRENT_USR_LASTNAME'];
$value['APP_UPDATE_DATE'] = $value['DEL_DELEGATE_DATE']; $value['APP_UPDATE_DATE'] = $value['DEL_DELEGATE_DATE'];
} }
if (isset($value['DEL_CURRENT_TAS_TITLE']) && $value['DEL_CURRENT_TAS_TITLE'] != '') {
$value['APP_TAS_TITLE'] = $value['DEL_CURRENT_TAS_TITLE'];
} elseif (!empty($value["TAS_TITLE"]) && empty($value["APP_TAS_TITLE"])) {
$value["APP_TAS_TITLE"] = $value["TAS_TITLE"];
}
if (isset($value['APP_STATUS'])) { if (isset($value['APP_STATUS'])) {
$value['APP_STATUS_LABEL'] = G::LoadTranslation("ID_{$value['APP_STATUS']}"); $value['APP_STATUS_LABEL'] = G::LoadTranslation("ID_{$value['APP_STATUS']}");
} }
if (!empty($value["PRO_TITLE"]) && empty($value["APP_PRO_TITLE"])) {
//$value = array_change_key_case($value, CASE_LOWER); $value["APP_PRO_TITLE"] = $value["PRO_TITLE"];
}
} }
} }
$response = array(); $response = array();

View File

@@ -30,12 +30,12 @@ class TaskSchedulerBM
"category" => "case_actions", "category" => "case_actions",
"file" => "workflow/engine/bin/cron.php", "file" => "workflow/engine/bin/cron.php",
"filew" => "workflow\\engine\bin\cron.php", "filew" => "workflow\\engine\bin\cron.php",
"startingTime" => "0:00", "startingTime" => null,
"endingTime" => "0:30", "endingTime" => null,
"timezone" => "default", "timezone" => "default",
"everyOn" => "1", "everyOn" => "1",
"interval" => "week", "interval" => "week",
"expression" => "0 */1 * * 0,1,2,3,4,5,6", "expression" => "0 0 * * 0,1,2,3,4,5,6",
"description" => 'ID_TASK_SCHEDULER_CALCULATE_ELAPSED_DESC' "description" => 'ID_TASK_SCHEDULER_CALCULATE_ELAPSED_DESC'
], ],
[ [
@@ -60,12 +60,12 @@ class TaskSchedulerBM
"category" => "case_actions", "category" => "case_actions",
"file" => "workflow/engine/bin/cron.php", "file" => "workflow/engine/bin/cron.php",
"filew" => "workflow\\engine\bin\cron.php", "filew" => "workflow\\engine\bin\cron.php",
"startingTime" => "0:00", "startingTime" => null,
"endingTime" => "0:30", "endingTime" => null,
"timezone" => "default", "timezone" => "default",
"everyOn" => "1", "everyOn" => "1",
"interval" => "week", "interval" => "week",
"expression" => "0 */1 * * 0,1,2,3,4,5,6", "expression" => "0 0 * * 0,1,2,3,4,5,6",
"description" => 'ID_TASK_SCHEDULER_CLEAN_SELF_DESC' "description" => 'ID_TASK_SCHEDULER_CLEAN_SELF_DESC'
], ],
[ [
@@ -83,6 +83,21 @@ class TaskSchedulerBM
"expression" => "*/1 * * * 0,1,2,3,4,5,6", "expression" => "*/1 * * * 0,1,2,3,4,5,6",
"description" => "ID_TIMER_EVENT_DESC" "description" => "ID_TIMER_EVENT_DESC"
], ],
[
"title" => "ID_CLEAN_WEBENTRIES",
"enable" => "0",
"service" => "",
"category" => "case_actions",
"file" => "workflow/engine/bin/webentriescron.php",
"filew" => "workflow\\engine\bin\\webentriescron.php",
"startingTime" => null,
"endingTime" => null,
"timezone" => null,
"everyOn" => "1",
"interval" => "week",
"expression" => "0 20 * * 5",
"description" => "ID_CLEAN_WEBENTRIES_DESC"
],
[ [
"title" => "ID_TASK_SCHEDULER_CASE_EMAILS", "title" => "ID_TASK_SCHEDULER_CASE_EMAILS",
"enable" => "1", "enable" => "1",
@@ -183,12 +198,12 @@ class TaskSchedulerBM
"category" => "processmaker_sync", "category" => "processmaker_sync",
"file" => "workflow/engine/bin/ldapcron.php", "file" => "workflow/engine/bin/ldapcron.php",
"filew" => "workflow\\engine\bin\ldapcron.php", "filew" => "workflow\\engine\bin\ldapcron.php",
"startingTime" => "0:00", "startingTime" => null,
"endingTime" => "0:30", "endingTime" => null,
"timezone" => "default", "timezone" => "default",
"everyOn" => "1", "everyOn" => "1",
"interval" => "week", "interval" => "week",
"expression" => "0 */1 * * 0,1,2,3,4,5,6", "expression" => "0 0 * * 0,1,2,3,4,5,6",
"description" => "ID_TASK_SCHEDULER_LDAP" "description" => "ID_TASK_SCHEDULER_LDAP"
], ],
[ [
@@ -198,12 +213,12 @@ class TaskSchedulerBM
"category" => "plugins", "category" => "plugins",
"file" => "workflow/engine/bin/cron.php", "file" => "workflow/engine/bin/cron.php",
"filew" => "workflow\\engine\bin\cron.php", "filew" => "workflow\\engine\bin\cron.php",
"startingTime" => "0:00", "startingTime" => null,
"endingTime" => "0:30", "endingTime" => null,
"timezone" => "default", "timezone" => "default",
"everyOn" => "1", "everyOn" => "1",
"interval" => "week", "interval" => "week",
"expression" => "0 */1 * * 0,1,2,3,4,5,6", "expression" => "0 0 * * 0,1,2,3,4,5,6",
"description" => "ID_TASK_SCHEDULER_PM_PLUGINS_DESC" "description" => "ID_TASK_SCHEDULER_PM_PLUGINS_DESC"
] ]
/*----------------------------------********---------------------------------*/ /*----------------------------------********---------------------------------*/

View File

@@ -1,8 +1,12 @@
<?php <?php
namespace ProcessMaker\BusinessModel; namespace ProcessMaker\BusinessModel;
use AppSequence;
use Cases;
use Criteria; use Criteria;
use Illuminate\Support\Facades\DB;
use ProcessMaker\Core\System; use ProcessMaker\Core\System;
use ProcessMaker\Model\Application;
use ResultSet; use ResultSet;
use WebEntryPeer; use WebEntryPeer;
@@ -1125,5 +1129,92 @@ class WebEntry
} }
return $message; return $message;
} }
}
/**
* Swap temporary web entry application number to a normal application number
*
* @param string $appUid
* @return int
*/
public function swapTemporaryAppNumber($appUid)
{
// Get the application
$application = Application::query()->select(['APP_NUMBER'])->where('APP_UID', '=', $appUid)->first()->toArray();
// If application exists, swap the number
if (!empty($application)) {
// Get a normal sequence number
$appSequence = new AppSequence();
$appNumber = $appSequence->sequenceNumber(AppSequence::APP_TYPE_NORMAL);
// Update case with the new application number
$cases = new Cases();
$casesData = $cases->loadCase($appUid);
$casesData['APP_NUMBER'] = $casesData['APP_DATA']['APP_NUMBER'] = $appNumber;
$cases->updateCase($appUid, $casesData);
// Build the query to update related tables and fields
$query = "UPDATE `APPLICATION` SET `APP_TITLE` = '#{$appNumber}' WHERE `APP_UID` = '{$appUid}';";
$query .= "UPDATE `APP_DATA_CHANGE_LOG` SET `APP_NUMBER` = {$appNumber} WHERE `APP_NUMBER` = {$application['APP_NUMBER']};";
$query .= "UPDATE `APP_DELEGATION` SET `APP_NUMBER` = {$appNumber} WHERE `APP_UID` = '{$appUid}';";
$query .= "UPDATE `LIST_INBOX` SET `APP_NUMBER` = {$appNumber}, `APP_TITLE` = '#{$appNumber}' WHERE `APP_UID` = '{$appUid}';";
$query .= "UPDATE `LIST_PARTICIPATED_HISTORY` SET `APP_NUMBER` = {$appNumber}, `APP_TITLE` = '#{$appNumber}' WHERE `APP_UID` = '{$appUid}';";
$query .= "UPDATE `LIST_PARTICIPATED_LAST` SET `APP_NUMBER` = {$appNumber}, `APP_TITLE` = '#{$appNumber}' WHERE `APP_UID` = '{$appUid}';";
// Execute the query
DB::connection('workflow')->unprepared($query);
// Return new application number
return $appNumber;
}
}
/**
* Convert Web Entries v1.0 to v2.0
*/
public static function convertFromV1ToV2()
{
// Build query
$query = "UPDATE
`WEB_ENTRY`
LEFT JOIN
`BPMN_PROCESS`
ON
(`WEB_ENTRY`.`PRO_UID` = `BPMN_PROCESS`.`PRJ_UID`)
SET
`WEB_ENTRY`.`DYN_UID` = '', `WEB_ENTRY`.`WE_TYPE` = 'MULTIPLE'
WHERE
`WE_TYPE` = 'SINGLE' AND `WE_AUTHENTICATION` = 'ANONYMOUS' AND
`WE_CALLBACK` = 'PROCESSMAKER' AND `BPMN_PROCESS`.`PRJ_UID` IS NOT NULL";
// Execute query
DB::connection('workflow')->statement($query);
}
/**
* Delete web entries created one week ago or more
*/
public static function deleteOldWebEntries()
{
// Define some values for PM tables classes
if (!defined('PATH_WORKSPACE')) {
define('PATH_WORKSPACE', PATH_DB . config('system.workspace') . PATH_SEP);
}
set_include_path(get_include_path() . PATH_SEPARATOR . PATH_WORKSPACE);
// Calculate date, one week ago from today
$date = now()->subWeek()->format('Y-m-d H:i:s');
// Build query
$query = "SELECT `APP_UID` FROM `APPLICATION` WHERE `APP_NUMBER` < 0 AND `APP_CREATE_DATE` < '{$date}'";
// Execute query
$cases = DB::connection('workflow')->select($query);
// Delete cases, one by one with all related records
$casesInstance = new Cases();
foreach ($cases as $case) {
$casesInstance->removeCase($case->APP_UID);
}
}
}

View File

@@ -1,6 +1,6 @@
<?php <?php
namespace ProcessMaker\AuditLog; namespace ProcessMaker\Log;
use Bootstrap; use Bootstrap;
use Configurations; use Configurations;

View File

@@ -0,0 +1,103 @@
<?php
namespace ProcessMaker\Model;
use Illuminate\Database\Eloquent\Model;
class AppTimeoutAction extends Model
{
protected $table = 'APP_TIMEOUT_ACTION_EXECUTED';
// We do not have create/update timestamps for this table
public $timestamps = false;
// Filter by a specific case using case number
private $caseUid = '';
// Filter by a specific index
private $index = 0;
/**
* Set Case Uid
*
* @param string $caseUid
*/
public function setCaseUid($caseUid)
{
$this->caseUid = $caseUid;
}
/**
* Get Case Uid
*
* @return string
*/
public function getCaseUid()
{
return $this->caseUid;
}
/**
* Set index
*
* @param int $index
*/
public function setIndex($index)
{
$this->index = $index;
}
/**
* Get index
*
* @return int
*/
public function getIndex()
{
return $this->index;
}
/**
* Scope a query to get specific case uid
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param string $appUid
*
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeCase($query, $appUid)
{
return $query->where('APP_UID', $appUid);
}
/**
* Scope a query to get index
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param int $index
*
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeIndex($query, $index)
{
return $query->where('DEL_INDEX', $index);
}
/**
* Get the records related to the case and index if it was defined
*
* @return array
*/
public function cases()
{
$query = AppTimeoutAction::query()->select();
// Specific case uid
if (!empty($this->getCaseUid())) {
$query->case($this->getCaseUid());
}
// Specific index
if (!empty($this->getIndex())) {
$query->index($this->getIndex());
}
$results = $query->get()->toArray();
return $results;
}
}

View File

@@ -35,6 +35,19 @@ class Application extends Model
return $this->belongsTo(User::class, 'APP_INIT_USER', 'USR_UID'); return $this->belongsTo(User::class, 'APP_INIT_USER', 'USR_UID');
} }
/**
* Scope for query to get the positive cases
*
* @param \Illuminate\Database\Eloquent\Builder $query
*
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopePositivesCases($query)
{
$result = $query->where('APP_NUMBER', '>', 0);
return $result;
}
/** /**
* Scope for query to get the application by APP_UID. * Scope for query to get the application by APP_UID.
* *
@@ -49,6 +62,20 @@ class Application extends Model
return $result; return $result;
} }
/**
* Scope for query to get the application by status Id
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param integer $status
*
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeStatusId($query, int $status)
{
$result = $query->where('APP_STATUS_ID', '=', $status);
return $result;
}
/** /**
* Scope for query to get the applications by PRO_UID. * Scope for query to get the applications by PRO_UID.
* *
@@ -76,6 +103,7 @@ class Application extends Model
$query = Application::query() $query = Application::query()
->select() ->select()
->proUid($proUid) ->proUid($proUid)
->positivesCases()
->orderBy('APP_NUMBER', 'ASC'); ->orderBy('APP_NUMBER', 'ASC');
return $query->get(); return $query->get();
} }
@@ -118,4 +146,24 @@ class Application extends Model
return $properties; return $properties;
} }
/**
* Get Applications by PRO_UID, ordered by APP_NUMBER.
*
* @param string $proUid
* @param int $status
*
* @return object
* @see ReportTables->populateTable()
*/
public static function getCountByProUid(string $proUid, $status = 2)
{
$query = Application::query()
->select()
->proUid($proUid)
->statusId($status)
->positivesCases();
return $query->get()->count();
}
} }

View File

@@ -13,4 +13,20 @@ class BpmnProject extends Model
// We do not have create/update timestamps for this table // We do not have create/update timestamps for this table
public $timestamps = false; public $timestamps = false;
/**
* Check is the Process is BPMN.
*
* @param string $proUid
*
* @return int 1 if is BPMN process or 0 if a Normal process
*/
public static function isBpmnProcess(string $proUid)
{
$query = BpmnProject::query()
->select()
->where('PRJ_UID', '=', $proUid);
$result = $query->get()->values()->toArray();
return empty($result) ? 0 : 1;
}
} }

View File

@@ -48,6 +48,7 @@ class ListUnassigned extends Model
* *
* @param \Illuminate\Database\Eloquent\Builder $query * @param \Illuminate\Database\Eloquent\Builder $query
* @param array $tasks * @param array $tasks
*
* @return \Illuminate\Database\Eloquent\Builder * @return \Illuminate\Database\Eloquent\Builder
*/ */
public function scopeTasksIn($query, array $tasks) public function scopeTasksIn($query, array $tasks)
@@ -100,7 +101,7 @@ class ListUnassigned extends Model
* @param string $userUid * @param string $userUid
* @param array $filters * @param array $filters
* *
* @return array * @return int
*/ */
public static function doCount($userUid, $filters = []) public static function doCount($userUid, $filters = [])
{ {
@@ -125,4 +126,21 @@ class ListUnassigned extends Model
return $result; return $result;
} }
/**
* Get the unassigned cases related to the self service timeout
*
* @return array
*/
public static function selfServiceTimeout()
{
$query = ListUnassigned::query()->select();
$query->join('TASK', function ($join) {
$join->on('LIST_UNASSIGNED.TAS_ID', '=', 'TASK.TAS_ID')
->where('TASK.TAS_SELFSERVICE_TIMEOUT', '=', 1);
});
$results = $query->get()->toArray();
return $results;
}
} }

View File

@@ -2,8 +2,10 @@
namespace ProcessMaker\Model; namespace ProcessMaker\Model;
use Configurations;
use Exception;
use G;
use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Model;
use RbacUsers;
use RBAC; use RBAC;
/** /**
@@ -20,22 +22,164 @@ class Process extends Model
// Our custom timestamp columns // Our custom timestamp columns
const CREATED_AT = 'PRO_CREATE_DATE'; const CREATED_AT = 'PRO_CREATE_DATE';
const UPDATED_AT = 'PRO_UPDATE_DATE'; const UPDATED_AT = 'PRO_UPDATE_DATE';
// Columns to see in the process list
public $listColumns = [
'PRO_UID',
'PRO_TITLE',
'PRO_DESCRIPTION',
'PRO_PARENT',
'PRO_STATUS',
'PRO_TYPE',
'PRO_CATEGORY',
'PRO_UPDATE_DATE',
'PRO_CREATE_DATE',
'PRO_CREATE_USER',
'PRO_DEBUG',
'PRO_TYPE_PROCESS',
'USR_UID',
'USR_USERNAME',
'USR_FIRSTNAME',
'USR_LASTNAME',
'CATEGORY_UID',
'CATEGORY_NAME'
];
/**
* Get the columns related to the process list
* @return array
*/
public function getListColumns()
{
return $this->listColumns;
}
/**
* Returns the task related to the process belongs to
*/
public function tasks() public function tasks()
{ {
return $this->belongsTo(Task::class, 'PRO_ID', 'PRO_ID'); return $this->belongsTo(Task::class, 'PRO_ID', 'PRO_ID');
} }
/**
* Returns the user creator belongs to
*/
public function creator() public function creator()
{ {
return $this->belongsTo(User::class, 'PRO_CREATE_USER', 'USR_UID'); return $this->belongsTo(User::class, 'PRO_CREATE_USER', 'USR_UID');
} }
/**
* Returns the category related to the process belongs to
*/
public function category() public function category()
{ {
return $this->belongsTo(ProcessCategory::class, 'PRO_CATEGORY', 'CATEGORY_UID'); return $this->belongsTo(ProcessCategory::class, 'PRO_CATEGORY', 'CATEGORY_UID');
} }
/**
* Scope a query to specific process
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param string $proUid
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeProcess($query, $proUid)
{
return $query->where('PRO_UID', '=', $proUid);
}
/**
* Scope a query to specific title
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param string $title
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeTitle($query, $title)
{
return $query->where('PRO_TITLE', 'LIKE', "%{$title}%");
}
/**
* Scope a query to exclude a specific status
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param string $status
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeNoStatus($query, $status = 'DISABLED')
{
return $query->where('PRO_STATUS', '!=', $status);
}
/**
* Scope a query to include subprocess
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeSubProcess($query)
{
return $query->where('PRO_SUBPROCESS', '=', 1);
}
/**
* Scope a query to include a specific process category
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param string $category
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeCategory($query, $category)
{
return $query->where('PROCESS.PRO_CATEGORY', $category);
}
/**
* Scope a query to include the user owner or public process
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param string $userUid
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopePerUser($query, string $userUid)
{
$query->where(function ($query) use ($userUid) {
$query->orWhere('PRO_CREATE_USER', $userUid);
$query->orWhere('PRO_TYPE_PROCESS', 'PUBLIC');
});
return $query;
}
/**
* Scope a query to include the process related to the specific user
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeJoinUsers($query)
{
$query->join('USERS', function ($join) {
$join->on('PROCESS.PRO_CREATE_USER', '=', 'USERS.USR_UID');
});
return $query;
}
/**
* Scope a query to join with categories
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeJoinCategory($query)
{
$query->leftJoin('PROCESS_CATEGORY', function ($join) {
$join->on('PROCESS.PRO_CATEGORY', '=', 'PROCESS_CATEGORY.CATEGORY_UID');
});
return $query;
}
/** /**
* Obtains the process list for an specific user and/or for the specific category * Obtains the process list for an specific user and/or for the specific category
* *
@@ -82,12 +226,168 @@ class Process extends Model
* @param array $privateProcesses * @param array $privateProcesses
* @return void * @return void
*/ */
public static function convertPrivateProcessesToPublic($privateProcesses) public static function convertPrivateProcessesToPublicAndUpdateUser($privateProcesses, $userUid)
{ {
$admin = RBAC::ADMIN_USER_UID; $admin = RBAC::ADMIN_USER_UID;
$processes = array_column($privateProcesses, 'PRO_ID'); $processes = array_column($privateProcesses, 'PRO_ID');
Process::whereIn('PRO_ID', $processes) Process::whereIn('PRO_ID', $processes)
->update(['PRO_TYPE_PROCESS' => 'PUBLIC', 'PRO_CREATE_USER' => $admin]); ->update(['PRO_TYPE_PROCESS' => 'PUBLIC']);
Process::where('PRO_CREATE_USER', $userUid)
->update(['PRO_CREATE_USER' => $admin]);
}
/**
* Get the process list applying some extra filters
*
* @param string $catUid
* @param string $proUid
* @param string $title
* @param string $userUid
* @param int $start
* @param int $limit
* @param string $dir
* @param string $sort
* @param boolean $counterByProcess
* @param boolean $subProcess
*
* @return array
* @throw Exception
*/
public static function getProcessesFilter(
$catUid = null,
$proUid = null,
$title = null,
$userUid = null,
$start = 0,
$limit = 25,
$dir = 'ASC',
$sort = 'PRO_CREATE_DATE',
$counterByProcess = true,
$subProcess = false
) {
$process = new Process();
$rows = $process->getListColumns();
if (!in_array($sort, $rows)) {
throw new Exception('The column ' . $sort . ' does not exist');
}
// Select rows
$query = Process::query()->select($rows)->noStatus();
// Join with users
$query->joinUsers();
// Join with category
$query->joinCategory();
// Check if the owner is the user logged or if the process is PUBLIC
if (!empty($userUid)) {
//Only process PRO_TYPE_PROCESS = "PUBLIC" or related user owner
$query->perUser($userUid);
}
// Check if we can list only the sub-process
if ($subProcess) {
$query->subProcess();
}
// Specific process
if ($proUid) {
$query->process($proUid);
}
// Specific process title
if ($title) {
$query->title($title);
}
// Search a specific category
if (!empty($catUid)) {
if ($catUid == 'NONE') {
// Processes without category
$query->category('');
} else {
// Processes with the category $catUid
$query->category($catUid);
}
}
// Order the data
$query->orderBy($sort, $dir);
// Define the pagination
$query->offset($start)->limit($limit);
// Get the results
$results = $query->get();
// Define the class for get workspace configurations
$systemConf = new Configurations();
$systemConf->loadConfig($obj, 'ENVIRONMENT_SETTINGS', '');
$mask = isset($systemConf->aConfig['dateFormat']) ? $systemConf->aConfig['dateFormat'] : '';
// Prepare the final result
$results->transform(function ($item, $key) use ($counterByProcess, $systemConf, $mask){
// Get the counter related to the status
// todo: those counters needs to remove when the PMCORE-2314 was implemented
$item['CASES_COUNT_DRAFT'] = $counterByProcess ? Application::getCountByProUid($item['PRO_UID'], 1) : 0;
$item['CASES_COUNT_TO_DO'] = $counterByProcess ? Application::getCountByProUid($item['PRO_UID'], 2) : 0;
$item['CASES_COUNT_COMPLETED'] = $counterByProcess ? Application::getCountByProUid($item['PRO_UID'], 3) : 0;
$item['CASES_COUNT_CANCELLED'] = $counterByProcess ? Application::getCountByProUid($item['PRO_UID'], 4) : 0;
$item['CASES_COUNT'] = $item['CASES_COUNT_DRAFT'] + $item['CASES_COUNT_TO_DO'] + $item['CASES_COUNT_COMPLETED'] + $item['CASES_COUNT_CANCELLED'];
// Get the description
// todo: we will to remove htmlspecialchars but frontEnd needs to add application wide XSS prevention measures
$item['PRO_DESCRIPTION'] = empty($item['PRO_DESCRIPTION']) ? '' : htmlspecialchars($item['PRO_DESCRIPTION']);
// Get the type: bpmn or classic
$bpmnProcess = BpmnProject::isBpmnProcess($item['PRO_UID']);
$item['PROJECT_TYPE'] = ($bpmnProcess) ? 'bpmn' : 'classic';
// Get the process type: PUBLIC or PRIVATE
$item['PRO_TYPE_PROCESS'] = ($item['PRO_TYPE_PROCESS'] == 'PUBLIC') ? G::LoadTranslation("ID_PUBLIC") : G::LoadTranslation("ID_PRIVATE");;
// Get information about the owner, with the format defined
$creatorOwner = $systemConf->usersNameFormat($item['USR_USERNAME'], $item['USR_FIRSTNAME'], $item['USR_LASTNAME']);
$item['PRO_CREATE_USER_LABEL'] = empty($creatorOwner) ? $item['USR_FIRSTNAME'] . ' ' . $item['USR_LASTNAME'] : $creatorOwner;
// Get debug label
$item['PRO_DEBUG_LABEL'] = ($item['PRO_DEBUG'] == '1') ? G::LoadTranslation('ID_ON') : G::LoadTranslation('ID_OFF');
// Get status label
$item['PRO_STATUS_LABEL'] = $item['PRO_STATUS'] == 'ACTIVE' ? G::LoadTranslation('ID_ACTIVE') : G::LoadTranslation('ID_INACTIVE');
// Get category label
$item['PRO_CATEGORY_LABEL'] = trim($item['PRO_CATEGORY']) != '' ? $item['CATEGORY_NAME'] : G::LoadTranslation('ID_PROCESS_NONE_CATEGORY');
// Apply the date format defined in environment
if (!empty($mask)) {
$item['PRO_CREATE_DATE_LABEL'] = $item['PRO_CREATE_DATE']->format($mask);
$item['PRO_UPDATE_DATE_LABEL'] = $item['PRO_UPDATE_DATE']->format($mask);
}
return $item;
});
return $results->values()->toArray();
}
/**
* Get the number of rows corresponding to the process
*
* @param string $userUid
* @return integer
*/
public static function getCounter($userUid = '')
{
$query = Process::query()->select();
$query->noStatus();
if (!empty($userUid)) {
//Only process PRO_TYPE_PROCESS = "PUBLIC" or related user owner
$query->perUser($userUid);
}
return $query->count();
} }
} }

View File

@@ -16,4 +16,26 @@ class ProcessCategory extends Model
protected $table = 'PROCESS_CATEGORY'; protected $table = 'PROCESS_CATEGORY';
public $timestamps = false; public $timestamps = false;
/**
* Get the categories
*
* @param string $dir
*
* @return array
*
* @see ProcessProxy::categoriesList()
* @link https://wiki.processmaker.com/3.0/Process_Categories
*/
public static function getCategories( $dir = 'ASC')
{
$query = ProcessCategory::query()
->select([
'CATEGORY_UID',
'CATEGORY_NAME'
])
->orderBy('CATEGORY_NAME', $dir);
return $query->get()->values()->toArray();
}
} }

View File

@@ -10,11 +10,34 @@ class Triggers extends Model
protected $table = 'TRIGGERS'; protected $table = 'TRIGGERS';
// No timestamps // No timestamps
public $timestamps = false; public $timestamps = false;
//primary key // Primary key
protected $primaryKey = 'TRI_UID'; protected $primaryKey = 'TRI_UID';
//No incrementing // No incrementing
public $incrementing = false; public $incrementing = false;
// Filter by a specific uid
private $triUid = '';
/**
* Set trigger uid
*
* @param string $triUid
*/
public function setTrigger($triUid)
{
$this->triUid = $triUid;
}
/**
* Get trigger uid
*
* @return int
*/
public function getTrigger()
{
return $this->triUid;
}
/** /**
* Scope a query to filter an specific process * Scope a query to filter an specific process
* *
@@ -22,8 +45,37 @@ class Triggers extends Model
* @param string $columns * @param string $columns
* @return \Illuminate\Database\Eloquent\Builder * @return \Illuminate\Database\Eloquent\Builder
*/ */
public function scopeProcess($query, string $proUID) public function scopeProcess($query, string $proUid)
{ {
return $query->where('PRO_UID', $proUID); return $query->where('PRO_UID', $proUid);
}
/**
* Scope a query to filter an specific trigger
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param string $triUid
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeTrigger($query, string $triUid)
{
return $query->where('TRI_UID', $triUid);
}
/**
* Get the records
*
* @return array
*/
public function triggers()
{
$query = Triggers::query()->select();
// Specific trigger
if (!empty($this->getTrigger())) {
$query->trigger($this->getTrigger());
}
$results = $query->get()->toArray();
return $results;
} }
} }

View File

@@ -0,0 +1,687 @@
<?php
namespace ProcessMaker\TaskScheduler;
use Application;
use AppAssignSelfServiceValueGroupPeer;
use AppAssignSelfServiceValuePeer;
use AppCacheView;
use AppDelegation;
use App\Jobs\TaskScheduler;
use Bootstrap;
use Cases;
use ConfigurationPeer;
use Criteria;
use Exception;
use G;
use Illuminate\Support\Facades\Log;
use ldapadvancedClassCron;
use NotificationQueue;
use ProcessMaker\BusinessModel\ActionsByEmail\ResponseReader;
use ProcessMaker\BusinessModel\Cases as BmCases;
use ProcessMaker\BusinessModel\Light\PushMessageAndroid;
use ProcessMaker\BusinessModel\Light\PushMessageIOS;
use ProcessMaker\BusinessModel\MessageApplication;
use ProcessMaker\BusinessModel\TimerEvent;
use ProcessMaker\Core\JobsManager;
use ProcessMaker\Plugins\PluginRegistry;
use Propel;
use ResultSet;
use SpoolRun;
class Task
{
/**
* Property asynchronous,
* @var bool
*/
private $asynchronous;
/**
* Property object
* @var mix
*/
private $object;
/**
* Constructor class.
* @param bool $async
* @param mix $object
*/
public function __construct(bool $asynchronous, $object)
{
$this->asynchronous = $asynchronous;
$this->object = $object;
}
/**
* Run job, the property async indicate if is synchronous or asynchronous.
* @param callable $job
*/
private function runTask(callable $job)
{
if ($this->asynchronous === false) {
$job();
}
if ($this->asynchronous === true) {
JobsManager::getSingleton()->dispatch(TaskScheduler::class, $job);
}
}
/**
* Print start message in console.
* @param string $message
*/
public function setExecutionMessage(string $message)
{
Log::channel('taskScheduler:taskScheduler')->info($message, Bootstrap::context());
if ($this->asynchronous === false) {
$len = strlen($message);
$linesize = 60;
$rOffset = $linesize - $len;
eprint("* $message");
for ($i = 0; $i < $rOffset; $i++) {
eprint('.');
}
}
}
/**
* Print result message in console.
* @param string $message
* @param string $type
*/
public function setExecutionResultMessage(string $message, string $type = '')
{
$color = 'green';
if ($type == 'error') {
$color = 'red';
Log::channel('taskScheduler:taskScheduler')->error($message, Bootstrap::context());
}
if ($type == 'info') {
$color = 'yellow';
Log::channel('taskScheduler:taskScheduler')->info($message, Bootstrap::context());
}
if ($type == 'warning') {
$color = 'yellow';
Log::channel('taskScheduler:taskScheduler')->warning($message, Bootstrap::context());
}
if ($this->asynchronous === false) {
eprintln("[$message]", $color);
}
}
/**
* Save logs.
* @param string $source
* @param string $type
* @param string $description
*/
public function saveLog(string $source, string $type, string $description)
{
if ($this->asynchronous === true) {
$context = [
'type' => $type,
'description' => $description
];
Log::channel('taskScheduler:taskScheduler')->info($source, Bootstrap::context($context));
}
if ($this->asynchronous === false) {
try {
G::verifyPath(PATH_DATA . "log" . PATH_SEP, true);
G::log("| $this->object | " . $source . " | $type | " . $description, PATH_DATA);
} catch (Exception $e) {
Log::channel('taskScheduler:taskScheduler')->error($e->getMessage(), Bootstrap::context());
}
}
}
/**
* This resend the emails.
* @param string $now
* @param string $dateSystem
*/
public function resendEmails($now, $dateSystem)
{
$scheduledTaskIdentifier = uniqid(__FUNCTION__ . "#");
Log::channel('taskScheduler:taskScheduler')->info("Start {$scheduledTaskIdentifier}", Bootstrap::context());
$job = function() use($now, $dateSystem, $scheduledTaskIdentifier) {
$this->setExecutionMessage("Resending emails");
try {
$dateResend = $now;
if ($now == $dateSystem) {
$arrayDateSystem = getdate(strtotime($dateSystem));
$mktDateSystem = mktime(
$arrayDateSystem["hours"],
$arrayDateSystem["minutes"],
$arrayDateSystem["seconds"],
$arrayDateSystem["mon"],
$arrayDateSystem["mday"],
$arrayDateSystem["year"]
);
$dateResend = date("Y-m-d H:i:s", $mktDateSystem - (7 * 24 * 60 * 60));
}
$spoolRun = new SpoolRun();
$spoolRun->resendEmails($dateResend, 1);
$this->saveLog("resendEmails", "action", "Resending Emails", "c");
$spoolWarnings = $spoolRun->getWarnings();
if ($spoolWarnings !== false) {
foreach ($spoolWarnings as $warning) {
print("MAIL SPOOL WARNING: " . $warning . "\n");
$this->saveLog("resendEmails", "warning", "MAIL SPOOL WARNING: " . $warning);
}
}
$this->setExecutionResultMessage("DONE");
} catch (Exception $e) {
$context = [
"trace" => $e->getTraceAsString()
];
Log::channel('taskScheduler:taskScheduler')->error($e->getMessage(), Bootstrap::context($context));
$criteria = new Criteria("workflow");
$criteria->clearSelectColumns();
$criteria->addSelectColumn(ConfigurationPeer::CFG_UID);
$criteria->add(ConfigurationPeer::CFG_UID, "Emails");
$result = ConfigurationPeer::doSelectRS($criteria);
$result->setFetchmode(ResultSet::FETCHMODE_ASSOC);
if ($result->next()) {
$this->setExecutionResultMessage("WARNING", "warning");
$message = "Emails won't be sent, but the cron will continue its execution";
if ($this->asynchronous === false) {
eprintln(" '-" . $message, "yellow");
}
} else {
$this->setExecutionResultMessage("WITH ERRORS", "error");
if ($this->asynchronous === false) {
eprintln(" '-" . $e->getMessage(), "red");
}
}
$this->saveLog("resendEmails", "error", "Error Resending Emails: " . $e->getMessage());
}
Log::channel('taskScheduler:taskScheduler')->info("Finish {$scheduledTaskIdentifier}", Bootstrap::context());
};
$this->runTask($job);
}
/**
* This unpause applications.
* @param string $now
*/
public function unpauseApplications($now)
{
$scheduledTaskIdentifier = uniqid(__FUNCTION__ . "#");
Log::channel('taskScheduler:taskScheduler')->info("Start {$scheduledTaskIdentifier}", Bootstrap::context());
$job = function() use($now, $scheduledTaskIdentifier) {
$this->setExecutionMessage("Unpausing applications");
try {
$cases = new Cases();
$cases->ThrowUnpauseDaemon($now, 1);
$this->setExecutionResultMessage('DONE');
$this->saveLog('unpauseApplications', 'action', 'Unpausing Applications');
} catch (Exception $e) {
$this->setExecutionResultMessage('WITH ERRORS', 'error');
if ($this->asynchronous === false) {
eprintln(" '-" . $e->getMessage(), 'red');
}
$this->saveLog('unpauseApplications', 'error', 'Error Unpausing Applications: ' . $e->getMessage());
}
Log::channel('taskScheduler:taskScheduler')->info("Finish {$scheduledTaskIdentifier}", Bootstrap::context());
};
$this->runTask($job);
}
/**
* Check if some task unassigned has enable the setting timeout and execute the trigger related
*
* @link https://wiki.processmaker.com/3.2/Tasks#Self-Service
*/
function executeCaseSelfService()
{
$scheduledTaskIdentifier = uniqid(__FUNCTION__ . "#");
Log::channel('taskScheduler:taskScheduler')->info("Start {$scheduledTaskIdentifier}", Bootstrap::context());
$job = function() use($scheduledTaskIdentifier) {
try {
$this->setExecutionMessage("Unassigned case");
$this->saveLog("unassignedCase", "action", "Unassigned case", "c");
$casesExecuted = BmCases::executeSelfServiceTimeout();
foreach ($casesExecuted as $caseNumber) {
$this->saveLog("unassignedCase", "action", "OK Executed trigger to the case $caseNumber");
}
$this->setExecutionResultMessage(count($casesExecuted) . " Cases");
} catch (Exception $e) {
$this->setExecutionResultMessage("WITH ERRORS", "error");
$this->saveLog("unassignedCase", "action", "Unassigned case", "c");
if ($this->asynchronous === false) {
eprintln(" '-" . $e->getMessage(), "red");
}
$this->saveLog("unassignedCase", "error", "Error in unassigned case: " . $e->getMessage());
}
Log::channel('taskScheduler:taskScheduler')->info("Finish {$scheduledTaskIdentifier}", Bootstrap::context());
};
$this->runTask($job);
}
/**
* This calculate duration.
*/
public function calculateDuration()
{
$scheduledTaskIdentifier = uniqid(__FUNCTION__ . "#");
Log::channel('taskScheduler:taskScheduler')->info("Start {$scheduledTaskIdentifier}", Bootstrap::context());
$job = function() use($scheduledTaskIdentifier) {
$this->setExecutionMessage("Calculating Duration");
try {
$appDelegation = new AppDelegation();
$appDelegation->calculateDuration(1);
$this->setExecutionResultMessage('DONE');
$this->saveLog('calculateDuration', 'action', 'Calculating Duration');
} catch (Exception $e) {
$this->setExecutionResultMessage('WITH ERRORS', 'error');
if ($this->asynchronous === false) {
eprintln(" '-" . $e->getMessage(), 'red');
}
$this->saveLog('calculateDuration', 'error', 'Error Calculating Duration: ' . $e->getMessage());
}
Log::channel('taskScheduler:taskScheduler')->info("Finish {$scheduledTaskIdentifier}", Bootstrap::context());
};
$this->runTask($job);
}
/**
* This calculate application duration.
*/
public function calculateAppDuration()
{
$scheduledTaskIdentifier = uniqid(__FUNCTION__ . "#");
Log::channel('taskScheduler:taskScheduler')->info("Start {$scheduledTaskIdentifier}", Bootstrap::context());
$job = function() use($scheduledTaskIdentifier) {
$this->setExecutionMessage("Calculating Duration by Application");
try {
$application = new Application();
$application->calculateAppDuration(1);
$this->setExecutionResultMessage('DONE');
$this->saveLog('calculateDurationByApp', 'action', 'Calculating Duration by Application');
} catch (Exception $e) {
$this->setExecutionResultMessage('WITH ERRORS', 'error');
if ($this->asynchronous === false) {
eprintln(" '-" . $e->getMessage(), 'red');
}
$this->saveLog('calculateDurationByApp', 'error', 'Error Calculating Duration: ' . $e->getMessage());
}
Log::channel('taskScheduler:taskScheduler')->info("Finish {$scheduledTaskIdentifier}", Bootstrap::context());
};
$this->runTask($job);
}
/**
* Clean unused records in tables related to the Self-Service Value Based feature.
*/
public function cleanSelfServiceTables()
{
$scheduledTaskIdentifier = uniqid(__FUNCTION__ . "#");
Log::channel('taskScheduler:taskScheduler')->info("Start {$scheduledTaskIdentifier}", Bootstrap::context());
$job = function() use($scheduledTaskIdentifier) {
try {
// Start message
$this->setExecutionMessage("Clean unused records for Self-Service Value Based feature");
// Get Propel connection
$cnn = Propel::getConnection(AppAssignSelfServiceValueGroupPeer::DATABASE_NAME);
// Delete related rows and missing relations, criteria don't execute delete with joins
$cnn->begin();
$stmt = $cnn->createStatement();
$stmt->executeQuery("DELETE " . AppAssignSelfServiceValueGroupPeer::TABLE_NAME . "
FROM " . AppAssignSelfServiceValueGroupPeer::TABLE_NAME . "
LEFT JOIN " . AppAssignSelfServiceValuePeer::TABLE_NAME . "
ON (" . AppAssignSelfServiceValueGroupPeer::ID . " = " . AppAssignSelfServiceValuePeer::ID . ")
WHERE " . AppAssignSelfServiceValuePeer::ID . " IS NULL");
$cnn->commit();
// Success message
$this->setExecutionResultMessage("DONE");
} catch (Exception $e) {
$cnn->rollback();
$this->setExecutionResultMessage("WITH ERRORS", "error");
if ($this->asynchronous === false) {
eprintln(" '-" . $e->getMessage(), "red");
}
$this->saveLog("ExecuteCleanSelfServiceTables", "error", "Error when try to clean self-service tables " . $e->getMessage());
}
Log::channel('taskScheduler:taskScheduler')->info("Finish {$scheduledTaskIdentifier}", Bootstrap::context());
};
$this->runTask($job);
}
/**
* This execute plugins cron.
* @return boolean
*/
public function executePlugins()
{
$scheduledTaskIdentifier = uniqid(__FUNCTION__ . "#");
Log::channel('taskScheduler:taskScheduler')->info("Start {$scheduledTaskIdentifier}", Bootstrap::context());
$job = function() use($scheduledTaskIdentifier) {
$pathCronPlugins = PATH_CORE . 'bin' . PATH_SEP . 'plugins' . PATH_SEP;
// Executing cron files in bin/plugins directory
if (!is_dir($pathCronPlugins)) {
return false;
}
if ($handle = opendir($pathCronPlugins)) {
$this->setExecutionMessage('Executing cron files in bin/plugins directory in Workspace: ' . config("system.workspace"));
while (false !== ($file = readdir($handle))) {
if (strpos($file, '.php', 1) && is_file($pathCronPlugins . $file)) {
$filename = str_replace('.php', '', $file);
$className = $filename . 'ClassCron';
// Execute custom cron function
$this->executeCustomCronFunction($pathCronPlugins . $file, $className);
}
}
}
// Executing registered cron files
// -> Get registered cron files
$pluginRegistry = PluginRegistry::loadSingleton();
$cronFiles = $pluginRegistry->getCronFiles();
// -> Execute functions
if (!empty($cronFiles)) {
$this->setExecutionMessage('Executing registered cron files for Workspace: ' . config('system.workspace'));
/**
* @var \ProcessMaker\Plugins\Interfaces\CronFile $cronFile
*/
foreach ($cronFiles as $cronFile) {
$path = PATH_PLUGINS . $cronFile->getNamespace() . PATH_SEP . 'bin' . PATH_SEP . $cronFile->getCronFile() . '.php';
if (file_exists($path)) {
$this->executeCustomCronFunction($path, $cronFile->getCronFile());
} else {
$this->setExecutionMessage('File ' . $cronFile->getCronFile() . '.php ' . 'does not exist.');
}
}
}
Log::channel('taskScheduler:taskScheduler')->info("Finish {$scheduledTaskIdentifier}", Bootstrap::context());
};
$this->runTask($job);
}
/**
* This execute custom cron function.
* @param string $pathFile
* @param string $className
*/
public function executeCustomCronFunction($pathFile, $className)
{
include_once $pathFile;
$plugin = new $className();
if (method_exists($plugin, 'executeCron')) {
$arrayCron = unserialize(trim(@file_get_contents(PATH_DATA . "cron")));
$arrayCron["processcTimeProcess"] = 60; //Minutes
$arrayCron["processcTimeStart"] = time();
@file_put_contents(PATH_DATA . "cron", serialize($arrayCron));
//Try to execute Plugin Cron. If there is an error then continue with the next file
$this->setExecutionMessage("\n--- Executing cron file: $pathFile");
try {
$plugin->executeCron();
$this->setExecutionResultMessage('DONE');
} catch (Exception $e) {
$this->setExecutionResultMessage('FAILED', 'error');
if ($this->asynchronous === false) {
eprintln(" '-" . $e->getMessage(), 'red');
}
$this->saveLog('executePlugins', 'error', 'Error executing cron file: ' . $pathFile . ' - ' . $e->getMessage());
}
}
}
/**
* This fills the report by user.
* @param string $dateInit
* @param string $dateFinish
* @return boolean
*/
public function fillReportByUser($dateInit, $dateFinish)
{
$scheduledTaskIdentifier = uniqid(__FUNCTION__ . "#");
Log::channel('taskScheduler:taskScheduler')->info("Start {$scheduledTaskIdentifier}", Bootstrap::context());
if ($dateInit == null) {
if ($this->asynchronous === false) {
eprintln("You must enter the starting date.", "red");
eprintln('Example: +init-date"YYYY-MM-DD HH:MM:SS" +finish-date"YYYY-MM-DD HH:MM:SS"', "red");
}
if ($this->asynchronous === true) {
$message = 'You must enter the starting date. Example: +init-date"YYYY-MM-DD HH:MM:SS" +finish-date"YYYY-MM-DD HH:MM:SS"';
Log::channel('taskScheduler:taskScheduler')->info($message, Bootstrap::context());
}
return false;
}
$job = function() use($dateInit, $dateFinish, $scheduledTaskIdentifier) {
try {
$dateFinish = ($dateFinish != null) ? $dateFinish : date("Y-m-d H:i:s");
$appCacheView = new AppCacheView();
$appCacheView->setPathToAppCacheFiles(PATH_METHODS . 'setup' . PATH_SEP . 'setupSchemas' . PATH_SEP);
$this->setExecutionMessage("Calculating data to fill the 'User Reporting'...");
$appCacheView->fillReportByUser($dateInit, $dateFinish);
setExecutionResultMessage("DONE");
} catch (Exception $e) {
$this->setExecutionResultMessage("WITH ERRORS", "error");
if ($this->asynchronous === false) {
eprintln(" '-" . $e->getMessage(), "red");
}
$this->saveLog("fillReportByUser", "error", "Error in fill report by user: " . $e->getMessage());
}
Log::channel('taskScheduler:taskScheduler')->info("Finish {$scheduledTaskIdentifier}", Bootstrap::context());
};
$this->runTask($job);
}
/**
* This fills the report by process.
* @param string $dateInit
* @param string $dateFinish
* @return boolean
*/
public function fillReportByProcess($dateInit, $dateFinish)
{
$scheduledTaskIdentifier = uniqid(__FUNCTION__ . "#");
Log::channel('taskScheduler:taskScheduler')->info("Start {$scheduledTaskIdentifier}", Bootstrap::context());
if ($dateInit == null) {
if ($this->asynchronous === false) {
eprintln("You must enter the starting date.", "red");
eprintln('Example: +init-date"YYYY-MM-DD HH:MM:SS" +finish-date"YYYY-MM-DD HH:MM:SS"', "red");
}
if ($this->asynchronous === true) {
$message = 'You must enter the starting date. Example: +init-date"YYYY-MM-DD HH:MM:SS" +finish-date"YYYY-MM-DD HH:MM:SS"';
Log::channel('taskScheduler:taskScheduler')->info($message, Bootstrap::context());
}
return false;
}
$job = function() use($dateInit, $dateFinish, $scheduledTaskIdentifier) {
try {
$dateFinish = ($dateFinish != null) ? $dateFinish : date("Y-m-d H:i:s");
$appcv = new AppCacheView();
$appcv->setPathToAppCacheFiles(PATH_METHODS . 'setup' . PATH_SEP . 'setupSchemas' . PATH_SEP);
$this->setExecutionMessage("Calculating data to fill the 'Process Reporting'...");
$appcv->fillReportByProcess($dateInit, $dateFinish);
$this->setExecutionResultMessage("DONE");
} catch (Exception $e) {
$this->setExecutionResultMessage("WITH ERRORS", "error");
if ($this->asynchronous === false) {
eprintln(" '-" . $e->getMessage(), "red");
}
$this->saveLog("fillReportByProcess", "error", "Error in fill report by process: " . $e->getMessage());
}
Log::channel('taskScheduler:taskScheduler')->info("Finish {$scheduledTaskIdentifier}", Bootstrap::context());
};
$this->runTask($job);
}
/**
* This execute ldap cron.
* @param boolean $debug
*/
public function ldapcron($debug)
{
$scheduledTaskIdentifier = uniqid(__FUNCTION__ . "#");
Log::channel('taskScheduler:taskScheduler')->info("Start {$scheduledTaskIdentifier}", Bootstrap::context());
$job = function() use($debug, $scheduledTaskIdentifier) {
require_once(PATH_HOME . 'engine' . PATH_SEP . 'methods' . PATH_SEP . 'services' . PATH_SEP . 'ldapadvanced.php');
$ldapadvancedClassCron = new ldapadvancedClassCron();
$ldapadvancedClassCron->executeCron($debug);
Log::channel('taskScheduler:taskScheduler')->info("Finish {$scheduledTaskIdentifier}", Bootstrap::context());
};
$this->runTask($job);
}
/**
* This execute the sending of notifications.
*/
function sendNotifications()
{
$scheduledTaskIdentifier = uniqid(__FUNCTION__ . "#");
Log::channel('taskScheduler:taskScheduler')->info("Start {$scheduledTaskIdentifier}", Bootstrap::context());
$job = function() use($scheduledTaskIdentifier) {
try {
$this->setExecutionMessage("Resending Notifications");
$this->setExecutionResultMessage("PROCESSING");
$notQueue = new NotificationQueue();
$notQueue->checkIfCasesOpenForResendingNotification();
$notificationsAndroid = $notQueue->loadStatusDeviceType('pending', 'android');
if ($notificationsAndroid) {
$this->setExecutionMessage("|-- Send Android's Notifications");
$n = 0;
foreach ($notificationsAndroid as $key => $item) {
$notification = new PushMessageAndroid();
$notification->setSettingNotification();
$notification->setDevices(unserialize($item['DEV_UID']));
$response['android'] = $notification->send($item['NOT_MSG'], unserialize($item['NOT_DATA']));
$notQueue = new NotificationQueue();
$notQueue->changeStatusSent($item['NOT_UID']);
$n += $notification->getNumberDevices();
}
$this->setExecutionResultMessage("Processed $n");
}
$notificationsApple = $notQueue->loadStatusDeviceType('pending', 'apple');
if ($notificationsApple) {
$this->setExecutionMessage("|-- Send Apple Notifications");
$n = 0;
foreach ($notificationsApple as $key => $item) {
$notification = new PushMessageIOS();
$notification->setSettingNotification();
$notification->setDevices(unserialize($item['DEV_UID']));
$response['apple'] = $notification->send($item['NOT_MSG'], unserialize($item['NOT_DATA']));
$notQueue = new NotificationQueue();
$notQueue->changeStatusSent($item['NOT_UID']);
$n += $notification->getNumberDevices();
}
$this->setExecutionResultMessage("Processed $n");
}
} catch (Exception $e) {
$this->setExecutionResultMessage("WITH ERRORS", "error");
if ($this->asynchronous === false) {
eprintln(" '-" . $e->getMessage(), "red");
}
$this->saveLog("ExecuteSendNotifications", "error", "Error when sending notifications " . $e->getMessage());
}
Log::channel('taskScheduler:taskScheduler')->info("Finish {$scheduledTaskIdentifier}", Bootstrap::context());
};
$this->runTask($job);
}
/**
* This executes an actions by email responses.
*/
public function actionsByEmailResponse()
{
$scheduledTaskIdentifier = uniqid(__FUNCTION__ . "#");
Log::channel('taskScheduler:taskScheduler')->info("Start {$scheduledTaskIdentifier}", Bootstrap::context());
$job = function() use($scheduledTaskIdentifier) {
$responseReader = new ResponseReader();
$responseReader->actionsByEmailEmailResponse();
Log::channel('taskScheduler:taskScheduler')->info("Finish {$scheduledTaskIdentifier}", Bootstrap::context());
};
$this->runTask($job);
}
/**
* This execute message event cron.
*/
public function messageeventcron()
{
$scheduledTaskIdentifier = uniqid(__FUNCTION__ . "#");
Log::channel('taskScheduler:taskScheduler')->info("Start {$scheduledTaskIdentifier}", Bootstrap::context());
$job = function() use($scheduledTaskIdentifier) {
$messageApplication = new MessageApplication();
$messageApplication->catchMessageEvent(true);
Log::channel('taskScheduler:taskScheduler')->info("Finish {$scheduledTaskIdentifier}", Bootstrap::context());
};
$this->runTask($job);
}
/**
* Start/Continue cases by Timer-Event
*
* @param string $datetime
* @param bool $frontEnd
*/
public function timerEventCron($datetime, $frontEnd)
{
$scheduledTaskIdentifier = uniqid(__FUNCTION__ . "#");
Log::channel('taskScheduler:taskScheduler')->info("Start {$scheduledTaskIdentifier}", Bootstrap::context());
$job = function() use ($datetime, $frontEnd, $scheduledTaskIdentifier) {
$timerEvent = new TimerEvent();
$timerEvent->startContinueCaseByTimerEvent($datetime, $frontEnd);
Log::channel('taskScheduler:taskScheduler')->info("Finish {$scheduledTaskIdentifier}", Bootstrap::context());
};
$this->runTask($job);
}
}

View File

@@ -688,3 +688,33 @@ function saveAppDocument($file, $appUid, $appDocUid, $version = 1, $upload = tru
throw $e; throw $e;
} }
} }
/**
* Add a specific date minutes, hours or days
*
* @param string $iniDate
* @param string $timeUnit
* @param int $time
*
* @return string
*
* @link https://www.php.net/manual/en/datetime.modify.php
*/
function calculateDate($iniDate, $timeUnit, $time)
{
$datetime = new DateTime($iniDate);
switch ($timeUnit) {
case 'DAYS':
$datetime->modify('+' . $time . ' day');
break;
case 'HOURS':
$datetime->modify('+' . $time . ' hour');
break;
case 'MINUTES':
$datetime->modify('+' . $time . ' minutes');
break;
}
return $datetime->format('Y-m-d H:i:s');
}

View File

@@ -135,7 +135,6 @@ Ext.onReady(function(){
Ext.QuickTips.init(); Ext.QuickTips.init();
store = new Ext.data.GroupingStore( { store = new Ext.data.GroupingStore( {
//var store = new Ext.data.Store( {
remoteSort: true, remoteSort: true,
proxy : new Ext.data.HttpProxy({ proxy : new Ext.data.HttpProxy({
url: 'processesList' url: 'processesList'
@@ -168,9 +167,6 @@ Ext.onReady(function(){
] ]
}), }),
//sortInfo:{field: 'PRO_TITLE', direction: "ASC"}
//groupField:'PRO_CATEGORY_LABEL'
listeners: { listeners: {
load: function (store) { load: function (store) {
Ext.ComponentMgr.get("export").setDisabled(true); Ext.ComponentMgr.get("export").setDisabled(true);
@@ -225,44 +221,6 @@ Ext.onReady(function(){
store.load({params: {category: filter, start: 0, limit: 25}}); store.load({params: {category: filter, start: 0, limit: 25}});
}} }}
}) })
/* storePageSize = new Ext.data.SimpleStore({
fields: ['size'],
data: [['20'],['30'],['40'],['50'],['100']],
autoLoad: true
});
var comboPageSize = new Ext.form.ComboBox({
typeAhead : false,
mode : 'local',
triggerAction : 'all',
store: storePageSize,
valueField: 'size',
displayField: 'size',
width: 50,
editable: false,
listeners:{
select: function(c,d,i){
//UpdatePageConfig(d.data['size']);
bbar.pageSize = parseInt(d.data['size']);
bbar.moveFirst();
//Ext.getCmp('bbar').setPageSize(comboPageSize.getValue());
}
}
});
comboPageSize.setValue(pageSize);
var bbar = new Ext.PagingToolbar({
id: 'bbar',
pageSize: '15',
store: store,
displayInfo: true,
displayMsg: 'Displaying Processes {0} - {1} of {2}',
emptyMsg: "",
items:[_('ID_PAGE_SIZE')+':',comboPageSize]
}) */
var mnuNewBpmnProject = { var mnuNewBpmnProject = {
text: _("ID_NEW_BPMN_PROJECT"), text: _("ID_NEW_BPMN_PROJECT"),
@@ -453,11 +411,11 @@ Ext.onReady(function(){
}} }}
,{header: _('ID_OWNER'), dataIndex: 'PRO_CREATE_USER_LABEL', width: 90} ,{header: _('ID_OWNER'), dataIndex: 'PRO_CREATE_USER_LABEL', width: 90}
,{header: _('ID_PRO_CREATE_DATE'), dataIndex: 'PRO_CREATE_DATE', width: 90} ,{header: _('ID_PRO_CREATE_DATE'), dataIndex: 'PRO_CREATE_DATE', width: 90}
,{header: _('ID_INBOX'), dataIndex: 'CASES_COUNT_TO_DO', width: 50, align:'right'} ,{header: _('ID_INBOX'), dataIndex: 'CASES_COUNT_TO_DO', width: 50, align:'right', sortable: false}
,{header: _('ID_DRAFT'), dataIndex: 'CASES_COUNT_DRAFT', width: 50, align:'right'} ,{header: _('ID_DRAFT'), dataIndex: 'CASES_COUNT_DRAFT', width: 50, align:'right', sortable: false}
,{header: _('ID_COMPLETED'), dataIndex: 'CASES_COUNT_COMPLETED', width: 50, align:'right'} ,{header: _('ID_COMPLETED'), dataIndex: 'CASES_COUNT_COMPLETED', width: 50, align:'right', sortable: false}
,{header: _('ID_CANCELLED'), dataIndex: 'CASES_COUNT_CANCELLED', width: 50, align:'right'} ,{header: _('ID_CANCELLED'), dataIndex: 'CASES_COUNT_CANCELLED', width: 50, align:'right', sortable: false}
,{header: _('ID_TOTAL_CASES'), dataIndex: 'CASES_COUNT', width: 70, renderer:function(v){return "<b>"+v+"</b>";}, align:'right'} ,{header: _('ID_TOTAL_CASES'), dataIndex: 'CASES_COUNT', width: 70, renderer:function(v){return "<b>"+v+"</b>";}, align:'right', sortable: false}
,{header: _('ID_PRO_DEBUG'), dataIndex: 'PRO_DEBUG_LABEL', width: 30} ,{header: _('ID_PRO_DEBUG'), dataIndex: 'PRO_DEBUG_LABEL', width: 30}
/*----------------------------------********---------------------------------*/ /*----------------------------------********---------------------------------*/
,{header: _("ID_TYPE_PROCESS"), dataIndex: "PRO_TYPE_PROCESS", width: 70} ,{header: _("ID_TYPE_PROCESS"), dataIndex: "PRO_TYPE_PROCESS", width: 70}
@@ -468,25 +426,14 @@ Ext.onReady(function(){
sm: proSelModel, sm: proSelModel,
store: store, store: store,
tbar:[ tbar:[
newTypeProcess,/* newTypeProcess,
{
text: _('ID_NEW'),
iconCls: 'button_menu_ext ss_sprite ss_add',
//icon: '/images/addc.png',
handler: newProcess
},*/
'-' '-'
,{ ,{
text: _('ID_EDIT'), text: _('ID_EDIT'),
iconCls: 'button_menu_ext', iconCls: 'button_menu_ext',
icon: '/images/pencil.png', icon: '/images/pencil.png',
handler: editProcess handler: editProcess
},/*{ },{
text: 'Edit (New Editor)',
iconCls: 'button_menu_ext',
icon: '/images/pencil_beta.png',
handler: editNewProcess
},*/{
text: _('ID_STATUS'), text: _('ID_STATUS'),
id:'activator', id:'activator',
icon: '', icon: '',
@@ -541,12 +488,9 @@ Ext.onReady(function(){
text:'X', text:'X',
ctCls:'pm_search_x_button_des', ctCls:'pm_search_x_button_des',
handler: function(){ handler: function(){
//store.setBaseParam( 'category', '<reset>');
store.setBaseParam('processName', ''); store.setBaseParam('processName', '');
store.load({params: {start: 0, limit: 25}}); store.load({params: {start: 0, limit: 25}});
Ext.getCmp('searchTxt').setValue(''); Ext.getCmp('searchTxt').setValue('');
//comboCategory.setValue('');
//store.reload();
} }
},{ },{
text: _('ID_SEARCH'), text: _('ID_SEARCH'),
@@ -881,13 +825,11 @@ function saveProcess()
} }
} }
function doSearch(){ function doSearch() {
if(comboCategory.getValue() == '')
store.setBaseParam( 'category', '<reset>');
filter = Ext.getCmp('searchTxt').getValue(); filter = Ext.getCmp('searchTxt').getValue();
store.setBaseParam('processName', filter); store.setBaseParam('processName', filter);
store.load({params:{processName: filter, start: 0 , limit: 25}}); store.load({params: {processName: filter, start: 0, limit: 25}});
} }
editProcess = function(typeParam) editProcess = function(typeParam)