Ejemplo n.º 1
2
    /**
     * Upload documents
     * @param $uploadType
     * @param bool $withoutMessage
     * @return int
     */
    public static function uploadDocuments($uploadType, $withoutMessage = false) {

        if(isset($_SESSION[$uploadType]) && count($_SESSION[$uploadType]) > 0) {
            $settings = UsersSettings::model()->findByAttributes(array(
                'User_ID' => Yii::app()->user->userID,
            ));

            //get default bank account
            $condition = new CDbCriteria();
            $condition->condition = "users_project_list.User_ID = '" . Yii::app()->user->userID . "'";
            $condition->addCondition("users_project_list.Client_ID = '" . Yii::app()->user->clientID . "'");
            $condition->addCondition("t.Account_Num_ID = '" . $settings->Default_Bank_Acct . "'");
            $condition->join = "LEFT JOIN projects ON projects.Project_ID = t.Project_ID
                                LEFT JOIN users_project_list ON users_project_list.Project_ID = t.Project_ID";
            $bankAcct = BankAcctNums::model()->with('client.company', 'project')->find($condition);
            $defaultBankAcct = 0;
            if ($bankAcct) {
                $defaultBankAcct = $settings->Default_Bank_Acct;
            }

            //get user to send email
            $person_to_email = false;
            if (Yii::app()->user->id != 'user' && Yii::app()->user->id != 'single_user') {
                $person_to_email = Users::model()->with('person')->findByPk(Yii::app()->user->userID);
            } else {
                $condition = new CDbCriteria();
                $condition->join = "LEFT JOIN users_client_list ON users_client_list.User_ID = t.User_ID";
                $condition->addInCondition('users_client_list.User_Type', array(UsersClientList::APPROVER, UsersClientList::PROCESSOR, UsersClientList::CLIENT_ADMIN));
                $condition->addInCondition('t.User_Type', array(Users::ADMIN, Users::DB_ADMIN, Users::DATA_ENTRY_CLERK), "OR");
                $condition->addCondition("users_client_list.Client_ID = '" . Yii::app()->user->clientID . "'");
                $person_to_email = Users::model()->with('person')->find($condition);
            }


            foreach ($_SESSION[$uploadType] as $key => $current_upload_file) {
                // check fed id
                if ($current_upload_file['doctype'] == self::W9) {
                    if (!preg_match('/^(\d{2}\-\d{7})|(\d{3}\-\d{2}\-\d{4})|(IN[-]\d{6})|(T0[-]\d{7})$/', $current_upload_file['fed_id'])) {
                        return 2;
                    }
                }
            }


            // insert documents into DB
            foreach ($_SESSION[$uploadType] as $key => $current_upload_file) {

                if (file_exists($current_upload_file['filepath'])) {
                    // create document

                    $document = new Documents();
                    $document->Document_Type = $current_upload_file['doctype'];
                    $document->User_ID = Yii::app()->user->userID;
                    $document->Client_ID = Yii::app()->user->clientID;
                    $document->Project_ID = Yii::app()->user->projectID;
                    $document->Created = date("Y-m-d H:i:s");
                    $document->save();
                    $new_doc_id=$document->Document_ID;

                    Audits::LogAction($document->Document_ID ,Audits::ACTION_UPLOAD);

                    // insert image
                    $image = new Images();
                    $imageData = addslashes(fread(fopen($current_upload_file['filepath'],"rb"),filesize($current_upload_file['filepath'])));
                    //$imageData = FileModification::ImageToPdfByFilePath($current_upload_file['filepath']);
                    $image->Document_ID = $document->Document_ID;
                    $image->Img = $imageData;
                    $image->File_Name = $current_upload_file['name'];
                    $image->Mime_Type = $current_upload_file['mimetype'];
                    $image->File_Hash = sha1_file($current_upload_file['filepath']);
                    $image->File_Size = intval(filesize($current_upload_file['filepath']));
                    $image->Pages_Count = FileModification::calculatePagesByPath($current_upload_file['filepath']);

                    $image->save();

                    $infile = @file_get_contents($current_upload_file['filepath'], FILE_BINARY);
                    if (($current_upload_file['mimetype'] == 'application/pdf' && $image->findPdfText($infile) == '')
                        || $current_upload_file['mimetype'] != 'application/pdf') {
                        Documents::crateDocumentThumbnail($current_upload_file['filepath'], 'thumbs', $current_upload_file['mimetype'], $document->Document_ID, 80);
                    }

                    // delete file from temporary catalog and from cache table
                    //unlink($current_upload_file['filepath']);
                    FileCache::deleteBothFromCacheById($current_upload_file['file_id']);

                    if ($current_upload_file['doctype'] == self::W9) {
                        // if document is W9
                        // get additional fields
                        $fedId = trim($current_upload_file['fed_id']);
                        $newCompanyName = trim($current_upload_file['company_name']);

                        // get company info
                        $company = Companies::model()->with('client')->findByAttributes(array(
                            'Company_Fed_ID' => $fedId,
                        ));

                        // create w9
                        $W9 = new W9();
                        $W9->Document_ID = $document->Document_ID;
                        $W9->W9_Owner_ID = Yii::app()->user->clientID;
                        $W9->Creator_ID = Yii::app()->user->userID;
                        $W9->Business_Name = trim($current_upload_file['bus_name']);
                        $W9->Tax_Class =  trim($current_upload_file['tax_name']);

                        // get user info
                        $user = Users::model()->with('person')->findByPk(Yii::app()->user->userID);

                        if ($company) {
                            // if company exisits
                            $client = $company->client;

                            //fill created company with dataentry values from session
                            Companies::fillWithSessionDataEntry($company,$current_upload_file);

                            $existingW9 = W9::model()->findByAttributes(array(
                                'Client_ID' => $client->Client_ID,
                                'W9_Owner_ID' => Yii::app()->user->clientID,
                            ));

                            if ($existingW9) {
                                $W9->Revision_ID = -1;
                            } else {
                                $W9->Revision_ID = 0;
                            }

                            $vendor = Vendors::model()->findByAttributes(array(
                                'Client_Client_ID' => Yii::app()->user->clientID,
                                'Vendor_Client_ID' => $client->Client_ID,
                            ));

                            if (isset($vendor->Active_Relationship) && $vendor->Active_Relationship == Vendors::NOT_ACTIVE_RELATIONSHIP) {
                                $vendor->Active_Relationship = Vendors::ACTIVE_RELATIONSHIP;
                                $vendor->save();
                            } else if (!$vendor && Yii::app()->user->clientID != 0 && Yii::app()->user->clientID != $client->Client_ID) {
                                $vendor = new Vendors();
                                $vendor->Vendor_ID_Shortcut = '';
                                $vendor->Vendor_Client_ID = $client->Client_ID;
                                $vendor->Client_Client_ID = Yii::app()->user->clientID;
                                $vendor->Vendor_Name_Checkprint = '';
                                $vendor->Vendor_1099 = '';
                                $vendor->Vendor_Default_GL = '';
                                $vendor->Vendor_Default_GL_Note = '';
                                $vendor->Vendor_Note_General = '';

                                $vendor->Vendor_Contact = trim($current_upload_file['contact']);
                                $vendor->Vendor_Phone = trim($current_upload_file['phone']);

                                $vendor->save();
                            }
                        } else {
                            //if company does not exists, create new company
                            $client = Companies::createEmptyCompany($fedId, $newCompanyName);
                            $company_model = Companies::model()->findByPk($client->Company_ID);
                            //fill created company with dataentry values from session
                            Companies::fillWithSessionDataEntry($company_model,$current_upload_file);

                            if (Yii::app()->user->clientID != 0) {
                                $vendor = new Vendors();
                                $vendor->Vendor_ID_Shortcut = '';
                                $vendor->Vendor_Client_ID = $client->Client_ID;
                                $vendor->Client_Client_ID = Yii::app()->user->clientID;
                                $vendor->Vendor_Name_Checkprint = '';
                                $vendor->Vendor_1099 = '';
                                $vendor->Vendor_Default_GL = '';
                                $vendor->Vendor_Default_GL_Note = '';
                                $vendor->Vendor_Note_General = '';

                                $vendor->Vendor_Contact = trim($current_upload_file['contact']);
                                $vendor->Vendor_Phone = trim($current_upload_file['phone']);

                                $vendor->save();
                            }

                            $W9->Revision_ID = 0;
                        }

                        // save w9
                        $W9->Client_ID = $client->Client_ID;
                        $W9->save();

                        if ($person_to_email) {
                            Mail::sendNewW9ForDataEntry($person_to_email->person->Email, $person_to_email->person->First_Name, $person_to_email->person->Last_Name);
                        }
                    } else if ($current_upload_file['doctype'] == self::AP) {
                        //create aps
                        $aps = new Aps();
                        $aps->Document_ID = $document->Document_ID;
                        $aps->Vendor_ID = 0;
                        $aps->PO_ID = 0;
                        $aps->AP_Approval_Value = Aps::NOT_READY_FOR_APPROVAL;
                        $aps->Invoice_Number = 0;
                        $aps->save();
                    } else if ($current_upload_file['doctype'] ==  self::PM) {
                        //create payment
                        $payment = new Payments();
                        $payment->Document_ID = $document->Document_ID;
                        $payment->Vendor_ID = 0;
                        $payment->Payment_Check_Number = 0;
                        $payment->Payment_Amount = 0;
                        if ($defaultBankAcct != 0) {
                            $payment->Account_Num_ID = $defaultBankAcct;
                        } else {
                            $payment->Account_Num_ID = 0;
                        }
                        $payment->save();
                    } else if ($current_upload_file['doctype'] == self::PO) {
                        //create pos
                        $po = new Pos();
                        $po->Document_ID = $document->Document_ID;
                        $po->Vendor_ID = 0;
                        $po->PO_Number = Pos::getNewPoNumber();
                        $po->PO_Date = date('Y-m-d');
                        $po->PO_Backup_Document_ID = 0;
                        $po->save();
                    } else if ($current_upload_file['doctype'] == self::PR) {
                        $payroll = new Payrolls();
                        $payroll->Document_ID = $document->Document_ID;
                        $payroll->save();
                    } else if ($current_upload_file['doctype'] == self::JE) {
                        $je = new Journals();
                        $je->Document_ID = $document->Document_ID;
                        $je->save();
                    } else if ($current_upload_file['doctype'] == self::PC) {
                        $pc = new Pcs();
                        $pc->Document_ID = $document->Document_ID;
                        $pc->save();
                    } else if ($current_upload_file['doctype'] == self::AR) {
                        $ar = new Ars();
                        $ar->Document_ID = $document->Document_ID;
                        $ar->save();
                    }
                }
                $arr[$current_upload_file['name']]['string']= Images::getAjaxStringForLastUploadSection($new_doc_id);
                $arr[$current_upload_file['name']]['key']=$key;

            }

            $_SESSION[$uploadType] = array();
            if (!$withoutMessage) {
                Yii::app()->user->setFlash('success', "Documents have been uploaded!");
            }
            return json_encode($arr);
        } else {
            $answer['empty']=1;
            return json_encode($answer);
        }
    }
 public function actionCreate()
 {
     if ($_GET["select"] == 1) {
         //print_r($_POST);
         if (!Trucks::checkPlate($_POST["plate"])) {
             $truck = new Trucks();
             // print_r($_POST);
             $truck->plate = MYChtml::check_num($_POST["plate"]);
             /* if (strlen($data[1]) > 4) {$truck->is_conctract = 1; $truck->contract_number = $data[1];} else {$truck->is_conctract = 0; $truck->contract_number = "";}
                if (strlen($data[7]) > 4) {$truck->is_act = 1; $truck->act_number = $data[7];} else {$truck->is_act = 0; $truck->act_number = "";}*/
             $truck->balance_license_fee = (int) $_POST["amount_fee_license"];
             $truck->daily_license_fee = $_POST["weight"];
             $truck->comment = $_POST["comment"];
             $truck->fio = $_POST["fio"];
             if (!$truck->save()) {
                 print_r($truck->getErrors());
             }
         }
         $payment = new Payments();
         $payment->plate = MYChtml::check_num($_POST["plate"]);
         if ($_POST["amount_installation"] > 0) {
             $payment->amount_installation = (int) $_POST["amount_installation"];
         }
         if ($_POST["amount_fee_license"] > 0) {
             $payment->amount_fee_license = (int) $_POST["amount_fee_license"];
         }
         $payment->date = $_POST["date"];
         $payment->comment = $_POST["comment"];
         if (!$payment->save()) {
             print_r($payment->getErrors());
         }
     }
     $this->render('create');
 }
