Exemplo n.º 1
0
class TaxCode(object):
    """Tax codes."""
    def __init__(self, company_code, tax_code, coverage_type, coverage_amount,
                 description, tax_type, tax_amount, detailid, flight_number,
                 departure_date, departure_airport, arrival_airport):
        self.company_code = company_code
        self.tax_code = tax_code
        self.coverage_type = coverage_type
        self.coverage_amount = coverage_amount
        self.description = description
        self.tax_type = tax_type
        self.tax_amount = tax_amount
        self.detailid = detailid
        self.flight_number = flight_number
        self.departure_date = ReadDate(departure_date)
        self.departure_date_iso = self.departure_date.strftime("%Y-%m-%d")
        self.departure_airport = departure_airport
        self.arrival_airport = arrival_airport
        self.segments = [1]
        logger.debug("New tax code %s (%s)" %
                     (self.tax_code, self.description))

    def display(self, prefix='\t'):
        print("\t\t*\tTax code          : %s" % self.tax_code)
        print("\t\t\tCompany code      : %s" % self.company_code)
        print("\t\t\tCoverage type     : %s" % self.coverage_type)
        print("\t\t\tCoverage value    : %s" % self.coverage_amount)
        print("\t\t\tDescription       : %s" % self.description)
        print("\t\t\tTax type          : %s" % self.tax_type)
        print("\t\t\tTax amount        : %s" % self.tax_amount)
        print("\t\t\tDetail id         : %s" % self.detailid)
        print("\t\t\tFlight number     : %s" % self.flight_number)
        print("\t\t\tDeparture date    : %s" % self.departure_date_iso)
        print("\t\t\tDeparture airport : %s" % self.departure_airport)
        print("\t\t\tArrival airport   : %s" % self.arrival_airport)
Exemplo n.º 2
0
def CheckForDuplicateSeatMaps(conn, acode=None):

    logger.info("Flights with duplicate seat maps")

    SmcSql = \
        "SELECT " \
        " fdl.flight_number fn, fdl.flight_date fd, count(*) smc" \
        " FROM flight_seat_map fsm" \
        " JOIN flight_date_leg fdl ON fsm.flight_date_leg_id = fdl.flight_date_leg_id" \
        " WHERE fdl.flight_date > CURRENT" \
        " GROUP BY fdl.flight_number, fdl.flight_date" \
        " HAVING count(*) > 1"

    logger.debug(SmcSql)
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    cur.execute(SmcSql)

    flights = []
    for row in cur:
        logger.info("\t%s %s %s" % (row['fn'], row['fd'], row['smc']))
        flight_number = str(row['fn'])
        flight_date = ReadDate(str(row['fd']))
        flight = ReadFlight(conn, flight_number, flight_date)
        if flight is None:
            print("No information for flight %s depart %s" \
                % (flight_number, flight_date.strftime("%Y-%m-%d")))
        else:
            if acode is None:
                flights.append(flight)
            else:
                if flight.aircraft_code == acode:
                    flights.append(flight)

    return flights
Exemplo n.º 3
0
class FareCode(object):

    company_code = 'ZZ'
    fare_basis_code = ''
    class_code = 'Y'
    passenger_code = 'ADULT'
    base_amount = 0.00
    fare_route_id = ''
    valid_from = ''
    valid_to = ''
    flights = []
    flight_codes = []

    def __init__(self, company_code, fare_basis_code, class_code,
                 passenger_code, base_amount, fare_route_id, valid_from,
                 valid_to, flightcodes):
        self.company_code = company_code
        self.fare_basis_code = fare_basis_code
        self.class_code = class_code
        self.passenger_code = passenger_code
        self.base_amount = float(base_amount)
        self.fare_route_id = fare_route_id
        self.valid_from = ReadDate(valid_from)
        self.valid_to = ReadDate(valid_to)
        self.flight_codes = flightcodes
        logger.debug(
            "New fare code %s class %s ID %s" %
            (self.fare_basis_code, self.class_code, self.fare_route_id))

    def display(self, prefix='\t'):
        print("\t\t*\tFare code       : %s" % self.fare_basis_code)
        print("\t\t\tCompany code    : %s" % self.company_code)
        print("\t\t\tClass code      : %s" % self.class_code)
        print("\t\t\tPassenger code  : %s" % self.passenger_code)
        print("\t\t\tBase amount     : R%.2f" % self.base_amount)
        print("\t\t\tFare route ID   : %s" % self.fare_route_id)
        print("\t\t\tValid from      : %s" %
              self.valid_from.strftime("%Y-%m-%d"))
        print("\t\t\tValid to        : %s" %
              self.valid_to.strftime("%Y-%m-%d"))
        print("\t\t\tFlight codes :")
        for flight_code in self.flight_codes:
            flight_code.display()
