Esempio n. 1
0
    def __init__(self, redis, features={}):
        NPC.__init__(self, redis, features, 'npc')
        self.logger = logging.getLogger(__name__)

        self.generate_features('leader')
        #generates self.scope = "country"

        self.generate_features('leader' + self.scope)
        # generate self.kind from scope; scope.kind = absolutemonarchy
        self.generate_features('leader' + self.kind)
        # generate self.leader from leaderabsolutemonarchy_leader
        # generate leader.description from leaderabsolutemonarchy_leader_description

        if self.scope == 'country':
            self.location = country.Country(self.redis, {'leader': self})
        elif self.scope == 'city':
            self.location = city.City(self.redis, {'leader': self})
        elif self.scope == 'organization':
            self.location = organization.Organization(self.redis,
                                                      {'leader': self})
        else:
            self.location = organization.Organization(self.redis,
                                                      {'leader': self})
            self.scope = 'organization'

        self.name.title = self.leader_description[self.sex['name']]
        #re-render the name with the title.
        self.name.render()
def print_products_and_lots():

    print( "##################  Printing Products and Lots: #################")

    # 1. get org id
    org = organization.Organization("Name", utils.global_args.client)
    org_id = org.get_id()

    # 2. get outboundAPI
    outbound_api = api_outbound.APIOutbound(5, org_id, utils.global_args.env)

    # 3. get products
    products = outbound_api.get_products(org_id, None, None, None)
    utils.d_pprint(2, "Products:", products)
    for p in products:
        if len(p) <= 0 or p == {} or p == []:
            continue
        fr = [p['id'], p['description']]
        pr_lots = {}
        # 4. get lots and serials
        lots = outbound_api.get_lots_and_serials([str(p['id'])])
        if len(lots) != 0:
            lot_count = 1
            for l in lots:
#                        print "---> ", str(p['id']), " ", str(p['description'])
#                        print "Lot:", l
                if str(lot_count) in pr_lots:
                    pr_lots[l['id']].append('')
                else:
                    pr_lots[l['id']] = ['']
                lot_count += 1
            # print as a table
            st = utils.StatsTable()
            st.pretty_table_output(fr, pr_lots, alternate_color=True)
Esempio n. 3
0
    def push_to_bts(self):
        company_prefixes = []
        inbound_api = None

        try:
            # 1. load the workbook
            wb = load_workbook(filename = self.filename)

            # 2. set up the inbound API
            org = organization.Organization("Name", utils.global_args.client)
            org_id = org.get_id()
            inbound_api = api_inbound.APIInbound(5, org_id, utils.global_args.env, utils.global_args.header_entitled_org)

            # get company prefixes, head quarters GLN, etc.
            org_params = org.get_properties()
            # if we are asked to use a different HQ GLN, use it.
            if utils.global_args.hq_gln:
                org_params['hq_gln'] = utils.global_args.hq_gln

            # 3. start parsing the excel sheet
            #     a. first gather global params
            sheet_names = wb.sheetnames
            utils.d_print(2, "Sheet Names in the Excel Sheet: ", sheet_names)


            # if arguments indicate specific rows to be pushed, push the same.
            if utils.global_args.specific_rows:
                self.specific_rows = utils.global_args.specific_rows.split(',')
            else:
                self.specific_rows = None

            if 'if' in utils.global_args.isheets:
                # b. next push if there are any facilities
                facilities = wb['Facilities']
                self.parse_and_push_worksheet(org_params, facilities, 'Facility', inbound_api)

            if 'ip' in utils.global_args.isheets:
                # c. next push any products   
                products = wb['Products']
                self.parse_and_push_worksheet(org_params, products, 'Product',inbound_api)

            if 'ie' in utils.global_args.isheets:
                # d. next push any events
                events = wb['Events']
                self.parse_and_push_worksheet(org_params, events, 'Event',inbound_api)

            if 'ipl' in utils.global_args.isheets:
                # e. next push any events
                payloads = wb['Payloads']
                self.parse_and_push_worksheet(org_params, payloads, 'Payload',inbound_api)
        except:
            utils.print_exception(1)

            return
