financementFromBudget.php 23.2 KB
Newer Older
Clément Damiens's avatar
 
Clément Damiens committed
1 2 3 4
<?php if($answer){ 
	
$copy = "opalProcess1.depense";

5 6
if( isset($this->costum["form"]["params"][$kunik]["budgetCopy"]) ) 
	$copy = $this->costum["form"]["params"][$kunik]["budgetCopy"];
7 8
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
9 10 11 12 13 14 15 16 17 18 19 20 21
//var_dump($copy);
$copyT = explode(".", $copy);
$copyF = $copyT[0];
$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 {
22
	if(!empty($budgetKey) && !empty($answer["answers"][$budgetKey]) )
Clément Damiens's avatar
 
Clément Damiens committed
23 24 25 26 27 28 29
		$answers = $answer["answers"][$budgetKey];
	else if(isset($answer["answers"][$kunik]))
		$answers = $answer["answers"][$kunik];
}
	
$editBtnL =  "";

30
$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
31 32 33 34 35 36 37 38 39



$paramsData = [ 
	"financerTypeList" => Ctenat::$financerTypeList,
	"limitRoles" =>["Financeur"],
	"openFinancing" => true 
];

40 41 42 43 44 45 46 47 48 49 50
if( isset($this->costum["form"]["params"][$kunik]) ) {
	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]["financerTypeList"]) ) 
		$paramsData["financerTypeList"] =  $this->costum["form"]["params"][$kunik]["financerTypeList"];
	if( isset($this->costum["form"]["params"][$kunik]["limitRoles"]) ) 
		$paramsData["limitRoles"] =  $this->costum["form"]["params"][$kunik]["limitRoles"];
	if( isset($this->costum["form"]["params"][$kunik]["openFinancing"]) ) 
		$paramsData["openFinancing"] =  $this->costum["form"]["params"][$kunik]["openFinancing"];
Clément Damiens's avatar
 
Clément Damiens committed
51 52
}

53
$communityLinks = Element::getCommunityByTypeAndId($this->costum["contextType"],$this->costum["contextId"]);
Clément Damiens's avatar
 
Clément Damiens committed
54 55 56 57 58
$organizations = Link::groupFindByType( Organization::COLLECTION,$communityLinks,["name","links"] );

$orgs = [];

