PageRenderTime 27ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/backend/controllers/ClientInvitationController.php

https://gitlab.com/haroldv22/tupadrino
PHP | 287 lines | 183 code | 59 blank | 45 comment | 20 complexity | 63b53b29f427912d6a8577c5d6bbd6dd MD5 | raw file
  1. <?php
  2. namespace backend\controllers;
  3. use Yii;
  4. use yii\data\ActiveDataProvider;
  5. use yii\web\Controller;
  6. use yii\web\NotFoundHttpException;
  7. use yii\filters\VerbFilter;
  8. use yii\filters\AccessControl;
  9. use app\models\User;
  10. use app\models\Status;
  11. use app\models\ClientInvitation;
  12. use app\models\Clients;
  13. use app\models\UploadForm;
  14. use yii\web\UploadedFile;
  15. use moonland\phpexcel\Excel;
  16. /**
  17. * ClientInvitationController implements the CRUD actions for ClientInvitation model.
  18. */
  19. class ClientInvitationController extends Controller{
  20. public function behaviors(){
  21. return [
  22. 'access' => [
  23. 'class' => AccessControl::className(),
  24. 'rules' => [
  25. [
  26. 'actions' => ['index','view','create','update','delete','logout'],
  27. 'allow' => true,
  28. 'roles' => ['@'],
  29. 'matchCallback' => function($rule,$action){
  30. return User::userRoles(Yii::$app->user->identity->id,Yii::$app->params['superUserRole']);
  31. },
  32. ],
  33. ],
  34. 'denyCallback' => function ($rule, $action) {
  35. $this->redirect(Yii::$app->user->loginUrl);
  36. // throw new \Exception('aaa are not allowed to access this page');
  37. },
  38. ],
  39. 'verbs' => [
  40. 'class' => VerbFilter::className(),
  41. 'actions' => [
  42. 'delete' => ['post'],
  43. ],
  44. ],
  45. ];
  46. }
  47. /**
  48. * Lists all ClientInvitation models.
  49. * @return mixed
  50. */
  51. public function actionIndex(){
  52. $model = new UploadForm();
  53. $dataProvider = new ActiveDataProvider([
  54. 'query' => ClientInvitation::find(),
  55. 'pagination' => [
  56. 'pageSize' => 15,
  57. ],
  58. 'sort' => [
  59. 'defaultOrder' => [
  60. 'date_exp' => SORT_DESC,
  61. ]
  62. ],
  63. ]);
  64. if (Yii::$app->request->isPost) {
  65. $excel = new Excel(); // Phpexcel
  66. $errorEmail = '';
  67. $fecha = date("Y-m-d");
  68. // se obtiene el archivo
  69. $fileName = UploadedFile::getInstance($model, 'importInvitation')->tempName;
  70. $model->scenario = 'invitations';
  71. $model->importInvitation = $fileName;
  72. if($model->validate()){
  73. $data = Excel::widget([
  74. 'mode' => 'import',
  75. 'fileName' => $fileName,
  76. 'setFirstTitle' =>true,
  77. 'setFirstRecordAsKeys' => false,
  78. 'setIndexSheetByName' => true,
  79. 'getOnlySheet' => 'invitaciones',
  80. ]);
  81. // Permite conocer si el archivo esta vacio o no!!
  82. if (sizeof($data) == 4){
  83. \Yii::$app->session->setFlash('warning', 'Revise el archivo a importar ya que esta vacio!!');
  84. return $this->render('index', [
  85. 'model' => $model,
  86. 'dataProvider' => $dataProvider,
  87. ]);
  88. }else{
  89. $i = 0;
  90. foreach ($data as $key => $value){
  91. if ($i>3){
  92. $modelClientInv = new ClientInvitation();
  93. $modelClientInv->invitation_code = $modelClientInv->getInvitationCode();
  94. $modelClientInv->id_godfather = 0;
  95. $modelClientInv->id_user_system = Yii::$app->user->identity->id;
  96. $modelClientInv->id_status = Yii::$app->params['invi_espera'];
  97. $modelClientInv->date_exp = date("Y-m-d", strtotime("$fecha +15 days")); // Fecha de Expiracion
  98. // verifica si el email existe registrado entre los clientes
  99. $validarClients = Clients::find()
  100. ->where( [ 'email' => strtolower($value['B']) ] )
  101. ->exists();
  102. // verficica si el email existe registrado entre los clientes invitados
  103. $validarClientsInv = ClientInvitation::find()
  104. ->where( [ 'email' => strtolower($value['B']) ] )
  105. ->exists();
  106. if ($validarClients == false && $validarClientsInv == false){
  107. $modelClientInv->name = $value['A'];
  108. $modelClientInv->email = strtolower($value['B']);
  109. $modelClientInv->cant_godson = $value['C'];
  110. if ($modelClientInv->save()){
  111. // se encarga de enviar la invitacion al usuario registrado
  112. $modelClientInv->sentInvitationUser( Yii::$app->user->identity->email,
  113. $value['B'],
  114. $modelClientInv->name,
  115. $modelClientInv->invitation_code );
  116. }
  117. }else{
  118. // Contiene todos los email a quienes no se le envio una invitacion
  119. $errorEmail .= $value['B'].'<br />';
  120. }
  121. }
  122. $i++;
  123. }
  124. }
  125. if (!empty($errorEmail)){
  126. \Yii::$app->session->setFlash('info', 'Estos correos electronicos ya se encuentran registrados en el sistema: <br /><strong>'.$errorEmail.'</strong> Por lo tanto no se les envio una invitacion');
  127. }else{
  128. \Yii::$app->session->setFlash('success', 'Se han enviado las invitaciones satisfactoriamente a sus destinatarios');
  129. }
  130. }
  131. }
  132. return $this->render('index', [
  133. 'model' => $model,
  134. 'dataProvider' => $dataProvider,
  135. ]);
  136. }
  137. /**
  138. * Displays a single ClientInvitation model.
  139. * @param integer $id
  140. * @return mixed
  141. */
  142. public function actionView($id){
  143. return $this->render('view', [
  144. 'model' => $this->findModel($id),
  145. ]);
  146. }
  147. /**
  148. * Creates a new ClientInvitation model.
  149. * If creation is successful, the browser will be redirected to the 'view' page.
  150. * @return mixed
  151. */
  152. public function actionCreate(){
  153. $model = new ClientInvitation();
  154. $modelClient = new Clients();
  155. $fecha = date("Y-m-d");
  156. if ($model->load(Yii::$app->request->post())) {
  157. // verifica si el email existe registrado entre los clientes
  158. $validarEmail = $modelClient::find()
  159. ->where( [ 'email' => strtolower($model->email) ] )
  160. ->exists();
  161. $model->email = strtolower($model->email);
  162. $model->invitation_code = $model->getInvitationCode();
  163. $model->id_godfather = 0;
  164. $model->id_user_system = Yii::$app->user->identity->id;
  165. $model->id_status = Yii::$app->params['invi_espera'];
  166. $model->date_exp = date("Y-m-d", strtotime("$fecha +15 days")); // Fecha de Expiracion
  167. $model->date_add = $fecha;
  168. if (!($validarEmail) && $model->save()){
  169. \Yii::$app->session->setFlash('success', 'Se ha enviado la invitacion satisfactoriamente al email <b>"'.$model->email.'"</b>>');
  170. // se encarga de enviar la invitacion al usuario registrado
  171. $model->sentInvitationUser( Yii::$app->user->identity->email,
  172. $model->email,$model->name,
  173. $model->invitation_code );
  174. return $this->redirect(['view', 'id' => $model->id]);
  175. }else{
  176. if ($validarEmail)
  177. \Yii::$app->session->setFlash('error', 'Este email <b>"'.$model->email.'"</b> le pertenece a un Cliente en <b>TuPadrino.net</b>');
  178. return $this->render('create', [
  179. 'model' => $model,
  180. ]);
  181. }
  182. }else {
  183. return $this->render('create', [
  184. 'model' => $model,
  185. ]);
  186. }
  187. }
  188. /**
  189. * Updates an existing ClientInvitation model.
  190. * If update is successful, the browser will be redirected to the 'view' page.
  191. * @param integer $id
  192. * @return mixed
  193. */
  194. public function actionUpdate($id){
  195. $model = $this->findModel($id);
  196. if ($model->load(Yii::$app->request->post()) && $model->save()) {
  197. return $this->redirect(['view', 'id' => $model->id]);
  198. } else {
  199. return $this->render('update', [
  200. 'model' => $model,
  201. ]);
  202. }
  203. }
  204. /**
  205. * Deletes an existing ClientInvitation model.
  206. * If deletion is successful, the browser will be redirected to the 'index' page.
  207. * @param integer $id
  208. * @return mixed
  209. */
  210. public function actionDelete($id){
  211. $this->findModel($id)->delete();
  212. return $this->redirect(['index']);
  213. }
  214. /**
  215. * Finds the ClientInvitation model based on its primary key value.
  216. * If the model is not found, a 404 HTTP exception will be thrown.
  217. * @param integer $id
  218. * @return ClientInvitation the loaded model
  219. * @throws NotFoundHttpException if the model cannot be found
  220. */
  221. protected function findModel($id){
  222. if (($model = ClientInvitation::findOne($id)) !== null) {
  223. return $model;
  224. } else {
  225. throw new NotFoundHttpException('The requested page does not exist.');
  226. }
  227. }
  228. }