def GetOrganizationForm(post_data):
  e = event_db.Event(name = "Test Incident",
  case_label = "B",
  counties = ["Kings"])
  query_string = "SELECT * FROM Organization WHERE is_active = True ORDER BY name"
  organizations = db.GqlQuery(query_string)
  events = event_db.GetAllCached()
  events = db.GqlQuery("SELECT * From Event ORDER BY created_date DESC")
  event_key = None
  if events.count() == 0:
    logging.warning("Initialize called")
    e = event_db.Event(name = "North Central Victorian Floods",
                       case_label = "A",
                       short_name = "ncv_floods")
    e.put()
    event_key = e.key()
    # TODO(Jeremy): This could be dangerous if we reset events.
    for s in site_db.Site.all().run(batch_size = 1000):
      event_db.AddSiteToEvent(s, e.key().id(), force = True)
    events = [e]

  if organizations.count() == 0:
    # init: populate the database with Admin user
    admin_org = organization.Organization(
        name="Admin",
        password="******",
        org_verified=True,
        is_active=True,
        is_admin=True,
        incidents=[event_key]
    )
    admin_org.put()
    admin_contact = primary_contact_db.Contact(
        first_name="Admin",
        last_name="Admin",
        title="Admin",
        phone="1234",
        email="*****@*****.**",
        organization=admin_org,
        is_primary=True
    )
    admin_contact.put()
    organizations = db.GqlQuery("SELECT * FROM Organization WHERE is_active = True ORDER BY name")

  class OrganizationForm(wtforms.form.Form):
    event = wtforms.fields.SelectField(
        'Work Event',
        choices = [(e.name, e.name) for e in events],
        validators = [wtforms.validators.required()])
    password = wtforms.fields.PasswordField(
        'Password',
        validators = [ wtforms.validators.required() ])
  form = OrganizationForm(post_data)
  return form
Esempio n. 5
0
    def __init__(self):
        for t in self.types:
            self.processed[t] = 0
            self.built[t] = [
            ]  # array per type holds any new manufactured ones

        # create and store an outbound_api in our object
        org = organization.Organization("Name", utils.global_args.client)
        self.org_id = org.get_id()
        self.api_outbound = api_outbound.APIOutbound(5, self.org_id,
                                                     utils.global_args.env)
        return
    def __init__(self, config, log):
        # Create object
        self.view = viewtable.Viewtable(config, log)
        self.coop = cooperation.Cooperation(config, log)
        self.employee = employee.Employee(config, log)
        self.organization = organization.Organization(config, log)

        # set logger
        self.log = json.loads(log['hr']['log'])
        logfile = config['logger']['logfile']
        rotation = config['logger']['rotation']
        retention = int(config['logger']['retention'])
        logger.remove()
        logger.add(logfile, rotation=rotation, retention=retention)
    def AuthenticatedPost(self, org, event):
        if not org.name == GLOBAL_ADMIN_NAME:
            self.redirect("/")
            return
        data = event_db.NewEventForm(self.request.POST)
        if not data.validate():
            query_string = "SELECT * FROM Event"
            events_list = db.GqlQuery(query_string)
            count = events_list.count()
            self.response.out.write(
                template.render({
                    "form": data,
                    "errors": data.errors,
                    "case_label": CASE_LABELS[count],
                }))
        else:
            query_string = "SELECT * FROM Event"
            events_list = db.GqlQuery(query_string)
            count = events_list.count()
            this_event = event_db.Event(
                name=data.name.data,
                short_name=data.short_name.data,
                case_label=CASE_LABELS[count],
            )
            ten_minutes = 600
            cache.PutAndCache(this_event, ten_minutes)

            # create local admin
            new_admin = organization.Organization(
                name="Local Admin - " + data.short_name.data,
                email="",
                phone="",
                address="",
                city="",
                state="",
                zip_code="",
                physical_presence=True,
                number_volunteers="0",
                voad_member=False,
                org_verified=True,
                twitter="",
                url="",
                facebook="",
                incidents=[this_event.key()],
                password=self.request.get("password"),
                is_active=True,
                is_admin=True,
            )
            organization.PutAndCache(new_admin, ten_minutes)
            self.redirect("/admin")
Esempio n. 8
0
    def get_owners(self):
        """Get a list of Organizations that control this domain

        :return: A list of one or more :class:`organization(s) <tracker_client.organization.Organization>`
            responsible for this domain.
        :rtype: list[Organization]
        """
        params = {"domain": self.domain_name}
        result = self.client.execute_query(queries.GET_DOMAIN_OWNERS, params)

        if "error" in result:
            print("Server error: ", result)
            raise ValueError("Unable to get owners for " + self.domain_name)

        org_list = []
        for edge in result["findDomainByDomain"]["organizations"]["edges"]:
            org_list.append(org.Organization(self.client, **edge["node"]))

        return org_list
Esempio n. 9
0
def main():
    list_of_commands = ["Exit", "Department", "Count", "People", "Avgage"]
    if len(sys.argv) < 3:
        print("Not enough arguments!")
        return 1
    orgchart_filename = sys.argv[1]
    employees_filename = sys.argv[2]
    org = organization.Organization()
    org.load_csv(orgchart_filename, employees_filename)
    departments = org.get_departments()
    while True:
        command_with_arg = input("User command: ")
        if not command_with_arg:
            continue
        command = command_with_arg.split()[0]
        if command not in list_of_commands:
            print("Invalid command! Supported commands: " +
                  ', '.join(list_of_commands))
            continue
        if command not in ["Exit"
                           ]:  # hack: for commands with 1 number argument
            dept_id = get_int(command_with_arg)
            if dept_id is None:
                print("Invalid number argument!")
                continue
            elif dept_id not in org.get_departments().keys():
                print("Invalid department ID!")
                continue
        if command == "Exit":
            break
        elif command == "Department":
            print(departments[dept_id].get_department_name_location())
        elif command == "Count":
            print(departments[dept_id].count_employees())
        elif command == "People":
            print(', '.join(departments[dept_id].get_employees_names()))
        elif command == "Avgage":
            print(departments[dept_id].avg_age())
