Exemplo n.º 1
0
def branch_get(id):
	if id:
		branch = Branch.query.filter_by(site_id=g.sid, is_active='Y', id=id).first()
	else:
		no = db.session.query(db.func.max(Branch.no)).filter_by(site_id=g.sid).scalar() or 0
		no = no + 1
		branch = Branch(site_id=g.sid)
		branch.no = no
		branch.code = 'BH' + str(no).zfill(3)
	schema = BranchSchema()
	return jsonify({
		'branch': schema.dump(branch).data
	})
Exemplo n.º 2
0
def add():
    data = request.json or request.data or request.form
    res_code = 200
    res = dict(status="fail")
    branch_name = data.get("name")
    if not branch_name:
        res["error"] = "cannot create branch with Empty name"
        return jsonify(res), res_code
    branch = Branch.query.filter_by(name=branch_name).first()
    if branch:
        res["error"] = "Branch with this name already present"
        return jsonify(res), res_code
    branch = Branch(name=branch_name)
    db.session.add(branch)
    db.session.commit()
    res["status"] = "success"
    res["branch"] = branch.serialize()
    return jsonify(res), res_code
Exemplo n.º 3
0
    def branch_update():
        """
        Updates a record based on id supplied
        Endpoint URL: /branch/update
        :return: JSON successful message or exception response
        """
        if request.method == "PUT":
            if request.data is None:
                return jsonify({
                    "status_code": 400,
                    "message": "Invalid request"
                })
            request_data = request.data

            try:
                # Validate id parameter passed
                id = helpers.check_missing('list', request_data, 'id')
                id = helpers.validate_int(id, 'id')

                # Find the object to update
                params = {"id": id}
                branch = Branch.get(params)

                # Return 404 if not found the object to update
                if not branch:
                    return jsonify({
                        "status_code": 404,
                        "message": "Branch not found"
                    })

                # Find and validate any allowed parameters
                if "city" in request_data.keys():
                    branch.city = helpers.validate_string(
                        request_data['city'], 'city')
                if "postcode" in request_data.keys():
                    branch.postcode = helpers.validate_postcode(
                        request_data['postcode'])
                if "capacity" in request_data.keys():
                    branch.capacity = helpers.validate_int(
                        request_data['capacity'], 'capacity')

                # Save an object and return successful message
                branch.save()
                return jsonify({
                    "status_code": 200,
                    "message": "Branch record was updated"
                })
            except Exception as e:
                return jsonify({
                    "status_code": e.args[0]['status_code'],
                    "message": e.args[0]['message']
                })
Exemplo n.º 4
0
def create_branch(company_id):
	company = Company.query.get(company_id)
	create_branch_form = CreateBranchForm()
	if create_branch_form.validate_on_submit():
		# create branch
		name = create_branch_form.name.data
		location = create_branch_form.location.data
		branch = Branch(name=name, location=location, company=company)
		db.session.commit()
		flash("Branch created.", "success")
		return redirect(url_for('company.get_company_branch', company_id=company.id, branch_id=branch.id))
	flash(str(create_branch_form.errors), "danger")
	return redirect(url_for('company.get_company_branches', company_id=company.id))
Exemplo n.º 5
0
def branch_create():
    form = BranchFormCreate()
    if form.validate_on_submit():
        branch = Branch(
            name=form.name.data, 
            description=form.description.data, 
            school_id=form.school_id.data
        )
        db.session.add(branch)
        db.session.commit()
        flash('Created and Saved Successfully.', 'alert-success')
        return redirect(url_for('branch_view', id=branch.id))
    return render_template('basic-forms/branch/create.html', title='Branch Create', form=form)