Ejemplo n.º 3
0
 /**
  * Creates a new model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  */
 public function actionCreate()
 {
     $model = new Payments();
     // Uncomment the following line if AJAX validation is needed
     // $this->performAjaxValidation($model);
     if (isset($_POST['Payments'])) {
         $model->attributes = $_POST['Payments'];
         if ($model->save()) {
             $this->redirect(array('view', 'id' => $model->id));
         }
     }
     $this->render('create', array('model' => $model));
 }
Ejemplo n.º 4
0
 public static function addBalanceAndInstatllFee($amountBalanceFee, $amountInstallFee, $plate, $date = false)
 {
     $payment = new Payments();
     $payment->plate = $plate;
     $payment->amount_fee_license = $amountBalanceFee;
     $payment->amount_installation = $amountInstallFee;
     if ($date) {
         $payment->date = $date;
     } else {
         $payment->date = new CDbExpression('NOW()');
     }
     if ($payment->save()) {
         return true;
     } else {
         return false;
     }
 }
Ejemplo n.º 5
0
 /**
  * Creates a new model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  */
 public function actionCreate()
 {
     $model = new Payments();
     // Uncomment the following line if AJAX validation is needed
     // $this->performAjaxValidation($model);
     if (isset($_POST['Payments'])) {
         $model->attributes = $_POST['Payments'];
         $member = Members::model()->findByPk($model->member_id);
         $transaction = $member->dbConnection->beginTransaction();
         if ($model->save()) {
             $member->next_payment_date = date('Y-m-d', strtotime('1 month'));
             if ($member->save()) {
                 $transaction->commit();
                 $this->redirect(array('view', 'id' => $model->id));
             }
         } else {
             $transaction->rollback();
         }
     }
     $this->render('create', array('model' => $model));
 }