Esempio n. 10
0
 def setUp(self):
     org = self._sample_organization = organization.Organization()
     org.load_csv("orgchart-data.csv", "employees-data.csv")
    def AuthenticatedPost(self, org, event):
        global_admin = False
        local_admin = False
        if org.name == GLOBAL_ADMIN_NAME:
            global_admin = True
        if org.is_admin == True and global_admin == False:
            local_admin = True

        if global_admin == False and local_admin == False:
            self.redirect("/")
            return

        if self.request.get("create_contact"):
            data = primary_contact_db.ContactFormFull(self.request.POST)
            if data.validate():
                organization_id = self.request.get("choose_organization")
                try:
                    id = int(organization_id)
                except:
                    return
                this_organization = organization.Organization.get_by_id(id)
                if not org.may_administer(this_organization):
                    self.abort(403)
                contact = primary_contact_db.Contact(
                    first_name=data.first_name.data,
                    last_name=data.last_name.data,
                    title=data.title.data,
                    phone=data.phone.data,
                    email=data.email.data,
                    is_primary=bool(data.is_primary.data),
                    organization=this_organization.key(),
                )
                primary_contact_db.PutAndCache(contact, ten_minutes)
                self.redirect(
                    "/admin-create-contact?selected_org=%s&message=Contact Created"
                    % this_organization.key().id())
                return
            else:
                #query_string = "SELECT * FROM Event"
                #events_list = db.GqlQuery(query_string)
                suggested_password = random_password.generate_password()
                query_string = "SELECT * FROM Organization"
                organization_list = db.GqlQuery(query_string)

                self.response.out.write(
                    template.render({
                        "form": data,
                        "errors": data.errors,
                        "create_contact": True,
                        "organization_list": organization_list,
                    }))
                return

        if self.request.get("create_admin"):
            data = organization.OrganizationAdminForm(self.request.POST)
            event_id = self.request.get("choose_event")
            try:
                id = int(event_id)
            except:
                return
            this_event = event_db.Event.get_by_id(id)
            if local_admin:
                if not this_event.key() == event.key():
                    self.redirect("/")
                    return

            if data.validate():
                new_org = organization.Organization(
                    name=data.name.data,
                    email=data.email.data,
                    phone=data.phone.data,
                    address=data.address.data,
                    city=data.city.data,
                    state=data.state.data,
                    zip_code=data.zip_code.data,
                    physical_presence=True,
                    number_volunteers="0",
                    voad_member=False,
                    org_verified=True,
                    twitter=data.twitter.data,
                    url=data.url.data,
                    facebook=data.facebook.data,
                    incidents=[this_event.key()],
                    password=self.request.get("password"),
                    is_active=True,
                    is_admin=True,
                )

                # set all phase fields true for admin
                for phase_name in new_org.get_phase_boolean_names():
                    setattr(new_org, phase_name, True)

                new_contact = primary_contact_db.Contact(
                    first_name=data.contact_first_name.data,
                    last_name=data.contact_last_name.data,
                    title=data.contact_title.data,
                    email=data.contact_email.data,
                    phone=data.contact_phone.data,
                    is_primary=True)

                organization.PutAndCacheOrganizationAndContact(
                    organization=new_org,
                    contact=new_contact,
                )
                self.redirect("/admin?message=Admin Created")
                return
            else:
                # needs events lists, password, errors
                query_string = "SELECT * FROM Event"
                suggested_password = random_password.generate_password()
                self.response.out.write(
                    template.render({
                        "form": data,
                        "errors": data.errors,
                        "create_admin": True,
                        #"events_list": events_list,
                        "auto_password": suggested_password,
                    }))
                return

        if self.request.get("delete_org_id"):
            # delete organization
            try:
                id = int(self.request.get("delete_org_id"))
                org_by_id = organization.Organization.get_by_id(id)
            except:
                self.abort(400)

            if not org.may_administer(org_by_id):
                self.abort(403)

            primary_contact_db.RemoveOrgFromContacts(org_by_id)
            db.delete(org_by_id)
            self.redirect("/admin")
            return

        if self.request.get("delete_contact_id"):
            # delete contact
            try:
                id = int(self.request.get("delete_contact_id"))
                contact_by_id = primary_contact_db.Contact.get_by_id(id)
            except:
                self.abort(400)

            if not org.may_administer(org_by_id):
                self.abort(403)

            db.delete(contact_by_id)
            self.redirect("/admin")
            return

        if self.request.get("verify_organization"):
            # verify organization
            try:
                id = int(self.request.get("verify_organization"))
                org_by_id = organization.Organization.get_by_id(id)
            except:
                self.abort(400)

            # check we are allowed
            if not org.may_administer(org_by_id):
                self.abort(403)

            # perform verification
            org_by_id.verify()

            # cache
            organization.PutAndCache(org_by_id, 600)
            self.redirect("/admin")
            return

        if self.request.get("save_org_id"):
            # save org (?)
            try:
                id = int(self.request.get("save_org_id"))
                org_by_id = organization.Organization.get_by_id(id)
            except:
                self.abort(400)

            if not org.may_administer(org_by_id):
                self.abort(403)

            org_by_id.org_verified = True
            organization.PutAndCache(org_by_id, 600)
            self.redirect("/admin")
            return