Exemplo n.º 4
0
def main(argv):
    """Pythonic entry point."""

    barsdir = os.environ['BARSDIR']
    etcdir = "%s/etc" % barsdir

    # Option values
    dt1 = None
    dt2 = None
    arriveAirport = None
    departAirport = None
    flightNumber = None
    flightNumber2 = None
    departTerm = 'A'
    arriveTerm = 'B'
    bn = None
    departTime = None
    arriveTime = None
    paxNames = []
    paxDobs = []
    payAmount = None
    payAmount2 = 0
    sellClass = None
    vTimeLimit = datetime.now() + timedelta(days=2)
    vDocNum = None
    paxCount = 0
    groupName = ''
    reqCode = None
    reqText = None

    # Option flags
    doavail = False
    dochk = False
    dodetail = False
    doprice = False
    dobook = False
    dopay = False
    dossr = False
    dohtml = False

    if len(argv) < 1:
        usage(os.path.basename(sys.argv[0]))

    opts, args = getopt.getopt(argv,
                               "cfhivyVB:C:D:E:F:G:I:K:L:M:N:P:Q:R:S:T:U:X:Y:",
                               ["help",
                                "avail", "book", "detail", "price", "pay",
                                "chk", "ssr", "html",
                                "bn=", "dob=", "card=", "req=",
                                "date=", "edate=", "flight=", "rflight="])

    for opt, arg in opts:
        if opt == '-h' or opt == '--help':
            usage(os.path.basename(sys.argv[0]))
        elif opt == '-v':
            logger.setLevel(logging.INFO)
        elif opt == '-V':
            logger.setLevel(logging.DEBUG)
        elif opt == '--html':
            dohtml = True
        elif opt == '--avail':
            doavail = True
        elif opt == '--book':
            dobook = True
        elif opt == '--chk':
            logger.debug("Check booking")
            dochk = True
        elif opt == '--detail':
            dodetail = True
        elif opt == '--price':
            doprice = True
        elif opt == '--pay':
            dopay = True
        elif opt == '--ssr':
            dossr = True
        elif opt in ('-B', '--bn'):
            bn = int(arg)
            logger.debug("Booking number %d" % bn)
        elif opt in ("-C", "--class"):
            sellClass = str(arg).upper()
        elif opt in ("-D", "--date"):
            dt1 = ReadDate(arg)
            logger.info("\t flight date %s" % dt1.strftime("%Y-%m-%d"))
        elif opt in ("-E", "--edate"):
            logger.info("\t end date %s" % dt1.strftime("%Y-%m-%d"))
            dt2 = ReadDate(arg)
        elif opt in ("-F", "--flight"):
            if ',' in arg:
                fndata = arg.split('/')
                flightNumber = fndata[0]
                dt1 = ReadDate(fndata[1])
            else:
                flightNumber = arg
            logger.debug("Flight number set to %s" % flightNumber)
        elif opt in ("-G", "--rflight"):
            if ',' in arg:
                fndata = arg.split('/')
                flightNumber2 = fndata[0]
                dt2 = ReadDate(fndata[1])
            else:
                flightNumber2 = arg
            logger.debug("Flight number set to %s" % flightNumber)
        elif opt == "-K":
            groupName = str(arg)
        elif opt == "-L":
            paxCount = int(arg)
        elif opt in ("-M", "--dob"):
            paxDobs = str(arg).upper().split(',')
        elif opt in ("-N", "--name"):
            paxNames = str(arg).upper().split(',')
        elif opt in ("-P", "--depart"):
            departAirport = str(arg).upper()
            logger.info("\t depart %s" % departAirport)
        elif opt in ("-Q", "--arrive"):
            arriveAirport = str(arg).upper()
            logger.info("\t arrive %s" % arriveAirport)
        elif opt in ("-R", "--amount"):
            payAmount = float(arg)
        elif opt in ("-S", "--ramount"):
            payAmount2 = float(arg)
        elif opt in ("-T", "--card"):
            vDocNum = str(arg)
        elif opt in ("-U", "--req"):
            vSsr = str(arg).split(':')
            reqCode =  vSsr[0]
            reqText = vSsr[1]
        elif opt == "-X":
            departTime = arg
        elif opt == "-Y":
            arriveTime = arg
        else:
            pass

    if bn is not None:
        pnr = int2base20(bn)
        print("Booking %d PNR %s" % (bn, pnr))

    cfg = BarsConfig('%s/bars.cfg' % etcdir)

    # Open connection to database
    conn = OpenDb(cfg.dbname, cfg.dbuser, cfg.dbhost)

    if sellClass is None:
        sellClass = cfg.SellingClass

    if dochk:
        print("Check booking %d" % bn)
        GetPreBookingInfo(conn, bn)
        return 0

    if dt1 is None and bn is None:
        print("No departure date or booking number specified")
        return 1

    if dt2 is None:
        dt2 = dt1

    selling_classes = get_selling_conf(conn, cfg.CompanyCode)
    if doavail:
        cityPairNo = GetCityPair(conn, departAirport, arriveAirport)
        GetAvail(conn, dt1, dt2, cityPairNo,
                 departAirport, arriveAirport,
                 selling_classes, cfg.CompanyCode)
    elif dodetail:
        GetFlightDetails(conn, flightNumber, dt1, departAirport, arriveAirport)
        if flightNumber2 is not None and dt2 is not None:
            GetFlightDetails(conn, flightNumber2, dt2, departAirport,
                             arriveAirport)
    elif doprice:
        if dohtml:
            msg = GetPriceHtml(conn,
                               cfg.CompanyCode,
                               departAirport, arriveAirport,
                               dt1, dt1,
                               sellClass,
                               cfg.OnwReturnIndicator,
                               cfg.FareCategory,
                               cfg.AuthorityLevel)
            print("%s\n" % msg)
        else:
            GetPrice(conn,
                    cfg.CompanyCode,
                    departAirport, arriveAirport,
                    dt1, dt2,
                    sellClass,  # cfg.SellingClass,
                    cfg.OnwReturnIndicator,
                    cfg.FareCategory,
                    cfg.AuthorityLevel)
    elif dobook:
        bn = DoBook(conn, cfg, paxCount, groupName, paxNames, paxDobs,
                    flightNumber, dt1,
                    departAirport, arriveAirport,
                    sellClass,
                    vTimeLimit, payAmount)
        if dopay:
            DoPay(conn, cfg, bn,departAirport, arriveAirport,
                  payAmount, payAmount2, vDocNum, sellClass)
    elif dopay:
        DoPay(conn, cfg, bn,departAirport, arriveAirport,
              payAmount, payAmount2, vDocNum, sellClass)
    elif dossr:
        DoRequest(conn, cfg, bn, paxCount, reqCode, reqText, None, None)
    elif bn is not None:
        GetPassengers(conn, bn)
        GetItinerary(conn, bn)
        ReadPayments(conn, bn)
    else:
        print("Nothing to do")

    CloseDb(conn)

    return 0
