def test_has_permission_basics(): u = User.objects.get(username="******") assert has_permission(u, "NC", "write") assert has_permission(u, "NC", Permissions.WRITE) assert has_permission(u, us.states.lookup("NC"), "write") assert has_permission(u, State(abbreviation="NC"), "write") assert not has_permission(u, "NC", "contact") assert not has_permission(u, "VA", "write")
def state_bulk_create(states, State): instances = [ State( id=state[0], name=state[1], uf=state[2] ) for state in states ] State.objects.bulk_create(instances) print(f"Quantidade de Estados no BD: {State.objects.count()}")
def jobs( show: bool = Option(True, help="display records for day/week/month/date_key"), add: str = Option( None, help="Add a new job, job names are stored lowercase only"), switch: str = Option( None, help="Switch to a different job and clock out current"), ): """Show and manage different jobs""" if add or switch: show = False if show: print(Job.print_header()) current_job = State.get().job for j in Job.query().all(): if j.id == current_job.id: print(f"{j} <- Current") else: print(j) elif add is not None: try: j = Job.query().filter(Job.name == add).one() print(f"Job '{add.lower()}' already exists.") except NoResultFound: print(f"Creating job '{add.lower()}'") j = Job(name=add) j.save() elif switch is not None: try: s = State.get() c = Clok.get_last_record() if c is not None: if c.time_out is None: print( f"Clocking you out of '{s.job.name}' at {get_date()}") Clok.clock_out() print(f"Switching to job '{switch.lower()}'") j = Job.query().filter(Job.name == switch.lower()).one() State.set_job(j) except NoResultFound: print(f"Job '{switch}' not found")
def in_( when: str = Argument(None, help="Set a specific time to clock in"), out: str = Option(None, help="Set time to clock out"), m: str = Option(None, help="Journal Message to add to record"), ): """Clock into a job, or add a job day""" if when is not None and len(when.split("-")) > 3: when, out = parse_date_time_junction(when) else: if out is not None: out = parse_date_and_time(out) if when is not None: when = parse_date_and_time(when) if when is not None and out is not None: print( f"Creating entry for {when:%Y-%m-%d}: {when:%H:%M:%S} to {out:%H:%M:%S}" ) c = Clok( time_in=when, time_out=out, date_key=get_date_key(when), month_key=get_month(when), week_key=get_week(when), ) c.update_span() c.save() if m is not None: c.add_journal(m) elif when is not None and out is None: Clok.clock_in_when(when, verbose=True) if m is not None: Clok.get_last_record().add_journal(m) State.set_clok(Clok.get_last_record()) else: Clok.clock_in(verbose=True) if m is not None: Clok.get_last_record().add_journal(m) State.set_clok(Clok.get_last_record())
def import_(file_path: str = Argument( None, help="the path of the file to import. Only json files are supported at this " "time.", )): """Import an exported json file to the database.""" if os.path.isfile(file_path): with open(file_path) as f: dump_obj = json.loads(f.read()) time_clok_jobs = dump_obj["time_clok_jobs"] time_clok = dump_obj["time_clok"] time_clok_state = dump_obj["time_clok_state"] time_clok_journal = dump_obj["time_clok_journal"] jobs = [] for job in time_clok_jobs: jobs.append(Job(**job)) add_items_to_database(jobs) cloks = [] for clok in time_clok: cloks.append(Clok(**clok)) add_items_to_database(cloks) journals = [] for journal in time_clok_journal: journals.append(Journal(**journal)) add_items_to_database(journals) try: s = State(**time_clok_state[0]) s.save() except IntegrityError: pass else: raise FileNotFoundError(f"'{file_path}' does not exist.")
def dump(file_path: str = Argument(None)): """Export the database to a json file""" if file_path is None: date_str = datetime.now().strftime("%Y%m%d_%H%M%S") file_path = f"{APPLICATION_DIRECTORY}/time-clock-dump-{date_str}.json" print(f"Dumping the database to > {file_path}") dump_dict = { "time_clok_jobs": Job.dump(), "time_clok_state": State.dump(), "time_clok": Clok.dump(), "time_clok_journal": Journal.dump(), } s = json.dumps(dump_dict, default=to_json) with open(file_path, "w") as f: f.write(s)
def init(testing=False): """Initialize the database with the default job""" if not os.path.exists(APPLICATION_DIRECTORY): os.mkdir(APPLICATION_DIRECTORY) if not os.path.exists(DATABASE_FILE) or testing: print(f"Creating TimeClok Database and default job.....") DB.create_tables(BaseModel) try: j = Job(name="default") j.save() s = State() s.save() s.set_job(j) except IntegrityError: DB.session.rollback()
def manage_state(request, state_id=None): if request.user.is_superuser: # Try to locate the object to use it as an instance and if not, create a new one # to use it in a new form. # common_data = common_ticket_data() if state_id: actual_state = get_object_or_404(State, pk=state_id) else: actual_state = State() # POST mode if request.method == 'POST': form = StateForm(request.POST, instance=actual_state) if form.is_valid(): form.save() return redirect('state-list') else: # Non-POST mode, show only form = StateForm(instance=actual_state) return render(request, 'core/states/create_edit_state.html', locals()) else: raise Http404
def parse_result(json): return State(json) if json is not None else State()
path = os.path.dirname(os.path.dirname(os.path.abspath(__name__))) path = path + "/LogisWare/core/install/NIGERIA_STATES_AND_LGS.json" with open(path) as json_file: json_data = json.load(json_file) for data in json_data: print() state_name = data['state']['name'] print(state_name) try: State.objects.get(name=state_name) except Exception: state_model = State() state_model.name = state_name state_model.save() # try: # State.objects.get( name = state_name ) # except State.DoesNotExist: # state_model = State() # state_model.name = state_name # state_model.save() # state_locals = data['state']['locals'] # print("---------------") # for local in state_locals: # local_name = local['name'] # if LGA.objects.filter( name = local_name ).count() == 0:
level.daily_task_count = 100 level.save() level = Level() level.code = 'PERAK' level.name = 'TAHAP PERAK' level.daily_task_count = 50 level.save() level = Level() level.code = 'GANGSA' level.name = 'TAHAP GANGSA' level.daily_task_count = 20 level.save() state = State() state.code = 'WP' state.name = 'WILAYAH PERSEKUTUAN' state.save() state = State() state.code = 'SL' state.name = 'SELANGOR' state.save() state = State() state.code = 'PK' state.name = 'PERAK' state.save() state = State()