foreach ($organizations as $id => $or) {
59 60 61 62 63 64
	$roles = null;
	if(!empty($or["links"]) && 
		!empty($or["links"]["memberOf"]) &&
		!empty($or["links"]["memberOf"][$this->costum["contextId"]]) &&
		!empty($or["links"]["memberOf"][$this->costum["contextId"]]["roles"]) )
		$roles = $or["links"]["memberOf"][$this->costum["contextId"]]["roles"];
Clément Damiens's avatar
 
Clément Damiens committed
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
	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(Ctenat::$financerTypeList,$orgs);

$properties = [
      // "financerType" => [
      //   "placeholder" => "Type de Financement",
      //       "inputType" => "select",
      //       "list" => "financerTypeList",
      //       "rules" => [
      //           "required" => true
      //       ]
      //   ],
		"poste" => [
            "inputType" => "text",
            "label" => "Contexte",
            "placeholder" => "Contexte",
            "size" => 4,
            "rules" => [ "required" => true ]
        ],
        "financer" => [
            "placeholder" => "Quel Financeur",
            "inputType" => "select",
            "list" => "financersList",
            "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",
            "size" => 6,
        ]
];
100
$amounts = (isset($this->costum["form"]["params"][$budgetKey]["amounts"])) ? $this->costum["form"]["params"][$budgetKey]["amounts"] : ["price" => "Montant Financé"] ; 
Clément Damiens's avatar
 
Clément Damiens committed
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
foreach ( $amounts as $k => $l) {
	$properties[$k] = [ "inputType" => "text",
			            "label" => $l,
			            "placeholder" => $l,
			            "propType" => "amount"
			        ];
}


	?>	
<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; 
117
				if( !isset($budgetKey) ) 
Clément Damiens's avatar
 
Clément Damiens committed
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
					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;
		$totalFunded = 0;
137
		$total = 0;
Clément Damiens's avatar
 
Clément Damiens committed
138 139 140 141 142 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
		if($answers){
			foreach ($answers as $q => $a) {

				//prepare td content
				$trStyle = "";
				$tds = "";
				foreach ($properties as $i => $inp) 
				{
					$size = (isset($inp["size"])) ? "col-xs-".$inp["size"] : "";
					$tds .= "<td class='".$size."'>";

					if( $i == "price" && isset($a[$i]) ){
						$tds .= $a[$i]."€";
						if(isset($percentDiv)){
							$tds .= $percentDiv;
							$tds .= "<br/> <span class='label label-primary'>".floor($percentAmountFunded)."%</span>";
							$percentDiv = "";
							$percentAmountFunded = 0;
						}
					}
					else if( $i == "financer"  )
					{
						
						$totalAmountFunded = 0;
						if( isset($a["financer"]) )
						{
							//if(count($a["financer"])>1){}
							$totalAmountFunded = 0;
							$tds .= "<table class='table table-bordered table-hover  directoryTable'>";
							foreach ($a["financer"] as $ix => $fin) {
								$tds .= "<tr>";
								
									$tds .= "<td class='col-xs-4'>";
										if(!empty($fin["id"])){
											$o = PHDB::findOne(Organization::COLLECTION,[ "_id" => new MongoId($fin["id"]) ],
																					 	["name","slug"]);
											$tds .= $o["name"];
										} else if( isset( $fin["email"] ) && isset( $fin["name"] ) ){
											$tds .= $fin["name"]."<br/>".$fin["email"];
										}else 
											$tds .= "unkknown";	
									$tds .= "</td>";

									$tds .= "<td  class='col-xs-5'>";
										if(!empty($fin["line"]))
											$tds .= $fin["line"];
									$tds .= "</td>";

									$tds .= "<td class='col-xs-2'>";
										if(!empty($fin["amount"])){
											$tds .= $fin["amount"]."€";
											$totalAmountFunded += (int)$fin["amount"];
190
											
Clément Damiens's avatar
 
Clément Damiens committed
191 192 193 194 195
										}
									$tds .= "</td>";

									$tds .= "<td class='col-xs-2'>";
										if(!empty($fin["amount"]) && isset($a["price"])){
196
											
Clément Damiens's avatar
 
Clément Damiens committed
197 198 199 200 201 202 203
											$percent = $fin["amount"] * 100 / (int)$a["price"];
											$tds .= " <span class='pull-right label label-primary'>".floor($percent)."%</span>";
										}
									$tds .= "</td>";
								
								$tds .= "</tr>";
							}
204

Clément Damiens's avatar
 
Clément Damiens committed
205
							$totalFunded += $totalAmountFunded;
206

Clément Damiens's avatar
 
Clément Damiens committed
207 208 209 210
							$tds .= "</table>";

							if($totalAmountFunded>0 && isset( $a["price"] )){
								$percentAmountFunded =  $totalAmountFunded * 100 / (int)$a["price"];
211
								$total += (int)$a["price"];
Clément Damiens's avatar
 
Clément Damiens committed
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
								$percol = "danger";
								$trStyle = "background-color:#ffdada";
								if( $percentAmountFunded >= 50 ){
									$percol = "warning";
									$trStyle = "background-color:#ffe7d1";
								}
								if( $percentAmountFunded >= 100 ){
									$percol = "success";
									$trStyle = "background-color:#e5ffe5";
								}

								$percentDiv = '<div class="progress btnFinancer"  data-id="'.$answer["_id"].'" data-budgetpath="'.$copy.'" data-form="'.$copyF.'" data-pos="'.$q.'"  style="cursor:pointer;margin-bottom: 0px;">'.
											  '<div class="progress-bar progress-bar-'.$percol.'" style="width:'.$percentAmountFunded.'%">'.
												    '<span class="sr-only">'.$percentAmountFunded.'% Complete</span>'.
											  '</div>'.
											'</div>';
							}
						}


						
						$tds .= "<div class='col-xs-12 text-center'>".
									
									" <div class='col-xs-12'><a href='javascript:;' data-id='".$answer["_id"]."' data-budgetpath='".$copy."' data-form='".$copyF."' data-pos='".$q."'  class='btn btn-xs btn-primary btnFinancer '><i class='fa fa-plus'></i> Ajouter un financeur</a></div></div>";
					}
					else if( isset($a[$i]) )
						$tds .= $a[$i];
					// else if( $i == "amount" && isset( $a["financer"]["amount"] ) ) 
					// 	$tds .= $a["financer"]["amount"];
					// else if( $i == "line" && isset( $a["financer"]["line"] ) ) 
					// 	$tds .= $a["financer"]["line"];
					
					$tds .= "</td>";
				} 
					
			

			echo "<tr id='".$kunik.$q."' class='".$kunik."Line text-center' style='".$trStyle."'>";
			echo $tds;		
			?>

			<td>

				<?php 
					$color = "default";
					$valbl = "?";
					$tool= "En attente de validation";
259 260
					if( isset($a["validFinal"]["valid"]) ){
						if( $a["validFinal"]["valid"] == "validated" ){
Clément Damiens's avatar
 
Clément Damiens committed
261 262 263
							$color = "success";
							$valbl = "V";
							$tool="Validé sans réserve";
264
						} else if( $a["validFinal"]["valid"] == "reserved" ){
Clément Damiens's avatar
 
Clément Damiens committed
265 266 267
							$color = "warning";
							$valbl = "R";
							$tool="Validé avec réserves";
268
						} else if( $a["validFinal"]["valid"] == "refused" ){
Clément Damiens's avatar
 
Clément Damiens committed
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
							$color = "danger";
							$valbl = "NV";
							$tool="Non validé";
						}
					}

					echo "<a href='javascript:;' data-id='".$answer["_id"]."' data-budgetpath='".$copy."' data-form='".$copyF."' data-pos='".$q."'  class='btnValidFinance btn btn-xs btn-".$color." margin-left-5 padding-10 tooltips' data-toggle='tooltip' data-placement='left' data-original-title='".$tool."'>".$valbl."</a>";

				
					?>
				<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>

			<?php 
				$ct++;
				echo "</tr>";
			}
		}



290
if($total > 0){
Clément Damiens's avatar
 
Clément Damiens committed
291 292

	echo "<tr class='bold'>";
293 294
	echo 	"<td colspan=2 style='text-align:right'>TOTAL À FINANCER : </td>";
	echo 	"<td colspan=2>".trim(strrev(chunk_split(strrev($total),3, ' ')))." €</td>";
Clément Damiens's avatar
 
Clément Damiens committed
295 296 297 298
	echo "</tr>";

}

299
if($totalFunded > 0){
Clément Damiens's avatar
 
Clément Damiens committed
300 301

	echo "<tr class='bold'>";
302 303
	echo 	"<td colspan=2 style='text-align:right'>TOTAL FINANCÉ: </td>";
	echo 	"<td colspan=2>".trim(strrev(chunk_split(strrev($totalFunded),3, ' ')))." €</td>";
Clément Damiens's avatar
 
Clément Damiens committed
304 305 306 307 308 309 310
	echo "</tr>";

}




311 312


Clément Damiens's avatar
 
Clément Damiens committed
313 314 315 316 317 318 319 320 321
?>
		</tbody>
	</table>
</div>


<?php 
$percol = "warning";
$financedPercentage = (!empty($total)) ? $totalFunded * 100 / $total: 0;
322
if( $financedPercentage >= 100 ){
Clément Damiens's avatar
 
Clément Damiens committed
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
	$percol = "success";
}
echo "<h4 style='color:".(($titleColor) ? $titleColor : "black")."'>Pourcentage de Financement Globale</h4>".
'<div class="progress " style="cursor:pointer" >'.
  '<div class="progress-bar progress-bar-'.$percol.'" style="width:'.$financedPercentage.'%">'.
	    '<span class="sr-only">'.$financedPercentage.'% Complete</span>'.
  '</div>'.
'</div>'; ?>

<table class="table table-bordered table-hover  ">
	<tbody class="">
		<tr>
			<td>Total à financer</td>
			<td><?php echo trim(strrev(chunk_split(strrev($total),3, ' '))) ?></td>
		</tr>
		<tr>
			<td>Total financé</td>
			<td><?php echo trim(strrev(chunk_split(strrev($totalFunded),3, ' '))) ?></td>
		</tr>
		<tr>
			<td>Pourcentage financé</td>
			<td><?php echo floor($financedPercentage) ?> %</td>
		</tr>
346
		<?php if($total>$totalFunded){ ?>
Clément Damiens's avatar
 
Clément Damiens committed
347 348 349 350 351
		<tr>
			<td>Reste à financer </td>
			<td><?php echo floor($total-$totalFunded) ?></td>
		</tr>
		<tr>
352 353 354 355
			<td>% Reste à financer </td>
			<td><?php echo floor(100-$financedPercentage) ?> %</td>
		</tr>	
		<?php } ?>	
Clément Damiens's avatar
 
Clément Damiens committed
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
	</tbody>
</table>


<div class="form-prioritize" 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>

<div class="form-financer" style="display:none;">
	<span class="bold">Financeur existant dans la communauté</span><br/>
	<select id="financer" style="width:100%;">
		<option value=0 >Quel financeur</option>
		<?php foreach ($orgs as $v => $f) {
			echo "<option value='".$v."'>".$f."</option>";
		} ?>
	</select>
	<br><span class="bold">ou Financeur inexistant dans la communauté</span><br/>
	<?php //if(!(boolean)$paramsData["openFinancing"]) { ?>
	<span class="bold">Nom du Financeur Libre</span>
	<br>
	<input type="text" id="financerName" name="financerName" style="width:100%;">

	<span class="bold">Email</span>
	<br>
	<input type="text" id="financerEmail" name="financerEmail" style="width:100%;">
	<?php //} ?>

	<br><br>
	<span class="bold">Fonds, enveloppe ou budget mobilisé</span>
	<br>
	<input type="text" id="financeLine" name="financeLine" style="width:100%;">
	<span class="bold">Montant Financé</span>
	<br>
	<input type="text" id="financeAmount" name="financeAmount" style="width:100%;">
</div>



<?php 
403 404 405
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
406 407 408
		[ "totalFin"  => $total,
		  "totalBudg" => Yii::app()->session["totalBudget"]["totalBudget"] ] );
	// else 