Exemplo n.º 6
0
    def branch_get():
        """
        Gets a record based on parameters supplied to the endpoint. Returns first suitable found object based on params
        Endpoint URL: /branch/get
        :return: JSON of an object or exception status
        """
        if request.method == "GET":
            if request.args is None:
                return jsonify({
                    "status_code": 400,
                    "message": "Invalid request"
                })

            try:
                params = {}  # list of params that we will search by
                # Check if any of the parameters are being passed and then validate them
                if "id" in request.args.keys():
                    params['id'] = helpers.validate_int(
                        request.args.get('id'), 'id')
                if "city" in request.args.keys():
                    params['city'] = helpers.validate_string(
                        request.args.get('city'), 'city')
                if "postcode" in request.args.keys():
                    params['postcode'] = helpers.validate_postcode(
                        request.args.get('postcode'))
                if "capacity" in request.args.keys():
                    params['capacity'] = helpers.validate_int(
                        request.args.get('capacity'), 'capacity')

                # If no allowed params were passed on - invalidate the request
                if not params:
                    return jsonify({
                        "status_code": 400,
                        "message": "Invalid request"
                    })

                # Get the object based on the given parameters
                branch = Branch.get(params)
                if not branch:
                    return jsonify({
                        "status_code": 404,
                        "message": "Branch not found"
                    })
                return jsonify(branch.serialize())

            except Exception as e:
                return jsonify({
                    "status_code": e.args[0]['status_code'],
                    "message": e.args[0]['message']
                })
Exemplo n.º 7
0
    def branch_create():
        """
        Creates a record based on params supplied
        Endpoint URL: /branch/create
        :return: JSON successful message or exception response
        """
        if request.method == "POST":
            if request.data is None:
                return jsonify({
                    "status_code": 400,
                    "message": "Invalid request"
                })
            request_data = request.data

            try:
                # Find and validate required parameters in order to create branch record
                city = helpers.check_missing('list', request_data, 'city')
                city = helpers.validate_string(city, 'city')
                postcode = helpers.check_missing('list', request_data,
                                                 'postcode')
                postcode = helpers.validate_postcode(postcode)
                capacity = helpers.check_missing('list', request_data,
                                                 'capacity')
                capacity = helpers.validate_int(capacity, 'capacity')

                # Create object and save it in the database
                branch = Branch(city, postcode, capacity)
                branch.save()
                return jsonify({
                    "status_code": 201,
                    "message": "Branch created"
                })
            except Exception as e:
                return jsonify({
                    "status_code": e.args[0]['status_code'],
                    "message": e.args[0]['message']
                })
Exemplo n.º 8
0
def validate_assigning(assigned_type, assigned_id):
    """
    Checks if we can assign this type to this id

    :param assigned_type:
    :param assigned_id:
    :return: list with type and id if passed validation
    :raises Exception: either type or id is invalid
    """
    from app.models import Branch, Driver

    # validate both as ints
    assigned_id = validate_int(assigned_id, 'assigned_id')
    assigned_type = validate_int(assigned_type, 'assigned_type')

    # only allow 1 and 2 to get through
    allowed_types = [1, 2]
    if assigned_type not in allowed_types:
        raise Exception({"status_code": 400, "message": "Invalid assigned_type"})

    if assigned_type == 1:  # 1 = driver
        # check if driver exists
        params = {"id": assigned_id}
        driver = Driver.get(params)
        if driver:
            assigned_id = driver.id
            return [assigned_type, assigned_id]
        else:
            raise Exception({"status_code": 404, "message": "Driver not found"})

    if assigned_type == 2:  # 2 = branch
        # check if branch exists
        params = {"id": assigned_id}
        branch = Branch.get(params)
        if branch:
            occupancy = branch.get_assigned_cars_count(assigned_id)
            if branch.capacity > occupancy:
                return [assigned_type, assigned_id]
            else:
                raise Exception({"status_code": 400, "message": "Branch has reached its capacity"})
        else:
            raise Exception({"status_code": 404, "message": "Branch not found"})
Exemplo n.º 9
0
    def branch_delete():
        """
        Deletes a record based on the id
        Endpoint URL: /branch/delete
        :return: JSON successful message or exception response
        """
        if request.method == "DELETE":
            if request.args is None:
                return jsonify({
                    "status_code": 400,
                    "message": "Invalid request"
                })

            try:
                # Validate id parameter passed
                id = helpers.check_missing('args', request, 'id')
                id = helpers.validate_int(id, 'id')

                # Find the object to delete
                params = {"id": id}
                branch = Branch.get(params)

                # Return 404 if not found the object to delete
                if not branch:
                    return jsonify({
                        "status_code": 404,
                        "message": "Branch not found"
                    })

                # Delete object and return successful message
                branch.delete()
                return jsonify({
                    "status_code": 200,
                    "message": "Branch deleted"
                })
            except Exception as e:
                return jsonify({
                    "status_code": e.args[0]['status_code'],
                    "message": e.args[0]['message']
                })