Ejemplo n.º 6
0
 public function postSavepayments()
 {
     $user_id = Session::get('user_id');
     $validator = Validator::make(Input::all(), Payments::$rules);
     if ($validator->passes()) {
         $payments = new Payments();
         $payments->agency_id = Input::get('agency_id');
         $payments->client_id = Input::get('client_id');
         $payments->bill_id = Input::get('bill_id');
         $payments->amount = Input::get('amount');
         $payments->tds = Input::get('tds');
         $payments->payment_date = Input::get('payment_date');
         $payments->payment_mode = Input::get('payment_mode');
         $payments->instrument_number = Input::get('instrument_number');
         $payments->remarks = Input::get('remarks');
         $payments->instrument_date = Input::get('instrument_date');
         $payments->user_id = $user_id;
         $payments->save();
     } else {
         return 0;
     }
     return Response::json($payments);
 }
Ejemplo n.º 7
0
 /**
  * Creates a new model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  */
 public function actionCreate()
 {
     $model = new Payments();
     // Uncomment the following line if AJAX validation is needed
     // $this->performAjaxValidation($model);
     if (isset($_GET['byorder']) and is_numeric($_GET['byorder'])) {
         $model->order_id = (int) $_GET['byorder'];
         $model->client_id = $model->order->client_id;
     }
     if (isset($_POST['Payments'])) {
         $model->attributes = $_POST['Payments'];
         if ($model->save()) {
             $msg = 'Платёж #' . $model->id . ' для Заказа #' . $model->order_id . ' ' . $model->order->name . ' создан';
             Yii::app()->user->setFlash('success', $msg);
             Yii::app()->logger->write($msg);
             if (isset($model->order_id)) {
                 $this->redirect(array('orders/view', 'id' => $model->order_id));
             } else {
                 $this->redirect(array('view', 'id' => $model->id));
             }
         }
     }
     $this->render('create', array('model' => $model));
 }
