/** * Run the database seeds. * * @return void */ public function run() { DB::table('cs_budgets')->delete(); $amount = array("10-100", "100-200", "200-500", "500-1000", "1000-2000", "> 2000"); foreach ($amount as $price) { $bg = new Budget(); $bg->price = $price; $bg->save(); } }
/** * Show the form for creating a new resource. * * @return Response */ public function create() { $data = array(); $data['budgets'] = Budget::getList(); $data['services'] = Service::getList(); return View::make('items.create', $data); }
public function scopeGetList() { $budgets = Budget::all(); $data = array(); foreach ($budgets as $budget) { $data[$budget->id] = $budget->price; } return $data; }
public function getHome() { $key = cacheKey('home', Session::get('period')); if (Cache::has($key)) { $data = Cache::get($key); } else { $max = 0; $min = 1000000; $data = array('accounts' => array(), 'budgets' => array(), 'targets' => array()); // we need this list: $accounts = Auth::user()->accounts()->get(); foreach ($accounts as $a) { $account = array('id' => intval($a->id), 'name' => Crypt::decrypt($a->name), 'currentbalance' => $a->balance()); $account['header'] = $account['currentbalance'] < 0 ? array('style' => 'color:red;', 'class' => 'tt', 'title' => $account['name'] . ' has a balance below zero. Try to fix this.') : array(); $min = $account['currentbalance'] < $min ? $account['currentbalance'] : $min; $max = $account['currentbalance'] > $max ? $account['currentbalance'] : $max; $data['accounts'][] = $account; } $min = $min > 0 ? 0 : $min; $max = $max < 0 ? 0 : $max; $min = floor($min / 1000) * 1000; $max = ceil($max / 1000) * 1000; $sum = 0; foreach ($data['accounts'] as $index => $account) { $sum += $account['currentbalance']; } $data['acc_data']['sum'] = $sum; // now everything for budgets: $data['budgets'] = Budget::getHomeOverview(); // some extra budget data: $monthlyAmount = Setting::getSetting('monthlyAmount', Session::get('period')->format('Y-m-') . '01'); if (is_null($monthlyAmount)) { $monthlyAmount = intval(Setting::getSetting('defaultAmount')); } $data['budget_data']['amount'] = $monthlyAmount; $data['budget_data']['spent_outside'] = floatval(Auth::user()->transactions()->where('amount', '<', 0)->whereNull('budget_id')->where(DB::Raw('DATE_FORMAT(`date`,"%m-%Y")'), '=', Session::get('period')->format('m-Y'))->sum('amount')) * -1; // targets, cant make it better im afraid. $data['targets'] = Target::getHomeOverview(); Cache::put($key, $data, 2440); } // flash some warnings: if (Auth::user()->transactions()->count() == 0) { Session::flash('warning', 'There are no transactions saved yet. Create some to make this overview less boring (Create → New transaction).'); } if (count($data['budgets']) == 0) { Session::flash('warning', 'You don\'t have any budgets defined.'); } if (count($data['accounts']) == 0) { Session::flash('warning', 'You do not have any accounts added. You should do this first (Create → New account)'); } if (Holmes::isMobile()) { return View::make('mobile.home.home')->with('data', $data); } else { return View::make('home.home')->with('data', $data); } }
public function initialLoad() { $advertisings = Advertising::orderBy('order', 'asc')->get(); $budgets = Budget::orderBy('order', 'asc')->get(); $doctors = Doctor::with('speciality')->get(); $nav_menus = NavigationMenu::orderBy('order', 'asc')->get(); $promos = Promo::all(); $services = Service::orderBy('order', 'asc')->get(); $slider_images = SliderImage::all(); $specialities = Speciality::all(); return View::make('layouts.main', array('advertisings' => $advertisings, 'budgets' => $budgets, 'doctors' => $doctors, 'nav_menus' => $nav_menus, 'promos' => $promos, 'services' => $services, 'slider_images' => $slider_images, 'specialities' => $specialities)); }
/** * Загружает список статей бюджета * @param User $user * @param DateTime $startDate - дата начала текущего месяца * @throws myBudgetWrongStartDateException */ public function load(User $user, DateTime $startDate) { if ($startDate->format('d') !== '01') { throw new myBudgetWrongStartDateException(sprintf('Дата должна быть первым числом месяца, получена %s', $startDate->format('Y-m-d'))); } //получим операции за этот месяц - для подсчета текущего бюджета, //и за предыдущие - для подсчета среднего показателя //средний показатель рассчитываем по трем предыдущим месяцам $meanRateMonthsAmount = 3; $beginDate = date_sub(clone $startDate, new DateInterval("P" . $meanRateMonthsAmount . "M")); //дата конца - последнее число заданного месяца, т.е. "начало месяца + 1 месяц - 1 день" $endDate = date_sub(date_add(clone $startDate, new DateInterval("P1M")), new DateInterval("P1D")); //получим выборку операций за рассчитанный период $operations = new OperationCollection($user); $operations->setPeriodStartDate($beginDate)->setPeriodEndDate($endDate)->fill(); //получим бюджет на месяц (коллекцию статей бюджета на заданный месяц) $budget = new Budget(); $budget->fill($user, $startDate); $calculator = new BudgetArticleIncrementCalculator($startDate, $user->getCurrency(), $meanRateMonthsAmount); //TODO: всю логику подсчета можно вынести в отдельный калькулятор бюджета и тестить его уже модульно, //без привлечения базы, передавая готовые операции и статьи бюджета //по каждой операции определим ее вклад в соотв. статью бюджета или средний показатель foreach ($operations->getOperations() as $operation) { $category = $operation->getCategory(); // отсутствие категории -- штатная ситуация // например, перевод или неподтвежденная операция в календаре if ($category) { //определяем, к какой категории относится операция, и по ней определяем статью бюджета //категорию берем не напрямую из связи операции, а вычисляем для корректного учета переводов //если категория не запланирована, создается и возвращается пустая $currentBudgetArticle = $budget->getBudgetArticleByCategory($category); $increment = $calculator->calculate($operation); $increment->apply($currentBudgetArticle); } } //возвращаем уже заполненные категории return $budget->getBudgetArticles(); }
public function budgetCharts() { $budgets = Budget::get(); $BC = new BudgetController(); $date = new Carbon('today'); $count = 0; foreach ($budgets as $budget) { Auth::loginUsingId($budget->fireflyuser_id); // remove cached entry: $key = cacheKey('Budget', 'homeOverviewChart', $budget->id, $date); Cache::forget($key); $BC->homeOverviewChart($budget->id, $date); $count++; Auth::logout(); } return 'Regenerated ' . $count . ' budget charts.'; }
public function run() { Budget::create(['name' => 'Revisión General', 'description' => 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi vulputate neque ac tortor pulvinar, in ullamcorper nunc elementum. Donec vestibulum pellentesque nunc sit amet ullamcorper. Praesent eleifend laoreet turpis, vel suscipit ante scelerisque ultrices. Nunc eu suscipit lorem, et tempor nunc. In a dictum nisi, at hendrerit nisi. Curabitur nibh enim, congue at magna eget, fringilla elementum nunc. Cras semper felis ac massa tempor, at laoreet diam volutpat. Ut non metus egestas, hendrerit ipsum at, iaculis sapien. Phasellus nisl mi, laoreet quis vulputate a, viverra eu ante. Fusce velit lectus, tincidunt id sem quis, consequat dignissim ante. Suspendisse feugiat lorem eu interdum accumsan. Donec condimentum ut lectus sed accumsan. Cras in velit a lectus maximus accumsan sed non leo. ', 'image' => 'img/resources/budgets/budget1.jpg', 'price' => 350, 'order' => 1]); Budget::create(['name' => 'Curación', 'description' => 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi vulputate neque ac tortor pulvinar, in ullamcorper nunc elementum. Donec vestibulum pellentesque nunc sit amet ullamcorper. Praesent eleifend laoreet turpis, vel suscipit ante scelerisque ultrices. Nunc eu suscipit lorem, et tempor nunc. In a dictum nisi, at hendrerit nisi. Curabitur nibh enim, congue at magna eget, fringilla elementum nunc. Cras semper felis ac massa tempor, at laoreet diam volutpat. Ut non metus egestas, hendrerit ipsum at, iaculis sapien. Phasellus nisl mi, laoreet quis vulputate a, viverra eu ante. Fusce velit lectus, tincidunt id sem quis, consequat dignissim ante. Suspendisse feugiat lorem eu interdum accumsan. Donec condimentum ut lectus sed accumsan. Cras in velit a lectus maximus accumsan sed non leo. ', 'image' => 'img/resources/budgets/budget1.jpg', 'price' => 450, 'order' => 2]); Budget::create(['name' => 'Análisis', 'description' => 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi vulputate neque ac tortor pulvinar, in ullamcorper nunc elementum. Donec vestibulum pellentesque nunc sit amet ullamcorper. Praesent eleifend laoreet turpis, vel suscipit ante scelerisque ultrices. Nunc eu suscipit lorem, et tempor nunc. In a dictum nisi, at hendrerit nisi. Curabitur nibh enim, congue at magna eget, fringilla elementum nunc. Cras semper felis ac massa tempor, at laoreet diam volutpat. Ut non metus egestas, hendrerit ipsum at, iaculis sapien. Phasellus nisl mi, laoreet quis vulputate a, viverra eu ante. Fusce velit lectus, tincidunt id sem quis, consequat dignissim ante. Suspendisse feugiat lorem eu interdum accumsan. Donec condimentum ut lectus sed accumsan. Cras in velit a lectus maximus accumsan sed non leo. ', 'image' => 'img/resources/budgets/budget1.jpg', 'price' => 550, 'order' => 3]); }
// Purpose of file: // ---------------------------------------------------------------------- define('GLPI_ROOT', '..'); include GLPI_ROOT . "/inc/includes.php"; header("Content-Type: text/html; charset=UTF-8"); header_nocache(); if (!isset($_POST["id"])) { exit; } if (!isset($_REQUEST['glpi_tab'])) { exit; } if (!isset($_POST["withtemplate"])) { $_POST["withtemplate"] = ""; } $budget = new Budget(); if ($_POST['id'] > 0 && $budget->can($_POST['id'], 'r')) { switch ($_REQUEST['glpi_tab']) { case -1: $budget->showValuesByEntity(); $budget->showItems(); Document::showAssociated($budget); Link::showForItem('Budget', $_POST["id"]); Plugin::displayAction($budget, $_REQUEST['glpi_tab'], $_POST["withtemplate"]); break; case 2: $budget->showItems(); break; case 5: Document::showAssociated($budget); break;
public function addBudget(Budget $l) { $this->collBudgets[] = $l; $l->setBudgetChart($this); }
public static function install(Migration $migration) { global $DB; $table = getTableForItemType(__CLASS__); //Installation if (!TableExists($table) && !TableExists("glpi_plugin_order")) { $migration->displayMessage("Installing {$table}"); $query = "CREATE TABLE IF NOT EXISTS `glpi_plugin_order_orders` (\n `id` int(11) NOT NULL auto_increment,\n `entities_id` int(11) NOT NULL default '0',\n `is_template` tinyint(1) NOT NULL default '0',\n `template_name` varchar(255) collate utf8_unicode_ci default NULL,\n `is_recursive` tinyint(1) NOT NULL default '0',\n `name` varchar(255) collate utf8_unicode_ci default NULL,\n `num_order` varchar(255) collate utf8_unicode_ci default NULL,\n `budgets_id` int(11) NOT NULL default '0' COMMENT 'RELATION to glpi_budgets (id)',\n `plugin_order_ordertaxes_id` int(11) NOT NULL default '0' COMMENT 'RELATION to glpi_plugin_order_ordertaxes (id)',\n `plugin_order_orderpayments_id` int (11) NOT NULL default '0' COMMENT 'RELATION to glpi_plugin_order_orderpayments (id)',\n `order_date` date default NULL,\n `duedate` date default NULL,\n `deliverydate` date default NULL,\n `is_late` tinyint(1) NOT NULL default '0',\n `suppliers_id` int(11) NOT NULL default '0' COMMENT 'RELATION to glpi_suppliers (id)',\n `contacts_id` int(11) NOT NULL default '0' COMMENT 'RELATION to glpi_contacts (id)',\n `locations_id` int(11) NOT NULL default '0' COMMENT 'RELATION to glpi_locations (id)',\n `plugin_order_orderstates_id` int(11) NOT NULL default 1,\n `plugin_order_billstates_id` int(11) NOT NULL default 1,\n `port_price` float NOT NULL default 0,\n `comment` text collate utf8_unicode_ci,\n `notepad` longtext collate utf8_unicode_ci,\n `is_deleted` tinyint(1) NOT NULL default '0',\n `users_id` int(11) NOT NULL default '0',\n `groups_id` int(11) NOT NULL default '0',\n `users_id_delivery` int(11) NOT NULL default '0',\n `groups_id_delivery` int(11) NOT NULL default '0',\n `plugin_order_ordertypes_id` int (11) NOT NULL default '0' COMMENT 'RELATION to glpi_plugin_order_ordertypes (id)',\n `date_mod` datetime default NULL,\n `is_helpdesk_visible` tinyint(1) NOT NULL default '1',\n PRIMARY KEY (`id`),\n KEY `name` (`name`),\n KEY `entities_id` (`entities_id`),\n KEY `plugin_order_ordertaxes_id` (`plugin_order_ordertaxes_id`),\n KEY `plugin_order_orderpayments_id` (`plugin_order_orderpayments_id`),\n KEY `states_id` (`plugin_order_orderstates_id`),\n KEY `suppliers_id` (`suppliers_id`),\n KEY `contacts_id` (`contacts_id`),\n KEY `locations_id` (`locations_id`),\n KEY `is_late` (`locations_id`),\n KEY `is_template` (`is_template`),\n KEY `is_deleted` (`is_deleted`),\n KEY date_mod (date_mod)\n ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;"; $DB->query($query) or die($DB->error()); Crontask::Register(__CLASS__, 'computeLateOrders', HOUR_TIMESTAMP, array('param' => 24, 'mode' => CronTask::MODE_EXTERNAL)); } else { //Upgrade $migration->displayMessage("Upgrading {$table}"); if (TableExists('glpi_plugin_order')) { //Update to 1.1.0 $migration->addField('glpi_plugin_order', "port_price", "FLOAT NOT NULL default '0'"); $migration->addField('glpi_plugin_order', "taxes", "FLOAT NOT NULL default '0'"); if (FieldExists("glpi_plugin_order", "numordersupplier")) { foreach ($DB->request("glpi_plugin_order") as $data) { $query = "INSERT INTO `glpi_plugin_order_suppliers`\n (`ID`, `FK_order`, `numorder`, `numbill`) VALUES\n (NULL, '" . $data["ID"] . "', '" . $data["numordersupplier"] . "', '" . $data["numbill"] . "') "; $DB->query($query) or die($DB->error()); } } $migration->dropField('glpi_plugin_order', 'numordersupplier'); $migration->dropField('glpi_plugin_order', 'numbill'); $migration->migrationOneTable('glpi_plugin_order'); } //1.2.0 $domigration_itemtypes = false; if ($migration->renameTable("glpi_plugin_order", $table)) { $domigration_itemtypes = true; } $migration->changeField($table, "ID", "id", "int(11) NOT NULL AUTO_INCREMENT"); $migration->changeField($table, "FK_entities", "entities_id", "int(11) NOT NULL default 0"); $migration->changeField($table, "recursive", "is_recursive", "tinyint(1) NOT NULL default 0"); $migration->changeField($table, "name", "name", "varchar(255) collate utf8_unicode_ci default NULL"); $migration->changeField($table, "budget", "budgets_id", "int(11) NOT NULL default '0' COMMENT 'RELATION to glpi_budgets (id)'"); $migration->changeField($table, "numorder", "num_order", "varchar(255) collate utf8_unicode_ci default NULL"); $migration->changeField($table, "taxes", "plugin_order_ordertaxes_id", "int(11) NOT NULL default '0' COMMENT 'RELATION to glpi_plugin_order_ordertaxes (id)'"); $migration->changeField($table, "payment", "plugin_order_orderpayments_id", "int (11) NOT NULL default '0' COMMENT 'RELATION to glpi_plugin_order_orderpayments (id)'"); $migration->changeField($table, "date", "order_date", "date default NULL"); $migration->changeField($table, "FK_enterprise", "suppliers_id", "int(11) NOT NULL default '0' COMMENT 'RELATION to glpi_suppliers (id)'"); $migration->changeField($table, "FK_contact", "contacts_id", "int(11) NOT NULL default '0' COMMENT 'RELATION to glpi_contacts (id)'"); $migration->changeField($table, "location", "locations_id", "int(11) NOT NULL default '0' COMMENT 'RELATION to glpi_locations (id)'"); $migration->changeField($table, "status", "states_id", "int(11) NOT NULL default '0'"); $migration->changeField($table, "comment", "comment", "text collate utf8_unicode_ci"); $migration->changeField($table, "notes", "notepad", "longtext collate utf8_unicode_ci"); $migration->changeField($table, "deleted", "is_deleted", "tinyint(1) NOT NULL default '0'"); $migration->addKey($table, "name"); $migration->addKey($table, "entities_id"); $migration->addKey($table, "plugin_order_ordertaxes_id"); $migration->addKey($table, "plugin_order_orderpayments_id"); $migration->addKey($table, "states_id"); $migration->addKey($table, "suppliers_id"); $migration->addKey($table, "contacts_id"); $migration->addKey($table, "locations_id"); $migration->addKey($table, "is_deleted"); $migration->migrationOneTable($table); //Only migrate itemtypes when it's only necessary, otherwise it breaks upgrade procedure ! if ($domigration_itemtypes) { Plugin::migrateItemType(array(3150 => 'PluginOrderOrder'), array("glpi_bookmarks", "glpi_bookmarks_users", "glpi_displaypreferences", "glpi_documents_items", "glpi_infocoms", "glpi_logs", "glpi_tickets"), array()); } if (TableExists("glpi_plugin_order_budgets")) { //Manage budgets (here because class has been remove since 1.4.0) $migration->changeField("glpi_plugin_order_budgets", "ID", "id", " int(11) NOT NULL auto_increment"); $migration->changeField("glpi_plugin_order_budgets", "FK_entities", "entities_id", "int(11) NOT NULL default '0'"); $migration->changeField("glpi_plugin_order_budgets", "FK_budget", "budgets_id", "int(11) NOT NULL default '0'"); $migration->changeField("glpi_plugin_order_budgets", "comments", "comment", "text collate utf8_unicode_ci"); $migration->changeField("glpi_plugin_order_budgets", "deleted", "is_deleted", "tinyint(1) NOT NULL default '0'"); $migration->changeField("glpi_plugin_order_budgets", "startdate", "start_date", "date default NULL"); $migration->changeField("glpi_plugin_order_budgets", "enddate", "end_date", "date default NULL"); $migration->changeField("glpi_plugin_order_budgets", "value", "value", "float NOT NULL DEFAULT '0'"); $migration->addKey("glpi_plugin_order_budgets", "entities_id"); $migration->addKey("glpi_plugin_order_budgets", "is_deleted"); $migration->migrationOneTable("glpi_plugin_order_budgets"); Plugin::migrateItemType(array(3153 => 'PluginOrderBudget'), array("glpi_bookmarks", "glpi_bookmarks_users", "glpi_displaypreferences", "glpi_documents_items", "glpi_infocoms", "glpi_logs", "glpi_tickets"), array()); //Manage budgets migration before dropping the table $budget = new Budget(); $matchings = array('budgets_id' => 'id', 'name' => 'name', 'start_date' => 'begin_date', 'end_date' => 'end_date', 'value' => 'value', 'comment' => 'comment', 'entities_id' => 'entities_id', 'is_deleted' => 'is_deleted'); foreach (getAllDatasFromTable("glpi_plugin_order_budgets") as $data) { $tmp = array(); $id = false; foreach ($matchings as $old => $new) { if (!is_null($data[$old])) { $tmp[$new] = $data[$old]; } } $tmp['comment'] = Toolbox::addslashes_deep($tmp['comment']); //Budget already exists in the core: update it if ($budget->getFromDB($data['budgets_id'])) { $budget->update($tmp); $id = $tmp['id']; } else { //Budget doesn't exists in the core: create it unset($tmp['id']); $id = $budget->add($tmp); } } $DB->query("DROP TABLE `glpi_plugin_order_budgets`"); foreach (array('glpi_displaypreferences', 'glpi_documents_items', 'glpi_bookmarks', 'glpi_logs') as $t) { $DB->query("DELETE FROM `{$t}` WHERE `itemtype` = 'PluginOrderBudget'"); } } //1.3.0 $migration->addField($table, "plugin_order_ordertypes_id", "int (11) NOT NULL default '0' COMMENT 'RELATION to glpi_plugin_order_ordertypes (id)'"); $migration->migrationOneTable($table); //1.4.0 if ($migration->changeField("glpi_plugin_order_orders", "states_id", "plugin_order_orderstates_id", "int(11) NOT NULL default 1")) { $migration->migrationOneTable($table); $query = "UPDATE `glpi_plugin_order_orders` SET `plugin_order_orderstates_id`=`plugin_order_orderstates_id`+1"; $DB->query($query) or die($DB->error()); } $migration->addField($table, "duedate", "DATETIME NULL"); $migration->migrationOneTable($table); //1.5.0 if (TableExists("glpi_dropdown_plugin_order_status")) { $DB->query("DROP TABLE `glpi_dropdown_plugin_order_status`") or die($DB->error()); } if (TableExists("glpi_plugin_order_mailing")) { $DB->query("DROP TABLE IF EXISTS `glpi_plugin_order_mailing`;") or die($DB->error()); } $migration->addField($table, 'plugin_order_billstates_id', "int(11) NOT NULL default 0"); //1.5.2 $migration->addField($table, 'deliverydate', "DATETIME NULL"); $migration->addField($table, "is_late", "TINYINT(1) NOT NULL DEFAULT '0'"); $migration->addKey($table, "is_late"); if (!countElementsInTable('glpi_crontasks', "`name`='computeLateOrders'")) { Crontask::Register(__CLASS__, 'computeLateOrders', HOUR_TIMESTAMP, array('param' => 24, 'mode' => CronTask::MODE_EXTERNAL)); } $migration->migrationOneTable($table); if ($migration->addField($table, "is_template", "tinyint(1) NOT NULL DEFAULT 0")) { $migration->addField($table, "template_name", "VARCHAR(255) collate utf8_unicode_ci default NULL"); $migration->migrationOneTable($table); } $migration->addField($table, "users_id", "INT(11) NOT NULL DEFAULT '0'"); $migration->addField($table, "groups_id", "INT(11) NOT NULL DEFAULT '0'"); $migration->addField($table, "users_id_delivery", "INT(11) NOT NULL DEFAULT '0'"); $migration->addField($table, "groups_id_delivery", "INT(11) NOT NULL DEFAULT '0'"); //1.7.0 $migration->addField($table, "date_mod", "datetime"); $migration->addKey($table, "date_mod"); //1.7.2 $migration->addField($table, "is_helpdesk_visible", "bool", array('value' => 1)); $migration->migrationOneTable($table); //Displayprefs $prefs = array(1 => 1, 2 => 2, 4 => 4, 5 => 5, 6 => 6, 7 => 7, 10 => 10); foreach ($prefs as $num => $rank) { if (!countElementsInTable("glpi_displaypreferences", "`itemtype`='PluginOrderOrder' AND `num`='{$num}'\n AND `users_id`='0'")) { $DB->query("INSERT INTO glpi_displaypreferences\n VALUES (NULL,'PluginOrderOrder','{$num}','{$rank}','0');"); } } //Remove unused notifications $notification = new Notification(); $notification->deleteByCriteria("`itemtype`='PluginOrderOrder_Item'"); } }
public function newBudget() { $budget = new Budget(); $budget->name = Input::get('name'); $budget->amount = floatval(Input::get('amount')); $budget->fireflyuser_id = Auth::user()->id; $budget->date = Session::get('period')->format('Y-m') . '-01'; $validator = Validator::make($budget->toArray(), Budget::$rules); if ($validator->fails()) { Log::error('Could not create Budget for user ' . Auth::user()->email . ': ' . print_r($validator->messages()->all(), true) . ' Budget: ' . print_r($budget, true)); return Redirect::to('/home/budget/add')->withErrors($validator)->withInput(); } else { $budget->name = Crypt::encrypt($budget->name); $budget->save(); return Redirect::to('/home'); } }
/** * Input multiple data to database */ public function actionEntry() { $model = new Package(); $lastDipa = Dipa::model()->find(array('order' => 'id DESC')); $lastDipaId = $lastDipa->id; if (isset($_POST['code'])) { if ($lastDipa) { $total = count($_POST['code']); for ($i = 0; $i < $total; $i++) { if ($_POST['code'][$i] != NULL && $_POST['ppk_code'][$i] != NULL && $_POST['city_code'][$i] != NULL) { $code = $_POST['code'][$i]; //Check existed record $record = Package::model()->findByAttributes(array('code' => $code)); if ($record) { $budgets = Budget::model()->findAllByAttributes(array('subcomponent_code' => "{$record->code}", 'dipa_id' => "{$lastDipaId}")); $record->ppk_code = $_POST['ppk_code'][$i]; $record->city_code = $_POST['city_code'][$i]; $record->province_code = City::model()->findByAttributes(array('code' => "{$record->city_code}"))->province_code; if ($budgets) { foreach ($budgets as $budgetData) { $pAccount = PackageAccount::model()->findByAttributes(array('code' => "{$budgetData->code}")); if ($pAccount) { $pAccount->limit = $budgetData->total_budget_limit; $pAccount->ppk_code = $record->ppk_code; $pAccount->province_code = $record->province_code; $pAccount->city_code = $record->city_code; $pAccount->update(); } } } $record->update(); } else { $data = new Package(); $data->code = $_POST['code'][$i]; $budget = Budget::model()->findByAttributes(array('subcomponent_code' => $_POST['code'][$i]), array('order' => 'dipa_id DESC')); if ($budget) { $data->satker_code = "{$budget->satker_code}"; $data->activity_code = "{$budget->activity_code}"; $data->output_code = "{$budget->output_code}"; $data->suboutput_code = "{$budget->suboutput_code}"; $data->name = $budget->subcomponentCode->name; $data->component_code = "{$budget->component_code}"; $data->ppk_code = $_POST['ppk_code'][$i]; $data->city_code = $_POST['city_code'][$i]; $data->province_code = City::model()->findByAttributes(array('code' => "{$data->city_code}"))->province_code; $budgets = Budget::model()->findAllByAttributes(array('subcomponent_code' => "{$data->code}", 'dipa_id' => "{$lastDipaId}")); if ($budgets) { foreach ($budgets as $dataBudget) { $paModel = new PackageAccount(); $paModel->code = "{$dataBudget->code}"; $paModel->satker_code = "{$dataBudget->satker_code}"; $paModel->activity_code = "{$dataBudget->activity_code}"; $paModel->output_code = "{$dataBudget->output_code}"; $paModel->suboutput_code = "{$dataBudget->suboutput_code}"; $paModel->component_code = "{$dataBudget->component_code}"; $paModel->package_code = "{$dataBudget->subcomponent_code}"; $paModel->account_code = "{$dataBudget->account_code}"; $paModel->ppk_code = "{$data->ppk_code}"; $paModel->province_code = "{$data->province_code}"; $paModel->city_code = "{$data->city_code}"; $paModel->limit = "{$dataBudget->total_budget_limit}"; $paModel->save(); } } $data->save(); } else { Yii::app()->user->setFlash('notice', 'Data DIPA belum diinput dengan lengkap. Beberapa data informasi tambahan gagal ditambahkan.'); $this->redirect(array('index')); } } } else { Yii::app()->user->setFlash('error', "Mohon isikan data secara lengkap."); $this->redirect(array('entry')); } } } else { Yii::app()->user->setFlash('error', 'Data DIPA/POK belum diinput.'); $this->redirect(array('index')); } Yii::app()->user->setFlash('success', 'Data berhasil disimpan.'); $this->redirect(array('index')); } $this->render('entry', array('model' => $model)); }
You should have received a copy of the GNU General Public License along with GLPI. If not, see <http://www.gnu.org/licenses/>. -------------------------------------------------------------------------- */ /** @file * @brief */ include '../inc/includes.php'; Session::checkRight("budget", READ); if (empty($_GET["id"])) { $_GET["id"] = ''; } if (!isset($_GET["withtemplate"])) { $_GET["withtemplate"] = ''; } $budget = new Budget(); if (isset($_POST["add"])) { $budget->check(-1, CREATE, $_POST); if ($newID = $budget->add($_POST)) { Event::log($newID, "budget", 4, "financial", sprintf(__('%1$s adds the item %2$s'), $_SESSION["glpiname"], $_POST["name"])); if ($_SESSION['glpibackcreated']) { Html::redirect($budget->getFormURL() . "?id=" . $newID); } } Html::back(); } else { if (isset($_POST["delete"])) { $budget->check($_POST["id"], DELETE); if ($budget->delete($_POST)) { Event::log($_POST["id"], "budget", 4, "financial", sprintf(__('%s deletes an item'), $_SESSION["glpiname"])); }
$t1 = microtime(true); $pdo->beginTransaction(); $t2 = microtime(true); $ps = NULL; for ($i = 0; $i < count($accountIds); $i++) { $accountId = $accountIds[$i]; $newBudget = $newBudgets[$i]; $budgetId = $budgetIds[$i]; $defaultBudget = $defaultBudgets[$i]; $comments = $budgetComments[$i]; if (empty($budgetId)) { // not editing, so set to -1 $budgetId = -1; } // update budget $budget = new Budget(); $budget->Init_budget($accountId, $budgetDate, $newBudget, $comments, $budgetId); $error = $budget->Save($pdo, $ps); if ($error != '') { break; } // update default budget $account = new Account(); $account->Init_for_budget_update($accountId, $defaultBudget); $error = $account->Update_budget_default($pdo, $ps); if ($error != '') { break; } } if ($error == '') { $t3 = microtime(true);
$category = Factory::getView(new CategoryKey($categoryId)); $budget->setUser($user); $budget->setActive(TRUE); $budget->setAmount($budgetedAmount); $budget->setCategory($category); $transaction->commit(); } elseif ($action === "remove") { $key = htmlentities($_POST['key']); $transaction = new Transaction(new MySqlDB()); $transaction->start(); $budgetItem = Factory::getView(new BudgetKey($key)); $budgetItem->setActive(0); $transaction->commit(); } } $budgets = Budget::getOptions(array("USER_ID" => $user->getId(), "ACTIVE" => 1)); $spent = array(); $budgetLeft = array(); foreach ($budgets as $key => $item) { $activities = Activity::getOptions(array("USER_ID" => $user->getId(), "CATEGORY_ID" => $item['category_id'], "TRANSACTION_DATE_START" => Date::firstOfMonth())); $value = 0; foreach ($activities as $activityKey => $activityItem) { $value += $activityItem['amount']; } $spent[$key] = 0 - $value; $budgetLeft[$key] = $item['amount'] + $value; } $smarty->assign('spent', $spent); $smarty->assign('budgets', $budgets); $smarty->assign('budgetLeft', $budgetLeft); if ($fullPage) {
/** Generate bigdump : generate items for an entity * * @param $ID_entity entity ID **/ function generate_entity($ID_entity) { global $MAX, $DB, $percent, $FIRST, $LAST, $MAX_KBITEMS_BY_CAT, $MAX_DISK, $DOCUMENTS, $NET_PORT, $NET_LOC; regenerateTreeCompleteName("glpi_entities"); $current_year = date("Y"); // DOMAIN $items = array("SP2MI", "CAMPUS"," IUT86", "PRESIDENCE", "CEAT", "D'omaine"); $dp = new Domain(); $FIRST["domain"] = getMaxItem("glpi_domains")+1; for ($i=0 ; $i<$MAX['domain'] ; $i++) { if (isset($items[$i])) { $val = $items[$i]; } else { $val = "domain $ID_entity '$i"; } $dp->add(toolbox::addslashes_deep(array('name' => $val, 'entities_id' => $ID_entity, 'is_recursive' => 1, 'comment' => "comment $val"))); } $LAST["domain"] = getMaxItem("glpi_domains"); // STATUS $items = array("Reparation", "En stock", "En fonction", "Retour SAV", "En attente d'"); $dp = new State(); $FIRST["state"] = getMaxItem("glpi_states")+1; for ($i=0 ; $i<$MAX['state'] ; $i++) { if (isset($items[$i])) { $val = $items[$i]; } else { $val = "State $ID_entity '$i"; } $state_id = $dp->add(toolbox::addslashes_deep(array('name' => $val, 'entities_id' => $ID_entity, 'is_recursive' => 1, 'comment' => "comment $val"))); // generate sub status for ($j=0 ; $j<$MAX['state'] ; $j++) { $val2 = "Sub $val $j"; $dp->add(toolbox::addslashes_deep(array('name' => $val2, 'entities_id' => $ID_entity, 'is_recursive' => 1, 'states_id' => $state_id, 'comment' => "comment $val"))); } } $LAST["state"] = getMaxItem("glpi_states"); // glpi_groups $FIRST["groups"] = getMaxItem("glpi_groups")+1; $group = new Group(); for ($i=0 ; $i<$MAX['groups'] ; $i++) { $gID = $group->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'name' => "group d'$i", 'comment' => "comment group d'$i", 'is_assign' => 0))); // Generate sub group for ($j=0 ; $j<$MAX['groups'] ; $j++) { $group->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'name' => "subgroup d'$j", 'comment' => "comment subgroup d'$j of group $i", 'groups_id' => $gID, 'is_assign' => 0))); } } $LAST["groups"] = getMaxItem("glpi_groups"); $FIRST["techgroups"] = $LAST["groups"]+1; for ($i=0 ; $i<$MAX['groups'] ; $i++) { $group->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'name' => "tech group d'$i", 'comment' => "comment tech group d'$i"))); } $LAST["techgroups"] = getMaxItem("glpi_groups"); regenerateTreeCompleteName("glpi_groups"); // glpi_users $FIRST["users_sadmin"] = getMaxItem("glpi_users")+1; $user = new User(); $gu = new Group_User(); for ($i=0 ; $i<$MAX['users_sadmin'] ; $i++) { $users_id = $user->add(toolbox::addslashes_deep( array('name' => "sadmin$i-$ID_entity", 'password' => "sadmin'$i", 'password2' => "sadmin'$i", 'phone' => "tel $i", 'phone2' => "tel2 $i", 'mobile' => "mobile $i", 'realname' => "sadmin '$i name", 'firstname' => "sadmin '$i firstname", 'comment' => "comment' $i", 'usertitles_id' => mt_rand(0,$MAX['user_title']), 'usercategories_id' => mt_rand(0,$MAX['user_type']), '_profiles_id' => 4, '_entities_id' => $ID_entity, '_is_recursive' => 1 ))); $gu->add(array('users_id' => $users_id, 'groups_id' => mt_rand($FIRST['groups'], $LAST['groups']))); $gu->add(array('users_id' => $users_id, 'groups_id' => mt_rand($FIRST['techgroups'], $LAST['techgroups']))); } $LAST["users_sadmin"] = getMaxItem("glpi_users"); $FIRST["users_admin"] = getMaxItem("glpi_users")+1; for ($i=0 ; $i<$MAX['users_admin'] ; $i++) { $users_id = $user->add(toolbox::addslashes_deep( array('name' => "admin$i-$ID_entity", 'password' => "admin'$i", 'password2' => "admin'$i", 'phone' => "tel $i", 'phone2' => "tel2 $i", 'mobile' => "mobile $i", 'realname' => "admin$i 'name", 'firstname' => "admin$i 'firstname", 'comment' => "comment '$i", 'usertitles_id' => mt_rand(0,$MAX['user_title']), 'usercategories_id' => mt_rand(0,$MAX['user_type']), '_profiles_id' => 3, '_entities_id' => $ID_entity, '_is_recursive' => 1))); $gu->add(array('users_id' => $users_id, 'groups_id' => mt_rand($FIRST['groups'], $LAST['groups']), 'is_manager' => 1, 'is_delegate' => 1)); $gu->add(array('users_id' => $users_id, 'groups_id' => mt_rand($FIRST['techgroups'], $LAST['techgroups']), 'is_manager' => 1, 'is_delegate' => 1)); } $LAST["users_admin"] = getMaxItem("glpi_users"); $FIRST["users_normal"] = getMaxItem("glpi_users")+1; for ($i=0 ; $i<$MAX['users_normal'] ; $i++) { $users_id = $user->add(toolbox::addslashes_deep( array('name' => "normal$i-$ID_entity", 'password' => "normal'$i", 'password2' => "normal'$i", 'phone' => "tel $i", 'phone2' => "tel2 $i", 'mobile' => "mobile $i", 'realname' => "normal$i 'name", 'firstname' => "normal$i 'firstname", 'comment' => "comment '$i", 'usertitles_id' => mt_rand(0,$MAX['user_title']), 'usercategories_id' => mt_rand(0,$MAX['user_type']), '_profiles_id' => 2, '_entities_id' => $ID_entity, '_is_recursive' => 1))); $gu->add(array('users_id' => $users_id, 'groups_id' => mt_rand($FIRST['groups'], $LAST['groups']))); $gu->add(array('users_id' => $users_id, 'groups_id' => mt_rand($FIRST['techgroups'], $LAST['techgroups']))); } $LAST["users_normal"] = getMaxItem("glpi_users"); $FIRST["users_postonly"] = getMaxItem("glpi_users")+1; for ($i=0 ; $i<$MAX['users_postonly'] ; $i++) { $users_id = $user->add(toolbox::addslashes_deep( array('name' => "postonly$i-$ID_entity", 'password' => "postonly'$i", 'password2' => "postonly'$i", 'phone' => "tel $i", 'phone2' => "tel2 $i", 'mobile' => "mobile $i", 'realname' => "postonly$i 'name", 'firstname' => "postonly$i 'firstname", 'comment' => "comment' $i", 'usertitles_id' => mt_rand(0,$MAX['user_title']), 'usercategories_id' => mt_rand(0,$MAX['user_type']), '_profiles_id' => 1, '_entities_id' => $ID_entity, '_is_recursive' => 1))); $gu->add(array('users_id' => $users_id, 'groups_id' => mt_rand($FIRST['groups'], $LAST['groups']))); } $LAST["users_postonly"] = getMaxItem("glpi_users"); $FIRST["kbcategories"] = getMaxItem("glpi_knowbaseitemcategories")+1; $kbc = new KnowbaseItemCategory(); for ($i=0 ; $i<max(1,pow($MAX['kbcategories'],1/3)) ; $i++) { $newID = $kbc->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => 1, 'name' => "entity ' categorie $i", 'comment' => "comment ' categorie $i"))); for ($j=0 ; $j<mt_rand(0,pow($MAX['kbcategories'],1/2)) ; $j++) { $newID2 = $kbc->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => 1, 'name' => "entity s-categorie '$j", 'comment' => "comment s-categorie '$j", 'knowbaseitemcategories_id' => $newID))); for ($k=0 ; $k<mt_rand(0,pow($MAX['kbcategories'],1/2)) ; $k++) { $newID2 = $kbc->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => 1, 'name' => "entity ss-categorie' $k", 'comment' => "comment ss-categorie' $k", 'knowbaseitemcategories_id' => $newID2))); } } } $query = "OPTIMIZE TABLE `glpi_knowbaseitemcategories`"; $DB->query($query) or die("PB REQUETE ".$query); regenerateTreeCompleteName("glpi_knowbaseitemcategories"); $LAST["kbcategories"] = getMaxItem("glpi_knowbaseitemcategories"); // LOCATIONS $added = 0; $FIRST["locations"] = getMaxItem("glpi_locations")+1; $loc = new Location(); for ($i=0 ; $i<pow($MAX['locations'],1/5)&&$added<$MAX['locations'] ; $i++) { $added++; $newID = $loc->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => 1, 'name' => "location' $i", 'comment' => "comment 'location $i", 'building' => "building $i"))); for ($j=0 ; $j<mt_rand(0,pow($MAX['locations'],1/4))&&$added<$MAX['locations'] ; $j++) { $added++; $newID2 = $loc->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => 1, 'name' => "s-location '$j", 'comment' => "comment s-location '$j", 'building' => "building $i", 'room' => "stage '$j", 'locations_id' => $newID))); for ($k=0 ; $k<mt_rand(0,pow($MAX['locations'],1/4))&&$added<$MAX['locations'] ; $k++) { $added++; $newID3 = $loc->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => 1, 'name' => "ss-location '$k", 'comment' => "comment ss-location' $k", 'building' => "building $i", 'room' => "part' $k", 'locations_id' => $newID2))); for ($l=0 ; $l<mt_rand(0,pow($MAX['locations'],1/4))&&$added<$MAX['locations'] ; $l++) { $added++; $newID4 = $loc->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => 1, 'name' => "sss-location' $l", 'comment' => "comment sss-location' $l", 'building' => "building $i", 'room' => "room' $l", 'locations_id' => $newID3))); for ($m=0 ; $m<mt_rand(0,pow($MAX['locations'],1/4))&&$added<$MAX['locations'] ; $m++) { $added++; $newID5 = $loc->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => 1, 'name' => "ssss-location' $m", 'comment' => "comment ssss-location' $m", 'building' => "building $i", 'room' => "room' $l-$m", 'locations_id' => $newID4))); } } } } } $query = "OPTIMIZE TABLE `glpi_locations`"; $DB->query($query) or die("PB REQUETE ".$query); regenerateTreeCompleteName("glpi_locations"); $LAST["locations"]=getMaxItem("glpi_locations"); // Task categories $added = 0; $FIRST["taskcategory"] = getMaxItem("glpi_taskcategories")+1; $tc = new TaskCategory(); for ($i=0 ; $i<pow($MAX['taskcategory'],1/5)&&$added<$MAX['taskcategory'] ; $i++) { $added++; $newID = $tc->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => 1, 'name' => "ent$ID_entity taskcategory' $i", 'comment' => "comment ent$ID_entity taskcategory' $i"))); for ($j=0 ; $j<mt_rand(0,pow($MAX['locations'],1/4))&&$added<$MAX['locations'] ; $j++) { $newID2 = $tc->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => 1, 'name' => "ent$ID_entity taskcategory' $i", 'comment' => "comment ent$ID_entity taskcategory' $i", 'taskcategories_id' => $newID))); $added++; } } $query = "OPTIMIZE TABLE `glpi_taskcategories`"; $DB->query($query) or die("PB REQUETE ".$query); regenerateTreeCompleteName("glpi_taskcategories"); $LAST["taskcategory"] = getMaxItem("glpi_taskcategories"); $ic = new ItilCategory(); // Specific ticket categories $newID = $ic->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => 1, 'name' => "category for entity' $ID_entity", 'comment' => "comment category for entity' $ID_entity", 'users_id' => mt_rand($FIRST['users_sadmin'],$LAST['users_admin']), 'groups_id' => mt_rand($FIRST['techgroups'],$LAST['techgroups']), 'tickettemplates_id_incident' => 1, 'tickettemplates_id_demand' => 1))); for ($i=0 ; $i<max(1,pow($MAX['tracking_category'],1/3)) ; $i++) { $ic->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => 1, 'name' => "scategory for entity' $ID_entity", 'comment' => "comment scategory for entity' $ID_entity", 'users_id' => mt_rand($FIRST['users_sadmin'], $LAST['users_admin']), 'groups_id' => mt_rand($FIRST['techgroups'], $LAST['techgroups']), 'tickettemplates_id_incident' => 1, 'tickettemplates_id_demand' => 1, 'itilcategories_id' => $newID))); } regenerateTreeCompleteName("glpi_itilcategories"); $FIRST["solutiontypes"] = getMaxItem("glpi_solutiontypes")+1; $items = array("d'après KB"); $st = new SolutionType(); for ($i=0 ; $i<$MAX['solutiontypes'] ; $i++) { if (isset($items[$i])) { $val = $items[$i]; } else { $val = "type de solution ' $i"; } $st->add(toolbox::addslashes_deep(array('name' => $val, 'comment' => "comment $val", 'entities_id' => $ID_entity, 'is_recursive' => 1))); } $LAST["solutiontypes"] = getMaxItem("glpi_solutiontypes"); $FIRST["solutiontemplates"] = getMaxItem("glpi_solutiontemplates")+1; $nb_items = mt_rand(0,$MAX['solutiontemplates']); $st = new SolutionTemplate(); for ($i=0 ; $i<$nb_items ; $i++) { $st-> add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => 1, 'name' => "solution' $i-$ID_entity", 'content' => "content solution' $i-$ID_entity", 'solutiontypes_id' => mt_rand(0,$MAX['solutiontypes']), 'comment' => "comment solution' $i-$ID_entity"))); } $LAST["solutiontemplates"] = getMaxItem("glpi_solutiontemplates"); // Add Specific questions $k = 0; $FIRST["kbitems"] = getMaxItem("glpi_knowbaseitems")+1; $ki = new KnowbaseItem(); $eki = new Entity_KnowbaseItem(); for ($i=$FIRST['kbcategories'] ; $i<=$LAST['kbcategories'] ; $i++) { $nb = mt_rand(0,$MAX_KBITEMS_BY_CAT); for ($j=0 ; $j<$nb ; $j++) { $k++; $newID = $ki->add(toolbox::addslashes_deep( array('knowbaseitemcategories_id' => $i, 'name' => "Entity' $ID_entity Question $k", 'answer' => "Answer' $k".Toolbox::getRandomString(50), 'is_faq' => mt_rand(0,1), 'users_id' => mt_rand($FIRST['users_sadmin'], $LAST['users_admin'])))); $eki->add(array('entities_id' => $ID_entity, 'knowbaseitems_id' => $newID, 'is_recursive' => 0)); } } // Add global questions for ($i=$FIRST['kbcategories'] ; $i<=$LAST['kbcategories'] ; $i++) { $nb = mt_rand(0,$MAX_KBITEMS_BY_CAT); for ($j=0 ; $j<$nb ; $j++) { $k++; $newID = $ki->add(toolbox::addslashes_deep( array('knowbaseitemcategories_id' => $i, 'name' => "Entity' $ID_entity Recursive Question $k", 'answer' => "Answer' $k".Toolbox::getRandomString(50), 'is_faq' => mt_rand(0,1), 'users_id' => mt_rand($FIRST['users_sadmin'], $LAST['users_admin'])))); $eki->add(array('entities_id' => $ID_entity, 'knowbaseitems_id' => $newID, 'is_recursive' => 1)); } } $LAST["kbitems"] = getMaxItem("glpi_knowbaseitems"); // Ajout documents specific $FIRST["document"] = getMaxItem("glpi_documents")+1; $doc = new Document(); for ($i=0 ; $i<$MAX['document'] ; $i++) { $link = ""; if (mt_rand(0,100)<50) { $link = "http://linktodoc/doc$i"; } $docID = $doc->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => 0, 'name' => "document' $i-$ID_entity", 'documentcategories_id' => mt_rand(1,$MAX['rubdocs']), 'comment' => "commen't $i", 'link' => $link, 'notepad' => "notes document' $i"))); $DOCUMENTS[$docID] = $ID_entity."-0"; } // Global ones for ($i=0 ; $i<$MAX['document']/2 ; $i++) { $link = ""; if (mt_rand(0,100)<50) { $link = "http://linktodoc/doc$i"; } $docID = $doc->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => 1, 'name' => "Recursive document' $i-$ID_entity", 'documentcategories_id' => mt_rand(1,$MAX['rubdocs']), 'comment' => "comment' $i", 'link' => $link, 'notepad' => "notes document' $i"))); $DOCUMENTS[$docID] = $ID_entity."-1"; } $LAST["document"] = getMaxItem("glpi_documents"); // Ajout budgets specific $FIRST["budget"] = getMaxItem("glpi_budgets")+1; $b = new Budget(); for ($i=0 ; $i<$MAX['budget'] ; $i++) { $date1 = strtotime(mt_rand(2000,$current_year)."-".mt_rand(1,12)."-".mt_rand(1,28)); $date2 = $date1+MONTH_TIMESTAMP*12*mt_rand(1,4); // + entre 1 et 4 ans $b->add(toolbox::addslashes_deep( array('name' => "budget' $i-$ID_entity", 'entities_id' => $ID_entity, 'is_recusive' => 0, 'comment' => "comment' $i-$ID_entity", 'begin_date' => date("Y-m-d",intval($date1)), 'end_date' => date("Y-m-d",intval($date2))))); } $LAST["budget"] = getMaxItem("glpi_budgets"); // GLobal ones for ($i=0 ; $i<$MAX['document']/2 ; $i++) { $date1 = strtotime(mt_rand(2000,$current_year)."-".mt_rand(1,12)."-".mt_rand(1,28)); $date2 = $date1+MONTH_TIMESTAMP*12*mt_rand(1,4); // + entre 1 et 4 ans $b->add(toolbox::addslashes_deep( array('name' => "Recursive budget' $i-$ID_entity", 'entities_id' => $ID_entity, 'is_recusive' => 1, 'comment' => "comment' $i-$ID_entity", 'begin_date' => date("Y-m-d",intval($date1)), 'end_date' => date("Y-m-d",intval($date2))))); } $LAST["document"] = getMaxItem("glpi_documents"); // glpi_suppliers $items = array("DELL", "IBM", "ACER", "Microsoft", "Epson", "Xerox", "Hewlett Packard", "Nikon", "Targus", "LG", "Samsung", "Lexmark"); $FIRST["enterprises"] = getMaxItem("glpi_suppliers")+1; $ent = new Supplier(); // Global ones for ($i=0 ; $i<$MAX['enterprises']/2 ; $i++) { if (isset($items[$i])) { $val = "Recursive ".$items[$i]; } else { $val = "Recursive enterprise_".$i."_ID_entity"; } $entID = $ent->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => 1, 'name' => "Recursive' $val-$ID_entity", 'suppliertypes_id' => mt_rand(1,$MAX['enttype']), 'address' => "address' $i", 'postcode' => "postcode $i", 'town' => "town' $i", 'state' => "state' $i", 'country' => "country $i", 'website' => "http://www.$val.com/", 'fax' => "fax $i", 'email' => "info@ent$i.com", 'notepad' => "notes enterprises' $i"))); addDocuments('Supplier', $entID); } // Specific ones for ($i=0 ; $i<$MAX['enterprises'] ; $i++) { if (isset($items[$i])) { $val = $items[$i]; } else { $val = "enterprise_".$i."_ID_entity"; } $entID = $ent->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => 0, 'name' => "'$val-$ID_entity", 'suppliertypes_id' => mt_rand(1,$MAX['enttype']), 'address' => "address' $i", 'postcode' => "postcode $i", 'town' => "town' $i", 'state' => "state' $i", 'country' => "country $i", 'website' => "http://www.$val.com/", 'fax' => "fax $i", 'email' => "info@ent$i.com", 'notepad' => "notes supplier' $i", 'comment' => "comment supplier' $i"))); addDocuments('Supplier', $entID); } $LAST["enterprises"] = getMaxItem("glpi_suppliers"); // Ajout contracts $FIRST["contract"] = getMaxItem("glpi_contracts")+1; $c = new Contract(); $cs = new Contract_Supplier(); $cc = new ContractCost(); // Specific for ($i=0 ; $i<$MAX['contract'] ; $i++) { $date = mt_rand(2000,$current_year)."-".mt_rand(1,12)."-".mt_rand(1,28); $contractID = $c->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => 0, 'name' => "contract' $i-$ID_entity", 'num' => "num' $i", 'contracttypes_id' => mt_rand(1,$MAX['contract_type']), 'begin_date' => $date, 'duration' => mt_rand(1,36), 'notice' => mt_rand(1,3), 'periodicity' => mt_rand(1,36), 'billing' => mt_rand(1,36), 'comment' => "comment' $i", 'accounting_number' => "compta num' $i", 'renewal' => 1))); addDocuments('Contract', $contractID); // Add an enterprise $cs->add(array('contracts_id' => $contractID, 'suppliers_id' => mt_rand($FIRST["enterprises"], $LAST["enterprises"]))); // Add a cost $cc->add(toolbox::addslashes_deep( array('contracts_id' => $contractID, 'cost' => mt_rand(100,10000), 'name' => "Initial 'cost", 'begin_date' => $date, 'budgets_id' => mt_rand($FIRST['budget'], $LAST['budget'])))); } for ($i=0 ; $i<$MAX['contract']/2 ; $i++) { $date = mt_rand(2000,$current_year)."-".mt_rand(1,12)."-".mt_rand(1,28); $contractID = $c->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => 1, 'name' => "Recursive contract' $i-$ID_entity", 'num' => "num' $i", 'cost' => mt_rand(100,10000), 'contracttypes_id' => mt_rand(1,$MAX['contract_type']), 'begin_date' => $date, 'duration' => mt_rand(1,36), 'notice' => mt_rand(1,3), 'periodicity' => mt_rand(1,36), 'billing' => mt_rand(1,36), 'comment' => "comment' $i", 'accounting_number' => "compta num' $i", 'renewal' => 1))); addDocuments('Contract', $contractID); // Add an enterprise $cs->add(array('contracts_id' => $contractID, 'suppliers_id' => mt_rand($FIRST["enterprises"], $LAST["enterprises"]))); } $LAST["contract"] = getMaxItem("glpi_contracts"); // Ajout contacts $prenoms = array("Jean", "John", "Louis", "Pierre", "Auguste", "Albert", "Julien", "Guillaume", "Bruno", "Maurice", "Francois", "Laurent", "Richard", "Henri", "Clement", "d'avy"); $noms = array("Dupont", "Smith", "Durand", "Martin", "Dubois", "Dufour", "Dupin", "Duval", "Petit", "Grange", "Bernard", "Bonnet", "Richard", "Leroy", "Dumont", "Fontaine", "d'orleans"); $FIRST["contacts"] = getMaxItem("glpi_contacts")+1; $c = new Contact(); $cs = new Contact_Supplier(); for ($i=0 ; $i<$MAX['contacts'] ; $i++) { if (isset($noms[$i])) { $val = $noms[$i]; } else { $val = "name $i"; } if (isset($prenoms[$i])) { $val2 = $prenoms[$i]; } else { $val2 = "firstname $i"; } $contactID = $c->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => 0, 'name' => "$val-$ID_entity", 'firstname' => $val2, 'contacttypes_id' => mt_rand(1,$MAX['contact_type']), 'usertitles_id' => mt_rand(0,$MAX['user_title']), 'phone' => "phone $i", 'phone2' => "phone2 $i", 'mobile' => "mobile $i", 'fax' => "fax $i", 'email' => "email $i", 'address' => "address' $i", 'postcode' => "postcode $i", 'town' => "town' $i", 'state' => "state' $i", 'country' => "country $i", 'comment' => "Comment' $i"))); // Link with enterprise $cs->add(array('contacts_id' => $contactID, 'suppliers_id' => mt_rand($FIRST['enterprises'],$LAST['enterprises']))); } for ($i=0 ; $i<$MAX['contacts']/2 ; $i++) { if (isset($items[$i])) { $val = "Recursive ".$items[$i]; } else { $val = "Recursive contact $i"; } $contactID = $c->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => 0, 'name' => "$val'-$ID_entity", 'contacttypes_id' => mt_rand(1,$MAX['contact_type']), 'usertitles_id' => mt_rand(0,$MAX['user_title']), 'phone' => "phone $i", 'phone2' => "phone2 $i", 'mobile' => "mobile $i", 'fax' => "fax $i", 'email' => "email $i", 'address' => "address' $i", 'postcode' => "postcode $i", 'town' => "town' $i", 'state' => "state' $i", 'country' => "country $i", 'comment' => "Comment' $i"))); // Link with enterprise $cs->add(array('contacts_id' => $contactID, 'suppliers_id' => mt_rand($FIRST['enterprises'],$LAST['enterprises']))); } $LAST["contacts"] = getMaxItem("glpi_contacts"); // TYPE DE CONSOMMABLES $FIRST["type_of_consumables"] = getMaxItem("glpi_consumableitems")+1; $ci = new Consumableitem(); for ($i=0 ; $i<$MAX['type_of_consumables'] ; $i++) { $consID = $ci->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => mt_rand(0,1), 'name' => "consumable type' $i", 'ref' => "ref d' $i", 'locations_id' => mt_rand($FIRST["locations"], $LAST['locations']), 'consumableitemtypes_id' => mt_rand(0,$MAX['consumable_type']), 'manufacturers_id' => mt_rand(1,$MAX['manufacturer']), 'users_id_tech' => mt_rand($FIRST['users_sadmin'], $LAST['users_admin']), 'groups_id_tech' => mt_rand($FIRST["groups"], $LAST["groups"]), 'comment' => "comment' $i", 'notepad' => "notes consumableitem' $i", 'alarm_threshold' => mt_rand(0,10)))); addDocuments('ConsumableItem', $consID); // AJOUT INFOCOMS addInfocoms('ConsumableItem', $consID, $ID_entity); // Ajout consommable en stock $c = new Consumable(); for ($j=0 ; $j<mt_rand(0,$MAX['consumables_stock']) ; $j++) { $date = mt_rand(2000,$current_year)."-".mt_rand(1,12)."-".mt_rand(1,28); $ID = $c->add(array('entities_id' => $ID_entity, 'consumableitems_id' => $consID, 'date_in' => $date)); // AJOUT INFOCOMS addInfocoms('Consumable', $ID, $ID_entity); } // Ajout consommable donne for ($j=0 ; $j<mt_rand(0,$MAX['consumables_given']) ; $j++) { $date = mt_rand(2000,$current_year-1)."-".mt_rand(1,12)."-".mt_rand(1,28); $ID = $c->add(array('entities_id' => $ID_entity, 'consumableitems_id' => $consID, 'date_in' => $date, 'date_out' => date("Y-m-d"))); // AJOUT INFOCOMS addInfocoms('Consumable', $ID, $ID_entity); } } $LAST["type_of_consumables"] = getMaxItem("glpi_consumableitems"); // TYPE DE CARTOUCHES $FIRST["type_of_cartridges"] = getMaxItem("glpi_cartridgeitems")+1; $ct = new CartridgeItem(); for ($i=0 ; $i<$MAX['type_of_cartridges'] ; $i++) { $cartID = $ct->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => mt_rand(0,1), 'name' => "cartridge ' type $i", 'ref' => "ref '$i", 'locations_id' => mt_rand($FIRST["locations"], $LAST['locations']), 'manufacturers_id' => mt_rand(1,$MAX['manufacturer']), 'users_id_tech' => mt_rand($FIRST['users_sadmin'], $LAST['users_admin']), 'groups_id_tech' => mt_rand($FIRST["groups"], $LAST["groups"]), 'comment' => "comment '$i", 'notepad' => "notes cartridgeitem '$i", 'alarm_threshold' => mt_rand(0,10)))); addDocuments('CartridgeItem', $cartID); // AJOUT INFOCOMS addInfocoms('CartridgeItem', $cartID, $ID_entity); $c = new Cartridge(); $cipm = new CartridgeItem_PrinterModel(); // Ajout cartouche en stock for ($j=0 ; $j<mt_rand(0,$MAX['cartridges_stock']) ; $j++) { $date = mt_rand(2000,$current_year-1)."-".mt_rand(1,12)."-".mt_rand(1,28); $ID = $c->add(array('entities_id' => $ID_entity, 'cartridgeitems_id' => $cartID, 'date_in' => $date)); // AJOUT INFOCOMS addInfocoms('Cartridge', $ID, $ID_entity); } // Assoc printer type to cartridge type $cipm->add(array('cartridgeitems_id' => $cartID, 'printermodels_id' => mt_rand(1,$MAX['type_printers']), )); } $LAST["type_of_cartridges"] = getMaxItem("glpi_cartridgeitems"); // Networking $NET_LOC = array(); $FIRST["networking"] = getMaxItem("glpi_networkequipments")+1; $FIRST["printers"] = getMaxItem("glpi_printers")+1; $ne = new NetworkEquipment(); $p = new Printer(); $np = new Netpoint(); $c = new Cartridge(); foreach ($DB->request('glpi_locations') as $data) { $i = $data["id"]; $techID = mt_rand($FIRST['users_sadmin'],$LAST['users_admin']); $gtechID = mt_rand($FIRST["techgroups"],$LAST["techgroups"]); $infoIP = getNextIP(); $domainID = mt_rand($FIRST['domain'],$LAST['domain']); $networkID = mt_rand(1,$MAX['network']); // insert networking $netwID = $ne->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'name' => "networking '$i-$ID_entity", 'ram' => mt_rand(32,256), 'serial' => Toolbox::getRandomString(10), 'otherserial' => Toolbox::getRandomString(10), 'contact' => "contact '$i", 'contact_num' => "num '$i", 'users_id_tech' => $techID, 'groups_id_tech' => $gtechID, 'comment' => "comment '$i", 'locations_id' => $i, 'domains_id' => $domainID, 'networks_id' => $networkID, 'networkequipmenttypes_id' => mt_rand(1,$MAX['type_networking']), 'networkequipmentmodels_id' => mt_rand(1,$MAX['model_networking']), 'networkequipmentfirmwares_id' => mt_rand(1,$MAX['firmware']), 'manufacturers_id' => mt_rand(1,$MAX['enterprises']), 'mac' => getNextMAC(), 'ip' => $infoIP["ip"], 'notepad' => "notes networking '$i", 'users_id' => mt_rand($FIRST['users_sadmin'], $LAST['users_admin']), 'groups_id' => mt_rand($FIRST["groups"], $LAST["groups"]), 'states_id' => (mt_rand(0,100)<$percent['state'] ?mt_rand($FIRST['state'],$LAST['state']):0) ))); $NET_LOC[$data['id']] = $netwID; addDocuments('NetworkEquipment', $netwID); addContracts('NetworkEquipment', $netwID); // AJOUT INFOCOMS addInfocoms('NetworkEquipment', $netwID, $ID_entity); // Link with father addNetworkEthernetPort('NetworkEquipment', $netwID, $ID_entity, $i); // Ajout imprimantes reseaux : 1 par loc + connexion d un matos reseau + ajout de cartouches // Add trackings addTracking('NetworkEquipment', $netwID, $ID_entity); $typeID = mt_rand(1,$MAX['type_printers']); $modelID = mt_rand(1,$MAX['model_printers']); $recur = mt_rand(0,1); $printID = $p->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => $recur, 'name' => "printer of loc '$i", 'serial' => Toolbox::getRandomString(10), 'otherserial' => Toolbox::getRandomString(10), 'contact' => "contact '$i", 'contact_num' => "num' $i", 'users_id_tech' => $techID, 'groups_id_tech' => $gtechID, 'have_serial' => mt_rand(0,1), 'have_parallel' => mt_rand(0,1), 'have_usb' => mt_rand(0,1), 'have_wifi' => mt_rand(0,1), 'have_ethernet' => mt_rand(0,1), 'comment' => "comment' $i", 'memory_size' => mt_rand(0,128), 'locations_id' => $i, 'domains_id' => $domainID, 'networks_id' => $networkID, 'printertypes_id' => $typeID, 'printermodels_id' => $modelID, 'manufacturers_id' => mt_rand(1,$MAX['enterprises']), 'is_global' => 1, 'notepad' => "notes printers '$i", 'users_id' => mt_rand($FIRST['users_sadmin'], $LAST['users_admin']), 'groups_id' => mt_rand($FIRST["groups"], $LAST["groups"]), 'states_id' => (mt_rand(0,100)<$percent['state'] ?mt_rand($FIRST['state'],$LAST['state']):0) ))); addDocuments('Printer', $printID); addContracts('Printer', $printID); // Add trackings addTracking('Printer', $printID, $ID_entity); // AJOUT INFOCOMS addInfocoms('Printer', $printID, $ID_entity, $recur); // Add Cartouches // Get compatible cartridge $query = "SELECT `cartridgeitems_id` FROM `glpi_cartridgeitems_printermodels` WHERE `printermodels_id` = '$typeID'"; $result2 = $DB->query($query) or die("PB REQUETE ".$query); if ($DB->numrows($result2)>0) { $ctypeID = $DB->result($result2,0,0) or die (" PB RESULT ".$query); $printed = 0; $oldnb = mt_rand(1,$MAX['cartridges_by_printer']); $date1 = strtotime(mt_rand(2000,$current_year)."-".mt_rand(1,12)."-".mt_rand(1,28)); $date2 = time(); $inter = abs(round(($date2-$date1)/$oldnb)); // Add old cartridges for ($j=0 ; $j<$oldnb ; $j++) { $printed += mt_rand(0,5000); $c->add(array('entities_id' => $ID_entity, 'cartridgeitems_id' => $ctypeID, 'printers_id' => $printID, 'date_in' => date("Y-m-d",$date1), 'date_use' => date("Y-m-d",$date1+$j*$inter), 'date_out' => date("Y-m-d",$date1+($j+1)*$inter), 'pages' => $printed)); } // Add current cartridges $c->add(array('entities_id' => $ID_entity, 'cartridgeitems_id' => $ctypeID, 'printers_id' => $printID, 'date_in' => $date, 'date_use' => date("Y-m-d",$date2))); } $iface = mt_rand(1,$MAX['iface']); // Add networking ports addNetworkEthernetPort('Printer', $printID, $ID_entity, $i); } unset($NET_LOC); $LAST["networking"] = getMaxItem("glpi_networkequipments"); //////////// INVENTORY // glpi_computers $FIRST["computers"] = getMaxItem("glpi_computers")+1; $FIRST["monitors"] = getMaxItem("glpi_monitors")+1; $FIRST["phones"] = getMaxItem("glpi_phones")+1; $FIRST["peripherals"] = getMaxItem("glpi_peripherals")+1; $c = new Computer(); $mon = new Monitor(); $cdevmb = new Item_DeviceMotherBoard(); $cdevproc = new Item_DeviceProcessor(); $cdevmem = new Item_DeviceMemory(); $cdevhd = new Item_DeviceHardDrive(); $cdevnc = new Item_DeviceNetworkCard(); $cdevdr = new Item_DeviceDrive(); $cdevcon = new Item_DeviceControl(); $cdevgc = new Item_DeviceGraphicCard(); $cdevsc = new Item_DeviceSoundCard(); $cdevpci = new Item_DevicePci(); $cdevcase = new Item_DeviceCase(); $cdevps = new Item_DevicePowerSupply(); $cdisk = new ComputerDisk(); $np = new Netpoint(); $ci = new Computer_Item(); $phone = new Phone(); $print = new Printer(); $periph = new Peripheral(); $cart = new Cartridge(); for ($i=0 ; $i<$MAX['computers'] ; $i++) { $loc = mt_rand($FIRST["locations"],$LAST['locations']); $techID = mt_rand($FIRST['users_sadmin'],$LAST['users_admin']); $userID = mt_rand($FIRST['users_normal'],$LAST['users_postonly']); $groupID = mt_rand($FIRST["groups"],$LAST["groups"]); $gtechID = mt_rand($FIRST["techgroups"],$LAST["techgroups"]); $domainID = mt_rand($FIRST['domain'],$LAST['domain']); $networkID = mt_rand(1,$MAX['network']); $compID = $c->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'name' => "computer ' $i-$ID_entity", 'serial' => Toolbox::getRandomString(10), 'otherserial' => Toolbox::getRandomString(10), 'contact' => "contact' $i", 'contact_num' => "num' $i", 'users_id_tech' => $techID, 'groups_id_tech' => $gtechID, 'comment' => "comment' $i", 'operatingsystems_id' => mt_rand(1,$MAX['os']), 'operatingsystemversions_id' => mt_rand(1,$MAX['os_version']), 'operatingsystemservicepacks_id' => mt_rand(1,$MAX['os_sp']), 'os_license_number' => "os sn $i", 'os_licenseid' => "os id $i", 'autoupdatesystems_id' => mt_rand(1,$MAX['os_sp']), 'locations_id' => $loc, 'domains_id' => $domainID, 'networks_id' => $networkID, 'computertypes_id' => mt_rand(1,$MAX['type_computers']), 'computermodels_id' => mt_rand(1,$MAX['model']), 'manufacturers_id' => mt_rand(1,$MAX['manufacturer']), 'is_global' => 1, 'notepad' => "notes computer '$i", 'users_id' => $userID, 'groups_id' => $groupID, 'states_id' => (mt_rand(0,100)<$percent['state'] ?mt_rand($FIRST['state'],$LAST['state']):0), 'uuid' => Toolbox::getRandomString(30) ))); addDocuments('Computer', $compID); addContracts('Computer', $compID); $NET_PORT['Computer'][$compID] = 0; // Add trackings addTracking('Computer', $compID, $ID_entity); // Add reservation addReservation('Computer', $compID, $ID_entity); // AJOUT INFOCOMS addInfocoms('Computer', $compID, $ID_entity); // ADD DEVICE $cdevmb->addDevices(1, 'Computer', $compID, mt_rand(1,$MAX['device']), array('serial' => Toolbox::getRandomString(15))); $max = mt_rand(1,4); $devid = mt_rand(1,$MAX['device']); for($nb = 0; $nb<$max; $nb++) { $cdevproc->addDevices(1, 'Computer', $compID, $devid, array('serial' => Toolbox::getRandomString(15))); } $max = mt_rand(1,4); $devid = mt_rand(1,$MAX['device']); for($nb = 0; $nb<$max; $nb++) { $cdevmem->addDevices(1, 'Computer', $compID, $devid, array('serial' => Toolbox::getRandomString(15))); } $max = mt_rand(1,2); $devid = mt_rand(1,$MAX['device']); for($nb = 0; $nb<$max; $nb++) { $cdevhd->addDevices(1, 'Computer', $compID, $devid, array('serial' => Toolbox::getRandomString(15))); } $cdevnc->addDevices(1, 'Computer', $compID, mt_rand(1,$MAX['device']), array('serial' => Toolbox::getRandomString(15), 'mac' => getNextMAC())); $cdevdr->addDevices(1, 'Computer', $compID, mt_rand(1,$MAX['device']), array('serial' => Toolbox::getRandomString(15))); $cdevcon->addDevices(1, 'Computer', $compID, mt_rand(1,$MAX['device']), array('serial' => Toolbox::getRandomString(15))); $cdevgc->addDevices(1, 'Computer', $compID, mt_rand(1,$MAX['device']), array('serial' => Toolbox::getRandomString(15))); $cdevsc->addDevices(1, 'Computer', $compID, mt_rand(1,$MAX['device']), array('serial' => Toolbox::getRandomString(15))); $max = mt_rand(1,4); for($nb = 0; $nb<$max; $nb++) { $cdevpci->addDevices(1, 'Computer', $compID, mt_rand(1,$MAX['device']), array('serial' => Toolbox::getRandomString(15))); } $cdevcase->addDevices(1, 'Computer', $compID, mt_rand(1,$MAX['device']), array('serial'=> Toolbox::getRandomString(15))); $max = mt_rand(1,2); $devid = mt_rand(1,$MAX['device']); for($nb = 0; $nb<$max; $nb++) { $cdevps->addDevices(1, 'Computer', $compID, $devid, array('serial' => Toolbox::getRandomString(15))); } // insert disk $nb_disk = mt_rand(1,$MAX_DISK); for ($j=1 ; $j<=$nb_disk ; $j++) { $totalsize = mt_rand(10000,1000000); $freesize = mt_rand(0,$totalsize); $cdisk->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'computers_id' => $compID, 'name' => "disk '$j", 'device' => "/dev/disk$j", 'mountpoint' => "/mnt/disk$j", 'filesystems_id' => mt_rand(1,10), 'totalsize' => $totalsize, 'freesize' => $freesize))); } // Add networking ports addNetworkEthernetPort('Computer', $compID, $ID_entity, $loc); // Ajout d'un ecran sur l'ordi $monID = $mon->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'name' => "monitor' $i-$ID_entity", 'serial' => Toolbox::getRandomString(10), 'otherserial' => Toolbox::getRandomString(10), 'contact' => "contact' $i", 'contact_num' => "num' $i", 'users_id_tech' => $techID, 'groups_id_tech' => $gtechID, 'comment' => "comment' $i", 'size' => mt_rand(14,22), 'have_micro' => mt_rand(0,1), 'have_speaker' => mt_rand(0,1), 'have_subd' => mt_rand(0,1), 'have_bnc' => mt_rand(0,1), 'have_dvi' => mt_rand(0,1), 'have_pivot' => mt_rand(0,1), 'have_hdmi' => mt_rand(0,1), 'have_displayport' => mt_rand(0,1), 'locations_id' => $loc, 'monitortypes_id' => mt_rand(1,$MAX['type_monitors']), 'monitormodels_id' => mt_rand(1,$MAX['model_monitors']), 'manufacturers_id' => mt_rand(1,$MAX['manufacturer']), 'notepad' => "notes monitor' $i", 'users_id' => $userID, 'groups_id' => $groupID, 'states_id' => (mt_rand(0,100)<$percent['state'] ?mt_rand($FIRST['state'],$LAST['state']):0) ))); addDocuments('Monitor', $monID); addContracts('Monitor', $monID); // Add trackings addTracking('Monitor', $monID, $ID_entity); // AJOUT INFOCOMS addInfocoms('Monitor', $monID, $ID_entity); $ci->add(array('itemtype' => 'Monitor', 'items_id' => $monID, 'computers_id' => $compID, )); // Ajout d'un telephhone avec l'ordi $telID = $phone->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'name' => "phone' $i-$ID_entity", 'serial' => Toolbox::getRandomString(10), 'otherserial' => Toolbox::getRandomString(10), 'contact' => "contact' $i", 'contact_num' => "num' $i", 'users_id_tech' => $techID, 'groups_id_tech' => $gtechID, 'comment' => "comment' $i", 'firmware' => Toolbox::getRandomString(10), 'brand' => "brand' $i", 'phonepowersupplies_id' => mt_rand(0,$MAX['phone_power']), 'number_line' => Toolbox::getRandomString(10), 'have_headset' => mt_rand(0,1), 'have_hp' => mt_rand(0,1), 'locations_id' => $loc, 'phonetypes_id' => mt_rand(1,$MAX['type_phones']), 'phonemodels_id' => mt_rand(1,$MAX['model_phones']), 'manufacturers_id' => mt_rand(1,$MAX['manufacturer']), 'notepad' => "notes phone' $i", 'users_id' => $userID, 'groups_id' => $groupID, 'states_id' => (mt_rand(0,100)<$percent['state'] ?mt_rand($FIRST['state'],$LAST['state']):0) ))); addDocuments('Phone', $telID); addContracts('Phone', $telID); // Add trackings addTracking('Phone', $telID, $ID_entity); // AJOUT INFOCOMS addInfocoms('Phone', $telID, $ID_entity); $ci->add(array('itemtype' => 'Phone', 'items_id' => $telID, 'computers_id' => $compID)); // Ajout des periphs externes en connection directe while (mt_rand(0,100)<$percent['peripherals']) { $periphID = $periph->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'name' => "periph of comp' $i-$ID_entity", 'serial' => Toolbox::getRandomString(10), 'otherserial' => Toolbox::getRandomString(10), 'contact' => "contact' $i", 'contact_num' => "num' $i", 'users_id_tech' => $techID, 'groups_id_tech' => $gtechID, 'comment' => "comment' $i", 'brand' => "brand' $i", 'locations_id' => $loc, 'phonetypes_id' => mt_rand(1,$MAX['type_peripherals']), 'phonemodels_id' => mt_rand(1,$MAX['model_peripherals']), 'manufacturers_id' => mt_rand(1,$MAX['manufacturer']), 'notepad' => "notes peripheral' $i", 'users_id' => $userID, 'groups_id' => $groupID, 'states_id' => (mt_rand(0,100)<$percent['state'] ?mt_rand($FIRST['state'],$LAST['state']):0) ))); addDocuments('Peripheral', $periphID); addContracts('Peripheral', $periphID); // Add trackings addTracking('Peripheral', $periphID, $ID_entity); // Add connection $ci->add(array('itemtype' => 'Peripheral', 'items_id' => $periphID, 'computers_id' => $compID)); } // Ajout d'une imprimante connection directe pour X% des computers + ajout de cartouches if (mt_rand(0,100)<=$percent['printer']) { // Add printer $typeID = mt_rand(1,$MAX['type_printers']); $modelID = mt_rand(1,$MAX['model_printers']); $printID = $p->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'name' => "printer of comp' $i-$ID_entity", 'serial' => Toolbox::getRandomString(10), 'otherserial' => Toolbox::getRandomString(10), 'contact' => "contact' $i", 'contact_num' => "num' $i", 'users_id_tech' => $techID, 'groups_id_tech' => $gtechID, 'have_serial' => mt_rand(0,1), 'have_parallel' => mt_rand(0,1), 'have_usb' => mt_rand(0,1), 'have_wifi' => mt_rand(0,1), 'have_ethernet' => mt_rand(0,1), 'comment' => "comment' $i", 'memory_size' => mt_rand(0,128), 'locations_id' => $loc, 'domains_id' => $domainID, 'networks_id' => $networkID, 'printertypes_id' => $typeID, 'printermodels_id' => $modelID, 'manufacturers_id' => mt_rand(1,$MAX['manufacturer']), 'notepad' => "notes printers '$i", 'users_id' => mt_rand($FIRST['users_postonly'], $LAST['users_postonly']), 'groups_id' => mt_rand($FIRST["groups"], $LAST["groups"]), 'states_id' => (mt_rand(0,100)<$percent['state'] ?mt_rand($FIRST['state'],$LAST['state']):0) ))); addDocuments('Printer', $printID); addContracts('Printer', $printID); // Add trackings addTracking('Printer', $printID, $ID_entity); // Add connection $ci->add(array('itemtype' => 'Printer', 'items_id' => $printID, 'computers_id' => $compID)); // AJOUT INFOCOMS addInfocoms('Printer', $printID, $ID_entity); // Add Cartouches // Get compatible cartridge $query = "SELECT `cartridgeitems_id` FROM `glpi_cartridgeitems_printermodels` WHERE `printermodels_id` = '$typeID'"; $result = $DB->query($query) or die("PB REQUETE ".$query); if ($DB->numrows($result)>0) { $ctypeID = $DB->result($result,0,0) or die (" PB RESULT ".$query); $printed = 0; $oldnb = mt_rand(1,$MAX['cartridges_by_printer']); $date1 = strtotime(mt_rand(2000,$current_year)."-".mt_rand(1,12)."-".mt_rand(1,28)); $date2 = time(); $inter = round(($date2-$date1)/$oldnb); // Add old cartridges for ($j=0 ; $j<$oldnb ; $j++) { $printed += mt_rand(0,5000); $cart->add(array('entities_id' => $ID_entity, 'cartridgeitems_id' => $ctypeID, 'printers_id' => $printID, 'date_in' => date("Y-m-d",$date1), 'date_use' => date("Y-m-d",$date1+$j*$inter), 'date_out' => date("Y-m-d",$date1+($j+1)*$inter), 'pages' => $printed)); } // Add current cartridges $cart->add(array('entities_id' => $ID_entity, 'cartridgeitems_id' => $ctypeID, 'printers_id' => $printID, 'date_in' => date("Y-m-d",$date1), 'date_use' => date("Y-m-d",$date2))); } } } $LAST["computers"] = getMaxItem("glpi_computers"); $LAST["monitors"] = getMaxItem("glpi_monitors"); $LAST["phones"] = getMaxItem("glpi_phones"); // Add global peripherals $periph = new Peripheral(); $ci = new Computer_Item(); for ($i=0 ; $i<$MAX['global_peripherals'] ; $i++) { $techID = mt_rand($FIRST['users_sadmin'],$LAST['users_admin']); $gtechID = mt_rand($FIRST["techgroups"],$LAST["techgroups"]); $periphID = $periph->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'name' => "periph '$i-$ID_entity", 'serial' => Toolbox::getRandomString(10), 'otherserial' => Toolbox::getRandomString(10), 'contact' => "contact' $i", 'contact_num' => "num' $i", 'users_id_tech' => $techID, 'groups_id_tech' => $gtechID, 'comment' => "comment' $i", 'brand' => "brand' $i", 'locations_id' => $loc, 'phonetypes_id' => mt_rand(1,$MAX['type_peripherals']), 'phonemodels_id' => mt_rand(1,$MAX['model_peripherals']), 'manufacturers_id' => mt_rand(1,$MAX['manufacturer']), 'is_global' => 1, 'notepad' => "notes peripheral' $i", 'users_id' => mt_rand($FIRST['users_normal'], $LAST['users_normal']), 'groups_id' => mt_rand($FIRST["groups"], $LAST["groups"]), 'states_id' => (mt_rand(0,100)<$percent['state'] ?mt_rand($FIRST['state'],$LAST['state']):0) ))); addDocuments('Peripheral', $periphID); addContracts('Peripheral', $periphID); // Add trackings addTracking('Peripheral', $periphID, $ID_entity); // Add reservation addReservation('Peripheral', $periphID, $ID_entity); // AJOUT INFOCOMS addInfocoms('Peripheral', $periphID, $ID_entity); // Add connections $val = mt_rand(1,$MAX['connect_for_peripherals']); for ($j=1 ; $j<$val ; $j++) { $ci->add(array('itemtype' => 'Peripheral', 'items_id' => $periphID, 'computers_id' => mt_rand($FIRST["computers"],$LAST['computers']))); } } $LAST["peripherals"] = getMaxItem("glpi_peripherals"); $FIRST["software"] = getMaxItem("glpi_softwares")+1; // Ajout logiciels + licences associees a divers PCs $items = array(array("Open'Office", "1.1.4", "2.0", "2.0.1"), array("Microsoft Office", "95", "97", "XP", "2000", "2003", "2007"), array("Acrobat Reader", "6.0", "7.0", "7.04"), array("Gimp", "2.0", "2.2"), array("InkScape", "0.4")); $soft = new Software(); $softvers = new SoftwareVersion(); $softlic = new SoftwareLicense(); $csv = new Computer_SoftwareVersion(); $csl = new Computer_SoftwareLicense(); for ($i=0 ; $i<$MAX['software'] ; $i++) { if (isset($items[$i])) { $name = $items[$i][0]; } else { $name = "software '$i"; } $loc = mt_rand(1,$MAX['locations']); $techID = mt_rand($FIRST['users_sadmin'],$LAST['users_admin']); $gtechID = mt_rand($FIRST["techgroups"],$LAST["techgroups"]); $recursive = mt_rand(0,1); $softID = $soft->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => $recursive, 'name' => $name, 'comment' => "comment '$i", 'locations_id' => $loc, 'users_id_tech' => $techID, 'groups_id_tech' => $gtechID, 'manufacturers_id' => mt_rand(1,$MAX['manufacturer']), 'notepad' => "notes software '$i", 'users_id' => mt_rand($FIRST['users_admin'], $LAST['users_admin']), 'groups_id' => mt_rand($FIRST["groups"], $LAST["groups"]), 'is_helpdesk_visible' => 1, 'softwarecategories_id' => mt_rand(1,$MAX['softwarecategory']) ))); addDocuments('Software', $softID); addContracts('Software', $softID); // Add trackings addTracking('Software', $softID, $ID_entity); // AJOUT INFOCOMS addInfocoms('Software', $softID, $ID_entity); // Add versions $FIRST["version"] = getMaxItem("glpi_softwareversions")+1; if (isset($items[$i])) { $val2 = count($items[$i]); } else { $val2 = mt_rand(1,$MAX['softwareversions']+1); } for ($j=1 ; $j<=$val2 ; $j++) { if (isset($items[$i])) { $version = $items[$i][mt_rand(1,count($items[$i])-1)]; } else { $version = "$j.0"; } $os = mt_rand(1,$MAX['os']); $versID = $softvers->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => $recursive, 'softwares_id' => $softID, 'name' => $version, 'comment' => "comment '$version", 'states_id' => (mt_rand(0,100)<$percent['state'] ?mt_rand($FIRST['state'],$LAST['state']):0), 'operatingsystems_id' => $os))); $val3 = min($LAST["computers"]-$FIRST['computers'], mt_rand(1,$MAX['softwareinstall'])); $comp_id = mt_rand($FIRST["computers"], $LAST['computers']); for ($k=0 ; $k<$val3 ; $k++) { $comp_id++; if ($comp_id>$LAST["computers"]) { $comp_id = $FIRST["computers"]; } $csv->add(array('computers_id' => $comp_id, 'softwareversions_id' => $versID)); } } $LAST["version"] = getMaxItem("glpi_softwareversions"); // Add licenses $val2 = mt_rand(1,$MAX['softwarelicenses']); for ($j=0 ; $j<$val2 ; $j++) { $softwareversions_id_buy = mt_rand($FIRST["version"],$LAST["version"]); $softwareversions_id_use = mt_rand($softwareversions_id_buy,$LAST["version"]); $nbused = min($LAST["computers"]-$FIRST['computers'], mt_rand(1,$MAX['softwareinstall'])); $licID = $softlic->add(toolbox::addslashes_deep( array('entities_id' => $ID_entity, 'is_recursive' => $recursive, 'softwares_id' => $softID, 'number' => $nbused, 'softwarelicensetypes_id' => mt_rand(1,$MAX['licensetype']), 'name' => "license '$j", 'serial' => "serial $j", 'otherserial' => "otherserial $j", 'comment' => "comment license '$j", 'softwareversions_id_buy' => $softwareversions_id_buy, 'softwareversions_id_use' => $softwareversions_id_use))); $comp_id = mt_rand($FIRST["computers"], $LAST['computers']); for ($k=0 ; $k<$nbused ; $k++) { $comp_id++; if ($comp_id>$LAST["computers"]) { $comp_id = $FIRST["computers"]; } $csl->add(array('computers_id' => $comp_id, 'softwarelicenses_id' => $licID)); } } } $LAST["software"] = getMaxItem("glpi_softwares"); }
/** * Print the item cost form * * @param $ID integer ID of the item * @param $options array options used **/ function showForm($ID, $options = array()) { if (isset($options['parent']) && !empty($options['parent'])) { $item = $options['parent']; } if ($ID > 0) { $this->check($ID, READ); } else { // Create item $options[static::$items_id] = $item->getField('id'); $this->check(-1, CREATE, $options); $this->initBasedOnPrevious(); } if ($ID > 0) { $items_id = $this->fields[static::$items_id]; } else { $items_id = $options['parent']->fields["id"]; } $item = new static::$itemtype(); if (!$item->getFromDB($items_id)) { return false; } $this->showFormHeader($options); echo "<tr class='tab_bg_1'>"; echo "<td>" . __('Name') . "</td>"; echo "<td>"; echo "<input type='hidden' name='" . static::$items_id . "' value='" . $item->fields['id'] . "'>"; Html::autocompletionTextField($this, 'name'); echo "</td>"; echo "<td>" . __('Begin date') . "</td>"; echo "<td>"; Html::showDateField("begin_date", array('value' => $this->fields['begin_date'])); echo "</td>"; echo "</tr>"; echo "<tr class='tab_bg_1'>"; echo "<td>" . __('Duration') . "</td>"; echo "<td>"; Dropdown::showTimeStamp('actiontime', array('value' => $this->fields['actiontime'], 'addfirstminutes' => true)); echo "</td>"; echo "<td>" . __('End date') . "</td>"; echo "<td>"; Html::showDateField("end_date", array('value' => $this->fields['end_date'])); echo "</td>"; echo "</tr>"; echo "<tr class='tab_bg_1'>"; echo "<td>" . __('Time cost') . "</td><td>"; echo "<input type='text' size='15' name='cost_time' value='" . Html::formatNumber($this->fields["cost_time"], true) . "'>"; echo "</td>"; $rowspan = 4; echo "<td rowspan='{$rowspan}'>" . __('Comments') . "</td>"; echo "<td rowspan='{$rowspan}' class='middle'>"; echo "<textarea cols='45' rows='" . ($rowspan + 3) . "' name='comment' >" . $this->fields["comment"] . "</textarea>"; echo "</td></tr>\n"; echo "<tr class='tab_bg_1'>"; echo "<td>" . __('Fixed cost') . "</td><td>"; echo "<input type='text' size='15' name='cost_fixed' value='" . Html::formatNumber($this->fields["cost_fixed"], true) . "'>"; echo "</td>"; echo "</tr>"; echo "<tr class='tab_bg_1'>"; echo "<td>" . __('Material cost') . "</td><td>"; echo "<input type='text' size='15' name='cost_material' value='" . Html::formatNumber($this->fields["cost_material"], true) . "'>"; echo "</td>"; echo "</tr>"; echo "<tr class='tab_bg_1'><td>" . __('Budget') . "</td>"; echo "<td>"; Budget::dropdown(array('value' => $this->fields["budgets_id"], 'entity' => $this->fields["entities_id"])); echo "</td></tr>"; $this->showFormButtons($options); return true; }
/** * Print the contract cost form * * @param $ID integer ID of the item * @param $options array options used **/ function showForm($ID, $options = array()) { if ($ID > 0) { $this->check($ID, READ); } else { // Create item $options['contracts_id'] = $options['parent']->getField('id'); $this->check(-1, CREATE, $options); $this->initBasedOnPrevious(); } $this->showFormHeader($options); echo "<tr class='tab_bg_1'>"; echo "<td>" . __('Name') . "</td>"; echo "<td>"; echo "<input type='hidden' name='contracts_id' value='" . $this->fields['contracts_id'] . "'>"; Html::autocompletionTextField($this, 'name'); echo "</td>"; echo "<td>" . __('Cost') . "</td>"; echo "<td>"; echo "<input type='text' name='cost' value='" . Html::formatNumber($this->fields["cost"], true) . "'\n size='14'>"; echo "</td></tr>"; echo "<tr class='tab_bg_1'><td>" . __('Begin date') . "</td>"; echo "<td>"; Html::showDateField("begin_date", array('value' => $this->fields['begin_date'])); echo "</td>"; $rowspan = 3; echo "<td rowspan='{$rowspan}'>" . __('Comments') . "</td>"; echo "<td rowspan='{$rowspan}' class='middle'>"; echo "<textarea cols='45' rows='" . ($rowspan + 3) . "' name='comment' >" . $this->fields["comment"] . "</textarea>"; echo "</td></tr>\n"; echo "<tr class='tab_bg_1'><td>" . __('End date') . "</td>"; echo "<td>"; Html::showDateField("end_date", array('value' => $this->fields['end_date'])); echo "</td></tr>"; echo "<tr class='tab_bg_1'><td>" . __('Budget') . "</td>"; echo "<td>"; Budget::dropdown(array('value' => $this->fields["budgets_id"])); echo "</td></tr>"; $this->showFormButtons($options); return true; }
private function setBudgetData() { if (isset($this->phkRequestData['budget_id']) && !isset($this->phkRequestData['budget_text'])) { App::import("Model", "Budget"); $budget = new Budget(); $result = $budget->find("first", array('conditions' => array('Budget.id' => $this->phkRequestData['budget_id']))); if (count($result)) { $this->phkRequestData['budget_id'] = $result['Budget']['id']; $this->phkRequestData['budget_text'] = $result['Budget']['title']; $this->phkRequestData['budget_status'] = $result['Budget']['budget_status_id']; $this->phkRequestData['condo_id'] = $result['Budget']['condo_id']; } } }
/** * Returns the data model based on the primary key given in the GET variable. * If the data model is not found, an HTTP exception will be raised. * @param integer $id the ID of the model to be loaded * @return Budget the loaded model * @throws CHttpException */ public function loadModel($id) { $model = Budget::model()->findByPk($id); if ($model === null) { throw new CHttpException(404, 'The requested page does not exist.'); } return $model; }
/** * Print the HTML array of value consumed for a budget * *@return Nothing (display) **/ function showValuesByEntity() { global $DB, $LANG; $budgets_id = $this->fields['id']; if (!$this->can($budgets_id, 'r')) { return false; } // Type for which infocom are only template $ignore = array('CartridgeItem', 'ConsumableItem', 'Software'); $query = "SELECT DISTINCT `itemtype`\n FROM `glpi_infocoms`\n WHERE `budgets_id` = '{$budgets_id}'\n AND `itemtype` NOT IN ('" . implode("','", $ignore) . "')" . getEntitiesRestrictRequest(" AND", 'glpi_infocoms', "entities_id") . "\n GROUP BY `itemtype`"; $result = $DB->query($query); $total = 0; $entities_values = array(); $entitiestype_values = array(); $found_types = array(); if ($DB->numrows($result)) { while ($types = $DB->fetch_array($result)) { if (!class_exists($types['itemtype'])) { continue; } $item = new $types['itemtype'](); $found_types[$types['itemtype']] = $item->getTypeName(); $table = getTableForItemType($types['itemtype']); $query_infos = "SELECT SUM(`glpi_infocoms`.`value`) AS `sumvalue`,\n `{$table}`.`entities_id`\n FROM `{$table}`\n INNER JOIN `glpi_infocoms`\n ON (`glpi_infocoms`.`items_id` = `{$table}`.`id`\n AND `glpi_infocoms`.`itemtype` = '" . $types['itemtype'] . "')\n LEFT JOIN `glpi_entities`\n ON (`{$table}`.`entities_id` = `glpi_entities`.`id`)\n WHERE `glpi_infocoms`.`budgets_id` = '{$budgets_id}' " . getEntitiesRestrictRequest(" AND", $table, "entities_id"); if ($item->maybeTemplate()) { $query_infos .= " AND `{$table}`.`is_template` = '0' "; } $query_infos .= "GROUP BY `{$table}`.`entities_id`\n ORDER BY `glpi_entities`.`completename` ASC"; if ($result_infos = $DB->query($query_infos)) { //Store, for each entity, the budget spent while ($values = $DB->fetch_array($result_infos)) { if (!isset($entities_values[$values['entities_id']])) { $entities_values[$values['entities_id']] = 0; } if (!isset($entitiestype_values[$values['entities_id']][$types['itemtype']])) { $entitiestype_values[$values['entities_id']][$types['itemtype']] = 0; } $entities_values[$values['entities_id']] += $values['sumvalue']; $entitiestype_values[$values['entities_id']][$types['itemtype']] += $values['sumvalue']; } } } $budget = new Budget(); $budget->getFromDB($budgets_id); $colspan = count($found_types) + 2; echo "<div class='spaced'><table class='tab_cadre'>"; echo "<tr><th colspan='{$colspan}'>" . $LANG['financial'][108] . "</th></tr>"; echo "<tr><th>" . $LANG['entity'][0] . "</th>"; if (count($found_types)) { foreach ($found_types as $type => $typename) { echo "<th>{$typename}</th>"; } } echo "<th>" . $LANG['common'][33] . "</th>"; echo "</tr>"; foreach ($entities_values as $entity => $value) { echo "<tr class='tab_bg_1'>"; echo "<td class='b'>" . Dropdown::getDropdownName('glpi_entities', $entity) . "</td>"; if (count($found_types)) { foreach ($found_types as $type => $typename) { echo "<td class='right'>"; $typevalue = 0; if (isset($entitiestype_values[$entity][$type])) { $typevalue = $entitiestype_values[$entity][$type]; } echo formatNumber($typevalue); echo "</td>"; } } echo "<td class='right b'>" . formatNumber($value) . "</td>"; echo "</tr>"; $total += $value; } echo "<tr class='tab_bg_1'><th colspan='{$colspan}'><br></th></tr>"; echo "<tr class='tab_bg_1'>"; echo "<td class='right' colspan='" . ($colspan - 1) . "'>" . $LANG['financial'][108] . "</td>"; echo "<td class='right b'>" . formatNumber($total) . "</td></tr>"; if ($_SESSION['glpiactive_entity'] == $budget->fields['entities_id']) { echo "<tr class='tab_bg_1'>"; echo "<td class='right' colspan='" . ($colspan - 1) . "'>" . $LANG['financial'][109] . "</td>"; echo "<td class='right b'>" . formatNumber($budget->fields['value'] - $total) . "</td></tr>"; } echo "</table></div>"; } }
Copyright (C) 2003-2014 by the INDEPNET Development Team. http://indepnet.net/ http://glpi-project.org ------------------------------------------------------------------------- LICENSE This file is part of GLPI. GLPI is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. GLPI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GLPI. If not, see <http://www.gnu.org/licenses/>. -------------------------------------------------------------------------- */ /** @file * @brief */ include '../inc/includes.php'; Session::checkRight("budget", READ); Html::header(Budget::getTypeName(1), $_SERVER['PHP_SELF'], "management", "budget"); Search::show('Budget'); Html::footer();
public function doOldImport() { DB::delete('DELETE FROM `cache`'); // delete old data: foreach (Auth::user()->accounts()->get() as $acc) { $acc->delete(); } foreach (Auth::user()->budgets()->get() as $b) { $b->delete(); } foreach (Auth::user()->categories()->get() as $b) { $b->delete(); } foreach (Auth::user()->beneficiaries()->get() as $b) { $b->delete(); } foreach (Icon::get() as $icon) { $icon->delete(); } $data = file_get_contents('http://commondatastorage.googleapis.com/nder/import.json'); $json = json_decode($data); $map = array(); $map['accounts'] = array(); $map['icons'] = array(); // all accounts: foreach ($json->accounts as $account) { $newAccount = new Account(); $newAccount->name = Crypt::encrypt($account->name); $newAccount->balance = floatval($account->balance); $newAccount->fireflyuser_id = Auth::user()->id; $newAccount->date = $account->date; $newAccount->save(); $map['accounts'][$account->id] = $newAccount->id; } // all icons: foreach ($json->icons as $icon) { $newIcon = new Icon(); $newIcon->file = $icon->file; $newIcon->save(); $map['icons'][intval($icon->id)] = $newIcon->id; } // all beneficiaries: foreach ($json->beneficiaries as $ben) { $nb = new Beneficiary(); $nb->fireflyuser_id = Auth::user()->id; $nb->name = Crypt::encrypt($ben->name); $nb->save(); $map['beneficiaries'][$ben->id] = $nb->id; } // all budgets foreach ($json->budgets as $bd) { $nbg = new Budget(); $nbg->fireflyuser_id = Auth::user()->id; $nbg->name = Crypt::encrypt($bd->name); $nbg->date = $bd->date; $nbg->amount = floatval($bd->amount); $nbg->save(); $map['budgets'][$bd->id] = $nbg->id; } // all categories: foreach ($json->categories as $c) { $nc = new Category(); $nc->fireflyuser_id = Auth::user()->id; $nc->icon_id = intval($map['icons'][intval($c->icon_id)]); $nc->name = Crypt::encrypt($c->name); $nc->showtrend = intval($c->showtrend); $nc->save(); $map['categories'][$c->id] = $nc->id; } foreach ($json->targets as $t) { $nt = new Target(); $nt->fireflyuser_id = Auth::user()->id; $nt->account_id = $map['accounts'][$t->account_id]; $nt->description = Crypt::encrypt($t->description); $nt->amount = floatval($t->amount); $nt->duedate = $t->duedate; $nt->startdate = $t->startdate; $nt->save(); $map['targets'][$t->id] = $nt->id; } foreach ($json->transactions as $t) { $nt = new Transaction(); $nt->fireflyuser_id = Auth::user()->id; $nt->account_id = $map['accounts'][$t->account_id]; $nt->budget_id = is_null($t->budget_id) ? NULL : intval($map['budgets'][$t->budget_id]); $nt->category_id = is_null($t->category_id) ? NULL : $map['categories'][$t->category_id]; $nt->beneficiary_id = is_null($t->beneficiary_id) ? NULL : $map['beneficiaries'][$t->beneficiary_id]; $nt->description = Crypt::encrypt($t->description); $nt->amount = floatval($t->amount); $nt->date = $t->date; $nt->onetime = intval($t->onetime); $nt->save(); $map['transactions'][$t->id] = $nt->id; } foreach ($json->transfers as $t) { $nt = new Transfer(); $nt->fireflyuser_id = Auth::user()->id; $nt->account_from = $map['accounts'][$t->account_from]; $nt->account_to = $map['accounts'][$t->account_to]; $nt->category_id = is_null($t->category_id) ? NULL : $map['categories'][$t->category_id]; $nt->budget_id = is_null($t->budget_id) ? NULL : intval($map['budgets'][$t->budget_id]); $nt->target_id = is_null($t->target_id) ? NULL : intval($map['targets'][$t->target_id]); $nt->description = Crypt::encrypt($t->description); $nt->amount = floatval($t->amount); $nt->date = $t->date; $nt->save(); $map['targets'][$t->id] = $nt->id; } // //var_dump($data); // create everything from this file. // we map the old id's to the new one to save problems. return 'Old data successfully imported.'; }
/** * Show Infocom form for an item (not a standard showForm) * * @param $item CommonDBTM object * @param $withtemplate integer template or basic item (default '') **/ static function showForItem(CommonDBTM $item, $withtemplate = '') { global $CFG_GLPI; // Show Infocom or blank form if (!Session::haveRight("infocom", "r")) { return false; } if (!$item) { echo "<div class='spaced'>" . __('Requested item not found') . "</div>"; } else { $date_tax = $CFG_GLPI["date_tax"]; $dev_ID = $item->getField('id'); $ic = new self(); $option = ""; if ($withtemplate == 2) { $option = " readonly "; } if (!strpos($_SERVER['PHP_SELF'], "infocoms-show") && in_array($item->getType(), array('CartridgeItem', 'ConsumableItem', 'Software'))) { echo "<div class='firstbloc center'>" . __('For this type of item, the financial and administrative information are only a model for the items which you should add.') . "</div>"; } if (!$ic->getFromDBforDevice($item->getType(), $dev_ID)) { $input = array('itemtype' => $item->getType(), 'items_id' => $dev_ID, 'entities_id' => $item->getEntityID()); if ($ic->can(-1, "w", $input) && $withtemplate != 2) { echo "<div class='spaced b'>"; echo "<table class='tab_cadre_fixe'><tr class='tab_bg_1'><th>"; echo sprintf(__('%1$s - %2$s'), $item->getTypeName(1), $item->getName()) . "</th></tr>"; echo "<tr class='tab_bg_1'><td class='center'>"; Html::showSimpleForm($CFG_GLPI["root_doc"] . "/front/infocom.form.php", 'add', __('Enable the financial and administrative information'), array('itemtype' => $item->getType(), 'items_id' => $dev_ID)); echo "</td></tr></table></div>"; } } else { // getFromDBforDevice $canedit = $ic->can($ic->fields['id'], "w") && $withtemplate != 2; if ($canedit) { echo "<form name='form_ic' method='post' action='" . $CFG_GLPI["root_doc"] . "/front/infocom.form.php'>"; } echo "<div class='spaced'>"; echo "<table class='tab_cadre" . (!strpos($_SERVER['PHP_SELF'], "infocoms-show") ? "_fixe" : "") . "'>"; echo "<tr><th colspan='4'>" . __('Financial and administrative information') . "</th></tr>"; echo "<tr class='tab_bg_1'>"; echo "<td>" . __('Supplier') . "</td>"; echo "<td>"; if ($withtemplate == 2) { echo Dropdown::getDropdownName("glpi_suppliers", $ic->fields["suppliers_id"]); } else { Supplier::dropdown(array('value' => $ic->fields["suppliers_id"], 'entity' => $item->getEntityID())); } echo "</td>"; if (Session::haveRight("budget", "r")) { echo "<td>" . __('Budget') . "</td><td >"; Budget::dropdown(array('value' => $ic->fields["budgets_id"], 'entity' => $item->getEntityID(), 'comments' => 1)); } else { echo "<td colspan='2'>"; } echo "</td></tr>"; // Can edit calendar ? $editcalendar = $withtemplate != 2; echo "<tr class='tab_bg_1'>"; echo "<td>" . __('Order number') . "</td>"; echo "<td >"; Html::autocompletionTextField($ic, "order_number", array('option' => $option)); echo "</td>"; echo "<td>" . __('Order date') . "</td><td>"; Html::showDateFormItem("order_date", $ic->fields["order_date"], true, $editcalendar); echo "</td></tr>"; echo "<tr class='tab_bg_1'>"; $istemplate = ''; if ($item->isTemplate() || in_array($item->getType(), array('CartridgeItem', 'ConsumableItem', 'Software'))) { $istemplate = '*'; } echo "<td>" . sprintf(__('%1$s%2$s'), __('Immobilization number'), $istemplate) . "</td>"; echo "<td>"; $objectName = autoName($ic->fields["immo_number"], "immo_number", $withtemplate == 2, 'Infocom', $item->getEntityID()); Html::autocompletionTextField($ic, "immo_number", array('value' => $objectName, 'option' => $option)); echo "</td>"; echo "<td>" . __('Date of purchase') . "</td><td>"; Html::showDateFormItem("buy_date", $ic->fields["buy_date"], true, $editcalendar); echo "</td></tr>"; echo "<tr class='tab_bg_1'>"; echo "<td>" . __('Invoice number') . "</td>"; echo "<td>"; Html::autocompletionTextField($ic, "bill", array('option' => $option)); echo "</td>"; echo "<td>" . __('Delivery date') . "</td><td>"; Html::showDateFormItem("delivery_date", $ic->fields["delivery_date"], true, $editcalendar); echo "</td></tr>"; echo "<tr class='tab_bg_1'>"; echo "<td>" . __('Delivery form') . "</td><td>"; Html::autocompletionTextField($ic, "delivery_number", array('option' => $option)); echo "</td>"; echo "<td>" . __('Startup date') . "</td><td>"; Html::showDateFormItem("use_date", $ic->fields["use_date"], true, $editcalendar); echo "</td></tr>"; echo "<tr class='tab_bg_1'>"; echo "<td>" . __('Value') . "</td>"; echo "<td><input type='text' name='value' {$option} value='" . Html::formatNumber($ic->fields["value"], true) . "' size='14'></td>"; echo "</td>"; echo "<td>" . __('Date of last physical inventory') . "</td><td>"; Html::showDateFormItem("inventory_date", $ic->fields["inventory_date"], true, $editcalendar); echo "</td></tr>"; echo "<tr class='tab_bg_1'>"; echo "<td>" . __('Warranty extension value') . "</td>"; echo "<td><input type='text' {$option} name='warranty_value' value='" . Html::formatNumber($ic->fields["warranty_value"], true) . "' size='14'></td>"; echo "<td rowspan='5'>" . __('Comments') . "</td>"; echo "<td rowspan='5' class='middle'>"; echo "<textarea cols='45' rows='9' name='comment' >" . $ic->fields["comment"]; echo "</textarea></td></tr>\n"; echo "<tr class='tab_bg_1'>"; echo "<td>" . __('Account net value') . "</td><td>"; echo Html::formatNumber(self::Amort($ic->fields["sink_type"], $ic->fields["value"], $ic->fields["sink_time"], $ic->fields["sink_coeff"], $ic->fields["warranty_date"], $ic->fields["use_date"], $date_tax, "n")); echo "</td></tr>"; echo "<tr class='tab_bg_1'>"; echo "<td>" . __('Amortization type') . "</td><td >"; if ($withtemplate == 2) { echo self::getAmortTypeName($ic->fields["sink_type"]); } else { self::dropdownAmortType("sink_type", $ic->fields["sink_type"]); } echo "</td></tr>"; echo "<tr class='tab_bg_1'>"; echo "<td>" . __('Amortization duration') . "</td><td>"; if ($withtemplate == 2) { printf(_n('%d year', '%d years', $ic->fields["sink_time"]), $ic->fields["sink_time"]); } else { Dropdown::showNumber("sink_time", array('value' => $ic->fields["sink_time"], 'max' => 15, 'unit' => 'year')); } echo "</td></tr>"; echo "<tr class='tab_bg_1'>"; echo "<td>" . __('Amortization coefficient') . "</td>"; echo "<td>"; Html::autocompletionTextField($ic, "sink_coeff", array('size' => 14, 'option' => $option)); echo "</td></tr>"; echo "<tr class='tab_bg_1'>"; if (!in_array($item->getType(), array('Cartridge', 'CartridgeItem', 'Consumable', 'ConsumableItem', 'Software', 'SoftwareLicense'))) { echo "<td>" . __('TCO (value + tracking cost)') . "</td><td>"; echo self::showTco($item->getField('ticket_tco'), $ic->fields["value"]); } else { echo "<td colspan='2'>"; } echo "</td>"; if (!in_array($item->getType(), array('Cartridge', 'CartridgeItem', 'Consumable', 'ConsumableItem', 'Software', 'SoftwareLicense'))) { echo "<td>" . __('Monthly TCO') . "</td><td>"; echo self::showTco($item->getField('ticket_tco'), $ic->fields["value"], $ic->fields["warranty_date"]); } else { echo "<td colspan='2'>"; } echo "</td></tr>"; echo "<tr><th colspan='4'>" . __('Warranty information') . "</th></tr>"; echo "<tr class='tab_bg_1'>"; echo "<td>" . __('Start date of warranty') . "</td><td>"; Html::showDateFormItem("warranty_date", $ic->fields["warranty_date"], true, $editcalendar); echo "</td>"; echo "<td>" . __('Warranty duration') . "</td><td>"; if ($withtemplate == 2) { // -1 = life if ($ic->fields["warranty_duration"] == -1) { _e('Lifelong'); } else { printf(_n('%d month', '%d months', $ic->fields["warranty_duration"]), $ic->fields["warranty_duration"]); } } else { Dropdown::showInteger("warranty_duration", $ic->fields["warranty_duration"], 0, 120, 1, array(-1 => __('Lifelong')), array('unit' => 'month')); } $tmpdat = self::getWarrantyExpir($ic->fields["warranty_date"], $ic->fields["warranty_duration"], 0, true); if ($tmpdat) { echo "<span class='small_space'>" . sprintf(__('Valid to %s'), $tmpdat) . "</span>"; } echo "</td></tr>"; echo "<tr class='tab_bg_1'>"; echo "<td>" . __('Warranty information') . "</td>"; echo "<td >"; Html::autocompletionTextField($ic, "warranty_info", array('option' => $option)); echo "</td>"; if ($CFG_GLPI['use_mailing']) { echo "<td>" . __('Alarms on financial and administrative information') . "</td>"; echo "<td>"; self::dropdownAlert(array('name' => "alert", 'value' => $ic->fields["alert"])); Alert::displayLastAlert('Infocom', $ic->fields['id']); echo "</td>"; } else { echo "</td><td colspan='2'>"; } echo "</td></tr>"; if ($canedit) { echo "<tr>"; echo "<td class='tab_bg_2 center' colspan='2'>"; echo "<input type='hidden' name='id' value='" . $ic->fields['id'] . "'>"; echo "<input type='submit' name='update' value=\"" . _sx('button', 'Save') . "\"\n class='submit'>"; echo "</td>"; echo "<td class='tab_bg_2 center' colspan='2'>"; echo "<input type='submit' name='delete' value=\"" . _sx('button', 'Delete permanently') . "\"\n class='submit'>"; echo "</td></tr>"; echo "</table></div>"; Html::closeForm(); } else { echo "</table></div>"; } } } }
You should have received a copy of the GNU General Public License along with GLPI. If not, see <http://www.gnu.org/licenses/>. -------------------------------------------------------------------------- */ /** @file * @brief */ include '../inc/includes.php'; Session::checkRight("budget", "r"); if (empty($_GET["id"])) { $_GET["id"] = ''; } if (!isset($_GET["withtemplate"])) { $_GET["withtemplate"] = ''; } $budget = new Budget(); if (isset($_POST["add"])) { $budget->check(-1, 'w', $_POST); if ($newID = $budget->add($_POST)) { $budget->refreshParentInfos(); Event::log($newID, "budget", 4, "financial", sprintf(__('%1$s adds the item %2$s'), $_SESSION["glpiname"], $_POST["name"])); } Html::back(); } else { if (isset($_POST["delete"])) { $budget->check($_POST["id"], 'd'); if ($budget->delete($_POST)) { Event::log($_POST["id"], "budget", 4, "financial", sprintf(__('%s deletes an item'), $_SESSION["glpiname"])); } $budget->redirectToList(); } else {
public function getBudgetForDipaOptions() { $models = Budget::model()->findAll(); $options = array(); foreach ($models as $model) { $subcomponent = Subcomponent::model()->findByAttributes(array('code' => $model->subcomponent_code)); if ($subcomponent) { $options[$model->code] = "[ {$model->code} ] | {$subcomponent->name}"; } else { $options[$model->code] = "[ {$model->code} ]"; } } return $options; }
public function getTotal($id) { $budgets = Budget::model()->findAllByAttributes(array('dipa_id' => $id)); $total = 0; if ($budgets) { foreach ($budgets as $budget) { $total += $budget->total_budget_limit; } } return $total; }
Copyright (C) 2003-2013 by the INDEPNET Development Team. http://indepnet.net/ http://glpi-project.org ------------------------------------------------------------------------- LICENSE This file is part of GLPI. GLPI is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. GLPI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GLPI. If not, see <http://www.gnu.org/licenses/>. -------------------------------------------------------------------------- */ /** @file * @brief */ include '../inc/includes.php'; Session::checkRight("budget", "r"); Html::header(Budget::getTypeName(1), $_SERVER['PHP_SELF'], "financial", "budget"); Search::show('Budget'); Html::footer();
public function close($id) { try { $user = User::find(Session::uid()); if (!$user->getId()) { throw new Exception('You have to be logged in to access user info!'); } $budget_id = (int) $id; $budget = new Budget(); if (!$budget->loadById($budget_id)) { throw new Exception('Invalid budget id'); } if ($budget->active != 1) { throw new Exception('This budget is already closed.'); } if ($user->getId() != $budget->receiver_id && $budget->giver_id != $user->getId()) { throw new Exception('Not enough rights'); } $budgetGiver = new User(); if (!$budgetGiver->findUserById($budget->giver_id)) { throw new Exception('Invalid giver id.'); } $budgetReceiver = new User(); if (!$budgetReceiver->findUserById($budget->receiver_id)) { throw new Exception('Invalid receiver id.'); } // all the child budgets are closed ? $childrenNotClosed = $budget->getChildrenNotClosed($budget->id); if ($childrenNotClosed != 0) { throw new Exception("This budget has one or more sub-allocated budget that are still active. " . "You may not close out this budget until the other budgets are closed out."); } // all the budgeted jobs are paid ? $feeAmountNotPaid = $this->getSumOfFeeNotPaidByBudget($budget->id); if ($feeAmountNotPaid !== null) { throw new Exception('Some fees are not paid.'); } $remainingFunds = $budget->getRemainingFunds(); if ($remainingFunds >= 0) { $budget->original_amount = $budget->amount; $budget->amount = $budget->original_amount - $remainingFunds; $budget->active = 0; $budgetReceiver->updateBudget(-$remainingFunds, $budget->id, false); $this->closeOutBudgetSource($remainingFunds, $budget, $budgetReceiver, $budgetGiver); if (!$budget->save('id')) { throw new Exception('Error in update budget.'); } } else { if ($user->getId() == $budget->receiver_id) { throw new Exception('Your budget is spent. Please contact the grantor (' . $budgetGiver->getNickname() . ') for additional funds.'); } $budget->original_amount = $budget->amount; $budget->amount = $budget->original_amount - $remainingFunds; $budget->active = 0; $budgetReceiver->updateBudget(-$remainingFunds, $budget->id, false); $this->closeOutBudgetSource($remainingFunds, $budget, $budgetReceiver, $budgetGiver); if (!$budget->save('id')) { throw new Exception('Error in update budget.'); } } $this->setOutput(array('success' => true, 'message' => 'Budget closed')); } catch (Exception $e) { return $this->setOutput(array('success' => false, 'message' => $e->getMessage())); } }