Commit 642ab9c4 authored by Anatole Rakotoson's avatar Anatole Rakotoson

coform community

parent 3eb5a5e4
......@@ -12,7 +12,8 @@
'new' => 'survey.controllers.answer.NewAction',
'index' => 'survey.controllers.answer.IndexAction',
'all'=>'survey.controllers.answer.AllAction',
'admindirectory'=>'survey.controllers.answer.admin.DirectoryAction'
'admindirectory'=>'survey.controllers.answer.admin.DirectoryAction',
'sendmail' => 'survey.controllers.answer.mail.SendAction',
);
}
}
<?php
class SendAction extends CAction {
public function run($id, $tpl="validation", $step=null) {
$controller=$this->getController();
$msg=null;
$infos=array();
if(isset($_POST["tpl"]))
$tpl=$_POST["tpl"];
if(isset($_POST["step"]))
$step=$_POST["step"];
// ALL infos
if(isset($_POST["tplObject"]))
$infos["tplObject"]=$_POST["tplObject"];
if(isset($_POST["html"]))
$infos["html"]=$_POST["html"];
if(isset($_POST["msg"]))
$infos["msg"]=$_POST["msg"];
if(isset($_POST["tplMail"]))
$infos["emails"]=$_POST["tplMail"];
if(isset($_POST["listContact"]))
$infos["community"]=$_POST["listContact"];
$mailParams=Answer::mailProcess($id, $tpl, $step, $infos);
Rest::json(array("result"=>true, "msg"=>"Ok : webhook handdled"));
}
}
<?php
class SendAction extends CAction {
public function run($msg="", $to="") {
$controller=$this->getController();
// $msg=null;
// $infos=array();
// if(isset($_POST["tpl"]))
// $tpl=$_POST["tpl"];
// if(isset($_POST["step"]))
// $step=$_POST["step"];
// // ALL infos
// if(isset($_POST["tplObject"]))
// $infos["tplObject"]=$_POST["tplObject"];
// if(isset($_POST["html"]))
// $infos["html"]=$_POST["html"];
// if(isset($_POST["msg"]))
// $infos["msg"]=$_POST["msg"];
// if(isset($_POST["tplMail"]))
// $infos["emails"]=$_POST["tplMail"];
// if(isset($_POST["listContact"]))
// $infos["community"]=$_POST["listContact"];
if(isset($_POST["to"]))
$to=$_POST["to"];
if(isset($_POST["tpl"]))
$msg=$_POST["msg"];
$mailParams=Answer::mailProcessOne($to, $msg);
Rest::json(array("result"=>true, "msg"=>"Ok : webhook handdled"));
}
}
<?php
class Answer{
const COLLECTION = "answers";
const CONTROLLER = "answer";
const ICON = "fa-calendar-check-o";
public static function getById($id, $fields=array()){
return PHDB::findOne( self::COLLECTION, array( "_id" => new MongoId((string)$id) ), $fields );
}
public static function generateAnswer($form, $draft = false){
$costum = [];
//Rest::json($costum); exit;
$ans = [
"user" => Yii::app()->session["userId"],
"links"=>[
"answered" => [ Yii::app()->session["userId"] ] ,
//proposed,particpated,decision,financed,financed,referenced,commented,worked,payed,tested,validated
//each actor is connectable to his activitystream
],
"created" => time()
];
if($draft === true)
$ans["draft"] = true;
$formList = null ;
if( !empty($form) ){
$ans["form"] = (String)$form["_id"];
if(!empty($form["subForms"])){
$formList = $form["subForms"];
$ans["formId"] = implode("|", $formList);
$ans["formList"] = count($formList);
}
//$ans["step"] = $formList[0];
}
//Rest::json($costum); exit;
if(!empty($costum) && !empty($costum["slug"]) ) {
$ans["source"] = Costum::getSource($costum["slug"]);
}
//Rest::json($ans); exit;
if(Costum::isSameFunction("generateAnswerBeforeSave")){
$paramBeforeSave=Costum::sameFunction("generateAnswerBeforeSave",
array("answer" => $ans, "formList"=>$formList) );
$ans = $paramBeforeSave["answer"];
}
PHDB::insert(Answer::COLLECTION, $ans);
$answer = PHDB::findOne( Answer::COLLECTION, [ "_id" => new MongoId($ans["_id"]) ] ) ;
return $answer;
}
public static function canAdmin($ans, $form=null){
if(Form::canAdmin((string)$form["_id"], $form))
return true;
else if(Costum::isSameFunction("canAdminAnswer", array("answer"=>$ans)))
return Costum::sameFunction("canAdminAnswer", array("answer"=>$ans));
return false;
}
public static function canEdit($ans, $form=null, $userId=null, $parent=null){
if(ctype_xdigit($ans)){
$ans=self::getById($ans);
$form = Form::getByIdMongo($ans["form"]);
$parent = Slug::getElementBySlug($form["id"]);
$userId=Yii::app()->session["userId"];
}
if($ans["user"] == $userId)
return true;
else if(Form::canAdmin((string)$form["_id"], $form))
return true;
else if(Costum::isSameFunction("canEditAnswer", array("answer"=>$ans)))
return Costum::sameFunction("canEditAnswer", array("answer"=>$ans));
return false;
}
public static function canAccess($answer, $form=null, $userId=null, $parentForm=null){
if(ctype_xdigit($answer)){
$answer=self::getById($answer);
$form = Form::getByIdMongo($answer["form"]);
$parent = Slug::getElementBySlug($form["id"]);
}
if(self::canEdit( $answer, $form, $userId, $parentForm))
return true;
else if(Costum::isSameFunction("canAccessAnswer", array("answer"=>$answer)))
return Costum::sameFunction("canAccessAnswer", array("answer"=>$answer));
return false;
}
public static function getListBy($form=null, $costum=null, $userId=null, $cond=null){
$where = array();
$lists = array();
if(!empty($form))
$where["form"]=$form;
if(!empty($costum))
$where["source.keys"]=array('$in' => array($costum) );
if(!empty($userId))
$where["user"]=$userId;
if(!empty($cond)){
$where=array('$and'=> array($where, $cond));
}
if(!empty($where))
$lists=PHDB::find( Answer::COLLECTION, $where);
return $lists;
}
public static function globalAutocomplete($form, $searchParams){
$searchParams["indexMin"] = (isset($searchParams["indexMin"])) ? $searchParams["indexMin"] : 0;
$searchParams["indexStep"] = (isset($searchParams["indexStep"])) ? $searchParams["indexStep"] : 100;
$mappingData=(isset($form["mapping"])) ? $form["mapping"] : array("name"=>"name", "address"=>"address");
$query=array("form"=>(string)$form["_id"]);
if(!empty($searchParams["userId"])){
$query = array('$and' =>
array(
$query ,
array("user" => $searchParams["userId"] )
)
) ;
}
if(!empty($searchParams["name"])){
$searchRegExp = Search::accentToRegex(trim(urldecode($searchParams['name'])));
$query = array('$and' =>
array(
$query ,
array($mappingData["name"] => new MongoRegex("/.*{$searchRegExp}.*/i"))
)
) ;
}
if(!empty($searchParams["filters"]["address"])){
$searchRegExp = Search::accentToRegex(trim(urldecode($searchParams["filters"]['address'])));
$query = array('$and' =>
array(
$query ,
array('$or'=> array(
array($mappingData["address"].".postalCode" => new MongoRegex("/.*{$searchRegExp}.*/i")),
array($mappingData["address"].".cityName" => new MongoRegex("/.*{$searchRegExp}.*/i"))
))
)
) ;
}
if(!empty($searchParams['filters'])){
$query = Search::searchFilters($searchParams['filters'], $query);
}
$res= array();
//var_dump($query);exit;
$res["results"] = PHDB::findAndLimitAndIndex ( self::COLLECTION , $query, $searchParams["indexStep"], $searchParams["indexMin"]);
if(isset($searchParams["count"]))
$res["count"][self::COLLECTION] = PHDB::count( self::COLLECTION , $query);
return $res;
}
public static function getMappingValues($mapping, $ans){
foreach($mapping as $k => $path){
$mapping[$k]=self::getValueByPath($path, $ans);
}
return $mapping;
}
public static function getValueByPath($indexes, $arrayToAccess){
if(is_string($indexes))
$indexes = explode( ".", $indexes );
if(isset($arrayToAccess[$indexes[0]])){
if(count($indexes) > 1)
return self::getValueByPath(array_slice($indexes, 1), $arrayToAccess[$indexes[0]]);
else
return $arrayToAccess[$indexes[0]];
}
}
public static function getDataAnswers($answerList, $subForms, $form){
$globalLinks = [];
$gUids = [];
if(!empty($answerList)){
foreach ($answerList as $key => $ans) {
if(isset($form["mapping"])){
$answerList[$key]["mappingValues"]=Answer::getMappingValues($form["mapping"], $ans);
}
$answerList[$key]["countComment"] = PHDB::count(Comment::COLLECTION, array("contextId"=>$key,"contextType"=>Form::ANSWER_COLLECTION));
$localLinks = [];
$uids = [];
$todo = 0;
$done = 0;
$tasksPerson = [];
if(!isset($ans["answers"])) {
$percent = 0;
} else {
$totalInputs = 0;
$answeredInputs = 0;
foreach ($subForms as $fid => $f){
$totalInputs += count($f["inputs"]);
if( isset( $ans["answers"][$fid] ) ){
$answeredInputs += count( $ans["answers"][$fid] );
}
//todo lists are on depense for the moment
//todo genereaclly not with a fixed input ID
if( isset( $ans["answers"][$fid]["depense"] ) ){
foreach ( $ans["answers"][$fid]["depense"] as $ix => $dep) {
if( isset( $dep["todo"] ) ){
foreach ($dep["todo"] as $ixx => $t) {
if(!isset($t["done"]) || $t["done"] == "0"){
$todo++;
$whos = (is_array($t["who"])) ? $t["who"] : explode(",",$t["who"]);
foreach ( $whos as $whoix => $who ) {
if( !isset( $tasksPerson[ $who ] ) )
$tasksPerson[ $who ] = [];
$tasksPerson[ $who ][] = $t["what"];
}
}
else
$done++;
}
}
}
}
}
if(isset($ans["links"])){
foreach ( $ans["links"] as $type => $ls ){
if(!isset($localLinks[$type]))
$localLinks[$type] = [];
if(!isset($globalLinks[$type]))
$globalLinks[$type] = [];
foreach ($ls as $uid => $time) {
if(is_string($uid) && strlen($uid) == 24 && ctype_xdigit($uid)){
if(!in_array($uid, $localLinks[$type] ))
$localLinks[$type][] = $uid;
if(!in_array($uid, $uids ))
$uids[] = new MongoId( $uid );
if(!in_array($uid, $globalLinks[$type] ))
$globalLinks[$type][] = $uid;
if(!in_array($uid, $gUids ))
$gUids[] = new MongoId( $uid );
}
}
}
}
$percent = floor( $answeredInputs*100 / $totalInputs );
}
$answerList[$key]["percent"] = $percent;
$answerList[$key]["uids"] = $uids;
$answerList[$key]["todo"] = $todo;
$answerList[$key]["done"] = $done;
$answerList[$key]["tasksPerson"] = $tasksPerson;
$answerList[$key]["canEdit"] = self::canEdit( $ans, $form, Yii::app()->session["userId"]) ;
}
}
return $answerList;
}
public static function csv($elements, $idElt, $valElt, $forms ){
$elements[$idElt]["id"] = $idElt;
$elements[$idElt]["user"] = $valElt["user"];
$elements[$idElt]["created"] = date("d/m/Y", $valElt["created"]);
if(!empty($valElt["answers"])){
foreach ($forms as $keyF => $valF) {
if(!empty($valF["id"]) && !empty($valElt["answers"][$valF["id"]])){
foreach ($valElt["answers"][$valF["id"]] as $keyAns => $valAns) {
if(!empty($valF["inputs"]) && !empty($valF["inputs"][$keyAns]) && !empty($valF["inputs"][$keyAns]["label"])){
$elements[$idElt][$valF["inputs"][$keyAns]["label"]] = $valAns;
}
}
}
}
}
return $elements;
}
public static $mailConfig=array(
"validation"=>["tpl"=>"answer.validation", "subject"=>"La candidature {what} a été validée"],
"rejected"=>["tpl"=>"answer.rejected", "subject"=>"La candidature {what} a été rejetée"],
"default"=>["tpl"=>"answer.default", "subject"=>""]
);
public static function getCommunityToNotify($answer, $entry=null){
$arrayMail=array();
if(!empty($answer["links"])){
foreach($answer["links"] as $k => $v){
if($k=="answered" && (empty($entry) || in_array("answered",$entry))){
foreach($v as $id){
$people=Element::getElementById($id, Person::COLLECTION, null, array("email","name","slug") );
array_push($arrayMail, $people);
}
}
}
if(Costum::isSameFunction("getAnswerCommunityToNotify")){
// CARREFUL $costumUserArray need to be return as result : return $params["costumUserArray"]
array_merge($arrayMail, Costum::sameFunction("getAnswerCommunityToNotify", array(
"answer"=>$answer)));
}
}
return $arrayMail;
}
public static function mailProcess($id, $tpl, $step, $infos){
$costum = [];
$answer=self::getById($id);
$mailsCommunity=array();
if(isset($infos["emails"]) && !empty($infos["emails"])){
foreach($infos["emails"] as $v){
array_push($mailsCommunity, Element::getElementByWhere(Person::COLLECTION, array("email"=>$v),array("email","name","slug") ) );
}
}
if(isset($infos["community"]) && !empty($infos["community"])){
$mailsCommunity=array();
foreach($infos["community"] as $k => $v){
if($v["type"]==Person::COLLECTION){
array_push($mailsCommunity, Element::getElementById($k, Person::COLLECTION, null, array("email","name","slug") ));
}else{
$community=Element::getCommunityByTypeAndId(Organization::COLLECTION, $k,Person::COLLECTION, "isAdmin");
foreach($community as $e => $val){
array_push($mailsCommunity, Element::getElementById($e, Person::COLLECTION, null, array("email","name","slug") ));
}
}
}
}
if(empty($mailsCommunity))
$mailsCommunity=self::getCommunityToNotify($answer);
$answer["mappingValues"]=array();
$form=Form::getByIdMongo($answer["form"]);
if(isset($form["mapping"]))
$answer["mappingValues"]=self::getMappingValues($form["mapping"], $answer);
$nameAnsw=(isset($answer["mappingValues"]["name"])) ? $answer["mappingValues"]["name"] : "";
$objMail="[".Mail::getAppName()."] ".Yii::t("mail",self::$mailConfig[$tpl]["subject"], array("{what}"=>$nameAnsw));
if(isset($infos["tplObject"]))
$objMail="[".Mail::getAppName()."] ".$infos["tplObject"];
foreach($mailsCommunity as $c){
$params = array (
"type" => Cron::TYPE_MAIL,
"tpl"=>self::$mailConfig[$tpl]["tpl"],
"subject" => $objMail,
"from"=>Yii::app()->params['adminEmail'],
"to" => $c["email"],
"tplParams" => array( "user"=> $c ,
"title" => Mail::getAppName() ,
"answer" => $answer,
"form"=>$form,
"msg"=>@$infos));
if(isset($infos["msg"]))
$params["tplParams"]["msg"]=$infos["msg"];
if(isset($infos["html"]))
$params["tplParams"]["html"]=$infos["html"];
$params=Mail::getCustomMail($params);
Mail::schedule($params);
}
if(Costum::isSameFunction("AnswerMailProcess")){
// CARREFUL $costumUserArray need to be return as result : return $params["costumUserArray"]
Costum::sameFunction("AnswerMailProcess", array(
"tpl"=>$tpl,
"step"=>$step,
"infos"=>$infos,
"form"=>$form,
"answer"=>$answer)
);
}
}
public static function mailProcessOne($to, $msg){
$params = array (
"type" => Cron::TYPE_MAIL,
"tpl"=>s$msg,
"subject" => "invitation",
"from"=>Yii::app()->params['adminEmail'],
"to" => $to,
"tplParams" => array( "user"=> "user" ,
"title" => Mail::getAppName() ,
"answer" => "answer",
"form"=>Yii::app()->params['adminEmail'],
"msg"=>$msg));
if(isset($infos["msg"]))
$params["tplParams"]["msg"]=$infos["msg"];
if(isset($infos["html"]))
$params["tplParams"]["html"]=$infos["html"];
$params=Mail::getCustomMail($params);
Mail::schedule($params);
}
}
<?php if($answer){
?>
<div class="form-group">
<?php
$i = 0;
$show = true;
if (isset($answers)) {
foreach ($answers as $q => $a) {
if (isset($answers)) {
$i++;
}
}
}
$editBtnL = (Yii::app()->session["userId"] == $answer["user"]) ? " <a href='javascript:;' data-id='".$answer["_id"]."' data-collection='".Form::ANSWER_COLLECTION."' data-path='".$answerPath."' class='add".$kunik." btn btn-default'><i class='fa fa-plus'></i> Ajouter une ligne </a>" : "";
$editParamsBtn = ($canEdit) ? " <a href='javascript:;' data-id='".$el["_id"]."' data-collection='".Yii::app()->session["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>" : "";
$paramsData = [
"mail_type" => ""
];
if( isset(Yii::app()->session["costum"]["form"]["params"][$kunik]["mail_type"]) )
$paramsData["mail_type"] = Yii::app()->session["costum"]["form"]["params"][$kunik]["mail_type"];
$properties = [
"liste_row" => [
"label" => "mot ou phrase",
"placeholder" => "mot ou phrase",
"inputType" => "text",
"rules" => [ "required" => true ]
]
];
?>
<h4 style="color:<?php echo ($titleColor) ? $titleColor : "black"; ?>"><?php echo $label.$editQuestionBtn.$editParamsBtn.$editBtnL?></h4>
<?php echo $info ?>
<style>
.s19{list-style: none;}
.s19 li:before{
content: '\f0a9';
margin-right: 15px;
font-family: FontAwesome;
color: #d9534f;
}
</style>
<ol class="s19" style="
white-space: normal;
">
<?php
$ct = 0;
if(isset($answers)){
foreach ($answers as $q => $a) {
?>
<li> <?php echo $a['liste_row']; ?>
<div class="pull-right"><?php
$this->renderPartial( "survey.views.tpls.forms.cplx.editDeleteLineBtn" , [
"canEdit"=>($canEdit||Yii::app()->session["userId"] == $answer["user"]),
"id" => $answer["_id"],
"collection" => Form::ANSWER_COLLECTION,
"q" => $q,
"path" => "answers.".$kunik.".".$q,
"keyTpl"=>$kunik
] ); ?><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></div>
</li>
<?php
}
}
?>
</ol>
</div>
<script type="text/javascript">
var <?php echo $kunik ?>Data = <?php echo json_encode( (isset($answers)) ? $answers : null ); ?>;
sectionDyf.<?php echo $kunik ?>ParamsData = <?php echo json_encode( $paramsData ); ?>;
$(document).ready(function() {
sectionDyf.<?php echo $kunik ?> = {
"jsonSchema" : {
"title" : "Mail",
"icon" : "fa-money",
"text" : "",
"properties" : <?php echo json_encode( $properties ); ?>,
save : function () {
var today = new Date();
tplCtx.value = { date : today.getDate() + '/' + (today.getMonth()+1) + '/' + today.getFullYear() };
$.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 {
ajaxPost(
null,
baseUrl+"/survey/answer/sendmail/id/<?php echo (string)$answer['_id'] ?>",
{to:$("#liste_row").val(),mailtype:sectionDyf.<?php echo $kunik ?>ParamsData.mail_type},
function(data){
toastr.success("Un mail a été envoyé à toutes les parties prenantes afin de les notifier");
//urlCtrl.loadByHash(location.hash);
}
);
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');
location.reload();
} );
}
}
}
};
sectionDyf.<?php echo $kunik ?>Params = {
"jsonSchema" : {
"title" : "<?php echo $kunik ?> config",
"description" : "Mail type",
"icon" : "fa-cog",
"properties" : {
mail_type : {
inputType : "text",
label : "Mail type",
values : sectionDyf.<?php echo $kunik ?>ParamsData.mail_type