409
	// 	$this->renderPartial( "costum.views.".$this->costum["form"]["params"]["financement"]["tpl"]);
Clément Damiens's avatar
 
Clément Damiens committed
410 411 412 413 414 415
}
 ?>

<script type="text/javascript">
if(typeof costum.lists == "undefined")
	costum.lists = {};
416 417
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
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441
costum.lists.financerTypeList = <?php echo json_encode(Ctenat::$financerTypeList); ?>;
costum.lists.financersList = <?php echo json_encode($orgs); ?>;


var <?php echo $kunik ?>Data = <?php echo json_encode( (isset($answer["answers"][$budgetKey])) ? $answer["answers"][$budgetKey] : 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 {
442
	                dataHelper.path2Value( tplCtx, closePrioModalRel );
Clément Damiens's avatar
 
Clément Damiens committed
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 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505
	            }

	    	}
	    }
	};

	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
	            },
	            openFinancing : {
	                inputType : "checkboxSimple",
                    label : "Financement Ouvert",
                    subLabel : "Le Finacement est ouvert aux personnes ou organisations non inscrites dans la communauté",
                    params : {
                        onText : "Oui",
                        offText : "Non",
                        onLabel : "Oui",
                        offLabel : "Non",
                        labelText : "Financement Ouvert"
                    },
                    checked : sectionDyf.<?php echo $kunik ?>ParamsData.estimate
	            }
	        },
	        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>");
