suiviFromBudget.php 40.7 KB
Newer Older
Clément Damiens's avatar
 
Clément Damiens committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
<?php 
/*
pour chaque ligne de dépense , on peut 
[X] associer un maitre d'oeuvre et ces type de travaux
[X] le maitre d'oeuvre peut déclaré le degré d'avancement
[X] l'administrateur poeut déclarer le total versé
[X] system de recettage ou validation globale par ligne de depense
[X] lister des sous tache ou todos
[X] connecté les todos à la progression de la ligne concerné

[/] edit les todos
[/] connecté les todos à la progression globale
[/] assigné une date de fin à une todo
[/] assigné les todos à d'autres

[ ] system de validation des todos
[ ] associer une url d'un outil de suivi externe
[ ] no reload sur la colonne total 
[ ] no reload sur la validation 
[ ] contraindre les actions à des roles  
*/

if($answer){ 
	$copy = "opalProcess1.depense";
25 26
	if( isset($this->costum["form"]["params"][$kunik]["budgetCopy"]) ) 
		$copy = $this->costum["form"]["params"][$kunik]["budgetCopy"];
27 28
	else if( count(Yii::app()->session["budgetInputList"]) == 1 )
		$copy = array_keys( Yii::app()->session["budgetInputList"])[0];
Clément Damiens's avatar
 
Clément Damiens committed
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
	//var_dump($copy);
	$copyT = explode(".", $copy);
	$copyF = $copyT[0];
	$copy = $copyT[1];

	$budgetKey = $copyT[1];
	$answers = null;	
	//var_dump($budgetKey);
	if($wizard){
		if( $budgetKey ){
			if( isset($answer["answers"][$copyF][$budgetKey]) && count($answer["answers"][$copyF][$budgetKey])>0)
			$answers = $answer["answers"][$copyF][$budgetKey];
		} else if( isset($answer["answers"][$copyF][$budgetKey]) && count($answer["answers"][$copyF][$budgetKey])>0 )
			$answers = $answer["answers"][$copyF][$kunik];
	} else {
44
		if(!empty($budgetKey) && !empty($answer["answers"][$budgetKey]))
Clément Damiens's avatar
 
Clément Damiens committed
45 46 47 48 49 50 51
			$answers = $answer["answers"][$budgetKey];
		else if(isset($answer["answers"][$kunik]))
			$answers = $answer["answers"][$kunik];
	}

$editBtnL =  "";

52
$editParamsBtn = ($canEditForm) ? " <a href='javascript:;' data-id='".$el["_id"]."' data-collection='".$this->costum["contextType"]."' data-path='costum.form.params.".$kunik."' class='previewTpl edit".$kunik."Params btn btn-xs btn-danger'><i class='fa fa-cog'></i> </a>" : "";
Clément Damiens's avatar
 
Clément Damiens committed
53 54 55 56 57 58 59


$paramsData = [ 
	"limitRoles" =>["worker","maitreoeuvre"]
];


60 61 62 63 64 65 66 67
if( isset($this->costum["form"]["params"][$kunik]["tpl"]) ) 
	$paramsData["tpl"] =  $this->costum["form"]["params"][$kunik]["tpl"];
if( isset($this->costum["form"]["params"][$kunik]["budgetCopy"]) ) 
	$paramsData["budgetCopy"] =  $this->costum["form"]["params"][$kunik]["budgetCopy"];
if( isset($this->costum["form"]["params"][$kunik]["limitRoles"]) ) 
	$paramsData["limitRoles"] =  $this->costum["form"]["params"][$kunik]["limitRoles"];
if( isset($this->costum["form"]["params"][$kunik]["budgetCopy"]) ) 
	$paramsData["budgetCopy"] =  $this->costum["form"]["params"][$kunik]["budgetCopy"];
Clément Damiens's avatar
 
Clément Damiens committed
68

69
$communityLinks = Element::getCommunityByTypeAndId($this->costum["contextType"],$this->costum["contextId"]);
Clément Damiens's avatar
 
Clément Damiens committed
70 71 72 73 74
$organizations = Link::groupFindByType( Organization::COLLECTION,$communityLinks,["name","links"] );

$orgs = [];

foreach ($organizations as $id => $or) {
75 76
	if( isset($or["links"]["memberOf"][$this->costum["contextId"]]["roles"]) )
		$roles = $or["links"]["memberOf"][ $this->costum["contextId"] ]["roles"];
Clément Damiens's avatar
 
Clément Damiens committed
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
	if( $paramsData["limitRoles"] && !empty($roles))
	{
		foreach ($roles as $i => $r) {
			if( in_array($r, $paramsData["limitRoles"]) )
				$orgs[$id] = $or["name"];
		}		
	}
}
//var_dump($orgs);exit;
$listLabels = array_merge($orgs);//Ctenat::$financerTypeList,

$properties = [
    "worker" => [
        "placeholder" => "Maitre d'oeuvre",
        "inputType" => "select",
        "list" => "workerList",
        "subLabel" => "Si financeur public, l’inviter dans la liste ci-dessous (au cas où il n’apparait pas demandez à votre référent territoire de le déclarer comme partenaire financeur"
    ],
    "workType" => [
        "inputType" => "text",
        "label" => "Type de travaux",
        "placeholder" => "Type de travaux",
        "rules" => [ "required" => true ]
    ],
    "poste" => [
        "inputType" => "text",
        "label" => "Contexte",
        "placeholder" => "Contexte",
        "rules" => [ "required" => true ]
    ],
    "todo" => [
        "inputType" => "text",
        "label" => "Todo Liste",
        "placeholder" => "Todo Liste",
        "rules" => [ "required" => true,"number" => true  ]
    ],
    "progress" => [
        "inputType" => "text",
        "label" => "Avancement Travaux",
        "placeholder" => "Avancement Travaux",
        "rules" => [ "required" => true,"number" => true  ]
    ],
    "total" => [
        "inputType" => "text",
        "label" => "Total",
        "placeholder" => "Total",
        "rules" => [ "required" => true,"number" => true ]
    ],
    "validation" => [
        "inputType" => "text",
        "label" => "Validation",
        "placeholder" => "Validation",
        "rules" => [ "number" => true  ]
    ]
];


	?>	
<div class="form-group">
	<table class="table table-bordered table-hover  directoryTable" id="<?php echo $kunik?>">

	<thead>
		<tr>
			<td colspan='<?php echo count( $properties)+2?>' ><h4 style="color:<?php echo ($titleColor) ? $titleColor : "black"; ?>"><?php echo $label.$editQuestionBtn.$editParamsBtn.$editBtnL?></h4>
				<?php echo $info;
142
				if( !isset($budgetKey) ) 
Clément Damiens's avatar
 
Clément Damiens committed
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
					echo "<br/><span class='text-red text-center'><i class='fa fa-warning fa-2x'></i> THIS FIELD HAS TO BE CONFIGURED FIRST ".$editParamsBtn."</span>"; ?>
			</td>
		</tr>	
		<?php if($answers){ ?>
		<tr>
			</th>
			<?php 
			
			foreach ($properties as $i => $inp) {
				echo "<th>".$inp["placeholder"]."</th>";
			} ?>
			<th></th>
		</tr>
		<?php } ?>
	</thead>
	<tbody class="directoryLines">	
		<?php 
		$ct = 0;
		$totalProgress = 0;
		$bigTotal = 0;
		$totalPayed = 0;
		$validWork = 0;
		$payedWork = 0;
		$totalTodos = 0;
		$totalTodosDone = 0;
		if($answers){
			foreach ($answers as $q => $a) {

				$trStyle = "";
				$tds = "";
				$todoDone  = 0;
				$todo = 0;
				foreach ($properties as $i => $inp) 
				{
					$tds .= "<td>";
					
					if( $i == "worker"  )
					{
						$valbl = "?";
						$class= "btn btn-default";
						if( isset( $a["worker"] ) )
						{
							$o = PHDB::findOne(Organization::COLLECTION,["_id"=>new MongoId($a["worker"]["id"])],["name","slug"]);	
							$valbl = $o["name"];
							$class="";
						}	
						$tds .= "<a href='javascript:;' data-id='".$answer["_id"]."' data-budgetpath='".$copy."' data-form='".$copyF."' data-pos='".$q."'  class='".$class." btnWorker margin-left-5 padding-10'>".$valbl."</a>";
					}

					if( $i == "todo"  )
					{
						$valbl = "<i class='fa fa-plus'></i>";
						$class= "btn btn-default";
						if( isset( $a["todo"] ) ){
							$valbl = count( $a["todo"] );
							$totalTodos += count($a["todo"]);
							foreach ($a["todo"] as $tix => $do) {
Tibor Katelbach's avatar
Tibor Katelbach committed
200
								if(isset($do["done"]) && $do["done"]=="1")
Clément Damiens's avatar
 
Clément Damiens committed
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
									$todoDone++;
								else 
									$todo++;
							}
							$totalTodosDone += $todoDone;
							$valbl = $todoDone."/".count( $a["todo"] );
						}
						$tds .= "<a href='javascript:;' id='btnTodo".$q."' data-id='".$answer["_id"]."' data-budgetpath='".$copy."' data-form='".$copyF."' data-pos='".$q."'  class='".$class." btnTodo margin-left-5 padding-10'>".$valbl."</a>";
					}
					else if( $i == "line" && isset( $a["financer"]["line"] ) ) 
						$tds .= $a["financer"]["line"];
					else if( $i == "workType" && isset( $a["worker"]["workType"] ) ) 
						$tds .= $a["worker"]["workType"];
					else if( $i == "progress"){
						if(isset($a["todo"])){
							$progress = floor($todoDone*100/count($a["todo"]));
						}
						else {
							$progress = (!empty($a["progress"]) ) ? (int)$a["progress"] : 0;
						}
						$totalProgress += $progress;
						$percol = "warning";
						if( $progress == 100 ){
							$percol = "success";
						}
						$tds .= "<a href='javascript:;' id='todoPerc".$q."' data-id='".$answer["_id"]."' data-budgetpath='".$copy."' data-form='".$copyF."' data-pos='".$q."'  class=' btnProgress margin-left-5 padding-10'>".$progress."%</a>";
						$tds .= '<div class="progress btnProgress"  data-id="'.$answer["_id"].'" data-budgetpath="'.$copy.'" data-form="'.$copyF.'" data-pos="'.$q.'"  style="cursor:pointer" >'.
						  '<div id="todoProgress'.$q.'" class="progress-bar progress-bar-'.$percol.'" style="width:'.$progress.'%">'.
							    '<span class="sr-only">'.$progress.'% Complete</span>'.
						  '</div>'.
						'</div>';
					}
					else if( $i == "total"){ 
						$total = 0;
						$totalPayedHere = 0;
236
						$amounts = (isset($this->costum["form"]["params"][$budgetKey]["amounts"])) ? $this->costum["form"]["params"][$budgetKey]["amounts"] : ["price" => "Price"] ; 
Clément Damiens's avatar
 
Clément Damiens committed
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
				        foreach ( $amounts as $k => $l) {
					    	if(!empty($a[$k]))
								$total += (int)$a[$k];	
					    }
						
						$bigTotal += $total;
						$color = "default";
						if(isset($a["payed"])){
							if($a["payed"]["status"] == "total"){
								$color = "success";
								$totalPayedHere = $total;
								$payedWork++;
							}
							else if($a["payed"]["status"] == "partly"){
								$color = "warning";
								$totalPayedHere = $a["payed"]["amount"];
							}
							else if($a["payed"]["status"] == "accompte"){
								$color = "warning";
								$totalPayedHere = $a["payed"]["amount"];
							}
							$totalPayed += $totalPayedHere;
						}
						$tds .= "<a href='javascript:;' data-id='".$answer["_id"]."' data-budgetpath='".$copy."' data-form='".$copyF."' data-pos='".$q."'  class='btnPay margin-left-5 padding-10'>".$total."€</a>";

						$percol = "default";
						$payedPercent = 0;
						if($totalPayedHere != 0){
							$payedPercent = $totalPayedHere * 100 / $total;
							$percol = "warning";
						}
						
						if( $payedPercent == 100 ){
							$percol = "success";
						}
						$tds .= '<div class="progress btnPay" data-id="'.$answer["_id"].'" data-budgetpath="'.$copy.'" data-form="'.$copyF.'" data-pos="'.$q.'"  style="cursor:pointer" >'.
						  '<div class="progress-bar progress-bar-'.$percol.'" style="width:'.$payedPercent.'%">'.
							    '<span class="sr-only">'.$payedPercent.'% Complete</span>'.
						  '</div>'.
						'</div>';
					}
					else if( $i == "validation"){ 
						$color = "default";
						$valbl = "?";
						$tool= "En attente de validation";
						if( isset($a["validFinal"]) ){
							if( $a["validFinal"]["valid"] == "validated" ){
								$color = "success";
								$valbl = "V";
								$trStyle = "background-color:#e5ffe5";
								$validWork++;
								$tool="Validé sans réserve";
							} else if( $a["validFinal"]["valid"] == "reserved" ){
								$color = "warning";
								$valbl = "R";
								$tool="Validé avec réserves";
							} else if( $a["validFinal"]["valid"] == "refused" ){
								$color = "danger";
								$valbl = "NV";
								$tool="Non validé";
							}
						}

						$tds .= "<a href='javascript:;' data-id='".$answer["_id"]."' data-budgetpath='".$copy."' data-form='".$copyF."' data-pos='".$q."'  class='btnValidateWork btn btn-xs btn-".$color." margin-left-5 padding-10 tooltips' data-toggle='tooltip' data-placement='left' data-original-title='".$tool."'>".$valbl."</a>";
					}else if( isset( $a[$i] ) && is_array($a[$i]) ) 
						$tds .= implode(" , ", $a[$i]);
					else if( isset( $a[$i] ) ) 
						$tds .= $a[$i];
					
					$tds .= "</td>";
				}
					
			?>
			
			<?php 
				$ct++;
				echo "<tr id='".$kunik.$q."' class='".$kunik."Line text-center' style='".$trStyle."'>";
				echo $tds;?>
				<td>
					<a href="javascript:;" class="btn btn-xs btn-primary openAnswersComment" onclick="commentObj.openPreview('answers','<?php echo $answer["_id"]?>','<?php echo $answer["_id"].$key.$q ?>', '<?php echo @$a['step'] ?>')"><?php echo PHDB::count(Comment::COLLECTION, array("contextId"=>$answer["_id"],"contextType"=>"answers", "path"=>$answer["_id"].$key.$q))?> <i class='fa fa-commenting'></i></a>
				</td>
			</tr>
			<?php 
			}
		}
?>
		</tbody>
	</table>

<?php 
$percol = "warning";
$totalProgress = (!empty($answers)) ? $totalProgress / count($answers) : 0;
if( $totalProgress == 100 ){
	$percol = "success";
}
echo "<h4 style='color:".(($titleColor) ? $titleColor : "black")."'>Pourcentage d'avancement Globale</h4>".
'<div class="progress " style="cursor:pointer" >'.
  '<div class="progress-bar progress-bar-'.$percol.'" style="width:'.$totalProgress.'%">'.
	    '<span class="sr-only">'.$totalProgress.'% Complete</span>'.
  '</div>'.
'</div>'; ?>

<table class="table table-bordered table-hover  ">
	<tbody class="">
		<tr>
			<td>Pourcentage d'avancement</td>
			<td><?php echo floor($totalProgress) ?>%</td>
		</tr>
		<tr>
			<td>Resta à faire </td>
			<td><?php echo floor(100-$totalProgress) ?>%</td>
		</tr>
		<tr>
			<td>Nombres de Travaux Validés </td>
			<td><?php echo $validWork."/".count($answers) ?></td>
		</tr>
		<tr>
			<td>Nombres de Taches Cloturés </td>
			<td><?php echo $totalTodosDone."/".$totalTodos ?></td>
		</tr>
		
	</tbody>
</table>

<?php 
$percol = "warning";
$bigTotalPercent = (!empty($bigTotal)) ? $totalPayed * 100 / $bigTotal : 0;
if( $bigTotalPercent == 100 ){
	$percol = "success";
}
echo "<h4 style='color:".(($titleColor) ? $titleColor : "black")."'>Suivi des dépenses Globale</h4>".
'<div class="progress " style="cursor:pointer" >'.
  '<div class="progress-bar progress-bar-'.$percol.'" style="width:'.$bigTotalPercent.'%">'.
	    '<span class="sr-only">'.$bigTotalPercent.'% Complete</span>'.
  '</div>'.
'</div>'; ?>

<table class="table table-bordered table-hover  ">
	<tbody class="">
		<tr>
			<td>BUDGET TOTAL</td>
			<td><?php echo trim(strrev(chunk_split(strrev($bigTotal),3, ' '))) ?></td>
		</tr>
		<tr>
			<td>TRAVAUX PAYÉS</td>
			<td><?php echo trim(strrev(chunk_split(strrev($totalPayed),3, ' '))) ?></td>
		</tr>
		<tr>
			<td>DELTA</td>
			<td><?php echo trim(strrev(chunk_split(strrev($bigTotal-$totalPayed),3, ' '))) ?></td>
		</tr>
		<tr>
			<td>Nombres de Travaux Cloturés </td>
			<td><?php echo $payedWork."/".count($answers) ?></td>
		</tr>
	</tbody>
</table>

</div>

<div class="form-worker" style="display:none;">
	<select id="worker" style="width:100%;">
		<option>Choisir un maitre d'oeuvre</option>
		<?php foreach ($orgs as $v => $f) {
			echo "<option value='".$v."'>".$f."</option>";
		} ?>
	</select>
	<br>
	<span class="bold">Type de travaux effectués :</span> <br/>
	<input type="text" id="workType" name="workType" style="width:100%;">
	<br><br>
	<span class="bold">Organisme qui effectue les travaux , s'il n'existe pas, créez le et ajoutez le à la communauté ici 
		<a class="btn btn-primary">Ajouter un maitre d'oeuvre</a>
	</span>
	<br>
</div>

<div class="form-progress" style="display:none;">
	<select id="progress" style="width:100%;">
		<option> DEGRÉ D'AVANCEMENT DE CE CHANTIER </option>
		<?php foreach ([25,50,75,100] as $v => $f) {
			echo "<option value='".$f."'>".$f."%</option>";
		} ?>
	</select>
</div>

<div class="form-pay" style="display:none;">
  	<select id="status" style="width:100%;">
		<option> État du paiement </option>
		<?php foreach (["accompte" => "Accompte avancé",
						"partly" => "Facture payées",
						"total" => "Soldé" ] as $v => $f) {
			echo "<option value='".$v."'>".$f."</option>";
		} ?>
		</select>
		<br/><br/>

	<span class="bold">Total des Montants payés :</span> <br/>
	<input type="text" id="amount" name="amount" style="width:100%;">
</div>

<div class="form-validate-work" style="display:none;">
  	<select id="validWork" style="width:100%;">
		<option> Valider ces travaux </option>
		<?php foreach (["validated" => "Validé sans réserve",
						"reserved" => "Validé avec réserves",
						"refused" => "Non validé" ] as $v => $f) {
			echo "<option value='".$v."'>".$f."</option>";
		} ?>
		</select>
</div>

<style type="text/css">
	.strike {text-decoration: line-through;}
	input[type=checkbox]
	{
	  /* Double-sized Checkboxes */
	  -ms-transform: scale(0.6); /* IE */
	  -moz-transform: scale(0.6); /* FF */
	  -webkit-transform: scale(0.6); /* Safari and Chrome */
	  -o-transform: scale(0.6); /* Opera */
	  transform: scale(0.6);
	  padding: 10px;
	  vertical-align: middle;
	}
	#todo-list{ list-style: none}
	#todo-list li{ border-bottom: 1px solid #ccc;padding: 5px;}
</style>
<div class="form-todo" style="display:none;">
	<!-- Url externe : <br/>
	<input type="text" id="todoUrl" name="todoUrl" style="width:100%;">
	<br/> -->
	<form id="form-add-todo" class="form-add-todo">
		<!-- <label for="todo">To do:</label> -->
Tibor Katelbach's avatar
Tibor Katelbach committed
471
		<?php 
Tibor Katelbach's avatar
tweaks  
Tibor Katelbach committed
472 473 474 475 476
		$uids = [];
		if(isset($el["links"]["members"])){
			foreach (array_keys($el["links"]["members"]) as $ix => $id) {
				$uids[] = new MongoId($id);
			}
Tibor Katelbach's avatar
Tibor Katelbach committed
477 478
		}
		$members = PHDB::find ( Person::COLLECTION, [ "_id" => [ '$in' => $uids ] ] , ["name","username"] );
Tibor Katelbach's avatar
tweaks  
Tibor Katelbach committed
479

Tibor Katelbach's avatar
Tibor Katelbach committed
480 481
		?>
		<!-- <textarea id="new-todo-item" class="new-todo-item col-xs-5" name="todo" placeholder="Quoi"></textarea> -->
Tibor Katelbach's avatar
Tibor Katelbach committed
482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500
		<div class="col-xs-12">
			<div class="col-xs-8">
				<label for="new-todo-item">Choses à faire</label>
				<input type="text" id="new-todo-item" class="new-todo-item  col-xs-12" name="todo" placeholder="Quoi"/>
			</div>
			<div class="col-xs-4">
				<label for="new-todo-item-price"> <i class='fa fa-money'></i> Cout de cette tache</label>
				<input type="text" id="new-todo-item-price" class="new-todo-item-price col-xs-12" name="price"  placeholder="Pour combien"/>
				<!-- <select id="votes" style="width:100%;">
					<option> VOTEZ pour cette partie </option>
					<?php foreach ([0,10,20,30,40,50,60,70,80,90,100] as $v => $f) {
						if($f == 0)
							$lbl = "Je ne suis pas pour!";
						else 
							$lbl = "Je suis pour à ".$f."%";
						echo "<option value='".$f."'>".$lbl."</option>";
					} ?>
				</select> -->
			</div>
Tibor Katelbach's avatar
Tibor Katelbach committed
501
		</div>
Tibor Katelbach's avatar
Tibor Katelbach committed
502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517
		<div class="col-xs-12 margin-top-10" >
			<div class="col-xs-6">
				<label for="new-todo-item-date"> <i class='fa fa-calendar'></i> Date de fin estimé :</label>
				<input type="date" id="new-todo-item-date" class="new-todo-item-date col-xs-12" name="when"  placeholder="Pour quand"/>
			</div>
			<div class="col-xs-6">
				<label for="new-todo-item-who"> <i class='fa fa-user'></i> Personne(s) qui réalisera cette tache :</label>
				<select id="new-todo-item-who" class="new-todo-item-who col-xs-12" multiple>
					<?php 
					foreach ( $members as $id => $p ) {
						$selected = ( $id == Yii::app()->session["userId"] ) ? "selected" : "";
						echo "<option value='".$p["username"]."' data-id='".$id."' ".$selected." >".$p["name"]."</option>";
					} 
					?> 	
				</select>
			</div>
Tibor Katelbach's avatar
Tibor Katelbach committed
518
		</div>
Tibor Katelbach's avatar
Tibor Katelbach committed
519 520
		<div class="col-xs-12 margin-top-10 text-center" >
			<a id="add-todo-item" class="btn btn-primary" href="javascript:;"><i class='fa fa-plus'></i> Ajouter</a>
Tibor Katelbach's avatar
Tibor Katelbach committed
521
		</div>
Clément Damiens's avatar
 
Clément Damiens committed
522 523 524
	</form>

	<form id="form-todo-list">
Tibor Katelbach's avatar
Tibor Katelbach committed
525
		<ul id="todo-list" class="margin-top-20 col-xs-12 todo-list" style="border: 1px solid black"></ul>
Clément Damiens's avatar
 
Clément Damiens committed
526 527 528 529 530
	</form>
</div>


<?php 
531 532 533
if( isset($this->costum["form"]["params"]["financement"]["tpl"])){
	//if( $this->costum["form"]["params"]["financement"]["tpl"] == "tpls.forms.equibudget" )
		$this->renderPartial( "costum.views.".$this->costum["form"]["params"]["financement"]["tpl"] , 
Clément Damiens's avatar
 
Clément Damiens committed
534 535 536
		[ "totalFin"   => $total,
		  "totalBudg" => Yii::app()->session["totalBudget"]["totalBudget"] ] );
	// else 
537
	// 	$this->renderPartial( "costum.views.".$this->costum["form"]["params"]["financement"]["tpl"]);
Clément Damiens's avatar
 
Clément Damiens committed
538 539 540 541 542 543
}
 ?>

<script type="text/javascript">
if(typeof costum.lists == "undefined")
	costum.lists = {};
544 545 546
if(typeof costum.lists == "undefined")
	costum.lists.budgetInputList = <?php echo json_encode( Yii::app()->session["budgetInputList"] ); ?>;

Clément Damiens's avatar
 
Clément Damiens committed
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572
//costum.lists.financerTypeList = <?php //echo json_encode(Ctenat::$financerTypeList); ?>;
costum.lists.workerList = <?php echo json_encode($orgs); ?>;


var <?php echo $kunik ?>Data = <?php echo json_encode( (isset($answer["answers"][$copy])) ? $answer["answers"][$copy] : null ); ?>;
sectionDyf.<?php echo $kunik ?>ParamsData = <?php echo json_encode( $paramsData ); ?>;

$(document).ready(function() { 
	
	sectionDyf.<?php echo $kunik ?> = {
		"jsonSchema" : {	
	        "title" : "Plan de Financement",
            "icon" : "fa-money",
            "text" : "Décrire ici les financements mobilisés ou à mobiliser. Les coûts doivent être en <b>hors taxe</b>.",
	        "properties" : <?php echo json_encode( $properties ); ?>,
	        save : function () {  
	            tplCtx.value = {};
	            $.each( sectionDyf.<?php echo $kunik ?>.jsonSchema.properties , function(k,val) { 
	        		tplCtx.value[k] = $("#"+k).val();
	        	 });
	            mylog.log("save tplCtx",tplCtx);
	            if(typeof tplCtx.value == "undefined")
	            	toastr.error('value cannot be empty!');
	            else {
	                dataHelper.path2Value( tplCtx, function(params) { 
	                    $("#ajax-modal").html("<div class='text-center'><i class='fa fa-spin fa-spinner'></i></div>");//$("#ajax-modal").modal('hide');
573
	                    urlCtrl.loadByHash(location.hash);
Clément Damiens's avatar
 
Clément Damiens committed
574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624
	                } );
	            }

	    	}
	    }
	};

	sectionDyf.<?php echo $kunik ?>Params = {
		"jsonSchema" : {	
	        "title" : "<?php echo $kunik ?> config",
	        "icon" : "fa-cog",
	        "properties" : {
	            // financerTypeList : {
	            //     inputType : "properties",
	            //     labelKey : "Clef",
	            //     labelValue : "Label affiché",
	            //     label : "Liste des type de Fiannceurs",
	            //     values :  sectionDyf.<?php echo $kunik ?>ParamsData.financerTypeList
	            // } , 
	            limitRoles : {
	                inputType : "array",
	                label : "Liste des roles financeurs",
	                values :  sectionDyf.<?php echo $kunik ?>ParamsData.limitRoles
	            },
	            tpl : {
	                label : "Sub Template",
	                value :  sectionDyf.<?php echo $kunik ?>ParamsData.tpl
	            },
	            budgetCopy : {
	            	label : "Input Bugdet",
	            	inputType : "select",
	            	options :  costum.lists.budgetInputList
	            }
	        },
	        save : function () {  
	            tplCtx.value = {};
	            $.each( sectionDyf.<?php echo $kunik ?>Params.jsonSchema.properties , function(k,val) { 
	        		if(val.inputType == "array")
	        		 	tplCtx.value[k] = getArray('.'+k+val.inputType);
	        		else if(val.inputType == "properties")
	        		 	tplCtx.value[k] = getPairsObj('.'+k+val.inputType);
	        		else
	        		 	tplCtx.value[k] = $("#"+k).val();
	        	 });
	            mylog.log("save tplCtx",tplCtx);
	            
	            if(typeof tplCtx.value == "undefined")
	            	toastr.error('value cannot be empty!');
	            else {
	                dataHelper.path2Value( tplCtx, function(params) { 
	                    $("#ajax-modal").html("<div class='text-center'><i class='fa fa-spin fa-spinner'></i></div>");
625
	                    urlCtrl.loadByHash(location.hash);
Clément Damiens's avatar
 
Clément Damiens committed
626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692
	                } );
	            }

	    	}
	    }
	};


    mylog.log("render","/modules/costum/views/tpls/forms/<?php echo $kunik ?>.php");

    //adds a line into answer
    $(".add<?php echo $kunik ?>").off().on("click",function() {  
        tplCtx.id = $(this).data("id");
        tplCtx.collection = $(this).data("collection");            
        tplCtx.path = $(this).data("path")+((notNull(<?php echo $kunik ?>Data) ? <?php echo $kunik ?>Data.length : "0"));
        dyFObj.openForm( sectionDyf.<?php echo $kunik ?> );
    });

    $(".edit<?php echo $kunik ?>").off().on("click",function() {  
        tplCtx.id = $(this).data("id");
        tplCtx.collection = $(this).data("collection"); 
        tplCtx.path = $(this).data("path");
        dyFObj.openForm( sectionDyf.<?php echo $kunik ?>,null, <?php echo $kunik ?>Data[$(this).data("key")]);
    });

    $(".edit<?php echo $kunik ?>Params").off().on("click",function() {  
        tplCtx.id = $(this).data("id");
        tplCtx.collection = $(this).data("collection");
        tplCtx.path = $(this).data("path");
        //mylog.log(".edit<?php echo $kunik ?>Params",tplCtx,sectionDyf.<?php echo $kunik ?>ParamsData);
        dyFObj.openForm( sectionDyf.<?php echo $kunik ?>Params,null, sectionDyf.<?php echo $kunik ?>ParamsData);
    });

    
    $('.btnValidateWork').off().click(function() { 
		tplCtx.pos = $(this).data("pos");
		tplCtx.budgetpath = $(this).data("budgetpath");
		tplCtx.collection = "answers";
		tplCtx.id = $(this).data("id");
		tplCtx.form = $(this).data("form");
		prioModal = bootbox.dialog({
	        message: $(".form-validate-work").html(),
	        title: "Validation des travaux",
	        show: false,
	        buttons: {
                success: {
                    label: trad.save,
                    className: "btn-primary",
                    callback: function () {
			            
			        	var formInputsHere = formInputs;
			        	tplCtx.path = "answers";
			        	if( notNull(formInputs [tplCtx.form]) )
			        		tplCtx.path = "answers."+tplCtx.form;    

			        	tplCtx.path = tplCtx.path+"."+tplCtx.budgetpath+"."+tplCtx.pos+".validFinal";	   
			        	
			        	var today = new Date();
						today = today.getDate() + '/' + (today.getMonth()+1) + '/' + today.getFullYear();	
			            tplCtx.value = { 
		        			valid : $(".bootbox #validWork").val(),
		        			user : userId,
		        			date : today
		        		};
		        		delete tplCtx.pos;
		        		delete tplCtx.budgetpath;
				    	mylog.log("btnValidateWork save",tplCtx);
693 694 695
				  	 	dataHelper.path2Value( tplCtx, function(){
				  	 		saveLinks(answerObj._id.$id,"workValidated",userId,closePrioModalRel);
				  	 	} );
Clément Damiens's avatar
 
Clément Damiens committed
696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743
				  	 }		
                },
                cancel: {
                  label: trad.cancel,
                  className: "btn-secondary",
                  callback: closePrioModal
                }
              },
		        onEscape: closePrioModal
	    });
	    prioModal.modal("show");
	});

    $('.btnWorker').off().click(function() { 
		tplCtx.pos = $(this).data("pos");
		tplCtx.budgetpath = $(this).data("budgetpath");
		tplCtx.collection = "answers";
		tplCtx.id = $(this).data("id");
		tplCtx.form = $(this).data("form");
		prioModal = bootbox.dialog({
	        message: $(".form-worker").html(),
	        title: "Choix du maitre d'oeuvre",
	        show: false,
	        buttons: {
                success: {
                    label: trad.save,
                    className: "btn-primary",
                    callback: function () {
			            
			        	var formInputsHere = formInputs;
			        	tplCtx.path = "answers";
			        	if( notNull(formInputs [tplCtx.form]) )
			        		tplCtx.path = "answers."+tplCtx.form;    

			        	tplCtx.path = tplCtx.path+"."+tplCtx.budgetpath+"."+tplCtx.pos+".worker";   

			        	var today = new Date();
						today = today.getDate() + '/' + (today.getMonth()+1) + '/' + today.getFullYear();	
			            tplCtx.value = { 
		        			id : $(".bootbox #worker").val(),
		        			name : $(".bootbox #worker option:selected").text(),
		        			workType : $(".bootbox #workType").val(),
		        			user : userId,
		        			date : today
		        		};
		        		delete tplCtx.pos;
		        		delete tplCtx.budgetpath;
				    	mylog.log("btnFinancer save",tplCtx);
744 745 746
				  	 	dataHelper.path2Value( tplCtx, function(){
				  	 		saveLinks(answerObj._id.$id,"worker",userId,closePrioModal);
				  	 	} );
Clément Damiens's avatar
 
Clément Damiens committed
747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787
			        }		
                },
                cancel: {
                  label: trad.cancel,
                  className: "btn-secondary",
                  callback: closePrioModal
                }
              },
		        onEscape: closePrioModal
	    });
	    prioModal.modal("show");
	});
	$('.btnProgress').off().click(function() { 
		tplCtx.pos = $(this).data("pos");
		tplCtx.budgetpath = $(this).data("budgetpath");
		tplCtx.collection = "answers";
		tplCtx.id = $(this).data("id");
		tplCtx.form = $(this).data("form");
		prioModal = bootbox.dialog({
	        message: $(".form-progress").html(),
	        title: "Degrés d'avancement",
	        show: false,
	        buttons: {
                success: {
                    label: trad.save,
                    className: "btn-primary",
                    callback: function () {
			            
			        	var formInputsHere = formInputs;
			        	tplCtx.path = "answers";
			        	if( notNull(formInputs [tplCtx.form]) )
			        		tplCtx.path = "answers."+tplCtx.form;    

			        	tplCtx.path = tplCtx.path+"."+tplCtx.budgetpath+"."+tplCtx.pos+".progress";   

			        	var today = new Date();
						today = today.getDate() + '/' + (today.getMonth()+1) + '/' + today.getFullYear();	
			            tplCtx.value = $(".bootbox #progress").val();
		        		delete tplCtx.pos;
		        		delete tplCtx.budgetpath;
				    	mylog.log("btnProgress save",tplCtx);
788 789 790
				  	 	dataHelper.path2Value( tplCtx, function(){
				  	 		saveLinks(answerObj._id.$id,"workProgress",userId,closePrioModalRel);
				  	 	} );
Clément Damiens's avatar
 
Clément Damiens committed
791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838
			        }		
                },
                cancel: {
                  label: trad.cancel,
                  className: "btn-secondary",
                  callback: closePrioModal
                }
              },
		        onEscape: closePrioModal
	    });
	    prioModal.modal("show");
	});

	$('.btnPay').off().click(function() { 
		tplCtx.pos = $(this).data("pos");
		tplCtx.budgetpath = $(this).data("budgetpath");
		tplCtx.collection = "answers";
		tplCtx.id = $(this).data("id");
		tplCtx.form = $(this).data("form");
		mylog.log("btnPay open",tplCtx);
		prioModal = bootbox.dialog({
	        message: $(".form-pay").html(),
	        title: "Statuts des réglements",
	        show: false,
	        buttons: {
                success: {
                    label: trad.save,
                    className: "btn-primary",
                    callback: function () {
			            
			        	var formInputsHere = formInputs;
			        	tplCtx.path = "answers";
			        	if( notNull(formInputs [tplCtx.form]) )
			        		tplCtx.path = "answers."+tplCtx.form;    

			        	tplCtx.path = tplCtx.path+"."+tplCtx.budgetpath+"."+tplCtx.pos+".payed";   
						
			        	var today = new Date();
						today = today.getDate() + '/' + (today.getMonth()+1) + '/' + today.getFullYear();	
			            tplCtx.value = { 
		        			status : $(".bootbox #status").val(),
		        			amount : $(".bootbox #amount").val(),
		        			user : userId,
		        			date : today
		        		};
		        		delete tplCtx.pos;
		        		delete tplCtx.budgetpath;
				    	mylog.log("btnPay save",tplCtx);
839 840 841
				  	 	dataHelper.path2Value( tplCtx, function(){
				  	 		saveLinks(answerObj._id.$id,"workPayed",userId,closePrioModalRel);
				  	 	} );
Clément Damiens's avatar
 
Clément Damiens committed
842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861
			        }		
                },
                cancel: {
                  label: trad.cancel,
                  className: "btn-secondary",
                  callback: closePrioModal
                }
              },
		        onEscape: closePrioModal
	    });
	    prioModal.modal("show");
	});

	$('.btnTodo').off().click(function() { 
		tplCtx.pos = $(this).data("pos");
		tplCtx.budgetpath = $(this).data("budgetpath");
		tplCtx.collection = "answers";
		tplCtx.id = $(this).data("id");
		tplCtx.form = $(this).data("form");
		mylog.log("btnTodo open",tplCtx);
Tibor Katelbach's avatar
Tibor Katelbach committed
862
		tplCtx.editTaskpos = null;
Clément Damiens's avatar
 
Clément Damiens committed
863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879

		prioModal = bootbox.dialog({
	        message: $(".form-todo").html(),
	        title: "Todo Liste",
	        size: "large",
	        show: false,
	        buttons: {
                success: {
                    label: trad.save,
                    className: "btn-primary",
                    callback: function () {
			            
			        	var formInputsHere = formInputs;
			        	tplCtx.path = "answers";
			        	if( notNull(formInputs [tplCtx.form]) )
			        		tplCtx.path = "answers."+tplCtx.form;    

Tibor Katelbach's avatar
Tibor Katelbach committed
880 881 882
			        	tplCtx.path = tplCtx.path+"."+tplCtx.budgetpath+"."+tplCtx.pos+".todo";
				        tplCtx.value = answerObj.answers[tplCtx.form][tplCtx.budgetpath][tplCtx.pos].todo;

Clément Damiens's avatar
 
Clément Damiens committed
883
				        var todoDone = 0;
Tibor Katelbach's avatar
Tibor Katelbach committed
884 885 886 887 888 889
				        $.each(tplCtx.value, function(ix,todo) { 
							if(parseInt(todo.done) == 1)
								todoDone++;
						})
				        $("#btnTodo"+tplCtx.pos).html( todoDone+"/"+tplCtx.value.length );
						$("#todoProgress"+tplCtx.pos).css( "width",Math.floor(todoDone*100/tplCtx.value.length)); 
Clément Damiens's avatar
 
Clément Damiens committed
890 891
						$("#todoPerc"+tplCtx.pos).html(Math.floor(todoDone*100/tplCtx.value.length)+"%");
				    	mylog.log("btnPay save",tplCtx);
892 893 894
				  	 	dataHelper.path2Value( tplCtx, function(){
				  	 		saveLinks(answerObj._id.$id,"workTodo",userId,closePrioModalRel);
				  	 	});
Clément Damiens's avatar
 
Clément Damiens committed
895 896 897 898 899 900 901 902 903 904 905
			        }		
                },
                cancel: {
                  label: trad.cancel,
                  className: "btn-secondary",
                  callback: closePrioModal
                }
              },
		        onEscape: closePrioModal
	    });
	    prioModal.on('shown.bs.modal', function (e) {
Tibor Katelbach's avatar
Tibor Katelbach committed
906
	    	prioModal.css({'background-color': '#000'} );
Clément Damiens's avatar
 
Clément Damiens committed
907 908
			$(".bootbox #add-todo-item").off().on('click', function(e){
				e.preventDefault();
Tibor Katelbach's avatar
Tibor Katelbach committed
909
				listObj.addTodoItem()
Clément Damiens's avatar
 
Clément Damiens committed
910
			});
Tibor Katelbach's avatar
Tibor Katelbach committed
911
			$(".bootbox #new-todo-item, .bootbox #new-todo-item-when,.bootbox #new-todo-item-who,.bootbox #new-todo-item-price ").off().on('keypress', function(e){
Clément Damiens's avatar
 
Clément Damiens committed
912 913 914
				var keycode;
				if (window.event) {keycode = window.event.keyCode;e=event;}
				else if (e){ keycode = e.which;}
Tibor Katelbach's avatar
Tibor Katelbach committed
915
				if( keycode=="13" )
Tibor Katelbach's avatar
Tibor Katelbach committed
916
					listObj.addTodoItem();
Clément Damiens's avatar
 
Clément Damiens committed
917
			});
Tibor Katelbach's avatar
Tibor Katelbach committed
918

Clément Damiens's avatar
 
Clément Damiens committed
919 920 921 922 923 924 925 926 927 928 929

			todoPath = "answerObj.answers."; 
			if( notNull(formInputs [tplCtx.form]) )
				todoPath = "answerObj.answers."+tplCtx.form+"."; 
			todoPath += tplCtx.budgetpath+"["+tplCtx.pos+"].todo";
			mylog.log("build todos path ",todoPath);
			if( notNull(todoPath ) )
			{
				var todos = eval( todoPath );
				mylog.log("build todos",todos);
				$.each(todos, function(ix,todo) { 
Tibor Katelbach's avatar
Tibor Katelbach committed
930
					listObj.buildTodo(todo, ix );
Clément Damiens's avatar
 
Clément Damiens committed
931 932
				})
			}
Tibor Katelbach's avatar
Tibor Katelbach committed
933 934

			listObj.btnInit();
Clément Damiens's avatar
 
Clément Damiens committed
935 936 937 938 939 940 941
	    })
	    prioModal.modal("show");
	});

	
});

Tibor Katelbach's avatar
Tibor Katelbach committed
942 943 944
var listObj = {
	addTodoItem : function () { 
	
Clément Damiens's avatar
 
Clément Damiens committed
945
		var today = new Date();
Tibor Katelbach's avatar
Tibor Katelbach committed
946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965
		today = today.getDate() + '/' + (today.getMonth()+1) + '/' + today.getFullYear();	

		var todo = { 
			what : $(".bootbox #new-todo-item").val(),
			uid : userId,
			who : userConnected.username,
			created : today
		};

		if ( $(".bootbox #new-todo-item-date").val() ) 
			todo.when = $(".bootbox #new-todo-item-date").val();
		if( $(".bootbox #new-todo-item-price").val() )
			todo.price = $(".bootbox #new-todo-item-price").val();
		if($(".bootbox #new-todo-item-who").val())
			todo.who = $(".bootbox #new-todo-item-who").val() ; 

		mylog.log("addTodoItem",todo, tplCtx.editTaskpos);
		
	  	listObj.buildTodo(todo, tplCtx.editTaskpos);
	  	listObj.btnInit();
Tibor Katelbach's avatar
Tibor Katelbach committed
966

Tibor Katelbach's avatar
Tibor Katelbach committed
967 968 969 970 971 972 973 974 975 976
	  	if( notNull(tplCtx.form) && notNull(formInputs [tplCtx.form]) ){
	    	if( typeof answerObj.answers[tplCtx.form][tplCtx.budgetpath][tplCtx.pos].todo == "undefined")
				answerObj.answers[tplCtx.form][tplCtx.budgetpath][tplCtx.pos].todo = [];
			answerObj.answers[tplCtx.form][tplCtx.budgetpath][tplCtx.pos].todo.push(todo);
	    }
		else if( notNull(tplCtx.budgetpath) ) {
			if( typeof answerObj.answers[tplCtx.budgetpath][tplCtx.pos].todo == "undefined")
				answerObj.answers[tplCtx.form][tplCtx.budgetpath][tplCtx.pos].todo = [];
		  	answerObj.answers[tplCtx.budgetpath][tplCtx.pos].todo.push(todo);
		}
Clément Damiens's avatar
 
Clément Damiens committed
977

Tibor Katelbach's avatar
Tibor Katelbach committed
978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062
	 	$(".bootbox #new-todo-item, .bootbox #new-todo-item-date, .bootbox #new-todo-item-price").val("");
	},

	//todoArray au lieu de géré avec des li
	//avoir un array avec des objets + render
	buildTodo : function (todoObj, pos) {
		mylog.log("buildTodo ",todoObj, pos);
		var uid = (notNull( todoObj.uid)) ? todoObj.uid : userId;
		var who = "";
		if(!notNull( todoObj.who)) who = userConnected.name;
		else if(typeof todoObj.who == "object"){
			$.each(todoObj.who,function(i,w) { 
				if( who!= "") who +=", ";
			 who += w; })
		} else 
			who = todoObj.who;

		var whoids = "";
		var price = (notNull(todoObj.price)) ? todoObj.price : "";
		var when = (typeof todoObj.when == "undefined" || todoObj.when == "" ) ? "" : todoObj.when;

		if(!notNull( todoObj.created)) {
			var today = new Date();
			var created = today.getDate() + '/' + (today.getMonth()+1) + '/' + today.getFullYear();	
		}
		var doneDate = (notNull( todoObj.doneDate)) ? " <br/><i class='fa fa-calendar-check-o'></i> "+todoObj.doneDate : "";

		if(pos === null)
			pos = $(".liTodo").length;

		var checked = ( ( parseInt(todoObj.done) ) ? "checked" : "" );

		str = "<div class='col-xs-1'>"+
				"<a class='btn btn-xs btn-danger todo-item-delete' href='javascript:;'><i class='fa fa-times-rectangle'></i></a>"+
				" <a class='btn btn-xs btn-primary todo-item-edit' href='javascript:;'><i class='fa fa-pencil'></i></a>"+
			"</div>"+
			"<div class='col-xs-1'><input type='checkbox' name='todo-item-done' class='todo-item-done' "+checked+" /></div> " + 
		     "<div class='col-xs-10 liText' >"+todoObj.what +"</div>"+
		     "<div class='col-xs-12' >"+
		     	"<div class='col-xs-2'></div>"+
		     	"<div class='col-xs-2' style='font-size:0.8em'> <i class='fa fa-money'></i> "+price+"</div>"+
		     	"<div class='col-xs-3' style='font-size:0.8em'> <i class='fa fa-calendar-o'></i> "+when+doneDate+"</div>"+
		     	"<div class='col-xs-5' style='font-size:0.8em' > <i class='fa fa-user'></i> "+who+"</div>"+
		     "</div>";


		if(tplCtx.editTaskpos != null){
			$(".liText").eq(pos).parent().html(str);
			delete tplCtx.editTaskpos;
		}
		else
			$(".bootbox #todo-list").append("<li class='liTodo col-xs-12' data-pos='"+pos+"' data-uid='"+uid+"' data-created='"+created+"' data-who='"+who+"' data-whoids='"+whoids+"'  data-when='"+when+"' data-price='"+price+"' >"+str+"</li>");
	},

	deleteTodoItem : function (e, item) {
	  e.preventDefault();
	  var taskPos = $(item).parent().parent().data("pos");
	  $(item).parent().parent().fadeOut('slow', function() { 

	  	if( notNull(formInputs [tplCtx.form]) ){
			answerObj.answers[tplCtx.form][tplCtx.budgetpath][tplCtx.pos].todo.splice(taskPos,1);
		 } else {	
			answerObj.answers[tplCtx.budgetpath][tplCtx.pos].todo.splice(taskPos,1);
		}
	    
	    $(item).parent().parent().remove();
	  });
	},

	editTodoItem : function (e, item) {
	  e.preventDefault();
		tplCtx.editTaskpos = $(item).parent().parent().data("pos");
	  $(".bootbox #new-todo-item").val( $(item).parent().parent().find(".liText").text() );
	  $(".bootbox #new-todo-item-date").val( $(item).parent().parent().data("when") );
	  $(".bootbox #new-todo-item-price").val( $(item).parent().parent().data("price") );
	  $(".bootbox #new-todo-item-who option").prop("selected",false)
	  if($(item).parent().parent().data("who").indexOf(",")){
	  	whosT = $(item).parent().parent().data("who").split(",");
	  	$.each(whosT,function(i,u){
	  		$(".bootbox #new-todo-item-who option[value='"+u+"']").prop("selected",true)
	  	})
	  }else 
		  $(".bootbox #new-todo-item-who").val( $(item).parent().parent().data("who") );
	  
	},
Clément Damiens's avatar
 
Clément Damiens committed
1063 1064

                           
Tibor Katelbach's avatar
Tibor Katelbach committed
1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125
	completeTodoItem : function () { 
		tplCtx.editTaskpos = $(this).parent().parent().data("pos");
		var today = new Date();
		var now = today.getDate() + '/' + (today.getMonth()+1) + '/' + today.getFullYear()+ ' ' + today.getHours()+ ':' + today.getMinutes();	
		var taskPos = ""+$(this).parent().parent().data("pos");
		if($(this).is(":checked") ){
			if( notNull(formInputs [tplCtx.form]) ){
				answerObj.answers[tplCtx.form][tplCtx.budgetpath][tplCtx.pos].todo[taskPos].done = 1;
				answerObj.answers[tplCtx.form][tplCtx.budgetpath][tplCtx.pos].todo[taskPos].doneDate = now;
			}
			else 
				answerObj.answers[tplCtx.budgetpath][tplCtx.pos].todo[taskPos].doneDate = now;
		} else {
			if( notNull(formInputs [tplCtx.form]) ){
				answerObj.answers[tplCtx.form][tplCtx.budgetpath][tplCtx.pos].todo[taskPos].done = 0;
				delete answerObj.answers[tplCtx.form][tplCtx.budgetpath][tplCtx.pos].todo[taskPos].doneDate;
			 } else {	
				answerObj.answers[tplCtx.budgetpath][tplCtx.pos].todo[taskPos].done = 0;
				delete answerObj.answers[tplCtx.budgetpath][tplCtx.pos].todo[taskPos].doneDate;
			}
		}

		var todoObj = ( notNull(formInputs [tplCtx.form]) ) ? answerObj.answers[tplCtx.form][tplCtx.budgetpath][tplCtx.pos].todo[taskPos] :
				answerObj.answers[tplCtx.budgetpath][tplCtx.pos].todo[taskPos];

		listObj.buildTodo(todoObj, tplCtx.editTaskpos);
		listObj.btnInit();

		var todoDone = 0;
		var todos = null;
		if( notNull(formInputs [tplCtx.form]) )
			todos = answerObj.answers[tplCtx.form][tplCtx.budgetpath][tplCtx.pos].todo;
		else
			todos = answerObj.answers[tplCtx.budgetpath][tplCtx.pos].todo;
		$.each(todos, function(ix,todo) { 
			if(parseInt(todo.done) == 1)
				todoDone++;
		})

		$("#btnTodo"+tplCtx.pos).html( todoDone+"/"+todos.length );
		$("#todoProgress"+tplCtx.pos).css( "width",Math.floor(todoDone*100/todos.length)); 
		$("#todoPerc"+tplCtx.pos).html(Math.floor(todoDone*100/todos.length)+"%");

		//alert(taskPos+"done"+todoDone+"/"+todos.length);
	},
	
	btnInit : function() { 
		$(".bootbox #todo-list").on('click', '.todo-item-delete', function(e){
			var item = this; 
			listObj.deleteTodoItem(e, item)
		})
		$(".bootbox #todo-list").on('click', '.todo-item-edit', function(e){
			var item = this; 
			listObj.editTodoItem(e, item)
		})
		$(".bootbox .todo-item-done").off().on('click', listObj.completeTodoItem);
		// $(".bootbox .liTodo").on('click', function(e){
		// 	var item = this; 
		// 	editTodoItem(e, item)
		// })
	}
Clément Damiens's avatar
 
Clément Damiens committed
1126 1127 1128
}


1129 1130


Clément Damiens's avatar
 
Clément Damiens committed
1131 1132 1133 1134
</script>
<?php } else {
	//echo "<h4 class='text-red'>CALENDAR works with existing answers</h4>";
} ?>