Ejemplo n.º 8
0
 public function actionCallback()
 {
     $model = new Payments();
     /*
               $model->hole_id = 6;
               $model->user_id = Yii::app()->user->id;
               $model->transaction_id = 122121;
               $model->status = 21212;
               $model->amount =12323;
               $model->save();
     */
     if (isset($_POST)) {
         $model->description = $_POST['description'];
         //$model->hole_id = $_POST['order_id'];
         $model->transaction_id = $_POST['transaction_id'];
         $model->status = $_POST['status'];
         $model->amount = $_POST['amount'];
         $model->save();
     }
     $file = fopen("dump.txt", a);
     $data = $_POST;
     file_put_contents('dump.txt', print_r($data, true), FILE_APPEND);
     fclose($file);
 }
Ejemplo n.º 9
0
 public function getSave()
 {
     $id = Input::get('id');
     $year = date('Y');
     $month = date('m');
     $date = date('d');
     $now = date('Y-m-d');
     if ($id) {
         // print_r($_POST);
         $employee_id = Input::get('employee_id');
         if ($employee_id) {
             $employee_id = Input::get('employee_id');
         } else {
             $employee_id = NULL;
         }
         $bs = BookingServices::where('booking_id', $id);
         $bs->delete();
         $br = BookingRooms::where('booking_id', $id);
         $br->delete();
         $bookings = Bookings::find($id);
         $service_id = Input::get('service_id');
         $TOTAL = 0;
         for ($i = 0; $i < count($service_id); $i++) {
             $cek_bs = BookingServices::where('service_id', '=', $service_id[$i])->first();
             if (empty($cek_bs)) {
                 $booking_service = new BookingServices();
                 $d_service = Services::find($service_id[$i]);
                 $booking_service->booking_id = $id;
                 $booking_service->service_id = $service_id[$i];
                 $booking_service->price = $d_service->price;
                 $TOTAL += $d_service->price;
                 $booking_service->save();
             }
         }
         $room_id = Input::get('room_id');
         for ($j = 0; $j < count($room_id); $j++) {
             $cek_r = BookingRooms::where('room_id', '=', $room_id[$j])->first();
             if (empty($cek_r)) {
                 $booking_room = new BookingRooms();
                 $d_room = Room::find($room_id[$j]);
                 $d_room->booked = 1;
                 $booking_room->booking_id = $id;
                 $booking_room->room_id = $room_id[$j];
                 $booking_room->price = $d_room->type->price;
                 $booking_room->save();
                 $d_room->save();
                 $TOTAL += $d_room->type->price;
             }
         }
         $bookings->guest_id = Input::get('guest_id');
         $bookings->employee_id = $employee_id;
         $bookings->number_of_days = Input::get('number_of_days');
         $bookings->date_booking = Input::get('date_booking');
         $bookings->date_booking_from = Input::get('date_booking');
         $bookings->date_booking_to = Input::get('date_booking_to');
         $bookings->save();
         $holiday = date('D');
         if ($holiday == 'Sat' || $holiday == 'Sun') {
             $disc = 0.05;
         } else {
             $disc = 0;
         }
         $TOTAL = $TOTAL * $bookings->number_of_days;
         $discount = $TOTAL * $disc;
         $grand_total = $TOTAL - $discount;
         $py = Payments::where('booking_id', '=', $id)->first();
         $payment = Payments::find($py->id);
         $payment->subtotal = $TOTAL;
         $payment->disc = $disc;
         $payment->grand_total = $grand_total;
         $payment->cashed = 0;
         $payment->save();
         Session::flash('message', 'The records are updated successfully');
         return Redirect::to('bookings/show/' . $id);
     } else {
         $data = Bookings::orderBy('id', 'desc')->first();
         if (isset($data->id)) {
             $index = $data->id + 1;
         } else {
             $index = 1;
         }
         $x = strlen($index);
         $y = null;
         for ($i = 4; $i > $x; $i--) {
             $y .= '0';
         }
         $y .= $index;
         $booking_code = $year . '' . $month . '' . $date . '' . $y;
         $employee_id = Input::get('employee_id');
         if ($employee_id) {
             $employee_id = Input::get('employee_id');
         } else {
             $employee_id = NULL;
         }
         $bookings = new Bookings();
         $bookings->booking_code = $booking_code;
         $bookings->guest_id = Input::get('guest_id');
         $bookings->employee_id = $employee_id;
         $bookings->number_of_days = Input::get('number_of_days');
         $bookings->date_booking = Input::get('date_booking');
         $bookings->date_booking_from = Input::get('date_booking');
         $bookings->date_booking_to = Input::get('date_booking_to');
         $bookings->save();
         $last = Bookings::orderBy('id', 'desc')->first();
         $last_id = $last->id;
         $service_id = Input::get('service_id');
         $TOTAL = 0;
         for ($i = 0; $i < count($service_id); $i++) {
             $cek_bs = BookingServices::where('service_id', '=', $service_id[$i])->first();
             if (empty($cek_bs)) {
                 $booking_service = new BookingServices();
                 $d_service = Services::find($service_id[$i]);
                 $booking_service->booking_id = $last_id;
                 $booking_service->service_id = $service_id[$i];
                 $booking_service->price = $d_service->price;
                 $booking_service->save();
                 $TOTAL += $d_service->price;
             }
         }
         $room_id = Input::get('room_id');
         for ($j = 0; $j < count($room_id); $j++) {
             $cek_r = BookingRooms::where('room_id', '=', $room_id[$j])->first();
             if (empty($cek_r)) {
                 $booking_room = new BookingRooms();
                 $d_room = Room::find($room_id[$j]);
                 $d_room->booked = 1;
                 $booking_room->booking_id = $last_id;
                 $booking_room->room_id = $room_id[$j];
                 $booking_room->price = $d_room->type->price;
                 $booking_room->save();
                 $d_room->save();
                 $TOTAL += $d_room->type->price;
             }
         }
         $TOTAL = $TOTAL * $bookings->number_of_days;
         $holiday = date('D');
         if ($holiday == 'Sat' || $holiday == 'Sun') {
             $disc = 0.05;
         } else {
             $disc = 0;
         }
         $discount = $TOTAL * $disc;
         $grand_total = $TOTAL - $discount;
         $payment = new Payments();
         $payment->booking_id = $last_id;
         $payment->subtotal = $TOTAL;
         $payment->disc = $disc;
         $payment->grand_total = $grand_total;
         $payment->cashed = 0;
         $payment->save();
         Session::flash('message', 'The records are inserted successfully');
         return Redirect::to('bookings/show/' . $last_id);
     }
 }
Ejemplo n.º 10
0
            $truck->daily_license_fee = 10;
            $truck->comment = $data[0] . " ";
            $truck->fio = $data[3];
            if (!$truck->save()) {
                print_r($truck->getErrors());
                echo "<hr>";
                echo "Строка:" . $i;
                die;
            }
        }
        $payment = new Payments();
        $payment->amount_fee_license = 0;
        $payment->amount_installation = (int) $data[4];
        $payment->date = date("Y-m-d", strtotime($data[2]));
        $payment->plate = MYChtml::check_num($data[8]);
        if (!$payment->save()) {
            print_r($payment->getErrors());
            echo "Строка:" . $i;
            die;
            echo "<hr>";
        }
    }
    ob_start();
    echo "Строка " . $i . "<br>";
    ob_end_flush();
}
?>

        </div><!-- panel -->

        <br />
Ejemplo n.º 11
0
 public function actionIndex()
 {
     if (Yii::app()->user->isGuest) {
         throw404();
     }
     $this->setActiveMenu('my_payments');
     $request = Yii::app()->request;
     $ad_id = $request->getParam('id', 0);
     $paid_id = $request->getParam('paid_id');
     $isFancy = $request->getParam('isFancy', 0);
     $paySubmit = $request->getParam('pay_submit');
     $tariffId = $request->getParam('tariffid', 0);
     if ($paySubmit) {
         $optionId = $request->getParam('option_id');
         $paySystemId = $request->getParam('pay_id');
         $amount = $request->getParam('amount', 0);
         $error = 0;
         // Если это поплнение баланса
         if ($paid_id == PaidServices::ID_ADD_FUNDS && $amount <= 0) {
             $this->setActiveMenu('my_balance');
             Yii::app()->user->setFlash('error', tc('Please specify the amount of the payment'));
             $error = 1;
         }
         Yii::app()->getModule('payment');
         $paysystem = Paysystem::model()->findByPk($paySystemId);
         if (!$paysystem) {
             throw404();
         }
         # покупка тарифного плана
         if ($tariffId && issetModule('tariffPlans')) {
             $tariffPlanInfo = TariffPlans::getFullTariffInfoById($tariffId);
             $paidOption = new PaidOptions();
             $paidOption->id = 0;
             if (!$tariffPlanInfo || $tariffPlanInfo['active'] == TariffPlans::STATUS_INACTIVE) {
                 throw404();
             }
             if ($tariffPlanInfo['price'] && $tariffPlanInfo['price'] > 0) {
                 // Если оплата тарифа с баланса пользователя
                 if ($paySystemId == Paysystem::ID_BALANCE) {
                     $user = User::model()->findByPk(Yii::app()->user->id);
                     if ($user->balance < $tariffPlanInfo['price']) {
                         Yii::app()->user->setFlash('error', tc('Please refill the balance'));
                         $error = 2;
                         $this->redirect(array('/tariffPlans/main/index'));
                     }
                 }
             } else {
                 # бесплатный тариф
                 Yii::app()->user->setFlash('error', tt('Selected tariff plan is free. Please contact the site administrator for transit to this tariff.', 'tariffPlans'));
                 $error = 2;
                 $this->redirect(array('/tariffPlans/main/index'));
             }
         } else {
             if ($paid_id != PaidServices::ID_ADD_FUNDS) {
                 $ad = Apartment::model()->findByPk($ad_id);
                 $paidOption = PaidOptions::model()->findByPk($optionId);
                 if (!$ad || !$paidOption || !isset($paidOption->paidService)) {
                     throw404();
                 }
                 // Если оплата платной услуги с баланса пользователя
                 if ($paySystemId == Paysystem::ID_BALANCE) {
                     $user = User::model()->findByPk(Yii::app()->user->id);
                     if ($user->id != $ad->owner_id || $ad->deleted) {
                         throw404();
                     }
                     if ($user->balance < $paidOption->price) {
                         Yii::app()->user->setFlash('error', tc('Please refill the balance'));
                         $error = 2;
                     }
                 }
             }
         }
         $paysystem->createPayModel();
         if ($paysystem->payModel === null) {
             throw404();
         }
         if ($error == 0) {
             // Создаем платеж и ставим ему статус "Ожидает оплаты"
             $payment = new Payments();
             $payment->user_id = Yii::app()->user->id;
             $payment->paid_id = $paid_id;
             if ($paid_id != PaidServices::ID_ADD_FUNDS) {
                 $payment->paid_option_id = $paidOption->id;
             }
             $payment->apartment_id = $ad_id;
             $payment->tariff_id = $tariffId;
             if ($tariffId && issetModule('tariffPlans')) {
                 $payment->amount = $tariffPlanInfo['price'];
             } else {
                 $payment->amount = $paid_id == PaidServices::ID_ADD_FUNDS ? $amount : $paidOption->price;
             }
             $payment->currency_charcode = Currency::getDefaultCurrencyModel()->char_code;
             $payment->status = Payments::STATUS_WAITPAYMENT;
             $payment->paysystem_id = $paysystem->id;
             $payment->save();
             /*echo '<pre>';
             		print_r($payment->getErrors());
             		echo '</pre>';
             		exit;*/
             // Передаем платеж на обработку в модель платежки.
             // Приложение либо звершается (происходит редирект по нужному адресу),
             // либо выдает сообщение, которое будет отображено пользователю
             $return = $paysystem->payModel->processPayment($payment);
             switch ($return['status']) {
                 case Paysystem::RESULT_OK:
                     Yii::app()->user->setFlash('success', $return['message']);
                     $this->redirect(array('/usercpanel/main/payments'));
                     break;
                 case Paysystem::RESULT_NOTICE:
                     Yii::app()->user->setFlash('notice', $return['message']);
                     $this->redirect(array('/userads/main/update', 'id' => $payment->apartment_id));
                     break;
                 case Paysystem::RESULT_ERROR:
                     Yii::app()->user->setFlash('error', $return['message']);
                     $this->redirect(array('/userads/main/update', 'id' => $payment->apartment_id));
                     break;
                 default:
                     $this->render('result', array('payment' => $payment, 'paysystem' => $paysystem, 'message' => $return['message']));
             }
             echo 'Loading ... ';
             exit;
         }
     }
     if ($paid_id != PaidServices::ID_ADD_FUNDS) {
         $apartment = Apartment::model()->findByPk($ad_id);
         if ($apartment->active != Apartment::STATUS_ACTIVE || $apartment->owner_active != 1) {
             echo '<h2>' . tt('To apply a paid service for the listing, it should be active.', 'paidservices') . '</h2>';
             exit;
         }
     }
     $paidService = PaidServices::model()->findByPk($paid_id);
     if (!$paidService || !$paidService->active) {
         throw404();
     }
     if ($paid_id == PaidServices::ID_ADD_IN_SLIDER) {
         $img = Images::getMainImageData(null, $apartment->id);
         if (!$img) {
             Yii::app()->user->setFlash('error', tt('Error! You must upload the image for the ad.', 'paidservices'));
             if (!$isFancy) {
                 $this->redirect(array('/userads/main/update', 'id' => $ad_id));
             } else {
                 echo tt('Error! You must upload the image for the ad.', 'paidservices');
             }
             Yii::app()->end();
         }
     }
     if (!isset($user)) {
         $user = User::model()->findByPk(Yii::app()->user->id);
     }
     if ($isFancy || Yii::app()->request->isAjaxRequest) {
         $this->excludeJs();
         if ($tariffId && issetModule('tariffPlans')) {
             $this->redirect(array('/tariffPlans/main/index'));
         } else {
             $this->renderPartial('paidform', array('paidService' => $paidService, 'user' => $user, 'ad_id' => $ad_id, 'isFancy' => true), false, true);
         }
     } else {
         if ($tariffId && issetModule('tariffPlans')) {
             $this->redirect(array('/tariffPlans/main/index'));
         } else {
             $this->render('paidform', array('paidService' => $paidService, 'user' => $user, 'ad_id' => $ad_id, 'isFancy' => false));
         }
     }
 }