506
	                    urlCtrl.loadByHash(location.hash);
Clément Damiens's avatar
 
Clément Damiens committed
507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560
	                } );
	            }

	    	}
	    }
	};


    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);
    });

 

	$('.btnValidFinance').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: "État du Financement",
	        show: false,
	        buttons: {
                success: {
                    label: trad.save,
                    className: "btn-primary",
                    callback: function () {
			            
			        	var formInputsHere = formInputs;
			        	tplCtx.path = "answers";
			        	if( notNull(formInputs [tplCtx.form]) )
561
			        		tplCtx.path = "answers";    
Clément Damiens's avatar
 
Clément Damiens committed
562 563 564 565 566 567 568 569 570 571 572 573 574

			        	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);
Tibor Katelbach's avatar
Tibor Katelbach committed
575 576 577
				  	 	dataHelper.path2Value( tplCtx, function(){
				  	 		saveLinks(answerObj._id.$id,"financeValidated",userId,closePrioModalRel);
				  	 	} );
Clément Damiens's avatar
 
Clément Damiens committed
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 625 626 627 628 629 630 631 632 633 634
				  	 }		
                },
                cancel: {
                  label: trad.cancel,
                  className: "btn-secondary",
                  callback: closePrioModal
                }
              },
		        onEscape: closePrioModal
	    });
	    prioModal.modal("show");
	});
    
    $('.btnFinancer').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-financer").html(),
	        title: "Ajouter un Financeur",
	        show: false,
	        buttons: {
                success: {
                    label: trad.save,
                    className: "btn-primary",
                    callback: function () {
			            
			        	//var formInputsHere = formInputs;
			        	var financersCount = ( typeof eval("answerObj.answers."+tplCtx.budgetpath+"["+tplCtx.pos+"].financer") != "undefined" ) ? eval("answerObj.answers."+tplCtx.budgetpath+"["+tplCtx.pos+"].financer").length : 0;
			        	tplCtx.path = "answers."+tplCtx.budgetpath+"."+tplCtx.pos+".financer."+financersCount;
			        	// if( notNull(formInputs [tplCtx.form]) )
			        	// 	tplCtx.path = "answers."+tplCtx.budgetpath+"."+tplCtx.pos+".financer."+financersCount;	       

			        	var today = new Date();
						today = today.getDate() + '/' + (today.getMonth()+1) + '/' + today.getFullYear();	
			            tplCtx.value = { 
		        			line   : $(".bootbox #financeLine").val(),
		        			amount : $(".bootbox #financeAmount").val(),
		        			user   : userId,
		        			date   : today
		        		};

		        		if($(".bootbox #financer").val() != 0 ){
		        			tplCtx.value.id = $(".bootbox #financer").val();
		        			tplCtx.value.name = $(".bootbox #financer option:selected").text();
		        		}else if($(".bootbox #financerName").val() != "" ){
		        			tplCtx.value.name = $(".bootbox #financerName").val();
		        			tplCtx.value.email = $(".bootbox #financerEmail").val();
		        		}

		        		delete tplCtx.pos;
		        		delete tplCtx.budgetpath;
				    	mylog.log("btnFinancer save",tplCtx);
				  	 	dataHelper.path2Value( tplCtx, function(params) { 
				  	 		prioModal.modal('hide');
635
				  	 		saveLinks(answerObj._id.$id,"financerAdded",userId,function(){urlCtrl.loadByHash(location.hash);});
Tibor Katelbach's avatar
Tibor Katelbach committed
636
				  	 		
Clément Damiens's avatar
 
Clément Damiens committed
637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657
				  	 	} );
			        }		
                },
                cancel: {
                  label: trad.cancel,
                  className: "btn-secondary",
                  callback: function() {
                  }
                }
              },
		        onEscape: function() {
		          prioModal.modal("hide");
		        }
	    });
	    prioModal.modal("show");
	});
});
</script>
<?php } else {
	//echo "<h4 class='text-red'>CALENDAR works with existing answers</h4>";
} ?>