Exemplo n.º 5
0
def main(argv):
    """Pythonic entry point."""
    barsdir = os.environ['BARSDIR']
    etcdir = "%s/etc" % barsdir
    flight_number = None
    dt1 = None
    dt2 = None
    asm_ssm = False
    ssm_data = False
    ssm_book = False
    ssm_tim = False
    ssmdir = None
    ssmfile = None
    departure_time = "11:00"
    arrival_time = "13:00"
    departure_airport = None
    arrival_airport = None
    aircraft_code = None

    if len(argv) < 1:
        usage()

    try:
        opts, args = getopt.getopt(
            argv, "cfhivyV"
            "A:B:C:D:E:F:I:K:L:M:N:P:Q:R:S:T:X:Y:", [
                "help", "date=", "edate=", "flight=", "period=", "seats=",
                "days=", "class=", "locator=", "bookno=", "depart=", "arrive=",
                "aircraft=", "freq=", "cfgtable=", 'msg', 'ssm', 'tim',
                'error', 'success', 'cfg', 'contact', 'ssmdata', 'ssmbook'
            ])
    except getopt.GetoptError:
        print("Error in options")
        sys.exit(1)

    for opt, arg in opts:
        if opt == '-h' or opt == '--help':
            usage()
        elif opt == '--ssm':
            asm_ssm = True
        elif opt == '--ssmdata':
            ssm_data = True
        elif opt == '--tim':
            ssm_tim = True
        elif opt == '--ssmbook':
            ssm_book = True
        elif opt == '-A':
            aircraft_code = str(arg)
        elif opt in ("-D", "--date"):
            dt1 = ReadDate(arg)
            logger.info("\t flight date %s" % dt1.strftime("%Y-%m-%d"))
        elif opt in ("-E", "--edate"):
            dt2 = ReadDate(arg)
        elif opt in ("-F", "--flight"):
            if '/' in arg:
                fndata = arg.split('/')
                flight_number = fndata[0]
                dt1 = ReadDate(fndata[1])
            else:
                flight_number = arg
            ssm_data = True
        elif opt in ("-P", "--depart"):
            departure_airport = str(arg).upper()
            logger.info("\t depart %s" % departure_airport)
        elif opt in ("-Q", "--arrive"):
            arrival_airport = str(arg).upper()
            logger.info("\t arrive %s" % arrival_airport)
        elif opt == '-S':
            ssmfile = arg
        elif opt == '-T':
            ssmdir = arg
        elif opt == '-v':
            # Debug output
            logger.setLevel(logging.INFO)
        elif opt == '-V':
            # Debug output
            logger.setLevel(logging.DEBUG)
        elif opt == '-X':
            departure_time = str(arg)
        elif opt == '-Y':
            arrival_time = str(arg)
        else:
            print("Unknown option %s" % opt)
            return 1

    procssm = "%s/support/bin/procssm" % os.environ['BARSDIR']

    cfg = BarsConfig('%s/bars.cfg' % etcdir)

    # Open connection to database
    conn = OpenDb(cfg.dbname, cfg.dbuser, cfg.dbhost)

    if ssmfile is not None:
        check_ssm_file(procssm, ssmfile)
    elif flight_number is None:
        pass
    else:
        if ssm_tim and dt1 is not None and dt2 is not None:
            flight = FlightData(cfg.SellingClass, flight_number, dt1,
                                departure_time, arrival_time,
                                departure_airport, arrival_airport, 0,
                                company_code, aircraft_code)
            n = ReadSsmTim(conn, flight, dt1, dt2, frequency_code)
            if n == 0:
                CheckSsmTim(conn, flight, dt1, dt2, frequency_code,
                            aircraft_code)
        elif ssm_data and dt1 is not None:
            flight = FlightData(cfg.SellingClass, flight_number, dt1,
                                departure_time, arrival_time,
                                departure_airport, arrival_airport, 0,
                                company_code, aircraft_code)
            ReadSsmFlightData(conn, flight, dt2)
        elif ssm_book and flight_number is not None and dt1 is not None:
            flight = FlightData(cfg.SellingClass, flight_number, dt1,
                                departure_time, arrival_time,
                                departure_airport, arrival_airport, 0,
                                company_code, aircraft_code)
            ReadSsmBookData(conn, flight, schedule_period_no)
        elif asm_ssm:
            if aircraft_code is None:
                print("No value for aircraft code")
                conn.close()
                return 1
            if dt1 is None or dt2 is None:
                print("No value for start and/or end dates")
                conn.close()
                return 1
            if frequency_code is None:
                print("No value for frequency code")
                conn.close()
                return 1
            ConfigTableNo, NoOfSeats = ReadConfigNumberOfSeats(
                conn, aircraft_code)
            viaCities = "%3s#%3s" % (departure_airport, arrival_airport)
            ReadSchedPeriod(conn, dt1, dt2, frequency_code, flight_number,
                            frequency_code, viaCities, ConfigTableNo)
            n = GetFlightDataSsm(conn, flight_number, dt1, dt2, frequency_code)
            if n == 0:
                CheckSsmTim(conn, flight, dt1, dt2, frequency_code,
                            aircraft_code)
        else:
            print("Say again?")

    # Commit transaction and close connection
    conn.commit()
    conn.close()

    return 0
Exemplo n.º 6
0
def read_ssm_file(procssm, fname):
    """Read SSM file."""
    t = os.path.getmtime(fname)
    dt = datetime.datetime.fromtimestamp(t).strftime('%Y-%m-%d %H:%M:%S')
    logger.info("Read %s %s" % (fname, dt))
    procf = "%s -X %s" % (procssm, fname)
    logger.info("%s" % procf)
    tmp = os.popen(procf).read()
    ssm_lines = tmp.split('\n')
    tzone = ''
    flight_number = None
    dt1 = None
    dt2 = None
    depart = None
    arrive = None
    tdep = None
    tarr = None
    aircraft_code = None
    cabin_class = '?'
    cabin_seats = 0
    for ssm_line in ssm_lines:
        logger.debug("%s" % ssm_line)
        ssm_datas = ssm_line.split(':')
        ssmi = ssm_datas[0]
        if ssmi == "Z":
            tzone = ssm_datas[1]
            logger.info("Time zone %s" % tzone)
        elif ssmi == "F":
            flight_number = ssm_datas[1]
            logger.info("Flight %s" % flight_number)
        elif ssmi == "D":
            date_data = ssm_datas[1].split(" ")
            dt1 = ReadDate(date_data[0])
            dt2 = ReadDate(date_data[1])
            logger.info("From %s to %s" %
                        (dt1.strftime("%Y-%m-%d"), dt2.strftime("%Y-%m-%d")))
        elif ssmi == "L":
            legs = ssm_datas[1].split(" ")
            depart = legs[0]
            tdep = int(legs[1])
            arrive = legs[2]
            tarr = int(legs[3])
            if tzone == 'UTC':
                tdep += 200
                tarr += 200
            logger.info("Depart %s %04d arrive %s %d" %
                        (depart, tdep, arrive, tarr))
        elif ssmi == "T":
            configs = ssm_datas[1].split(" ")
            aircraft_code = configs[0]
            logger.info("Aircraft code %s" % aircraft_code)
        elif ssmi == "C":
            # cabins = ssm_datas[1].split(" ")
            cabins = ssm_datas[1]
            cabin_class = cabins[0]
            cabin_seats = int(cabins[1:])
            logger.info("Cabin class %s seats %d" % (cabin_class, cabin_seats))
        elif ssmi == "S10":
            codeshare = ssm_datas[1]
            logger.info("Codeshare %s" % codeshare)
        else:
            pass
Exemplo n.º 7
0
class WriteSsmData():

    ftype = None  # file type i.e. NEW, CNL, TIM or EQT
    Address = None  # origin address
    Sender = None  # sender address
    TimeMode = None  # time mode - local or UTC
    FlightNumber = None  # flight number
    FlightDateStart = None  # start date
    FlightDateEnd = None  # end date
    DepartCity = None  # departure airport
    DepartTime = None  # departure time
    ArriveCity = None  # arrival airport
    ArriveTime = None  # arrival time
    AircraftCode = None  # aircraft configuration code
    FrequencyCode = None  # frequency code
    Codeshare = None  # codeshare flight number
    SeatCount = None  # number of seats
    BookingClasses = None  # booking classes
    TailNumber = None  # aircraft tail number

    def __init___(self, aftype, aAddress, aSender, aTimeMode, aFlightNumber,
                  aFlightDateStart, aFlightDateEnd, aDepartCity, aDepartTime,
                  aArriveCity, aArriveTime, aAircraftCode, aFrequencyCode,
                  aCodeshare, aTailNumber):
        """ Constructor. """
        self.ftype = aftype
        self.Address = aAddress
        self.Sender = aSender
        self.TimeMode = aTimeMode
        self.FlightNumber = str(aFlightNumber)
        self.FlightDateStart = ReadDate(aFlightDateStart)
        self.FlightDateEnd = ReadDate(aFlightDateEnd)
        self.DepartCity = str(aDepartCity)
        logger.debug("Depart %s" % self.DepartCity)

        self.DepartTime = ReadTime(aDepartTime)
        logger.debug("Depart time '%s'" % self.DepartTime)

        self.ArriveCity = str(aArriveCity)
        logger.debug("Arrive %s" % self.ArriveCity)

        self.ArriveTime = ReadTime(aArriveTime)
        logger.debug("Arrive time '%s'" % self.ArriveTime)

        self.AircraftCode = aAircraftCode
        logger.debug("Aircraft code '%s'" % self.AircraftCode)

        self.FrequencyCode = str(aFrequencyCode)
        logger.debug("Frequency '%s'" % self.FrequencyCode)

        self.Codeshare = aCodeshare
        logger.debug("Codeshare '%s'" % self.Codeshare)

        if self.AircraftCode == "733":
            self.SeatCount = "Y144"
            self.BookingClasses = "YZAUSBMPDITHQVWLXRNGEFKJO144"
        elif self.AircraftCode == "738":
            self.SeatCount = "C2Y186"
            self.BookingClasses = "C002YZAUSBMPDITHQVWLXRNGEFKJO186"
        elif self.AircraftCode == "320":
            self.SeatCount = "Y180"
            self.BookingClasses = "YZAUSBMPDITHQVWLXRNGEFKJO177"
        elif self.ftype == "CNL":
            # No aircraft code needed here
            self.SeatCount = None
            self.BookingClasses = None
        else:
            logger.error("Unknown aircraft code '%s'" % self.AircraftCode)
            raise 1

        if aTailNumber is None and self.ftype != "CNL":
            self.TailNumber = "ZS"
            self.TailNumber += self.DepartCity[0]
            self.TailNumber += self.ArriveCity[0]
            self.TailNumber += (aDepartTime / 100) + 65
        else:
            TailNumber = aTailNumber

        try:
            # Weekday as a decimal number 0(Sunday), 1(Monday) to 6(Saturday)
            sdate = str(self.FlightDateStart.strftime("%w"))
            if sdate == "0":
                sdate = "7"
            edate = str(self.FlightDateEnd.strftime("%w"))
            if edate == "0":
                edate = "7"

            if sdate not in self.FrequencyCode:
                logger.error("Start %s day of week %d not in frequency %s" %
                             (self.FlightDateStart, sdate, self.FrequencyCode))
                raise WriteSsmDataError

            if edate not in self.FrequencyCode:
                logger.error("End %s day of week %d not in frequency %s" %
                             (self.FlightDateEnd, edate, self.FrequencyCode))
                raise WriteSsmDataError

        except Exception:
            logger.error("Some sort of date error")
            raise WriteSsmDataError

        # logger.debug("Start %s end %s" % date1, date2)

        now = time(0)  # get time now
        if self.TimeMode == "LT":
            nowstruct = time.time()
        elif self.TimeMode == "UTC":
            nowstruct = time.gmtime()
        else:
            logger.error("Invalid time mode %s" % self.TimeMode)
            raise WriteSsmDataError
        self.timenow = nowstruct.strftime("%H%M%S")
        logger.debug("Time is %s" % self.timenow)

    def WriteCnl(self):
        '''Write cancel SSM.'''
        self.obuff = self.Address + "\n" \
            + "." + self.Sender + " " + self.timenow + "\n" \
            + "SSM\n" \
            + self.TimeMode + "\n" \
            + "CNL\n" \
            + self.FlightNumber + "\n" \
            + self.date1 + " " + self.date2 + " " + self.FrequencyCode + "\n"
        # @todo is this legit?
        if len(self.Codeshare) > 0:
            self.obuff = self.obuff + self.DepartCity + self.ArriveCity \
                    + " 10/" + self.Codeshare + "\n"

    def WriteEqt(self):
        '''Write equipment SSM.'''
        self.obuff = self.Address + "\n" \
            + "." + self.Sender + " " + self.timenow + "\n" \
            + "SSM\n" \
            + self.TimeMode + "\n" \
            + "EQT\n" \
            + self.FlightNumber + "\n" \
            + self.date1 + " " + self.date2 + " " + self.FrequencyCode + "\n" \
            + "J " + self.AircraftCode + " XX." + self.SeatCount + " " \
            + self.TailNumber + "\n" \
            + "QQQQQQ 106/" + self.BookingClasses + "\n"

    def WriteNew(self):
        '''Write new flight SSM.'''
        self.obuff = self.Address + "\n" \
            + "." + self.Sender + " " + self.timenow + "\n" \
            + "SSM\n" \
            + self.TimeMode + "\n" \
            + "NEW\n" \
            + self.FlightNumber + "\n" \
            + self.date1 + " " + self.date2 + " " + self.FrequencyCode + "\n" \
            + "J " + self.AircraftCode \
            + " XX." + self.SeatCount + " " + self.TailNumber + "\n" \
            + self.DepartCity + self.DepartTime + " " \
            + self.ArriveCity + self.ArriveTime \
            + " 7\n" \
            + self.DepartCity + self.ArriveCity + " 8/A\n" \
            + self.DepartCity + self.ArriveCity + " 99/0\n"
        if len(self.Codeshare) > 0:
            self.obuff = self.obuff + self.DepartCity + self.ArriveCity \
                + " 10/" + self.Codeshare + "\n"
        if self.AircraftCode == "738":
            self.obuff = self.obuff + self.DepartCity + self.ArriveCity \
                + " 106/C002YZAUSBMPDITHQVWLXRNGEFKJO186\n"
        elif self.AircraftCode == "733":
            self.obuff = self.obuff + self.DepartCity + self.ArriveCity \
                + " 106/YZAUSBMPDITHQVWLXRNGEFKJO144"
        elif self.AircraftCode == "320":
            self.obuff = self.obuff + self.DepartCity + self.ArriveCity \
                + " 106/YZAUSBMPDITHQVWLXRNGEFKJO177"
        else:
            # @todo something
            pass

    def WriteRpl(self):
        '''Write replace flight SSM.'''
        self.obuff = self.Address + "\n" \
            + "." + self.Sender + " " + self.timenow + "\n" \
            + "SSM\n" \
            + self.TimeMode + "\n" \
            + "RPL\n" \
            + self.FlightNumber + "\n" \
            + self.date1 + " " + self.date2 + " " + self.FrequencyCode + "\n" \
            + "J " + self.AircraftCode \
            + " XX." + self.SeatCount + " " + self.TailNumber + "\n" \
            + self.DepartCity + self.DepartTime \
            + " " + self.ArriveCity + self.ArriveTime + " 7\n" \
            + self.DepartCity + self.ArriveCity \
            + " 106/" + self.BookingClasses + "\n"
        if len(self.Codeshare):
            self.obuff = self.obuff + self.DepartCity + self.ArriveCity \
                + " 10/" + self.Codeshare + "\n"

    def WriteTim(self):
        '''Write time change SSM.'''
        obuff = self.Address + "\n" \
            + "." + self.Sender + " " + self.timenow + "\n" \
            + "SSM\n" \
            + self.TimeMode + "\n" \
            + "TIM\n" \
            + self.FlightNumber + "\n" \
            + self.date1 + " " + self.date2 + " " + self.FrequencyCode + "\n" \
            + self.DepartCity + self.DepartTime \
            + " " + self.ArriveCity + self.ArriveTime + "\n"

    def FileName(self):
        '''Generate output file name.'''
        fname = IntToRoman(self.FlightNumber[2:]) + self.FlightDateStart \
            + self.ftype \
            + self.FlightDateEnd

        return fname

    def WriteSsmFile(self, ofname):
        '''Write SSM file.'''
        rv = 0

        if self.ftype == "CNL":
            self.WriteCnl()
        elif self.ftype == "EQT":
            self.WriteEqt()
        elif self.ftype == "NEW":
            self.WriteNew()
        elif self.ftype == "RPL":
            self.WriteRpl()
        elif self.ftype == "TIM":
            self.WriteTim()
        else:
            print("Unknown file type '%s'" % self.ftype)
            raise WriteSsmDataError

        self.obuff += "\n"

        if len(ofname) == 0:
            ofname = "-"

        if ofname != "-":
            logger.debug("Write output file %s" % ofname)
            try:
                pfile = os.popen(ofname, "w")
                pfile.write(self.obuff)
                pfile.close()
            except KeyboardInterrupt:
                try:
                    pfile.close()
                except IOError:
                    pass
                return -1
            except IOError:
                pass
            # obuff += "\03\03\n"
            # fprintf(ofile, "%s", obuff)
        else:
            print("%s" % self.obuff)

        return rv
Exemplo n.º 8
0
def main(argv):

    barsdir = os.environ['BARSDIR']
    etcdir = "%s/etc" % barsdir
    fname = None
    rv = 0

    if len(argv) < 1:
        usage()

    opts, args = getopt.getopt(argv,
                               "cfhivyVA:B:C:D:E:F:I:K:L:M:N:P:Q:R:S:T:X:Y:",
                               ["help", "date=", "edate=", "flight="])

    dt1 = None
    dt2 = None
    arrive_airport = None
    depart_airport = None

    for opt, arg in opts:
        if opt == '-h' or opt == '--help':
            usage()
        elif opt == '-v':
            logger.setLevel(logging.INFO)
        elif opt == '-V':
            logger.setLevel(logging.DEBUG)
        # elif opt in ("-C", "--class"):
            # selling_cls = str(arg).upper()
        elif opt in ("-D", "--date"):
            dt1 = ReadDate(arg)
            logger.info("\t flight date %s" % dt1.strftime("%Y-%m-%d"))
        # elif opt in ("-E", "--edate"):
            # dt2 = ReadDate(arg)
        elif opt in ("-F", "--flight"):
            if ',' in arg:
                fndata = arg.split('/')
                flight_number = fndata[0]
                dt1 = ReadDate(fndata[1])
            else:
                flight_number = arg
            logger.debug("Flight number set to %s" % flight_number)
        # elif opt in ("-P", "--depart"):
            # depart_airport = str(arg).upper()
            # logger.info("\t depart %s" % depart_airport)
        # elif opt in ("-Q", "--arrive"):
            # arrive_airport = str(arg).upper()
            # logger.info("\t arrive %s" % arrive_airport)
        else:
            pass

    if dt1 is None:
        print("No departure date specified")
        return 1

    if dt2 is None:
        dt2 = dt1

    cfg = BarsConfig('%s/bars.cfg' % etcdir)

    # Open connection to database
    conn = OpenDb(cfg.dbname, cfg.dbuser, cfg.dbhost)

    GetFlightDetails(conn, flight_number, dt1, depart_airport, arrive_airport)

    conn.commit()
    conn.close()
    logger.info("Disconnected")

    return 0
Exemplo n.º 9
0
def main(argv):
    """Pythonic entry point."""
    verbose = 0
    status_flag = None
    bookno = None
    dt1 = None
    dt2 = None
    flight_pattrn = None
    flight_number = None
    PassengerName = None
    agency_code = None
    dest_id = None
    action_codes_arg = None
    locator = None
    recCount = None
    ext_locator = None
    bci_new = False
    bci_trl = False
    chk_paid = False
    bci_msk = 0
    origin_address = None
    summ_code = None
    hist_code = None
    chk_rem = False
    doSsr = False
    doPay = False
    doSeat = False
    doItenary = False
    showTty = False
    doBook = False
    doBsXml = False
    doFaresPayment = False
    payment_form = None

    if len(argv) < 1:
        usage()

    try:
        opts, args = getopt.getopt(
            argv, "1234ghnprtvV"
            "A:B:C:D:E:F:G:I:J:K:L:N:P:T:U:X:", [
                "help", "ssr", "tty"
                "book", "pay", "seat", "itinerary", "origin=", "bookno=",
                "end=", "start=", "create=", "action=", "flight=", "ext=",
                "pax=", "pay=", "dest=", "field=", "locator=", "count=",
                "depart=", "delim=", "agency"
            ])
    except getopt.GetoptError:
        print("Error in options")
        # usage()
        sys.exit(1)

    barsdir = os.environ['BARSDIR']
    etcdir = "%s/etc" % barsdir
    lstfiles = {}
    lstfiles['pay'] = [
        '%s/pay.book_no.lst' % etcdir,
        '%s/pay.locator.lst' % etcdir
    ]
    lstfiles['tty'] = [
        '%s/tty.book_no.lst' % etcdir,
        '%s/tty.locator.lst' % etcdir
    ]
    lstfiles['book'] = [
        '%s/book.book_no.lst' % etcdir,
        '%s/book.locator.lst' % etcdir
    ]
    lstfiles['seat'] = [
        '%s/seat.book_no.lst' % etcdir,
        '%s/seat.locator.lst' % etcdir
    ]
    lstfiles['itinerary'] = ['%s/itinerary.book_no.lst' % etcdir]

    for opt, arg in opts:
        if opt == '-h' or opt == '--help':
            usage()
        elif opt == '-n':
            bci_new = True
        elif opt == '-p':
            chk_paid = True
        elif opt == '-r':
            chk_rem = True
        elif opt == "--book":
            doBook = True
        elif opt == "--itinerary":
            doItenary = True
        elif opt == "--pay":
            doPay = True
        elif opt == "--seat":
            doSeat = True
        elif opt == "--ssr":
            doSsr = True
            # logger.debug("Check SSR")
        elif opt == '-t':
            bci_trl = True
        elif opt == '-1':
            bci_msk += 1
        elif opt == '-2':
            bci_msk += 2
        elif opt == '-3':
            bci_msk += 4
        elif opt == '-4':
            bci_msk += 8
        elif opt == '-v':
            # Debug output
            logger.setLevel(logging.INFO)
        elif opt == '-V':
            # Debug output
            logger.setLevel(logging.DEBUG)
        elif opt in ("-A", "--origin"):
            origin_address = arg
            # logger.debug("origin %s" % origin_address)
        elif opt in ("-B", "--bookno"):
            bookno = int(arg)
            # logger.debug("\t bookno %d" % bookno)
        elif opt in ("-C", "--create"):
            # Create date
            dt1 = ReadDate(arg)
            # logger.debug("\t start %s" % dt1.strftime("%Y-%m-%d"))
        elif opt in ("-D", "--start", "--depart"):
            # Depart date
            dt1 = ReadDate(arg)
            # logger.debug("\t start %s" % dt1.strftime("%Y-%m-%d"))
        elif opt in ("-E", "--end"):
            dt2 = ReadDate(arg)
            # logger.debug("end %s" % dt2.strftime("%Y-%m-%d"))
        elif opt in ("-F", "--flight"):
            if '%' in arg or '_' in arg or len(arg) == 0:
                flight_pattrn = arg
                # logger.debug("\t flight wildcard %s" % flight_number)
            else:
                flight_number = arg
                # logger.debug("flight number %s" % flight_number)
        elif opt in ("-G", "--agency"):
            agency_code = arg
            # logger.debug("agency %s" % agency_code)
        elif opt in ("-I", "--dest"):
            dest_id = str(arg)
            # logger.debug("dest id %s" % dest_id)
        elif opt in ("-K", "--pay"):
            payment_form = arg
        elif opt in ("-L", "--locator"):
            locator = arg
            ## logger.debug("locator %s" % locator)
        elif opt in ("-N", "--count"):
            recCount = int(arg)
            # logger.debug("count %d" % recCount)
        elif opt in ("-P", "--pax"):
            PassengerName = arg
        elif opt in ("-X", "--ext"):
            ext_locator = str(arg)
        elif opt == "--tty":
            showTty = True
        else:
            print("Unknown option %s" % opt)

    cfg = BarsConfig('%s/bars.cfg' % etcdir)

    # Open connection to database
    conn = OpenDb(cfg.dbname, cfg.dbuser, cfg.dbhost)

    if locator is not None:
        # logger.debug("Read locator %s" % locator)
        bookno = ReadLocator(conn, locator)
    elif bookno is not None:
        # logger.debug("Read booking number %d" % bookno)
        locator = ReadBookNo(conn, bookno)

    if bci_msk == 0:
        bci_msk = 0xf

    if doSsr and bookno is not None:
        if dt1 is None:
            pnr, dt1 = ReadBooking(conn, bookno)
        irecs = ReadItinerary(conn,
                              bookno,
                              None,
                              None,
                              fnumber=None,
                              start_date=None,
                              end_date=None)
        for irec in irecs:
            irec.display()
            flights = \
                ReadDeparture(conn, cfg.CompanyCode, 'Y',
                              irec.flight_number, dt1)
            if len(flights) == 0:
                print("Could not find flight %s on %s" %
                      (irec.flight_number, dt1.strftime("%Y-%m-%d")))
                return 1
            ssrs = ReadRequestsPnl(conn, bookno, cfg.CompanyCode,
                                   flights[0].departure_airport, dt1,
                                   PassengerName)
            for ssr in ssrs:
                ssr.display()
    elif bci_new and origin_address is not None and ext_locator is not None \
            and locator is not None:
        check_bci_new(conn, origin_address, ext_locator, locator, bci_msk)
    elif bci_trl and origin_address is not None and ext_locator is not None \
            and locator is not None:
        check_bci_trl(conn, origin_address, ext_locator, locator)
    elif origin_address is not None and ext_locator is not None \
            and locator is not None:
        check_bci(conn, origin_address, ext_locator, locator, bci_msk)
    elif chk_paid and bookno is not None:
        ReadBooking(conn, bookno)
        rv = BookingIsPaid(conn, bookno)
        if rv:
            print("Booking %d is paid up" % bookno)
        else:
            print("Booking %d is not paid up" % bookno)
    elif chk_rem and bookno is not None:
        ReadBookSummary(conn, bookno, summ_code)
        ReadBookSummaryHistory(conn, bookno, hist_code)
    elif doPay and bookno is not None and locator is not None:
        ReadBookingData(conn, lstfiles['pay'], bookno, locator)
    elif showTty and bookno is not None and locator is not None:
        ReadBookingData(conn, lstfiles['tty'], bookno, locator)
    elif doBook and bookno is not None:
        ReadBookingData(conn, lstfiles['book'], bookno, None)
    elif doSeat and bookno is not None:
        ReadBookingData(conn, lstfiles['seat'], bookno, None)
    elif doItenary and bookno is not None:
        ReadBookingData(conn, lstfiles['itinerary'], bookno, None)
    elif bookno is not None and locator is not None:
        ReadBookingData(conn, lstfiles['pay'], bookno, locator)
    else:
        print("Nothing to do!")

    # Commit transaction and close connection
    CloseDb(conn)

    sys.exit(0)
Exemplo n.º 10
0
def main(argv):
    """Pythonic entry point."""
    barsdir = os.environ['BARSDIR']
    if barsdir is None:
        barsdir = "/opt/bars"
    etcdir = "%s/etc" % barsdir
    docity = False
    dofare = False
    dofaredel = False
    donew = False
    doeqt = False
    dopax = False
    dopnl = False
    dotax = False
    docontact = False
    departDate = None
    arriveDate = None
    payAmount = 0
    departAirport = ''
    arriveAirport = ''
    flightNumber = ''
    codeShare = ''
    departTime = None
    arriveTime = None
    frequencyCode = '1234567'
    aircraftCode = ''
    configTable = ''
    tailNumber = ''
    cabinClasses = []
    seatCapacities = []
    aircraftName = None

    if len(argv) < 1:
        usage()

    try:
        opts, args = getopt.getopt(argv,
                                   "cfhivxyVA:D:E:F:G:I:J:K:N:P:Q:R:T:U:X:Y:",
                                   ["help", "city", "fare", "faredel",
                                    "new", "eqt", "cnl", "tim", "rpl",
                                    "utc", "pax", "contact", "tax", "pnl",
                                    "date=", "edate=", "flight=",
                                    "depart=", "arrive=", "name=",
                                    "share=", "cfg=",
                                    "aircraft=", "freq=", "cfgtable="
                                    ])
    except getopt.GetoptError:
        print("Error in options")
        sys.exit(1)

    for opt, arg in opts:
        if opt == '-h' or opt == '--help':
            usage()
        elif opt == '-v':
            # Debug output
            logger.setLevel(logging.INFO)
        elif opt == '-V':
            # Debug output
            logger.setLevel(logging.DEBUG)
        elif opt == "--city":
            docity = True
        elif opt == "--fare":
            dofare = True
        elif opt == "--faredel":
            dofaredel = True
        elif opt == "--eqt":
            doeqt = True
        elif opt == "--new":
            donew = True
        elif opt == "--pax":
            dopax = True
        elif opt == "--pnl":
            dopnl = True
        elif opt == "--tax":
            dotax = True
        elif opt == "--contact":
            docontact = True
        elif opt == "-A" or opt == "--aircraft":
            aircraftCode = str(arg).upper()
            logger.debug("aircraft code %s" % aircraftCode)
        elif opt in ("-D", "--date"):
            departDate = ReadDate(arg)
            logger.debug("start date %s" % departDate.strftime("%Y-%m-%d"))
        elif opt in ("-E", "--edate"):
            arriveDate = ReadDate(arg)
            logger.debug("end date %s" % departDate.strftime("%Y-%m-%d"))
        elif opt in ("-F", "--flight"):
            flightNumber = arg
        elif opt in ("-G", "--share"):
            codeShare = arg
        elif opt in ("-I", "--cabin"):
            cabinClasses = str(arg).split(',')
            logger.debug("classes %s" % cabinClasses)
        elif opt in ("-J", "--seat"):
            seatCapacities = str(arg).split(',')
            logger.debug("seats %s" % seatCapacities)
        elif opt in ("-K", "--freq"):
            frequencyCode = str(arg)
        elif opt in ("-N", "--name"):
            aircraftName = str(arg)
        elif opt in ("-P", "--depart"):
            departAirport = str(arg).upper()
            logger.debug("depart %s" % departAirport)
        elif opt in ("-Q", "--arrive"):
            arriveAirport = str(arg).upper()
            logger.debug("arrive %s" % arriveAirport)
        elif opt in ("-R", "--amount"):
            payAmount = int(arg)
            logger.debug("payment %d" % payAmount)
        elif opt in ("-T", "--tail"):
            tailNumber = str(arg)
            logger.debug("tail number %s" % tailNumber)
        elif opt in ("-U", "--cfg"):
            configTable = str(arg)
            logger.debug("configuration %s" % configTable)
        elif opt == "-X":
            departTime = ReadTime(arg)
            logger.debug("depart time %s" % departTime)
        elif opt == "-Y":
            arriveTime = ReadTime(arg)
            logger.debug("arrive time %s" % arriveTime)
        else:
            print("Unknown option '%s'" % opt)
            return 1

    files = []
    for arg in args:
        files.append(arg.strip())

    cfg = BarsConfig('%s/bars.cfg' % etcdir)

    # Open connection to database
    conn = OpenDb(cfg.dbname, cfg.dbuser, cfg.dbhost)

    if donew and flightNumber != '' \
            and departDate is not None \
            and arriveDate is not None \
            and departTime is not None \
            and arriveTime is not None \
            and departAirport != '' \
            and arriveAirport != '' \
            and frequencyCode != '' \
            and tailNumber != '':
        NewFlight(conn, cfg.Address, cfg.Sender, cfg.TimeMode,
                  flightNumber, departDate, arriveDate,
                  departAirport, departTime, arriveAirport, arriveTime,
                  frequencyCode, codeShare, tailNumber,
                  cfg.User, cfg.Group)
    elif donew and len(cabinClasses) > 0 \
            and len(seatCapacities) > 0 \
            and aircraftCode != '' \
            and tailNumber != '' \
            and configTable != '':
        cfgt = CheckAircraftConfig(conn, cfg.CompanyCode, aircraftCode,
                                   cabinClasses, seatCapacities)
        if cfgt is None:
            WriteEquipmentConfig(conn, cfg.CompanyCode, aircraftCode,
                                 tailNumber, configTable, cabinClasses,
                                 seatCapacities, cfg.User, cfg.Group)
            AddAircraftConfig(conn, cfg.CompanyCode, aircraftCode, configTable,
                              cabinClasses, seatCapacities,
                              cfg.User, cfg.Group)
        else:
            print("Found configuration %s" % cfgt)
            eqt = ReadEquipmentConfig(conn, tailNumber)
            if eqt is None:
                WriteEquipmentConfig(conn, cfg.CompanyCode, aircraftCode,
                                     tailNumber, cfgt, cabinClasses,
                                     seatCapacities, cfg.User, cfg.Group)
            else:
                eqt.display()
    elif donew and aircraftCode != '' \
            and aircraftName != '':
        AddAircraft(conn, aircraftCode, aircraftName)
    elif docity and departAirport != '' \
            and arriveAirport != '':
        NewCityPair(conn, departAirport, arriveAirport,
                    cfg.User, cfg.Group)
    elif dopax and flightNumber != '' and departDate is not None:
        ReadFlightBookings(conn, flightNumber, departDate)
    elif dopnl and flightNumber != '' and departDate is not None:
        ReadFlightBookings(conn, flightNumber, departDate, "A")
    elif docontact and flightNumber != '' and departDate is not None:
        ReadFlightContacts(conn, flightNumber, departDate)
    elif docity:
        ReadCityPairs(conn)
    elif dofare and departAirport != '' \
            and arriveAirport != '' and departDate is not None \
            and arriveDate is not None:
        city_pair = GetCityPair(conn, departAirport, arriveAirport)
        if city_pair > 0:
            AddFareSegments(conn, cfg.CompanyCode,
                            departAirport, arriveAirport, city_pair,
                            departDate, arriveDate, payAmount,
                            cfg.User, cfg.Group)
            AddFares(conn, cfg.CompanyCode, departAirport, arriveAirport,
                     cfg.SellingClasses, cfg.User, cfg.Group)
    elif dofaredel and departAirport != '' \
            and arriveAirport != '' \
            and departDate is not None \
            and arriveDate is not None:
        DelFareSegments(conn, cfg.CompanyCode,
                        departAirport, arriveAirport, departDate, arriveDate)
    elif doeqt and tailNumber != '':
        ReadEquipment(conn, tailNumber)
    elif dofare:
        ReadFareCodes(conn)
        ReadFareSegments(conn)
    elif dotax and departAirport != '' and departDate is not None:
        GetTaxes(conn, cfg.CompanyCode, departDate, arriveDate, departAirport)
    else:
        print("Huh?")

    # Commit transaction and close connection
    CloseDb(conn)

    return 0