Action used to add a discount to the users session via a URL.
This is preferable to using the dicount form as disount code
forms seem to provide a less than perfect user experience
351658
public function usediscount()
    {   
        $code_to_search = $this->request->param("ID");
        $code = false;
        $curr = $this->getDiscount();
        
        if (!$code_to_search) {
            return $this->httpError(404, "Page not found");
        }
        
        // First check if the discount is already added (so we don't
        // query the DB if we don't have to).
        if (!$curr || ($curr && $curr->Code != $code_to_search)) {
            $this->setDiscount($code_to_search);
            ShoppingCartFactory::create()->save();
        } elseif ($curr && $code->Code == $code_to_search) {
            $code = $this->getDiscount();
        }

        $this->extend("onBeforeUseDiscount");

        return $this
            ->customise([
                "Discount" => $code
            ])->render();
    }
1163423
public static MozuUrl unAssignDiscountUrl(String couponSetCode, Integer discountId)
	{
		UrlFormatter formatter = new UrlFormatter("/api/commerce/catalog/admin/couponsets/{couponSetCode}/assigneddiscounts/{discountId}");
		formatter.formatUrl("couponSetCode", couponSetCode);
		formatter.formatUrl("discountId", discountId);
		return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
	}
81151
function addUser(user) {
	var slElement = $(document.createElement("option"));
	slElement.attr("value", user);
	slElement.text(user);
	$("#usersList").append(slElement);
}
500754
public function DiscountForm()
    {
        $form = DiscountCodeForm::create(
            $this,
            "DiscountForm",
            ShoppingCartFactory::create()->getCurrent()
        );
        
        $this->extend("updateDiscountForm", $form);
        
        return $form;
    }
1099310
function createAction() {
    if( !isset( $this->action['value'] ))
      return;
    $attributes = $this->_createParams( $this->action['params'] );
    return $this->_createElement( 'ACTION', $attributes, $this->action['value'] );
  }
1312156
public function addUsageAction(string $usage_code, array $options = []) {
		$codes = \Object\Controller\Model\UsageCodes::getStatic();
		if (empty($codes[$usage_code])) {
			Throw new \Exception('You must register usage code in overrides: ' . $usage_code);
		}
		// generate url
		if (empty($options['url'])) {
			if (in_array('*', $codes[$usage_code]['methods']) || in_array(\Request::method(), $codes[$usage_code]['methods'])) {
				$options['url'] = \Application::get('mvc.full') . '?' . http_build_query2(\Request::input());
			}
		}
		self::$usage_actions[] = [
			'usage_code' => $usage_code,
			'message' => $options['message'] ?? $codes[$usage_code]['message'],
			'replace' => $options['replace'] ?? [],
			'affected_rows' => $options['affected_rows'] ?? 0,
			'error_rows' => $options['error_rows'] ?? 0,
			'url' => $options['url'] ?? null,
			'history' => ($options['history'] ?? $codes[$usage_code]['history']) ? 1 : 0
		];
	}
470152
def add_session(session=None):
    
    """
    user_id, sid_s = session['user_id'], session.sid_s
    with db.session.begin_nested():
        session_activity = SessionActivity(
            user_id=user_id,
            sid_s=sid_s,
            ip=request.remote_addr,
            country=_ip2country(request.remote_addr),
            **_extract_info_from_useragent(
                request.headers.get('User-Agent', '')
            )
        )
        db.session.merge(session_activity)
575159
private void createAccount() {
        // TODO Validate form data and send off request

        String name = nameView.getText().toString();
        ((MainActivity) getActivity()).setComplete(name);
    }
651137
def authorize_demo
      if !request.xhr? && !request.get? && ( !current_user.blank? && current_user.username.downcase == 'demo' && Setting.get('demonstration_mode') == 'Y' )
        redirect_to :back, flash: { error: I18n.t('generic.demo_notification') } and return 
      end

      render :inline => 'demo' and return if params[:action] == 'save_menu' && !current_user.blank? && current_user.username.downcase == 'demo' && Setting.get('demonstration_mode') == 'Y'

    end
1013693
protected function _fillOutDiscount(IDiscount $discountPayload, array $discountData)
    {
        return $discountPayload
            ->setAmount($this->_nullCoalesce($discountData, 'amount', 0.00))
            ->setAppliedCount($this->_nullCoalesce($discountData, 'applied_count', null))
            ->setCode($this->_nullCoalesce($discountData, 'code', null))
            ->setDescription($this->_nullCoalesce($discountData, 'description', null))
            ->setEffectType($this->_nullCoalesce($discountData, 'effect_type', null))
            ->setId($this->_nullCoalesce($discountData, 'id', null));
    }
1192495
public int doEndTag()
            throws JspException
    {
        String idScript = null;

        HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
        HttpServletResponse response = (HttpServletResponse) pageContext.getResponse();

        // Acquire the label value we will be generating
        if (_value == null)
            _value = Bundle.getString("Tags_ButtonText", null);
        _state.value = _value;

        // Generate an HTML element
        _state.disabled = isDisabled();

        // Add parameters for popup window support.
        if (_popupSupport != null) {
            _popupSupport.addParams(this, request);
        }

        // targetScope implies an extra parameter.  If there's no action on this button, get the action from the
        // nearest form, so we can construct an action url with our extra parameter.
        if (_targetScope != null && _action == null) {
            Form parentForm = getNearestForm();
            if (parentForm != null) {
                _action = parentForm.getAction();
            }
        }

        if (_action == null && _params != null && _popupSupport == null) {
            Form parentForm = getNearestForm();
            if (parentForm != null) {
                _action = parentForm.getAction();
            }
        }

        if (_action != null) {
            boolean isAction = PageFlowTagUtils.isAction(request, _action);
            if (isAction) {

                // If the action we're submitting to is checking for double-submits, save a token in the session.
                // This will be written out as a param (below), and will be checked in PageFlowRequestProcessor.
                String token = PageFlowTagUtils.getToken(request, _action);
                if (token != null) {
                    if (_params == null) {
                        _params = new HashMap();
                    }
                    _params.put(Constants.TOKEN_KEY, token);
                }

                // Add the scope ID parameter if there's one on the tag, or if there's one in the request.
                if (_targetScope != null) {
                    if (_params == null) {
                        _params = new HashMap();
                    }
                    _params.put(ScopedServletUtils.SCOPE_ID_PARAM, _targetScope);
                }

                String overrideAction = ACTION_OVERRIDE + _action;
                overrideAction = HtmlUtils.addParams(overrideAction, _params, response.getCharacterEncoding());
                String buttonOutput = URLRewriterService.getNamePrefix(pageContext.getServletContext(),
                        pageContext.getRequest(), overrideAction) + overrideAction;
                if (buttonOutput.indexOf(";") > -1) {
                    buttonOutput = buttonOutput.substring(0, buttonOutput.indexOf(";"));
                }
                _state.name = buttonOutput;

                // don't write the id attribute
                Form parentForm = getNearestForm();
                idScript = renderNameAndId(request, _state, parentForm);
            }
            else {
                // set the error because the action is invalid
                registerTagError(Bundle.getString("Tags_BadAction", _action), null);
            }
        }
        else {
            Form parentForm = getNearestForm();
            idScript = renderNameAndId(request, _state, parentForm);
        }

        boolean buttonDisableAndSubmit = false;
        boolean buttonDisable = false;
        
        // if the user overrides the onclick we will ignore this
        if (getOnClick() == null) {
            if (_disableSecondClick) {
                Form parentForm = getNearestForm();
                String href = getActionUrl(request, response);
                String entry;
                if (parentForm != null && href != null && (_state.type == null || _state.type == INPUT_SUBMIT)) {
                    entry = ScriptRequestState.getString("buttonDisableAndSubmitFormAction",
                            new Object[]{parentForm.getRealFormId(), href});
                    buttonDisableAndSubmit = true;
                }
                else {
                    entry = ScriptRequestState.getString("buttonDisableAction", null);
                    buttonDisable = true;
                }
                _state.registerAttribute(AbstractHtmlState.ATTR_JAVASCRIPT, ONCLICK, entry);
                if (parentForm != null)
                    parentForm.insureRealId();
            }
            else if (_popupSupport != null) {
                String href = getActionUrl(request, response);

                if (href != null) {
                    href = response.encodeURL(href);
                    setOnClick(_popupSupport.getOnClick(request,href));
                }
            }
        }
        
        // report any errors that may have been generated.
        if (hasErrors())
            return reportAndExit(EVAL_PAGE);

        WriteRenderAppender writer = new WriteRenderAppender(pageContext);
        TagRenderingBase br = null;
        if (_renderAsButton) {
            br = TagRenderingBase.Factory.getRendering(TagRenderingBase.BUTTON_TAG, request);
            br.doStartTag(writer, _state);
            // add the body content
            if (_text != null)
                write(_text);
            else if (_value != null)
                write(_value);
        }
        else {
            br = TagRenderingBase.Factory.getRendering(TagRenderingBase.INPUT_SUBMIT_TAG, request);
            br.doStartTag(writer, _state);
        }
        br.doEndTag(writer);

        //Emit javascript if this button needs to sumbit the form or open a popup window
        if (idScript != null || _popupSupport != null || buttonDisable || buttonDisableAndSubmit) {
            ScriptRequestState srs = ScriptRequestState.getScriptRequestState(request);
            InternalStringBuilder script = new InternalStringBuilder(32);
            StringBuilderRenderAppender scriptWriter = new StringBuilderRenderAppender(script);
            IScriptReporter sr = getScriptReporter();

            if (buttonDisableAndSubmit)
                srs.writeFeature(sr, scriptWriter, CoreScriptFeature.BUTTON_DISABLE_AND_SUBMIT, true, false, null);
            if (buttonDisable)
                srs.writeFeature(sr, scriptWriter, CoreScriptFeature.BUTTON_DISABLE, true, false, null);
            if (_popupSupport != null)
                _popupSupport.writeScript(request, srs, getScriptReporter(), scriptWriter);
            if (idScript != null)
                scriptWriter.append(idScript);
            write(script.toString());
        }
        
        // Evaluate the remainder of this page
        localRelease();
        return EVAL_PAGE;
    }
328864
public function indexAction()
    {
        // Clear the user identity, if any. (#370)
        if (PHP_SESSION_ACTIVE !== session_status()) {
            session_start();
        }
        session_destroy();

        $form    = $this->installForm;
        $prereqs = $this->plugin('Install/Prerequisites')->check();
    
        return $this->createViewModel(
            array(
                'prerequisites' => $prereqs,
                'form'          => $form,
                'lang'          => $this->params('lang'),
            )
        );
    }
581118
public static MozuUrl deleteDiscountUrl(Integer discountId)
	{
		UrlFormatter formatter = new UrlFormatter("/api/commerce/catalog/admin/discounts/{discountId}");
		formatter.formatUrl("discountId", discountId);
		return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
	}
292340
def do_action_for_many(self, context, request):
        
        savepoint = transaction.savepoint()
        workflow = getToolByName(context, 'portal_workflow')
        site_path = request['PATH_INFO'].replace("/@@API/doActionFor_many", "")

        obj_paths = json.loads(request.get('f', '[]'))
        action = request.get('action', '')
        if not action:
            raise BadRequest("No action specified in request")

        ret = {
            "url": router.url_for("doActionFor_many", force_external=True),
            "success": True,
            "error": False,
        }

        for obj_path in obj_paths:
            if not obj_path.startswith("/"):
                obj_path = "/" + obj_path
            obj = context.restrictedTraverse(str(site_path + obj_path))
            if obj_path.startswith(site_path):
                obj_path = obj_path[len(site_path):]
            try:
                workflow.doActionFor(obj, action)
                obj.reindexObject()
            except Exception as e:
                savepoint.rollback()
                msg = "Cannot execute '{0}' on {1} ({2})".format(
                    action, obj, e.message)
                msg = msg.replace("${action_id}", action)
                raise BadRequest(msg)
        return ret
635911
def add_one(self, url: str,
                url_properties: Optional[URLProperties]=None,
                url_data: Optional[URLData]=None):
        '''
        '''
        self.add_many([AddURLInfo(url, url_properties, url_data)])
693902
public function RegisterForm()
    {

        // If back URL set, push to session
        if (isset($_REQUEST['BackURL'])) {
            Session::set('BackURL', $_REQUEST['BackURL']);
        }

        $config = Users::config();

        // Setup form fields
        $fields = FieldList::create(
            TextField::create("FirstName"),
            TextField::create("Surname"),
            EmailField::create("Email"),
            $password_field = ConfirmedPasswordField::create("Password")
        );

        $password_field->minLength = $config->get("password_min_length");
        $password_field->maxLength = $config->get("password_max_length");
        $password_field->requireStrongPassword = $config->get("password_require_strong");

        // Setup form actions
        $actions = new FieldList(
            FormAction::create("doRegister", "Register")
                ->addExtraClass("btn")
                ->addExtraClass("btn-green")
        );

        // Setup required fields
        $required = new RequiredFields(
            array(
            "FirstName",
            "Surname",
            "Email",
            "Password"
            )
        );

        $form = Form::create(
            $this,
            "RegisterForm",
            $fields,
            $actions,
            $required
        )->addExtraClass("forms")
        ->addExtraClass("forms-columnar");

        $this->extend("updateRegisterForm", $form);

        $session_data = Session::get("Form.{$form->FormName()}.data");

        if ($session_data && is_array($session_data)) {
            $form->loadDataFrom($session_data);
            Session::clear("Form.{$form->FormName()}.data");
        }

        return $form;
    }
137259
def action(context, request, action=None, resource=None, uid=None):
    

    # allow to set the method via the header
    if action is None:
        action = request.get_header("HTTP_X_HTTP_METHOD_OVERRIDE", "CREATE").lower()

    # Fetch and call the action function of the API
    func_name = "{}_items".format(action)
    action_func = getattr(api, func_name, None)
    if action_func is None:
        api.fail(500, "API has no member named '{}'".format(func_name))

    portal_type = api.resource_to_portal_type(resource)
    items = action_func(portal_type=portal_type, uid=uid)

    return {
        "count": len(items),
        "items": items,
        "url": api.url_for("senaite.jsonapi.v1.action", action=action),
    }