Exemplo n.º 10
0
def mngtree():
  #for_test()

  # get data from request
  ## via GET method
  if request.method == "GET":
    # curtree_id is require only for cases when jstree return '#' as a sign of root branch_id. To get rid of it we have to rewrite a big part of jstree
    try:
      curtree_id = request.args.get('tree_id', default='', type=str)
    except AttributeError as e:
      msg='Can\'t find any trees. Try to create one.'
      print('\n' + str(msg) + '\n')
      return ""

    import app.general
    nestedocs = app.general.str2bool(request.args.get('nestedocs', default='False', type=str))
    cmd = request.args.get('cmd', default='', type=str)
    id = request.args.get('id', default='', type=str)

    # after integration with flask symbole '%' has started to add to id. So we need to remove it
    if id[:1] == "%":
      id = int(id[1:])
    if id == '#' or id == None or id == '':
      curtree = Tree.getTree(id = curtree_id)
      id = curtree.rootb_id

    data = request.args.get('data', default='', type=str)

  ## via POST method
  else:
    form = SaveDataForm(request.form)
    if request.method == "POST" and form.validate():
      nestedocs = form.nestedocs.data
      cmd = form.cmd.data
      id = form.id.data
      data = form.data.data
  ##

  branch = Branch.get(id=id)
  curtree = Tree.getTree(id=branch.tree_id)
  tree_owner = curtree.owner

  """
  cmd = "load_subbs"
  id = 4
  id = '#'
  """

  # set permission for actions
  if g.user is not None and g.user.is_authenticated():
    curuser = g.user
  else:
    curuser = '******'

  owner = True
  if tree_owner.id != curuser.id:
    owner = False
    if not ( branch.read and cmd == "load_subbs" ):
      cmd = ''
  #

  if cmd != "" :
    if cmd == "fold":
      branch.folded = True
    elif cmd == "unfold":
      branch.folded = False
    elif cmd == "rename_node":
      branch.text = data
    elif cmd == "move_node":
      new_parent_id = request.args.get('new_parent', default=curtree.rootb_id, type=int)
      position = request.args.get('position', default=-1, type=int)
      branch.move(new_parent_id, position)
    elif cmd == "load_data":
      return branch.text
    elif cmd == "delete_node":
      branch.remove()
    elif cmd == "create_node":
      parent_id = request.args.get('parent_id', default=curtree.rootb_id, type=int)
      parentB = curtree.getB(parent_id)
      newB = Branch(main = (not nestedocs), parent_id = parent_id)
      position = request.args.get('position', default=-1, type=int)
      newB.move(pos=position)
      return str( newB.id )
    elif cmd == "load_subbs":
      curtree.set_latestB(id)
      return json.dumps(getList_subbsOf(branch, nestedocs, withReadLabel=(not owner)))
    elif cmd == "get_privileges":
      return json.dumps(branch.get_priv_all())
    elif cmd == "set_privileges":
      for_class = request.args.get('for_class', default='bydefault', type=str)
      priv_read = app.general.str2bool(request.args.get('read', default=None, type=str))
      priv_rw = app.general.str2bool(request.args.get('rw', default=None, type=str))
      if for_class == 'bydefault':
        new_privs = branch.set_priv_bydefault(priv_read, priv_rw)
      elif for_class == 'users':
        nickname = request.args.get('nickname', default=None, type=str)
        if nickname != None:
          user = Users.getUser(nickname = nickname)
          new_privs = branch.set_priv_foruserid(user.id, priv_read, priv_rw)
      return json.dumps(new_privs)
    elif cmd == "set_priv_adduser":
      nickname = request.args.get('nickname', default=None, type=str)
      if nickname != None:
        user = Users.getUser(nickname = nickname)
        if branch.set_priv_adduser(user) == 0:
          return 0
      return -1
    else:
      if nestedocs :
        if cmd == "save_data":
          branch.text = data
        else:
          pass
  db.session.commit()
  return ""