Esempio n. 12
0
    def post(self):
        # create inactive, unverified org with a random password
        org = organization.Organization(
            name=self.request.get("name"),
            is_active=False,
            org_verified=False,
            voad_referral=self.request.get("voad_referral"),
            password=random_password.generate_password())

        # set non-contact org attributes by type
        for k, v in self.request.POST.iteritems():
            if not any(
                    k.startswith(prop)
                    for prop in self.CONTACT_PROPERTIES_LIST):
                if k == "choose_event":
                    chosen_event = event_db.Event.get_by_id(int(v))
                    setattr(org, "incidents", [chosen_event.key()])
                elif k in self.BOOLEAN_PROPERTIES_LIST:
                    setattr(org, k, bool(int(v)))
                else:
                    # clean away known pre-supplied strings
                    if v.strip() in ('http://', '@'):
                        v = None
                    setattr(org, k, v)

        # create contacts
        def get_contact_field(field_name, contact_num):
            field_value = self.request.get(field_name + '_%d' % i)
            return field_value.strip() if field_value else None

        new_contacts = []

        for i in range(10):
            first_name = get_contact_field('first_name', i)
            last_name = get_contact_field('last_name', i)
            title = get_contact_field('title', i)
            email = get_contact_field('personal_email', i)
            phone = get_contact_field('personal_phone', i)

            if first_name and last_name and email and phone:  # required fields
                new_contacts.append(
                    primary_contact_db.Contact(
                        first_name=first_name,
                        last_name=last_name,
                        title=title,
                        email=email,
                        phone=phone,
                        is_primary=(i == 0
                                    )  # the first contact is the primary one
                    ))

        # save
        organization.PutAndCacheOrganizationAndContact(org, new_contacts)

        # email primary contacts & administrators
        organization_form = organization.OrganizationForm(None, org)
        contact_forms = [
            primary_contact_db.ContactFormFull(None, contact)
            for contact in new_contacts
        ]
        messaging.email_contacts_using_templates(
            event=chosen_event,
            contacts=[c for c in new_contacts if c.is_primary],
            subject_template_name='new_organization.to_contacts.subject.txt',
            body_template_name='new_organization.to_contacts.body.txt',
            new_organization=org,
            primary_contact=new_contacts[0],
            application_id=messaging.get_application_id(),
            organization_form=organization_form,
            contact_forms=contact_forms,
        )
        approval_url = "%s://%s/admin-new-organization?new_organization=%d" % (
            urlparse(self.request.url).scheme, urlparse(
                self.request.url).netloc, org.key().id())
        messaging.email_administrators_using_templates(
            event=chosen_event,
            subject_template_name='new_organization.to_admins.subject.txt',
            body_template_name='new_organization.to_admins.body.txt',
            new_organization=org,
            primary_contact=new_contacts[0],
            application_id=messaging.get_application_id(),
            approval_url=approval_url,
            organization_form=organization_form,
            contact_forms=contact_forms,
        )

        self.redirect("/welcome")
os.environ['HTTP_PROXY'] = 'https://proxygate2.nic.nec.co.jp:8080'
os.environ['HTTPS_PROXY'] = 'https://proxygate2.nic.nec.co.jp:8080'


config = configparser.ConfigParser()
config.read('../conf/config.ini', encoding='utf-8')

log = configparser.ConfigParser()
log.read('../conf/log.ini', encoding='utf-8')


nowtime = datetime.datetime.now()

coop = cooperation.Cooperation(config, log)
org = organization.Organization(config, log)

regist = [\
		'113305',\
		'NECネッツエスアイ株式会社',\
		'NEC Networks & System Integration Corporation',\
		'NESIC',\
		'NESIC_RYAKU',\
		'2020-01-31 06:00:00.123456',\
		'',\
		'10-20-30-40',\
		'1010',\
		'和田テスト組織',\
		'和田略組織',\
		'10',\
		'10',\
Esempio n. 14
0
def main():
    print("BEGINNING\n")
    my_organization = organization.Organization()
    my_organization.get_all_phones()
    print("\nCOMPLETED")