Advertisement
Guest User

Untitled

a guest
Jul 21st, 2014
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 13.94 KB | None | 0 0
  1.    public function registration($clubId = null) {
  2.  
  3.       // Find the club as specified in the URL
  4.       // TODO: Change this to use *** class as findByIdOrSubdomain is deprecated
  5.       $club = $this->Club->findByIdOrSubdomain($clubId, [
  6.           'contain' => [
  7.               'Season',
  8.               'Season.MemberType' => ['conditions' => ['MemberType.active' => 1], 'order' => 'MemberType.weight']],
  9.       ]);
  10.       if (empty($club))
  11.         throw new NotFoundException('Unfortunately the registration form you attempted to access is no longer available.');
  12.  
  13.       //--------------- SAVING A REGISTRATION ---------------
  14.       if ($this->request->isPost()) {
  15.  
  16.         // We need to create member and registration records (only 1 registration record is submitted by the form)
  17.         $dataToSave = $this->request->data;
  18.         // debug($dataToSave);
  19.         // If the only key in the user model is acceptTerms, we'll trash that (don't want to save a User model unnecessarily)
  20.         if (array_keys($dataToSave[0]['User']) == ['acceptTerms'])
  21.           unset($dataToSave[0]['User']);
  22.  
  23.         $paymentMethod = $dataToSave[0]['Member']['Registration'][0]['payment_method'];
  24.         $totalAmount = 0;
  25.         foreach($dataToSave as $i => $member) {
  26.           $dataToSave[$i]['Member']['club_id'] = $club['Club']['id'];
  27.  
  28.           // If we are saving a primary (parent) user, we also need to copy their email address to the users table
  29.           if ($i === 0) {
  30.             $dataToSave[$i]['User']['email'] = $member['Member']['email'];
  31.             $dataToSave[$i]['User']['user_type'] = 'member';
  32.           }
  33.  
  34.           /*
  35.             Here we restructure the array of registrations slightly
  36.             (create a separate registration entry for each member type they selected)
  37.  
  38.             FROM:
  39.  
  40.             'Member' => array(
  41.             ...
  42.             'Registration' => array(
  43.             (int) 0 => array(
  44.             'MemberType' => array(
  45.             (int) 0 => '70',
  46.             (int) 1 => '123',
  47.             ),
  48.             'payment_method' => 'paypal'
  49.             )))
  50.  
  51.             TO:
  52.  
  53.             'Member' => array(
  54.             ...
  55.             'Registration' => array(
  56.             (int) 0 => array(
  57.             'payment_method' => 'paypal',
  58.             'member_type_id' => '70'
  59.             ),
  60.             (int) 1 => array(
  61.             'payment_method' => 'paypal',
  62.             'member_type_id' => '123'
  63.             ))
  64.  
  65.            */
  66.           $registrations = [];
  67.           // Loop through the checked member types (registrations)
  68.           // May be empty if doing a renewal for only certain members in group
  69.           if (is_array($member['Member']['Registration'][0]['MemberType'])) {
  70.             foreach($member['Member']['Registration'][0]['MemberType'] as $memberTypeId) {
  71.               // Fetch the member type data
  72.               $this->MemberType->contain('Season');
  73.               $memberType = $this->MemberType->findById($memberTypeId);
  74.  
  75.               // Create a new registration
  76.               $rego = $member['Member']['Registration'][0];
  77.               $rego['member_type_id'] = $memberTypeId;
  78.               $rego['amount_due'] = $memberType['MemberType']['price'];
  79.               $rego['payment_method'] = $paymentMethod;
  80.               $totalAmount += -$rego['amount_due'];
  81.               unset($rego['MemberType']);
  82.               $registrations[] = $rego;
  83.  
  84.               //----- Create a new transaction (negative amounts, as they will not have paid yet) -----
  85.            /*   if ($i == 0) {*/
  86.                 // For primary members
  87.                 $dataToSave[$i]['Member']['Payment'][] = [
  88.                     'payment_method' => $paymentMethod,
  89.                     'amount' => -$rego['amount_due'],
  90.                     'season_id' => $memberType['Season']['id'],
  91.                     'membertype_id' => $memberType['MemberType']['id'],
  92.                     'extra_notes' => 'Registered for ' . $memberType['Season']['name'] . ': ' . $memberType['MemberType']['name'],
  93.                 ];
  94.           /*    } else {
  95.                 // Additional members ($0 amount, cos they won't be paying)
  96.                 $dataToSave[$i]['Member']['Payment'][] = [
  97.                     'payment_method' => $paymentMethod,
  98.                     'amount' => 0,
  99.                     'season_id' => $memberType['Season']['id'],
  100.                     'membertype_id' => $memberType['MemberType']['id'],
  101.                     'extra_notes' => 'Registered for ' . $memberType['Season']['name'] . ': ' . $memberType['MemberType']['name']
  102.                     . ', fees of $' . $rego['amount_due'] . ' assigned to primary member',
  103.                 ];
  104.                 // Transaction for their primary member (who will be paying the bill)
  105.                 $dataToSave[0]['Member']['Payment'][] = [
  106.                     'payment_method' => $paymentMethod,
  107.                     'amount' => -$rego['amount_due'],
  108.                     'season_id' => $memberType['Season']['id'],
  109.                     'membertype_id' => $memberType['MemberType']['id'],
  110.                     'extra_notes' => 'Additional member ('
  111.                     . $member['Member']['first_name'] . ' ' . $member['Member']['first_name']
  112.                     . ') registered for '
  113.                     . $memberType['Season']['name'] . ': ' . $memberType['MemberType']['name'],
  114.                 ];
  115.               }*/
  116.             }
  117.           }
  118.           $dataToSave[$i]['Member']['Registration'] = $registrations;
  119.         }
  120.  
  121.         // Fix: now that we're performing renewals and new regos in same function, the money outstanding gets adjusted later
  122.         // $dataToSave[0]['Member']['money_outstanding'] = $totalAmount;
  123.         // We now want to restructure the numerical array of members so that all
  124.         // the *additional* members sit underneath the primary member,
  125.         // so that Cake assigns the parent_id properly
  126.         // (could have done by altering the front-end form, but think it might be easier here)
  127.         /*
  128.          *  FROM:
  129.          *  [0 => ['Member' => ['name' => 'X', ['Registration' => []]]],
  130.          *   1 => ['Member' => ['name' => 'X', ['Registration' => []]]]]
  131.          *
  132.          *  TO:
  133.          *  ['Member' => [name => 'X'],
  134.          *   'ChildMember' => [['name' => 'x', 'Registration' => []]],
  135.          *   'Registration' => []]]
  136.          */
  137.         $dataToSave['ChildMember'] = Set::extract(array_slice($dataToSave, 1), '{n}.Member');  // all members from 1 onwards
  138.         $dataToSave = $dataToSave[0] + ['ChildMember' => $dataToSave['ChildMember']];
  139.         $dataToSave['Registration'] = $dataToSave['Member']['Registration'];
  140.         unset($dataToSave['Member']['Registration']);
  141.  
  142.         // debug($dataToSave);
  143.         // If validation succeeds and data is successfully saved...
  144.         if ($this->Member->saveAssociated($dataToSave, ['deep' => true])) {
  145.  
  146.           // Increment the parent member's balance by the total amount of all registrations
  147.           $this->Member->updateAll(
  148.             ['Member.money_outstanding' => "Member.money_outstanding + $totalAmount"], ['Member.id' => $this->Member->id]);
  149.  
  150.           $this->view = 'registration_complete';
  151.  
  152.           //----------------- PAYPAL ------------------------------------
  153.           // Members who chose Paypal will see an extra step here
  154.           if ($paymentMethod == 'paypal') {
  155.             $this->view = 'registration_paypal';
  156.             $this->set('memberId', $this->Member->id);
  157.             $this->set('amountDue', $totalAmount);
  158.             $this->Session->write('PaypalController.ApiLogin', $club['Club']['payment_settings']['paypal']);
  159.           }
  160.  
  161.           //--------------------------- EMAIL THE MEMBER -----------------------------
  162.           $memberRegoFields = [];
  163.  
  164.           // We will display a section for each additional member
  165.           // (each member is a different index in $memberRegoFields)
  166.           foreach($this->request->data as $i => $member) {
  167.             $memberRegoFields[$i]['First Name'] = $member['Member']['first_name'];
  168.             $memberRegoFields[$i]['Last Name'] = $member['Member']['last_name'];
  169.             $memberRegoFields[$i]['Email'] = $member['Member']['email'];
  170.  
  171.             // Will be displaying unhashed password in email (only for primary user)
  172.             if (isset($member['User']['password']))
  173.               $memberRegoFields[$i]['Password'] = $member['User']['password'];
  174.  
  175.             // Loop through the members types they subscribed to and display this as a row in the email
  176.             // $types = Hash::extract($member['Member']['Registration'], '{n}.MemberType.{n}');
  177.             $memberTypeIds = (array)$member['Member']['Registration'][0]['MemberType'];
  178.             // debug($memberTypeIds);
  179.             foreach($memberTypeIds as &$t) {
  180.               $memberType = Hash::extract($club, 'Season.{n}.MemberType.{n}[id=' . $t . ']')[0];
  181.               $seasonName = Hash::extract($club, 'Season.{n}[id=' . $memberType['season_id'] . ']')[0]['name'];
  182.               $memberRegoFields[$i]['Regos'][] = [
  183.                   'Season' => $seasonName,
  184.                   'Type' => $memberType['name'],
  185.                   'Price' => '$' . $memberType['price'],
  186.               ];
  187.               // $t = "$seasonName: $memberType[name] ($$memberType[price])";   // assigning by reference
  188.             }
  189.  
  190.             /*             * ***** no longer displaying custom fields on rego email ***************
  191.               // Loop through the custom fields and use the labels the admin has specified
  192.               foreach ($member['Member'] as $key => $value) {
  193.               $label = Hash::extract($club['Club']['rego_form'], '{n}[dbField=' . $key . '].label');
  194.               // debug($label);
  195.               if ($label)
  196.               // $emailFields[$label[0]] = $value;
  197.               $memberRegoFields[$i][$label[0]] = $value;
  198.               }
  199.               /************************************************************************ */
  200.           }
  201.  
  202.           /*
  203.            * At this point, the $memberRegoFields array looks something like this...
  204.            * (ready for use in the email template)
  205.            *
  206.            * array(
  207.            *        (int) 0 => array(
  208.            *            'First Name' => 'Haviva',
  209.            *            'Last Name' => 'Kidd',
  210.            *            'Email' => 'tyva@gmail.com',
  211.            *            'Password' => 'pass',
  212.            *            'Regos' => array(
  213.            *                (int) 0 => array(
  214.            *                    'Season' => 'Season 1',
  215.            *                    'Type' => 'Family',
  216.            *                    'Price' => '$200.00'
  217.            *                ),
  218.            *                (int) 1 => array(
  219.            *                    'Season' => 'Season 1',
  220.            *                    'Type' => 'Junior',
  221.            *                    'Price' => '$123.00'
  222.            *                )
  223.            *            ),
  224.            *        ),
  225.            *        (int) 1 => array(
  226.            *            'First Name' => 'Ivan',
  227.            *            'Last Name' => 'Franks',
  228.            *            'Email' => 'mojo@yahoo.com',
  229.            *            'Regos' => array(
  230.            *                (int) 0 => array(
  231.            *                    'Season' => 'Season 1',
  232.            *                    'Type' => 'Additional Family member',
  233.            *                    'Price' => '$0.00'
  234.            *                ),
  235.            *                (int) 1 => array(
  236.            *                    'Season' => 'Season 1',
  237.            *                    'Type' => 'Junior',
  238.            *                    'Price' => '$123.00'
  239.            *                )
  240.            *            ),
  241.            *        )
  242.            * )
  243.            */
  244.  
  245.           // debug($memberRegoFields);
  246.           // Club email addresses are a recent addition (April 2013), so for clubs that don't have them yet,
  247.           // we'll send the email "from" a non-existent **** address
  248.           if (!Validation::email($club['Club']['email']))
  249.             $club['Club']['email'] = 'NO-REPLY@****';
  250.  
  251.           //----- Render and send the actual email -----
  252.           App::uses('CakeEmail', 'Network/Email');
  253.           $email = new CakeEmail('DebugAndLog');
  254.           $email->to($dataToSave['Member']['email'])
  255.             ->from([$club['Club']['email'] => $club['Club']['name'] . ' Registrations (via ***)'])
  256.             ->subject('Your registration was successful, here\'s your receipt.')
  257.             ->viewVars([
  258.                 'memberRegoFields' => $memberRegoFields,
  259.                 'paymentMethod' => $paymentMethod,
  260.                 'club' => h($club),
  261.                 'memberId' => $this->Member->id,
  262.                 'totalFees' => $totalAmount,
  263.             ])
  264.             // TODO: use a club-specific template
  265.             ->template('member_registration')   // View/Emails/html/member_registration.ctp
  266.             // and View/Layouts/Emails/html/default.ctp
  267.             ->emailFormat('html')
  268.             ->send();
  269.  
  270.           // TODO: send email notification to the club?
  271.         } else { // if validation failed
  272.           // debug($this->Member->validationErrors);
  273.         }
  274.       }
  275.       //---- end of saving to DB -----
  276.       // $this->layout = '../../webroot/themes/***/standard_header_footer';
  277.       $club['Club']['rego_form'] = Hash::filter($club['Club']['rego_form']);  // remove empty items from array (why?)
  278.       $this->set('club', $club);
  279.  
  280.       // Always display at least one blank member form
  281.       if (empty($this->request->data))
  282.         $this->request->data = [null];
  283.  
  284.       // Find the payment methods this club is willing to accept and send these to the view
  285.       $paymentMethods = [];
  286.       foreach($club['Club']['payment_settings'] as $paymentType => $options)
  287.         if ($options['enabled'])
  288.           if ($paymentType == 'EFT')
  289.             $paymentMethods[$paymentType] = 'Electronic Funds Transfer (EFT)';
  290.           elseif ($paymentType == 'paypal')
  291.             $paymentMethods[$paymentType] = 'VISA / Mastercard (PayPal)';
  292.           elseif ($paymentType == 'CH')
  293.             $paymentMethods[$paymentType] = 'Cheque';
  294.           elseif ($paymentType == 'CA')
  295.             $paymentMethods[$paymentType] = 'Cash';
  296.  
  297.       $this->set('paymentMethods', $paymentMethods);
  298.       $this->set('title_for_layout', $club['Club']['name'] . ' Member Registration Form');
  299.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement