/** * Event - triggered every beforeFilter-callback. * Sets the date and time when the user is last seen. * * @param \Cake\Event\Event $event Event. * @return void */ public function lastSeenEvent($event) { $user = $this->_getUsermetas(); if ($user) { $user->set('last_seen', Time::now()); $this->Usermetas->save($user); } }
/** Perform a curl request based on url provided * @access public * @uses Zend_Cache * @uses Zend_Json_Decoder * @param string $method * @param array $params */ public function get($method, array $params) { $this->_url = $this->_createUrl($method, $params); if (!$this->_cache->test(md5($this->_url))) { $config = array('adapter' => 'Zend_Http_Client_Adapter_Curl', 'curloptions' => array(CURLOPT_POST => true, CURLOPT_USERAGENT => $this->_getUserAgent(), CURLOPT_FOLLOWLOCATION => true, CURLOPT_RETURNTRANSFER => true, CURLOPT_LOW_SPEED_TIME => 1)); $client = new Zend_Http_Client($this->_url, $config); $response = $client->request(); $data = $response->getBody(); $this->_cache->save($data); } else { $data = $this->_cache->load(md5($this->_url)); } if ($this->getFormat() === 'json') { return $this->_decoder($data); } else { return $data; } }
/** * Establece un ejercicio como predeterminado para este usuario * @param type $cod el código del ejercicio */ protected function save_codejercicio($cod) { if ($cod != $this->user->codejercicio) { $this->default_items->set_codejercicio($cod); $this->user->codejercicio = $cod; if (!$this->user->save()) { $this->new_error_msg('Error al establecer el ejercicio ' . $cod . ' como ejercicio predeterminado para este usuario.'); } } }
/** * add or update global status (query) * @param type $o * @param type $data */ protected function addOrUpdateGlobalStatus($o, $data) { $o->name = $data['name']; $o->manual_order = $data['manual_order']; $o->color = $data['color']; $flags = array('flag_first' => 0, 'flag_unreg' => 0, 'flag_error' => 0, 'flag_payment' => 0, 'flag_delivery' => 0, 'flag_close' => 0, 'secret' => 0); if (!empty($data['flag'])) { $flags[$data['flag']] = 1; } $o->fill($flags); $o->save(); }
/** * Создание категории точек на Google Maps * @param type $page_id ID страницы * @param type $model Ссылка на обрабатываемую модель */ public function create_item($page_id = null, $model) { $controller = Yii::app()->getController(); if (isset($_POST['ModuleYmapsCategories'])) { $_POST['ModuleYmapsCategories']['mpage_id'] = ModulesInPages::model()->getLink($page_id, $this->module_id); $model->attributes = $_POST['ModuleYmapsCategories']; if ($model->save()) { Yii::app()->user->setFlash($this->module_id . '_add_message', '<p style="color:green;">Добавлено</p>'); $controller->redirect(Yii::app()->baseUrl . '?r=pages/update&id=' . $page_id . '&/#!/tab_' . $this->module_id); } else { Yii::app()->user->setFlash($this->module_id . '_add_message', '<p style="color:red;">Ошибка</p>'); } } }
/** * @param type $res * @param type $measurement * * @return type */ public function resourceToModel($res, $measurement) { //$measurement->patient_id = $res->patient_id; foreach ($res as $key => $value) { if ($key == 'resourceType') { continue; } $measurement->{$key} = $value; } $saved = $measurement->save(); if (!$saved) { print_r($measurement->getErrors()); } return $measurement; }
/** * Saves the profile field type * * The settings/configuration for a ProfileFieldType are saved in ProfileField * in attribute "field_type_config" as JSON data. * * The ProfileFieldType Class itself can overwrite this behavior. */ public function save() { $data = array(); foreach ($this->attributeNames() as $attributeName) { // Dont save profile field attribute if ($attributeName == 'profileField') { continue; } $data[$attributeName] = $this->{$attributeName}; } $this->profileField->field_type_config = CJSON::encode($data); $this->profileField->save(); // Clear Database Schema Yii::app()->db->schema->getTable('profile', true); Profile::model()->refreshMetaData(); }
/** * Saves the profile field type * * The settings/configuration for a ProfileFieldType are saved in ProfileField * in attribute "field_type_config" as JSON data. * * The ProfileFieldType Class itself can overwrite this behavior. */ public function save() { $data = array(); foreach ($this->attributes as $attributeName => $value) { // Dont save profile field attribute if ($attributeName == 'profileField') { continue; } $data[$attributeName] = $this->{$attributeName}; } $this->profileField->field_type_config = \yii\helpers\Json::encode($data); if (!$this->profileField->save()) { throw new \yii\base\Exception("Could not save profile field!"); } // Clear Database Schema Yii::$app->getDb()->getSchema()->getTableSchema(\humhub\modules\user\models\Profile::tableName(), true); return true; }
/** * This method prepares the response of the current element based on the * $bean object and the $flowData, an external action such as * ROUTE or ADHOC_REASSIGN could be also processed. * * This method probably should be override for each new element, but it's * not mandatory. However the response structure always must pass using * the 'prepareResponse' Method. * * As defined in the example: * * $response['route_action'] = 'ROUTE'; //The action that should process the Router * $response['flow_action'] = 'CREATE'; //The record action that should process the router * $response['flow_data'] = $flowData; //The current flowData * $response['flow_filters'] = array('first_id', 'second_id'); //This attribute is used to filter the execution of the following elements * $response['flow_id'] = $flowData['id']; // The flowData id if present * * * @param type $flowData * @param type $bean * @param type $externalAction * @return type */ public function run($flowData, $bean = null, $externalAction = '', $arguments = array()) { switch ($externalAction) { case 'RESUME_EXECUTION': $flowAction = 'UPDATE'; break; default: $flowAction = 'CREATE'; break; } $bpmnElement = $this->retrieveDefinitionData($flowData['bpmn_id']); $act_assign_user = $bpmnElement['act_assign_user']; $userData = $this->retrieveUserData($act_assign_user); if (isset($bean->field_name_map['assigned_user_id']) && (isset($userData->id) && $userData->id == $act_assign_user)) { $this->logger->debug("Assign user to '{$act_assign_user}'"); $bean->skipPartialUpdate = true; $historyData = $this->retrieveHistoryData($flowData['cas_sugar_module']); $historyData->savePreData('assigned_user_id', $flowData['cas_user_id']); //$bean->assigned_user_id = $act_assign_user; if (isset($bpmnElement['act_update_record_owner']) && $bpmnElement['act_update_record_owner'] == 1) { $bean->assigned_user_id = $act_assign_user; $bean->save(); } $flowData['cas_user_id'] = $act_assign_user; $historyData->savePostData('assigned_user_id', $act_assign_user); //$bean->team_id = '1'; $params = array(); $params['cas_id'] = $flowData['cas_id']; $params['cas_index'] = $flowData['cas_index']; $params['act_id'] = $bpmnElement['id']; $params['pro_id'] = $bpmnElement['pro_id']; $params['user_id'] = $this->currentUser->id; $params['frm_action'] = 'Assing user'; $params['frm_comment'] = 'Assing user Applied'; $params['log_data'] = $historyData->getLog(); $this->caseFlowHandler->saveFormAction($params); // just update the record instead //$query = "update pmse_bpm_flow set " . // " cas_user_id = '$act_assign_user' " . // " where cas_id = {$flowData['cas_id']} and cas_index = {$flowData['cas_index']} "; //$bean->db->query($query); } return $this->prepareResponse($flowData, 'ROUTE', $flowAction); }
/** * * @param type $args */ public function updateProcessDefinition($args) { $this->initWrapper(); //Update ProcessDefinition $this->processDefinition = $this->getBean('pmse_BpmProcessDefinition')->retrieve_by_string_fields(array('prj_id' => $args['record'])); //Update Diagrams $this->diagram = $this->getBean('pmse_BpmnDiagram')->retrieve_by_string_fields(array('prj_id' => $args['record'])); //Update Process $this->process = $this->getBean('pmse_BpmnProcess')->retrieve_by_string_fields(array('prj_id' => $args['record'])); foreach ($args as $key => $value) { $this->diagram->{$key} = $value; $this->process->{$key} = $value; $this->processDefinition->{$key} = $value; } $this->diagram->save(); $this->process->save(); $this->processDefinition->save(); $this->notify(); }
/** * Annulation des remboursement de la commande * @param type $order */ protected function _cancelRefundOrder($order) { //On mets tous les champs relatifs au remboursement à NULL $order->setBaseDiscountRefunded(NULL); $order->setBaseShippingTaxRefunded(NULL); $order->setBaseSubtotalRefunded(NULL); $order->setBaseTaxRefunded(NULL); $order->setBaseTotalOfflineRefunded(NULL); $order->setBaseTotalOnlineRefunded(NULL); $order->setBaseTotalRefunded(NULL); $order->setBaseHiddenTaxRefunded(NULL); $order->setDiscountRefunded(NULL); $order->setShippingTaxRefunded(NULL); $order->setSubtotalRefunded(NULL); $order->setTaxRefunded(NULL); $order->setTotalOfflineRefunded(NULL); $order->setTotalOnlineRefunded(NULL); $order->setTotalRefunded(NULL); $order->setBaseHiddenTaxRefunded(NULL); $order->save(); }
/** * Update user records * @param type $model */ protected function update($model) { $model_class_name = $model->getClassName(); if (isset($_POST[$model_class_name])) { $model->attributes = $_POST[$model_class_name]; if ($model->save()) { Yii::app()->user->setFlash('success', Lang::t('SUCCESS_MESSAGE')); $this->refresh(); } } }
/** * * @param type $prorrogacaoRow * @param type $observacao * @param type $atendimento * @param type $logon * @param type $dataInicial * @param type $dataFinal */ public function atualizaAnaliseProrrogacao($prorrogacaoRow, $observacao, $atendimento, $logon, $dataInicial, $dataFinal) { $prorrogacaoRow->Observacao = $observacao; $prorrogacaoRow->Atendimento = $atendimento; $prorrogacaoRow->Logon = $logon; $prorrogacaoRow->DtInicio = Data::dataAmericana($dataInicial); $prorrogacaoRow->DtFinal = Data::dataAmericana($dataFinal); $prorrogacaoRow->save(); }
/** * Return activity content by given user. * * This output is generated by current mode. * * @param type $user * @return string */ private function getActivityContent($user) { $receive_email_activities = $user->getSetting("receive_email_activities", 'core', HSetting::Get('receive_email_activities', 'mailing')); // User never wants activity content if ($receive_email_activities == User::RECEIVE_EMAIL_NEVER) { return ""; } // We are in hourly mode and user wants receive a daily summary if ($this->mode == 'hourly' && $receive_email_activities == User::RECEIVE_EMAIL_DAILY_SUMMARY) { return ""; } // We are in daily mode and user wants receive not daily if ($this->mode == 'daily' && $receive_email_activities != User::RECEIVE_EMAIL_DAILY_SUMMARY) { return ""; } // User is online and want only receive when offline if ($this->mode == 'hourly') { $isOnline = count($user->httpSessions) > 0; if ($receive_email_activities == User::RECEIVE_EMAIL_WHEN_OFFLINE && $isOnline) { return ""; } } $lastMailDate = $user->last_activity_email; if ($lastMailDate == "" || $lastMailDate == "0000-00-00 00:00:00") { $lastMailDate = new CDbExpression('NOW() - INTERVAL 24 HOUR'); } // Get Stream contents $action = new StreamAction(null, 'console'); $action->mode = StreamAction::MODE_ACTIVITY; $action->type = Wall::TYPE_DASHBOARD; $action->userId = $user->id; $action->userWallId = $user->wall_id; $action->wallEntryLimit = 50; $action->wallEntryDateTo = $lastMailDate; $activities = $action->runConsole(); # Save last run $user->last_activity_email = new CDbExpression('NOW()'); $user->save(); // Nothin new if ($activities['counter'] == 0) { return ""; } // Return Output return $activities['output']; }
/** * @desc order comments or history * @param type $order * @param Varien_Object $response */ protected function _addStatusHistoryComment($order, Varien_Object $response, $status = false) { Mage::log("_addStatusHistoryComment", Zend_Log::DEBUG, "adyen_notification.log", true); //notification $pspReference = $response->getData('pspReference'); $success = trim($response->getData('success')); $success_result = strcmp($success, 'false') == 0 || !$success ? 'false' : 'true'; $eventCode = $response->getData('eventCode'); $reason = $response->getData('reason'); $success = !empty($reason) ? "{$success_result} <br />reason:{$reason}" : $success_result; $klarnaReservationNumber = $response->getData('additionalData_additionalData_acquirerReference'); $boletoPaidAmount = $response->getData('additionalData_boletobancario_paidAmount'); //post $authResult = $response->getData('authResult'); $pspReference = $response->getData('pspReference'); //payment method $paymentMethod = $response->getData('paymentMethod'); //data type $type = !empty($authResult) ? 'Adyen Result URL Notification(s):' : 'Adyen HTTP Notification(s):'; switch ($type) { case 'Adyen Result URL Notification(s):': /*PCD*/ // choose not to update the adyen_event_code in the order when the order is already on notification:Authorisation status and authresult = resultURL:Authorised if (!(substr($order->getAdyenEventCode(), 0, 13) == Adyen_Payment_Model_Event::ADYEN_EVENT_AUTHORISATION && $authResult == Adyen_Payment_Model_Event::ADYEN_EVENT_AUTHORISED)) { Mage::log("Adyen Result URL order authResult:" . $authResult, Zend_Log::DEBUG, "adyen_notification.log", true); $order->setAdyenEventCode($authResult); } $comment = Mage::helper('adyen')->__('%s <br /> authResult: %s <br /> pspReference: %s <br /> paymentMethod: %s', $type, $authResult, $pspReference, $paymentMethod); break; default: Mage::log("default order authResult:" . $eventCode . " : " . strtoupper($success_result), Zend_Log::DEBUG, "adyen_notification.log", true); if ($eventCode == Adyen_Payment_Model_Event::ADYEN_EVENT_REFUND) { $currency = $order->getOrderCurrencyCode(); // check if it is a full or partial refund $amount = Mage::helper('adyen')->formatAmount($response->getValue() / 100, $currency); $orderAmount = Mage::helper('adyen')->formatAmount($order->getGrandTotal(), $currency); if ($amount == $orderAmount) { $order->setAdyenEventCode($eventCode . " : " . strtoupper($success_result)); } else { $order->setAdyenEventCode("(PARTIAL) " . $eventCode . " : " . strtoupper($success_result)); } } else { $order->setAdyenEventCode($eventCode . " : " . strtoupper($success_result)); } // if payment method is klarna or openinvoice/afterpay show the reservartion number if (($paymentMethod == "klarna" || $paymentMethod == "afterpay_default" || $paymentMethod == "openinvoice") && ($klarnaReservationNumber != null && $klarnaReservationNumber != "")) { $klarnaReservationNumberText = "<br /> reservationNumber: " . $klarnaReservationNumber; } else { $klarnaReservationNumberText = ""; } if ($boletoPaidAmount != null && $boletoPaidAmount != "") { $boletoPaidAmountText = "<br /> Paid amount: " . $boletoPaidAmount; } else { $boletoPaidAmountText = ""; } $comment = Mage::helper('adyen')->__('%s <br /> eventCode: %s <br /> pspReference: %s <br /> paymentMethod: %s <br /> success: %s %s %s', $type, $eventCode, $pspReference, $paymentMethod, $success, $klarnaReservationNumberText, $boletoPaidAmountText); break; } $order->addStatusHistoryComment($comment, $status); $order->save(); }
/** * Add billing * @param type $org_model * @param type $sms_model * @param type $recipients_count * @return boolean */ public static function addBilling($org_model, $sms_model, $recipients_count) { if (!ModulesEnabled::model()->isModuleEnabled(ModulesEnabled::MOD_BILLING)) { return FALSE; } $message_length = strlen($sms_model->message); $no_of_sms = ceil($message_length / self::MAX_SMS_LENGTH); $price_per_sms = !empty($org_model->price_per_sms) ? $org_model->price_per_sms : OrgSmsBilling::getDefaultPricePerSms(); $total_cost = $price_per_sms * $no_of_sms * $recipients_count; $model = new OrgSmsBilling(); $model->org_id = $sms_model->org_id; $model->msg_batch_id = $sms_model->batch_id; $model->no_of_recipients = $recipients_count; $model->no_of_sms = $no_of_sms; $model->message_length = $message_length; $model->total_amount = $total_cost; $model->paid_amount = $org_model->acc_balance >= $total_cost ? $total_cost : $org_model->acc_balance; if ($model->paid_amount < 0) { $model->paid_amount = 0; } else { $model->payment_date = new CDbExpression('NOW()'); } $model->payment_status = $model->paid_amount < $model->total_amount ? OrgSmsBilling::PAYMENT_STATUS_PENDING : OrgSmsBilling::PAYMENT_STATUS_PAID; $model->pending_amount = $model->total_amount - $model->paid_amount; $model->save(); $org_model->acc_balance -= $total_cost; $org_model->save(FALSE); }
/** * * @param Entradas $entradas * @return type */ public function save(Entradas $entradas) { $result = $this->entradasDAO->save($entradas); return $result; }
/** * Return activity content by given user. * * This output is generated by current mode. * * @param type $user * @return string */ private function getActivityContent($user) { $receive_email_activities = $user->getSetting("receive_email_activities", 'core', HSetting::Get('receive_email_activities', 'mailing')); // User never wants activity content if ($receive_email_activities == User::RECEIVE_EMAIL_NEVER) { return ""; } // We are in hourly mode and user wants receive a daily summary if ($this->mode == 'hourly' && $receive_email_activities == User::RECEIVE_EMAIL_DAILY_SUMMARY) { return ""; } // We are in daily mode and user wants receive not daily if ($this->mode == 'daily' && $receive_email_activities != User::RECEIVE_EMAIL_DAILY_SUMMARY) { return ""; } // User is online and want only receive when offline if ($this->mode == 'hourly') { $isOnline = count($user->httpSessions) > 0; if ($receive_email_activities == User::RECEIVE_EMAIL_WHEN_OFFLINE && $isOnline) { return ""; } } $lastMailDate = $user->last_activity_email; if ($lastMailDate == "" || $lastMailDate == "0000-00-00 00:00:00") { $lastMailDate = new CDbExpression('NOW() - INTERVAL 24 HOUR'); } $action = new DashboardStreamAction(null, 'console'); $action->limit = 50; $action->mode = BaseStreamAction::MODE_ACTIVITY; $action->user = $user; $action->init(); //$action->criteria->condition .= " AND 1=2"; // Limit results to last activity mail $action->criteria->condition .= " AND wall_entry.created_at > :maxDate"; $action->criteria->params[':maxDate'] = $lastMailDate; $output = ""; foreach ($action->getWallEntries() as $wallEntry) { $output .= $wallEntry->content->getUnderlyingObject()->getMailOut(); } # Save last run $user->last_activity_email = new CDbExpression('NOW()'); $user->save(); // Return Output return $output; }
/** * Unified save child function. * * @param type $child_id * @param type $parent_id */ function save_child($parent_id, $child_id, $save_fields = array()) { global $wpdb; $parent = get_post(intval($parent_id)); $child = get_post(intval($child_id)); $post_data = array(); if (empty($parent) || empty($child)) { return new WP_Error('wpcf-relationship-save-child', 'no parent/child post'); } // Save relationship update_post_meta($child->ID, '_wpcf_belongs_' . $parent->post_type . '_id', $parent->ID); // Check if added via AJAX $check = get_post_meta($child->ID, '_wpcf_relationship_new', true); $new = !empty($check); delete_post_meta($child->ID, '_wpcf_relationship_new'); if ($new) { } // Set post data $post_data['ID'] = $child->ID; // Title needs to be checked if submitted at all if (!isset($save_fields['_wp_title'])) { // If not submitted that means it is not offered to be edited if (!empty($child->post_title)) { $post_title = $child->post_title; } else { // DO NOT LET IT BE EMPTY $post_title = $child->post_type . ' ' . $child->ID; } } else { $post_title = $save_fields['_wp_title']; } $post_data['post_title'] = $post_title; $post_data['post_content'] = !empty($save_fields['_wp_body']) ? $save_fields['_wp_body'] : ''; $post_data['post_type'] = $child->post_type; // TODO This should be revised $post_data['post_status'] = 'publish'; /* * * * * * * * UPDATE POST */ $updated_id = wp_update_post($post_data); if (empty($updated_id)) { return new WP_Error('relationship-update-post-failed', 'Updating post failed'); } // Save parents if (!empty($save_fields['parents'])) { foreach ($save_fields['parents'] as $parent_post_type => $parent_post_id) { update_post_meta($child->ID, '_wpcf_belongs_' . $parent_post_type . '_id', $parent_post_id); } } // Unset non-types unset($save_fields['_wp_title'], $save_fields['_wp_body'], $save_fields['parents']); /* * * * * * * * UPDATE Loop over fields */ foreach ($save_fields as $slug => $value) { $this->cf->set($child, $slug); $this->cf->context = 'post_relationship'; $this->cf->save($value); } // Set the language // TODO WPML // TODO Move this and use hook global $sitepress; if (isset($sitepress)) { $lang_details = $sitepress->get_element_language_details($parent->ID, 'post_' . $parent->post_type); if ($lang_details) { $sitepress->set_element_language_details($child->ID, 'post_' . $child->post_type, null, $lang_details->language_code); } } do_action('wpcf_relationship_save_child', $child, $parent); clean_post_cache($parent->ID); clean_post_cache($child->ID); return true; }
/** * * @param User $entity * @return type */ public function save(User $entity) { $result = $this->cbo->save($entity); return $result; }
/** * * @param Documentos $documentos * @return type */ public function save(Documentos $documentos) { $result = $this->documentosDAO->save($documentos); return $result; }
/** * Genera el asiento contable para una factura de venta. * Devuelve TRUE si el asiento se ha generado correctamente, False en caso contrario. * Si genera el asiento, este es accesible desde $this->asiento. * @param type $factura */ public function generar_asiento_venta(&$factura) { $ok = FALSE; $this->asiento = FALSE; $cliente0 = new cliente(); $subcuenta_cli = FALSE; /// obtenemos las tasas de conversión, para las ocasiones en que la factura está en otra divisa $tasaconv = 1; $tasaconv2 = $factura->tasaconv; if ($factura->coddivisa != $this->empresa->coddivisa) { $div0 = new divisa(); $divisa = $div0->get($this->empresa->coddivisa); if ($divisa) { $tasaconv = $divisa->tasaconv / $factura->tasaconv; $tasaconv2 = $divisa->tasaconv_compra; } } /// obtenemos el clientes y su subcuenta $cliente = $cliente0->get($factura->codcliente); if ($cliente) { $subcuenta_cli = $cliente->get_subcuenta($factura->codejercicio); } if (!$subcuenta_cli) { $eje0 = $this->ejercicio->get($factura->codejercicio); $this->new_message("No se ha podido generar una subcuenta para el cliente\n <a href='" . $eje0->url() . "'>¿Has importado los datos del ejercicio?</a>"); if (!$this->soloasiento) { $this->new_message("Aun así la <a href='" . $factura->url() . "'>factura</a> se ha generado correctamente,\n pero sin asiento contable."); } } else { $asiento = new asiento(); $asiento->codejercicio = $factura->codejercicio; if ($factura->idfacturarect) { $asiento->concepto = ucfirst(FS_FACTURA_RECTIFICATIVA) . " de " . $factura->codigo . " (ventas) - " . $factura->nombrecliente; } else { $asiento->concepto = "Factura de venta " . $factura->codigo . " - " . $factura->nombrecliente; } $asiento->documento = $factura->codigo; $asiento->editable = FALSE; $asiento->fecha = $factura->fecha; $asiento->importe = abs($factura->total * $tasaconv); $asiento->tipodocumento = 'Factura de cliente'; if ($asiento->save()) { $asiento_correcto = TRUE; $subcuenta = new subcuenta(); $partida0 = new partida(); $partida0->idasiento = $asiento->idasiento; $partida0->concepto = $asiento->concepto; $partida0->idsubcuenta = $subcuenta_cli->idsubcuenta; $partida0->codsubcuenta = $subcuenta_cli->codsubcuenta; $partida0->debe = $factura->total * $tasaconv; $partida0->coddivisa = $this->empresa->coddivisa; $partida0->tasaconv = $tasaconv2; $partida0->codserie = $factura->codserie; if (!$partida0->save()) { $asiento_correcto = FALSE; $this->new_error_msg("¡Imposible generar la partida para la subcuenta " . $partida0->codsubcuenta . "!"); } /// generamos una partida por cada impuesto foreach ($factura->get_lineas_iva() as $li) { $subcuenta_iva = FALSE; /// ¿El impuesto tiene una subcuenta específica? if (isset($this->impuestos[$li->codimpuesto])) { if ($this->impuestos[$li->codimpuesto]->codsubcuentarep) { $subcuenta_iva = $subcuenta->get_by_codigo($this->impuestos[$li->codimpuesto]->codsubcuentarep, $asiento->codejercicio); } } if (!$subcuenta_iva) { $subcuenta_iva = $subcuenta->get_cuentaesp('IVAREP', $asiento->codejercicio); } if ($subcuenta_iva and $asiento_correcto) { $partida1 = new partida(); $partida1->idasiento = $asiento->idasiento; $partida1->concepto = $asiento->concepto; $partida1->idsubcuenta = $subcuenta_iva->idsubcuenta; $partida1->codsubcuenta = $subcuenta_iva->codsubcuenta; $partida1->haber = $li->totaliva * $tasaconv; $partida1->idcontrapartida = $subcuenta_cli->idsubcuenta; $partida1->codcontrapartida = $subcuenta_cli->codsubcuenta; $partida1->cifnif = $cliente->cifnif; $partida1->documento = $asiento->documento; $partida1->tipodocumento = $asiento->tipodocumento; $partida1->codserie = $factura->codserie; $partida1->factura = $factura->numero; $partida1->baseimponible = $li->neto * $tasaconv; $partida1->iva = $li->iva; $partida1->coddivisa = $this->empresa->coddivisa; $partida1->tasaconv = $tasaconv2; if (!$partida1->save()) { $asiento_correcto = FALSE; $this->new_error_msg("¡Imposible generar la partida para la subcuenta " . $partida1->codsubcuenta . "!"); } if ($li->recargo != 0) { $partida11 = new partida(); $partida11->idasiento = $asiento->idasiento; $partida11->concepto = $asiento->concepto; $partida11->idsubcuenta = $subcuenta_iva->idsubcuenta; $partida11->codsubcuenta = $subcuenta_iva->codsubcuenta; $partida11->haber = $li->totalrecargo * $tasaconv; $partida11->idcontrapartida = $subcuenta_cli->idsubcuenta; $partida11->codcontrapartida = $subcuenta_cli->codsubcuenta; $partida11->cifnif = $cliente->cifnif; $partida11->documento = $asiento->documento; $partida11->tipodocumento = $asiento->tipodocumento; $partida11->codserie = $factura->codserie; $partida11->factura = $factura->numero; $partida11->baseimponible = $li->neto * $tasaconv; $partida11->recargo = $li->recargo; $partida11->coddivisa = $this->empresa->coddivisa; $partida11->tasaconv = $tasaconv2; if (!$partida11->save()) { $asiento_correcto = FALSE; $this->new_error_msg("¡Imposible generar la partida para la subcuenta " . $partida11->codsubcuenta . "!"); } } } else { if (!$subcuenta_iva) { $asiento_correcto = FALSE; $this->new_error_msg('No se encuentra la subcuenta de ' . FS_IVA); } } } $subcuenta_ventas = $subcuenta->get_cuentaesp('VENTAS', $asiento->codejercicio); if ($subcuenta_ventas and $asiento_correcto) { $partida2 = new partida(); $partida2->idasiento = $asiento->idasiento; $partida2->concepto = $asiento->concepto; $partida2->idsubcuenta = $subcuenta_ventas->idsubcuenta; $partida2->codsubcuenta = $subcuenta_ventas->codsubcuenta; $partida2->haber = $factura->neto * $tasaconv; $partida2->coddivisa = $this->empresa->coddivisa; $partida2->tasaconv = $tasaconv2; $partida2->codserie = $factura->codserie; if (!$partida2->save()) { $asiento_correcto = FALSE; $this->new_error_msg("¡Imposible generar la partida para la subcuenta " . $partida2->codsubcuenta . "!"); } } else { if (!$subcuenta_ventas) { $asiento_correcto = FALSE; $this->new_error_msg('No se encuentra la subcuenta de ventas'); } } /// ¿IRPF? if ($factura->totalirpf != 0 and $asiento_correcto) { $subcuenta_irpf = $subcuenta->get_cuentaesp('IRPF', $asiento->codejercicio); if (!$subcuenta_irpf) { $subcuenta_irpf = $subcuenta->get_by_codigo('4730000000', $asiento->codejercicio); } if ($subcuenta_irpf) { $partida3 = new partida(); $partida3->idasiento = $asiento->idasiento; $partida3->concepto = $asiento->concepto; $partida3->idsubcuenta = $subcuenta_irpf->idsubcuenta; $partida3->codsubcuenta = $subcuenta_irpf->codsubcuenta; $partida3->debe = $factura->totalirpf * $tasaconv; $partida3->coddivisa = $this->empresa->coddivisa; $partida3->tasaconv = $tasaconv2; $partida3->codserie = $factura->codserie; if (!$partida3->save()) { $asiento_correcto = FALSE; $this->new_error_msg("¡Imposible generar la partida para la subcuenta " . $partida3->codsubcuenta . "!"); } } else { if (!$subcuenta_irpf) { $asiento_correcto = FALSE; $this->new_error_msg('No se encuentra la subcuenta de ' . FS_IRPF); } } } /// comprobamos si algún artículo tiene una subcuenta asociada if ($asiento_correcto) { $partidaA = new partida(); $partidaA->idasiento = $asiento->idasiento; $partidaA->concepto = $asiento->concepto; $partidaA->coddivisa = $this->empresa->coddivisa; $partidaA->tasaconv = $tasaconv2; /// importe a restar a la partida2 $restar = 0; /** * Para cada artículo de la factura, buscamos su subcuenta de compra o compra con irpf */ $ap = new articulo_propiedad(); foreach ($factura->get_lineas() as $lin) { $subcart = FALSE; $aprops = $ap->array_get($lin->referencia); if (isset($aprops['codsubcuentaventa'])) { $subcart = $subcuenta->get_by_codigo($aprops['codsubcuentaventa'], $factura->codejercicio); } if (!$subcart) { /// no hay / no se encuentra ninguna subcuenta asignada al artículo } else { if ($subcart->idsubcuenta != $subcuenta_ventas->idsubcuenta) { if (is_null($partidaA->idsubcuenta)) { $partidaA->idsubcuenta = $subcart->idsubcuenta; $partidaA->codsubcuenta = $subcart->codsubcuenta; $partidaA->haber = $lin->pvptotal * $tasaconv; } else { if ($partidaA->idsubcuenta == $subcart->idsubcuenta) { $partidaA->haber += $lin->pvptotal * $tasaconv; } else { $partidaA->haber = round($partidaA->haber, FS_NF0); $restar += $partidaA->haber; if (!$partidaA->save()) { $asiento_correcto = FALSE; $this->new_error_msg("¡Imposible generar la partida para la subcuenta del artículo " . $lin->referencia . "!"); } $partidaA = new partida(); $partidaA->idasiento = $asiento->idasiento; $partidaA->concepto = $asiento->concepto; $partidaA->idsubcuenta = $subcart->idsubcuenta; $partidaA->codsubcuenta = $subcart->codsubcuenta; $partidaA->haber = $lin->pvptotal * $tasaconv; $partidaA->coddivisa = $this->empresa->coddivisa; $partidaA->tasaconv = $tasaconv2; } } } } } if ($partidaA->idsubcuenta and $partidaA->codsubcuenta) { $partidaA->haber = round($partidaA->haber, FS_NF0); $restar += $partidaA->haber; if ($partidaA->save()) { $partida2->haber -= $restar; $partida2->save(); } else { $asiento_correcto = FALSE; $this->new_error_msg("¡Imposible generar la partida para la subcuenta del artículo " . $lin->referencia . "!"); } } } if ($asiento_correcto) { /// si es una factura rectificativa, invertimos los importes if ($factura->idfacturarect) { $this->invertir_asiento($asiento); } $factura->idasiento = $asiento->idasiento; if ($factura->save()) { $ok = $this->check_asiento($asiento); if (!$ok) { $this->new_error_msg('El asiento está descuadrado.'); } $this->asiento = $asiento; } else { $this->new_error_msg("¡Imposible añadir el asiento a la factura!"); } } else { if ($asiento->delete()) { $this->new_message("El asiento se ha borrado."); } else { $this->new_error_msg("¡Imposible borrar el asiento!"); } } } else { $this->new_error_msg("¡Imposible guardar el asiento!"); } } return $ok; }
/** * * @param Subsecretaria $subsecretaria * @return type */ public function save(Subsecretaria $subsecretaria) { $result = $this->subsecretariaDAO->save($subsecretaria); return $result; }
/** * Return a message on successful model save or otherwise * * @param type $model * @param type $authority * @return boolean */ public function setFlash($model, $authority) { if ($model->save()) { if ($authority != 'chairman') { if ($authority == 'secretary' && $model->forwarded_by_secretary == 'Yes' || $authority == 'treasurer' && $model->forwarded_by_treasurer == 'Yes') { Yii::app()->user->setFlash('saved', 'The withdrawal has been forwarded'); } else { if ($authority == 'secretary' && $model->forwarded_by_secretary == 'No' || $authority == 'treasurer' && $model->forwarded_by_treasurer == 'No') { Yii::app()->user->setFlash('saved', 'The withdrawal has been declined'); } else { Yii::app()->user->setFlash('saved', 'The withdrawal has been withdrawn'); } } } else { if ($model->approved_by_chairman == 'Yes') { Yii::app()->user->setFlash('saved', 'The withdrawal has been approved'); } else { if ($model->approved_by_chairman == 'No') { Yii::app()->user->setFlash('saved', 'The withdrawal has been declined'); } else { Yii::app()->user->setFlash('saved', 'The withdrawal has been withdrawn'); } } } $this->userStatus($model); return true; } else { Yii::app()->user->setFlash('saved', 'The alteration has not been captured'); } return false; }
/** * change User Discount Status - call when making of order is over * @param type $discount * @param type $status * @todo unused $status variable * @todo expiration for user discounts is not correctly checked (anywhere) */ public function changeUserDiscountStatus($discount, $status = null) { $discount->expiration_times = $discount->expiration_times - 1; if ($discount->expiration_times <= 0) { $discount->expiration_times = -1; } if ($discount->expires == true && $discount->expiration_times <= 0) { $discount->status = 'expired'; } if ($discount->expires == true && \Carbon\Carbon::parse($discount->expiration_day)->timestamp > 0 && \Carbon\Carbon::parse($discount->expiration_day)->timestamp < time()) { $discount->status = 'expired'; } $discount->save(); $this->flushRememberedDiscounts(); }
/** * @desc order comments or history * @param type $order */ protected function _addStatusHistoryComment($order) { $success_result = strcmp($this->_success, 'true') == 0 || strcmp($this->_success, '1') == 0 ? 'true' : 'false'; $success = !empty($this->_reason) ? "{$success_result} <br />reason:{$this->_reason}" : $success_result; if ($this->_eventCode == Adyen_Payment_Model_Event::ADYEN_EVENT_REFUND || $this->_eventCode == Adyen_Payment_Model_Event::ADYEN_EVENT_CAPTURE) { $currency = $order->getOrderCurrencyCode(); // check if it is a full or partial refund $amount = $this->_value; $orderAmount = (int) Mage::helper('adyen')->formatAmount($order->getGrandTotal(), $currency); $this->_debugData[$this->_count]['_addStatusHistoryComment amount'] = 'amount notification:' . $amount . ' amount order:' . $orderAmount; if ($amount == $orderAmount) { $order->setAdyenEventCode($this->_eventCode . " : " . strtoupper($success_result)); } else { $order->setAdyenEventCode("(PARTIAL) " . $this->_eventCode . " : " . strtoupper($success_result)); } } else { $order->setAdyenEventCode($this->_eventCode . " : " . strtoupper($success_result)); } // if payment method is klarna or openinvoice/afterpay show the reservartion number if (($this->_paymentMethod == "klarna" || $this->_paymentMethod == "afterpay_default" || $this->_paymentMethod == "openinvoice") && ($this->_klarnaReservationNumber != null && $this->_klarnaReservationNumber != "")) { $klarnaReservationNumberText = "<br /> reservationNumber: " . $this->_klarnaReservationNumber; } else { $klarnaReservationNumberText = ""; } if ($this->_boletoPaidAmount != null && $this->_boletoPaidAmount != "") { $boletoPaidAmountText = "<br /> Paid amount: " . $this->_boletoPaidAmount; } else { $boletoPaidAmountText = ""; } $type = 'Adyen HTTP Notification(s):'; $comment = Mage::helper('adyen')->__('%s <br /> eventCode: %s <br /> pspReference: %s <br /> paymentMethod: %s <br /> success: %s %s %s', $type, $this->_eventCode, $this->_pspReference, $this->_paymentMethod, $success, $klarnaReservationNumberText, $boletoPaidAmountText); // If notification is pending status and pending status is set add the status change to the comment history if ($this->_eventCode == Adyen_Payment_Model_Event::ADYEN_EVENT_PENDING) { if ($order->isCanceled() || $order->getState() === Mage_Sales_Model_Order::STATE_HOLDED) { $this->_debugData[$this->_count]['_addStatusHistoryComment'] = 'Did not change status because order is already canceled or on hold.'; } else { $pendingStatus = $this->_getConfigData('pending_status', 'adyen_abstract', $order->getStoreId()); if ($pendingStatus != "") { $order->addStatusHistoryComment($comment, $pendingStatus); /** * save order needed for old magento version so that status is not reverted to state NEW */ $order->save(); $this->_debugData[$this->_count]['_addStatusHistoryComment'] = 'Created comment history for this notification with status change to: ' . $pendingStatus; return; } } } // if manual review is accepted and a status is selected. Change the status through this comment history item if ($this->_eventCode == Adyen_Payment_Model_Event::ADYEN_EVENT_MANUAL_REVIEW_ACCEPT && $this->_getFraudManualReviewAcceptStatus($order) != "") { $manualReviewAcceptStatus = $this->_getFraudManualReviewAcceptStatus($order); $order->addStatusHistoryComment($comment, $manualReviewAcceptStatus); $order->setState(Mage_Sales_Model_Order::STATE_PROCESSING); /** * save order needed for old magento version so that status is not reverted to state NEW */ $order->save(); $this->_debugData[$this->_count]['_addStatusHistoryComment'] = 'Created comment history for this notification with status change to: ' . $manualReviewAcceptStatus; return; } $order->addStatusHistoryComment($comment); $this->_debugData[$this->_count]['_addStatusHistoryComment'] = 'Created comment history for this notification'; }
/** * Unified save child function. * * @param int $parent_id * @param int $child_id * @param array $save_fields * @return bool|WP_Error */ function save_child($parent_id, $child_id, $save_fields = array()) { $parent = get_post(intval($parent_id)); $child = get_post(intval($child_id)); $post_data = array(); if (empty($parent) || empty($child)) { return new WP_Error('wpcf-relationship-save-child', 'no parent/child post'); } // Save relationship update_post_meta($child->ID, '_wpcf_belongs_' . $parent->post_type . '_id', $parent->ID); // Check if added via AJAX $check = get_post_meta($child->ID, '_wpcf_relationship_new', true); $new = !empty($check); delete_post_meta($child->ID, '_wpcf_relationship_new'); // Set post data $post_data['ID'] = $child->ID; // Title needs to be checked if submitted at all if (!isset($save_fields['_wp_title'])) { // If not submitted that means it is not offered to be edited if (!empty($child->post_title)) { $post_title = $child->post_title; } else { // DO NOT LET IT BE EMPTY $post_title = $child->post_type . ' ' . $child->ID; } } else { $post_title = $save_fields['_wp_title']; } $post_data['post_title'] = $post_title; $post_data['post_content'] = isset($save_fields['_wp_body']) ? $save_fields['_wp_body'] : $child->post_content; $post_data['post_type'] = $child->post_type; // Check post status - if new, convert to 'publish' else keep remaining if ($new) { $post_data['post_status'] = 'publish'; } else { $post_data['post_status'] = get_post_status($child->ID); } /* * * * * * * * UPDATE POST */ $cf = new WPCF_Field(); if (isset($_POST['wpcf_post_relationship'][$parent_id]) && isset($_POST['wpcf_post_relationship'][$parent_id][$child_id])) { $_POST['wpcf'] = array(); foreach ($_POST['wpcf_post_relationship'][$parent_id][$child_id] as $slug => $value) { $_POST['wpcf'][$cf->__get_slug_no_prefix($slug)] = $value; $_POST['wpcf'][$slug] = $value; } } unset($cf); /** * avoid filters for children * / global $wp_filter; $save_post = $wp_filter['save_post']; $wp_filter['save_post'] = array(); */ $updated_id = wp_update_post($post_data); /* $wp_filter['save_post'] = $save_post; */ unset($save_post); if (empty($updated_id)) { return new WP_Error('relationship-update-post-failed', 'Updating post failed'); } // Save parents if (!empty($save_fields['parents'])) { foreach ($save_fields['parents'] as $parent_post_type => $parent_post_id) { update_post_meta($child->ID, '_wpcf_belongs_' . $parent_post_type . '_id', $parent_post_id); } } // Update taxonomies if (!empty($save_fields['taxonomies']) && is_array($save_fields['taxonomies'])) { $_save_data = array(); foreach ($save_fields['taxonomies'] as $taxonomy => $t) { if (!is_taxonomy_hierarchical($taxonomy)) { $_save_data[$taxonomy] = strval($t); continue; } foreach ($t as $term_id) { if ($term_id != '-1') { $term = get_term($term_id, $taxonomy); if (empty($term)) { continue; } $_save_data[$taxonomy][] = $term_id; } } } wp_delete_object_term_relationships($child->ID, array_keys($save_fields['taxonomies'])); foreach ($_save_data as $_taxonomy => $_terms) { wp_set_post_terms($child->ID, $_terms, $_taxonomy, $append = false); } } // Unset non-types unset($save_fields['_wp_title'], $save_fields['_wp_body'], $save_fields['parents'], $save_fields['taxonomies']); /* * * * * * * * UPDATE Loop over fields */ foreach ($save_fields as $slug => $value) { if (defined('WPTOOLSET_FORMS_VERSION')) { // Get field by slug $field = wpcf_fields_get_field_by_slug(str_replace(WPCF_META_PREFIX, '', $slug)); if (empty($field)) { continue; } // Set config $config = wptoolset_form_filter_types_field($field, $child->ID); // Check if valid $valid = wptoolset_form_validate_field('post', $config, $value); if (is_wp_error($valid)) { $errors = $valid->get_error_data(); $msg = sprintf(__('Child post "%s" field "%s" not updated:', 'wpcf'), $child->post_title, $field['name']); wpcf_admin_message_store($msg . ' ' . implode(', ', $errors), 'error'); continue; } } $this->cf->set($child, $field); $this->cf->context = 'post_relationship'; $this->cf->save($value); } do_action('wpcf_relationship_save_child', $child, $parent); clean_post_cache($parent->ID); clean_post_cache($child->ID); // Added because of caching meta 1.5.4 wp_cache_flush(); return true; }
/** * * @param Permissao $entity * @return type */ public function save(Permissao $entity) { $result = $this->cbo->save($entity); return $result; }
/** * This method prepares the response of the current element based on the * $bean object and the $flowData, an external action such as * ROUTE or ADHOC_REASSIGN could be also processed. * * This method probably should be override for each new element, but it's * not mandatory. However the response structure always must pass using * the 'prepareResponse' Method. * * As defined in the example: * * $response['route_action'] = 'ROUTE'; //The action that should process the Router * $response['flow_action'] = 'CREATE'; //The record action that should process the router * $response['flow_data'] = $flowData; //The current flowData * $response['flow_filters'] = array('first_id', 'second_id'); //This attribute is used to filter the execution of the following elements * $response['flow_id'] = $flowData['id']; // The flowData id if present * * * @param type $flowData * @param type $bean * @param type $externalAction * @return type */ public function run($flowData, $bean = null, $externalAction = '', $arguments = array()) { switch ($externalAction) { case 'RESUME_EXECUTION': $flowAction = 'UPDATE'; break; default: $flowAction = 'CREATE'; break; } $bpmnElement = $this->retrieveDefinitionData($flowData['bpmn_id']); $act_assign_team = $bpmnElement['act_assign_team']; //$objTeamBean = $this->beanFactory->getBean('Teams'); //$teamBean = $objTeamBean->getById($act_assign_team); $teamBean = $this->retrieveTeamData($act_assign_team); $act_assignment_method = $bpmnElement['act_assignment_method']; if (isset($bean->team_id) && isset($teamBean->id) && $teamBean->id == $act_assign_team) { //$this->bpmLog('DEBUG', "[{$flowData['cas_id']}][{$flowData['cas_index']}] assign team to $act_assign_team $act_assignment_method"); $bean->load_relationship('teams'); //$bean->teams->replace(array($act_assign_team)); $historyData = $this->retrieveHistoryData($flowData['cas_sugar_module']); $historyData->savePreData('team_id', $bean->team_id); //$bean->team_id = $act_assign_team; $historyData->savePostData('team_id', $act_assign_team); //check if the team_set exists for this team, if yes, we change the field team_set_id $queryTeam = "select count(*) as count from team_sets where id = '{$act_assign_team}' "; $resultTeam = $bean->db->Query($queryTeam); $rowTeam = $bean->db->fetchByAssoc($resultTeam); if ($rowTeam['count'] >= 1) { $historyData->savePreData('team_set_id', $bean->team_set_id); //$bean->team_set_id = $act_assign_team; if (isset($bpmnElement['act_update_record_owner']) && $bpmnElement['act_update_record_owner'] == 1) { $bean->team_set_id = $act_assign_team; $bean->save(); } $historyData->savePostData('team_set_id', $act_assign_team); } if (strtolower($act_assignment_method) == 'balanced') { $nextUser = $this->userAssignmentHandler->getNextUserUsingRoundRobin($bpmnElement['id']); $historyData->savePreData('assigned_user_id', $bean->assigned_user_id); //$bean->assigned_user_id = $nextUser; if (isset($bpmnElement['act_update_record_owner']) && $bpmnElement['act_update_record_owner'] == 1) { $bean->assigned_user_id = $nextUser; } $flowData['cas_user_id'] = $nextUser; //$query = "update pmse_bpm_flow set " . // " cas_user_id = '$nextUser' " . // " where cas_id = {$flowData['cas_id']} and cas_index = {{$flowData['cas_index']}} "; //$bean->db->query($query); $historyData->savePostData('assigned_user_id', $nextUser); //$this->bpmLog('INFO', "[{$flowData['cas_id']}][{$flowData['cas_index']}] assigned to user $nextUser"); } $bean->skipPartialUpdate = true; $bean->save(); $params = array(); $params['cas_id'] = $flowData['cas_id']; $params['cas_index'] = $flowData['cas_index']; $params['act_id'] = $bpmnElement['id']; $params['pro_id'] = $bpmnElement['pro_id']; $params['user_id'] = $this->getCurrentUser()->id; $params['frm_action'] = 'Event Team Assign'; $params['frm_comment'] = 'Team Assign Applied'; $params['log_data'] = $historyData->getLog(); $this->caseFlowHandler->saveFormAction($params); } return $this->prepareResponse($flowData, 'ROUTE', $flowAction); }
/** * Genera el asiento contable para una factura de venta. * Devuelve TRUE si el asiento se ha generado correctamente, False en caso contrario. * Si genera el asiento, este es accesible desde $this->asiento. * @param type $factura */ public function generar_asiento_venta(&$factura) { $ok = FALSE; $this->asiento = FALSE; $cliente0 = new cliente(); $subcuenta_cli = FALSE; $cliente = $cliente0->get($factura->codcliente); if ($cliente) { $subcuenta_cli = $cliente->get_subcuenta($factura->codejercicio); } if ($factura->totalirpf != 0 or $factura->totalrecargo != 0) { $this->new_error_msg('Todavía no se pueden generar asientos de facturas con IRPF o recargo.'); } else { if (!$subcuenta_cli) { $eje0 = $this->ejercicio->get($factura->codejercicio); $this->new_message("No se ha podido generar una subcuenta para el cliente\n <a href='" . $eje0->url() . "'>¿Has importado los datos del ejercicio?</a>\n Aun así la <a href='" . $factura->url() . "'>factura</a> se ha generado correctamente,\n pero sin asiento contable."); } else { $asiento = new asiento(); $asiento->codejercicio = $factura->codejercicio; $asiento->concepto = "Factura de venta " . $factura->codigo . " - " . $factura->nombrecliente; $asiento->documento = $factura->codigo; $asiento->editable = FALSE; $asiento->fecha = $factura->fecha; $asiento->importe = $factura->total; $asiento->tipodocumento = 'Factura de cliente'; if ($asiento->save()) { $asiento_correcto = TRUE; $subcuenta = new subcuenta(); $partida0 = new partida(); $partida0->idasiento = $asiento->idasiento; $partida0->concepto = $asiento->concepto; $partida0->idsubcuenta = $subcuenta_cli->idsubcuenta; $partida0->codsubcuenta = $subcuenta_cli->codsubcuenta; $partida0->debe = $factura->total; $partida0->coddivisa = $factura->coddivisa; $partida0->tasaconv = $factura->tasaconv; if (!$partida0->save()) { $asiento_correcto = FALSE; $this->new_error_msg("¡Imposible generar la partida para la subcuenta " . $partida0->codsubcuenta . "!"); } /// generamos una partida por cada impuesto $subcuenta_iva = $subcuenta->get_cuentaesp('IVAREP', $asiento->codejercicio); foreach ($factura->get_lineas_iva() as $li) { if ($subcuenta_iva and $asiento_correcto) { $partida1 = new partida(); $partida1->idasiento = $asiento->idasiento; $partida1->concepto = $asiento->concepto; $partida1->idsubcuenta = $subcuenta_iva->idsubcuenta; $partida1->codsubcuenta = $subcuenta_iva->codsubcuenta; $partida1->haber = $li->totaliva; $partida1->idcontrapartida = $subcuenta_cli->idsubcuenta; $partida1->codcontrapartida = $subcuenta_cli->codsubcuenta; $partida1->cifnif = $cliente->cifnif; $partida1->documento = $asiento->documento; $partida1->tipodocumento = $asiento->tipodocumento; $partida1->codserie = $factura->codserie; $partida1->factura = $factura->numero; $partida1->baseimponible = $li->neto; $partida1->iva = $li->iva; $partida1->coddivisa = $factura->coddivisa; $partida1->tasaconv = $factura->tasaconv; if (!$partida1->save()) { $asiento_correcto = FALSE; $this->new_error_msg("¡Imposible generar la partida para la subcuenta " . $partida1->codsubcuenta . "!"); } } } $subcuenta_ventas = $subcuenta->get_cuentaesp('VENTAS', $asiento->codejercicio); if ($subcuenta_ventas and $asiento_correcto) { $partida2 = new partida(); $partida2->idasiento = $asiento->idasiento; $partida2->concepto = $asiento->concepto; $partida2->idsubcuenta = $subcuenta_ventas->idsubcuenta; $partida2->codsubcuenta = $subcuenta_ventas->codsubcuenta; $partida2->haber = $factura->neto; $partida2->coddivisa = $factura->coddivisa; $partida2->tasaconv = $factura->tasaconv; if (!$partida2->save()) { $asiento_correcto = FALSE; $this->new_error_msg("¡Imposible generar la partida para la subcuenta " . $partida2->codsubcuenta . "!"); } } if ($asiento_correcto) { $factura->idasiento = $asiento->idasiento; if ($factura->save()) { $ok = TRUE; $this->asiento = $asiento; } else { $this->new_error_msg("¡Imposible añadir el asiento a la factura!"); } } else { if ($asiento->delete()) { $this->new_message("El asiento se ha borrado."); } else { $this->new_error_msg("¡Imposible borrar el asiento!"); } } } else { $this->new_error_msg("¡Imposible guardar el asiento!"); } } } return $ok; }