Esempio n. 1
0
def calc_worksheettopdf():
    try:
        args = request.args.to_dict()
        print(args)
        db = config.get_database()
        calcs = db.select('Calc', **args)
        result = ""
        for calc in calcs:
            result += generate_worksheet_from_calc(calc, 'n')
            result += "<hr>"

        # text_file = open("out.html", "w", encoding="utf-8")
        # text_file.write(result)
        # text_file.write(result. .encode("UTF-8"))
        # text_file.close()

        print("about to set path")
        path_wkthmltopdf = r'C:\Program Files (x86)\wkhtmltopdf\bin\wkhtmltopdf.exe'
        print("about to set config")
        configpdf = pdfkit.configuration(wkhtmltopdf=path_wkthmltopdf)
        print("about to pdfkit")
        pdfkit.from_string(result, 'out.pdf', configuration=configpdf)

        return "pdf should have been created"

    except Exception as e:
        print('PDF worksheet: ***Error:', e)
        traceback.print_exc(file=sys.stdout)
        tb = traceback.format_exc()
        return "<h2>Error generating pdf" + \
               '<plaintext>' + tb + '</plaintext>'
def generate_worksheet(well_id, prod_month, rpba):
    try:
        db = config.get_database()
        product = "OIL"
        well = db.select1('WellRoyaltyMaster', ID=well_id)
        well_lease_link_array = db.select('WellLeaseLink', WellID=well_id)
        if len(well_lease_link_array) == 0:
            raise AppError("There were no well_lease_link records for " + str(well_id) + str(prod_month))
        well_lease_link = well_lease_link_array[0]
        royalty = db.select1('LeaseRoyaltyMaster', ID=well_lease_link.LeaseID)
        royalty.format_gorr = format_gorr(royalty.Gorr)
        lease = db.select1('Lease', ID=well_lease_link.LeaseID)

        if rpba:
            monthly_array = db.select('Monthly', WellID=well_id, prodMonth=prod_month, product=product, RPBA=rpba)
        else:
            monthly_array = db.select('Monthly', WellID=well_id, prodMonth=prod_month, product=product)
        if len(monthly_array) == 0:
            raise AppError("There were no monthly records for " + str(well_id) + str(prod_month) + product)
        monthly = monthly_array[0] # if there are multiple pick the first one

        ba = db.select1('BAInfo',BAid=monthly.RPBA)
        calc = db.select1('Calc', WellID=well_id, ProdMonth=prod_month,RPBA=monthly.RPBA)
        rtp_info = db.select1('RTPInfo', WellEvent=well.WellEvent, Product=product, Payer=monthly.RPBA,
                                   Date=prod_month_to_date(prod_month))
        # calc = calc_array[0]
        # print(monthly)
        return render_template('worksheet/calc_worksheet.html',
                               well=well, rm=royalty, m=monthly, lease=lease,
                               calc=calc, well_lease_link=well_lease_link, ba=ba, rtp_info=rtp_info)
    except Exception as e:
        print('views.worksheet: ***Error:', e)
        traceback.print_exc(file=sys.stdout)
        return "<h2>Error displaying worksheet for well %s</h2><br>" % well_id + str(e)
def details(wellevent_num):
    if not wellevent_num: redirect(url_for('wellevents.search'))
    try:
        db = config.get_database()
        statement="""SELECT WellEventInfo.*, RTAMineralOwnership.Product
        FROM WellEventInfo
        LEFT OUTER JOIN RTAMineralOwnership ON WellEventInfo.WellEvent = RTAMineralOwnership.WellEvent
        AND (DATE('{proddate}') BETWEEN RTAMineralOwnership.StartDate AND RTAMineralOwnership.EndDate)
        WHERE (DATE('{proddate}') BETWEEN WellEventInfo.StartDate AND WellEventInfo.EndDate)
        AND WellEventInfo.WellEvent = '{wellevent}'""".format(proddate=get_proddate(), wellevent=wellevent_num)
        wellevent = db.select_sql(statement)[0]
    except Exception as e:
        print(e)
        abort(404)

    statement_volumetric = """SELECT * From VolumetricInfo WHERE FromTo = '{wellevent}' AND DATE(ProdMonth) = DATE('{proddate}')""".format(wellevent=wellevent_num, proddate=get_proddate())
    volumetric = db.select_sql(statement_volumetric)

    try:
        well = db.select1('WellRoyaltyMaster', WellEvent=wellevent_num)

        statement_leases = """SELECT Lease.*, WellLeaseLink.PEFNInterest FROM Lease, WellLeaseLink WHERE WellLeaseLink.WellID="%s" AND Lease.ID=WellLeaseLink.LeaseID"""
        leases = db.select_sql(statement_leases % well.ID)

        statement_facilities = """SELECT FacilityInfo.* FROM FacilityInfo, WellFacilitylink WHERE FacilityInfo.Facility=WellFacilitylink.Facility AND WellFacilitylink.WellEvent="%s" """
        facilities = db.select_sql(statement_facilities % wellevent_num)
    except Exception as e:
        print(e)
        pass

    return render_template('wellevent/details.html', wellevent=wellevent, leases=leases, facilities=facilities, volumetric=volumetric, well=well)
Esempio n. 4
0
def calc_worksheet():
    args = request.args.to_dict()
    db = config.get_database()
    calcs = db.select('Calc', **args)
    result = ""
    for calc in calcs:
        result += generate_worksheet_from_calc(calc)
        # result += "<hr>"

    return result
Esempio n. 5
0
def generate_pdfworksheet_from_calc(calc):
    try:
        db = config.get_database()
        if calc.Entity == 'Well':
            well = db.select1('WellRoyaltyMaster', ID=calc.EntityID)
        else:
            well = None
        entity_lease_link_array = db.select('EntityLeaseLink', Entity=calc.Entity, EntityID=calc.EntityID)
        if len(entity_lease_link_array) == 0:
            raise AppError("There were no well_lease_link records for " + str(calc.WellID) + str(calc.ProdMonth))
        entity_lease_link = entity_lease_link_array[0]
        royalty = db.select1('LeaseRoyaltyMaster', ID=calc.LeaseID)
        lease = db.select1('Lease', ID=calc.LeaseID)

        history = db.select_sql("""SELECT ID, ExtractDate, BaseNetRoyaltyValue, GorrNetRoyaltyValue
                   from Calc
                   WHERE ProdMonth = "{}" and LeaseID = "{}" and Entity = "{}" and EntityID = "{}"
                   and Product = "{}" and RPBA = "{}"
                   order by ExtractDate""".format(calc.ProdMonth, calc.LeaseID, calc.Entity, calc.EntityID,
                                                  calc.Product, calc.RPBA))

        prev_BaseNetRoyaltyValue = 0.0
        prev_GorrNetRoyaltyValue = 0.0
        for h in history:
            h.BookedBaseNetRoyaltyValue = h.BaseNetRoyaltyValue - prev_BaseNetRoyaltyValue
            h.BookedGorrNetRoyaltyValue = h.GorrNetRoyaltyValue - prev_GorrNetRoyaltyValue
            h.Booked = h.BookedBaseNetRoyaltyValue + h.BookedGorrNetRoyaltyValue
            prev_BaseNetRoyaltyValue = h.BaseNetRoyaltyValue
            prev_GorrNetRoyaltyValue = h.GorrNetRoyaltyValue

        monthly_array = db.select('Monthly', ExtractDate=calc.ExtractDate, Entity=calc.Entity, EntityID=calc.EntityID,
                                  prodMonth=calc.ProdMonth, product=calc.Product, RPBA=calc.RPBA)
        if len(monthly_array) == 0:
            raise AppError("There were no monthly records for well: " + str(calc.WellID) + " ProdDate: " +
                           str(calc.ProdMonth) + " Product: " + calc.Product)
        monthly = monthly_array[0]  # if there are multiple pick the first one

        ba = db.select1('BAInfo', BAid=monthly.RPBA, BAType='RTP')

        calc_specific = DataStructure(calc.RoyaltySpecific)
        rtp_info = db.select1('RTPInfo', WellEvent=well.WellEvent, Product=calc.Product, Payer=monthly.RPBA,
                              Date=prod_month_to_date(calc.ProdMonth))

        royalty.format_gorr = format_gorr(calc.Gorr)

        return render_template('worksheet/pdfcalc_worksheet.html',
                               well=well, rm=royalty, m=monthly, lease=lease,
                               calc=calc, calc_sp=calc_specific, entity_lease_link=entity_lease_link,
                               ba=ba, rtp_info=rtp_info, history=history)
    except Exception as e:
        print('views.worksheet: ***Error:', e)
        traceback.print_exc(file=sys.stdout)
        tb = traceback.format_exc()
        return "<h2>Error displaying worksheet for " + calc.Entity + " %s</h2><br>" % calc.EntityID + str(e) + \
               '<plaintext>' + tb + '</plaintext>'
Esempio n. 6
0
def band():
    try:
        db = config.get_database()
        statement = """SELECT * FROM FNBand
                       WHERE FNBandName LIKE "%{bandname}%"
                    """.format(bandname=request.args['FNBandName'])
        results = db.select_sql(statement)
        return render_template('lookups/band_results.html', results=results)
    except Exception as e:
        print(e)
        return 'Something went wrong fetching bands'
Esempio n. 7
0
def app_help():
    help_item = request.args['item']
    try:
        db = config.get_database()
        v = help_item.split('.')
        data = db.select1('DataDictionary', TableName=v[0], Attribute=v[1])
        if not data.Documentation:
            data.Documentation = 'Help text has not been entered for ' + help_item
        else:
            data.Documentation = resolve_lookups_in_description(data.Documentation)
        return data.Documentation
    except Exception as e:
        print(e)
        return 'Help text not found in the Data Dictionary...'
Esempio n. 8
0
def ba_results():
    db = config.get_database()
    statement = """SELECT * FROM BAInfo
                    WHERE (DATE('{proddate}') BETWEEN BAInfo.StartDate AND BAInfo.EndDate OR
                    BAInfo.StartDate IS NULL)""".format(proddate=get_proddate())
    argument_tables = {'CorpLegalName': 'BAInfo', 'BAType': 'BAInfo', 'BAid': 'BAInfo'}
    kwargs = dict((k, v) for k, v in request.args.items() if v)  # this is to get rid of empty values coming from forms
    search_arguments = ""
    for arg in kwargs:
        if arg in argument_tables:
            compound = argument_tables[arg] + '.' + arg + '=' + '"' + kwargs[arg] + '"'
            if arg == 'CorpLegalName':
                compound = argument_tables[arg] + '.' + arg + ' LIKE ' + '"%' + kwargs[arg] + '%"'
            search_arguments += " AND " + compound
    print(statement + search_arguments)
    results = db.select_sql(statement + search_arguments)
    return render_template('lookups/ba_results.html', results=results)
Esempio n. 9
0
def details(wellevent_num):
    if not wellevent_num: redirect(url_for('wellevents.search'))
    try:
        db = config.get_database()
        statement = """SELECT WellEventInfo.*, RTAMineralOwnership.Product
        FROM WellEventInfo
        LEFT OUTER JOIN RTAMineralOwnership ON WellEventInfo.WellEvent = RTAMineralOwnership.WellEvent
        AND (DATE('{proddate}') BETWEEN RTAMineralOwnership.StartDate AND RTAMineralOwnership.EndDate)
        WHERE (DATE('{proddate}') BETWEEN WellEventInfo.StartDate AND WellEventInfo.EndDate)
        AND WellEventInfo.WellEvent = '{wellevent}'""".format(
            proddate=get_proddate(), wellevent=wellevent_num)
        wellevent = db.select_sql(statement)[0]
    except Exception as e:
        print(e)
        abort(404)

    statement_volumetric = """SELECT * From VolumetricInfo WHERE FromTo = '{wellevent}' AND DATE(ProdMonth) = DATE('{proddate}')""".format(
        wellevent=wellevent_num, proddate=get_proddate())
    volumetric = db.select_sql(statement_volumetric)

    try:
        well = db.select1('WellRoyaltyMaster', WellEvent=wellevent_num)

        statement_leases = """SELECT Lease.*, WellLeaseLink.PEFNInterest FROM Lease, WellLeaseLink WHERE WellLeaseLink.WellID="%s" AND Lease.ID=WellLeaseLink.LeaseID"""
        leases = db.select_sql(statement_leases % well.ID)

        statement_facilities = """SELECT FacilityInfo.* FROM FacilityInfo, WellFacilitylink WHERE FacilityInfo.Facility=WellFacilitylink.Facility AND WellFacilitylink.WellEvent="%s" """
        facilities = db.select_sql(statement_facilities % wellevent_num)
    except Exception as e:
        print(e)
        pass

    return render_template('wellevent/details.html',
                           wellevent=wellevent,
                           leases=leases,
                           facilities=facilities,
                           volumetric=volumetric,
                           well=well)
Esempio n. 10
0
def search():
    if not request.args: return render_template('wellevents/search.html')
    statement = """SELECT WellEventInfo.WellEvent, RTAHeader.RTPOperator, WellEventStatus.Status, WellLicence.Licensee, BAInfo.CorpShortName, WellFacilitylink.Facility, FacilityInfo.Name, WellEventLoc.Lat, WellEventLoc.Long
    FROM WellEventInfo
    LEFT OUTER JOIN RTAHeader ON WellEventInfo.WellEvent = RTAHeader.WellEvent
    AND (DATE('{proddate}') BETWEEN RTAHeader.StartDate AND RTAHeader.EndDate OR RTAHeader.StartDate IS NULL OR RTAHeader.StartDate = '')
    LEFT OUTER JOIN WellEventStatus ON WellEventInfo.WellEvent = WellEventStatus.WellEvent
    AND (DATE('{proddate}') BETWEEN WellEventStatus.StartDate AND WellEventStatus.EndDate OR WellEventStatus.StartDate IS NULL OR WellEventStatus.StartDate = '')
    LEFT OUTER JOIN BAInfo ON RTAHeader.RTPOperator = BAInfo.BAid
    AND (DATE('{proddate}') BETWEEN BAInfo.StartDate AND BAInfo.EndDate OR BAInfo.StartDate IS NULL OR BAInfo.StartDate = '')
    LEFT OUTER JOIN WellFacilityLink ON WellEventInfo.WellEvent = WellFacilityLink.WellEvent
    AND (DATE('{proddate}') BETWEEN WellFacilityLink.StartDate AND WellFacilityLink.EndDate OR WellFacilityLink.StartDate IS NULL OR WellFacilityLink.StartDate = '')
    LEFT OUTER JOIN FacilityInfo ON FacilityInfo.Facility = WellFacilityLink.Facility
    AND (DATE('{proddate}') BETWEEN FacilityInfo.StartDate AND FacilityInfo.EndDate OR FacilityInfo.StartDate IS NULL OR FacilityInfo.StartDate = '')
    LEFT OUTER JOIN WellEventLoc ON WellEventInfo.WellEvent = WellEventLoc.WellEvent
    LEFT OUTER JOIN WellInfo ON WellEventInfo.Well = WellInfo.Well
    AND (DATE('{proddate}') BETWEEN WellInfo.StartDate AND WellInfo.EndDate OR WellInfo.StartDate IS NULL OR WellInfo.StartDate = '')
    LEFT OUTER JOIN WellLicence ON WellLicence.WellLicence = WellInfo.WellLicence
    AND (DATE('{proddate}') BETWEEN WellLicence.StartDate AND WellLicence.EndDate OR WellLicence.StartDate IS NULL OR WellLicence.StartDate = '')
    WHERE (DATE('{proddate}') BETWEEN WellEventInfo.StartDate AND WellEventInfo.EndDate OR WellEventInfo.StartDate IS NULL OR WellEventInfo.StartDate = '')""".format(
        proddate=get_proddate())

    db = config.get_database()
    # the following allows us to check incoming arguments against a dictionary of allowed ones and match them with a relevant table name:
    argument_tables = {
        'WellEvent': 'WellEventInfo',
        'Licensee': 'WellLicence',
        'RTPOperator': 'RTAHeader',
        'LSD': 'WellEventInfo',
        'Section': 'WellEventInfo',
        'Township': 'WellEventInfo',
        'Range': 'WellEventInfo',
        'Meridian': 'WellEventInfo'
    }
    kwargs = dict((k, v) for k, v in request.args.items()
                  if v)  # this is to get rid of empty values coming from forms
    search_arguments = ""
    for arg in kwargs:
        if arg in argument_tables:
            compound = argument_tables[arg] + '.' + arg + '=' + '"' + kwargs[
                arg] + '"'
            search_arguments += " AND " + compound

    results = db.select_sql(statement + search_arguments)
    d = request.args.to_dict()
    output = 'browse'
    print('The Request is:', request.args.to_dict())
    if 'Output' in d:
        if d['Output'] == 'map':
            output = "map"
        elif d['Output'] == 'excel':
            output = "excel"
    print('The output is:', output)
    if results:
        if output == 'map':
            points = []
            for result in results:
                if result.Long:
                    json_obj = {}
                    json_obj['type'] = 'Feature'
                    json_obj['properties'] = {}
                    json_obj['properties']['name'] = result.WellEvent
                    json_obj['properties'][
                        'popupContent'] = '<b>%s</b> <br> Pool Name: %s<br><a href="/wellevent/%s">Details</a>' % (
                            result.WellEvent, result.RTPOperator,
                            result.WellEvent)
                    json_obj['geometry'] = {}
                    json_obj['geometry']['type'] = 'Point'
                    json_obj['geometry']['coordinates'] = [
                        round(result.Long * -1, 5),
                        round(result.Lat, 5)
                    ]
                    points.append(json_obj)
            print('***** points: ', json.dumps(points))
            print('Center is...:', center_point(points))
            return render_template('map.html',
                                   results=json.dumps(points),
                                   center=center_point(points))

        elif output == 'excel':
            """ Export relies on python's csv module to generate csv, StringIO writer to simulate a file for csv,
                as we don't need to save it on hard drive, and dbi.execute and cursor to get raw results of a query
                as that's what we need for csv to work properly"""
            db.dbi.execute(statement + search_arguments)
            output = io.StringIO()
            writer = csv.writer(output, quoting=csv.QUOTE_NONNUMERIC)
            writer.writerow([i[0] for i in db.dbi.cursor.description])
            writer.writerows(db.dbi.cursor)
            return Response(output.getvalue(),
                            mimetype="text/csv",
                            headers={
                                "Content-disposition":
                                "attachment; filename=WellEvent_export.csv"
                            })

        else:
            return render_template('wellevents/search.html',
                                   results=results,
                                   search_terms=request.args.to_dict())
    else:
        flash('No well events found.', 'error')
        return render_template('wellevents/search.html',
                               search_terms=request.args.to_dict())
Esempio n. 11
0
def generate_worksheet_from_calc(calc, with_js='y'):
    """
    Generate html for the calc row that is passed
    :param calc: a full calc record
    :param with_js: default is 'y' only other option is 'n' and should only be used to work around a
                    pdf generation issue
    :return: html of the worksheet for the calc record
    """
    try:
        db = config.get_database()
        if calc.Entity == 'Well':
            well = db.select1('WellRoyaltyMaster', ID=calc.EntityID)
        else:
            well = None
        entity_lease_link_array = db.select('EntityLeaseLink', Entity=calc.Entity, EntityID=calc.EntityID)
        if len(entity_lease_link_array) == 0:
            raise AppError("There were no well_lease_link records for " + str(calc.WellID) + str(calc.ProdMonth))
        entity_lease_link = entity_lease_link_array[0]
        royalty = db.select1('LeaseRoyaltyMaster', ID=calc.LeaseID)
        lease = db.select1('Lease', ID=calc.LeaseID)

        history = db.select_sql("""SELECT *
                   from Calc
                   WHERE ProdMonth = "{}" and LeaseID = "{}" and Entity = "{}" and EntityID = "{}"
                   and Product = "{}" and RPBA = "{}"
                   order by ExtractDate""".format(calc.ProdMonth, calc.LeaseID, calc.Entity, calc.EntityID,
                                                  calc.Product, calc.RPBA))
        # history = db.select_sql("""SELECT ID, ExtractDate, BaseNetRoyaltyValue, GorrNetRoyaltyValue
        #            from Calc
        #            WHERE ProdMonth = "{}" and LeaseID = "{}" and Entity = "{}" and EntityID = "{}"
        #            and Product = "{}" and RPBA = "{}"
        #            order by ExtractDate""".format(calc.ProdMonth, calc.LeaseID, calc.Entity, calc.EntityID,
        #                                           calc.Product, calc.RPBA))

        prev_BaseNetRoyaltyValue = 0.0
        prev_GorrNetRoyaltyValue = 0.0
        i = 0
        for h in history:
            h.BookedBaseNetRoyaltyValue = h.BaseNetRoyaltyValue - prev_BaseNetRoyaltyValue
            h.BookedGorrNetRoyaltyValue = h.GorrNetRoyaltyValue - prev_GorrNetRoyaltyValue
            h.Booked = h.BookedBaseNetRoyaltyValue + h.BookedGorrNetRoyaltyValue
            prev_BaseNetRoyaltyValue = h.BaseNetRoyaltyValue
            prev_GorrNetRoyaltyValue = h.GorrNetRoyaltyValue
            # Set the original calc record to the history record the one before this one
            if h.ExtractDate == calc.ExtractDate and i > 0:
                calc.original(history[i-1])

            i += 1

        monthly_array = db.select('Monthly', ExtractDate=calc.ExtractDate, Entity=calc.Entity, EntityID=calc.EntityID,
                                  prodMonth=calc.ProdMonth, product=calc.Product, RPBA=calc.RPBA)
        if len(monthly_array) == 0:
            raise AppError("There were no monthly records for well: " + str(calc.WellID) + " ProdDate: " +
                           str(calc.ProdMonth) + " Product: " + calc.Product)
        monthly = monthly_array[0]  # if there are multiple pick the first one

        ba = db.select1('BAInfo', BAid=monthly.RPBA, BAType='RTP')

        calc_specific = DataStructure(calc.RoyaltySpecific)
        rtp_info = db.select1('RTPInfo', WellEvent=well.WellEvent, Product=calc.Product, Payer=monthly.RPBA,
                              Date=prod_month_to_date(calc.ProdMonth))

        royalty.format_gorr = format_gorr(calc.Gorr)

        return render_template('worksheet/calc_worksheet.html',
                               with_js=with_js,
                               well=well, rm=royalty, m=monthly, lease=lease,
                               calc=calc, calc_sp=calc_specific, entity_lease_link=entity_lease_link,
                               ba=ba, rtp_info=rtp_info, history=history)
    except Exception as e:
        print('views.worksheet: ***Error:', e)
        traceback.print_exc(file=sys.stdout)
        tb = traceback.format_exc()
        return "<h2>Error displaying worksheet for " + calc.Entity + " %s</h2><br>" % calc.EntityID + str(e) + \
               '<plaintext>' + tb + '</plaintext>'
def search():
    if not request.args: return render_template('wellevents/search.html')
    statement = """SELECT WellEventInfo.WellEvent, RTAHeader.RTPOperator, WellEventStatus.Status, WellLicence.Licensee, BAInfo.CorpShortName, WellFacilitylink.Facility, FacilityInfo.Name, WellEventLoc.Lat, WellEventLoc.Long
    FROM WellEventInfo
    LEFT OUTER JOIN RTAHeader ON WellEventInfo.WellEvent = RTAHeader.WellEvent
    AND (DATE('{proddate}') BETWEEN RTAHeader.StartDate AND RTAHeader.EndDate OR RTAHeader.StartDate IS NULL OR RTAHeader.StartDate = '')
    LEFT OUTER JOIN WellEventStatus ON WellEventInfo.WellEvent = WellEventStatus.WellEvent
    AND (DATE('{proddate}') BETWEEN WellEventStatus.StartDate AND WellEventStatus.EndDate OR WellEventStatus.StartDate IS NULL OR WellEventStatus.StartDate = '')
    LEFT OUTER JOIN BAInfo ON RTAHeader.RTPOperator = BAInfo.BAid
    AND (DATE('{proddate}') BETWEEN BAInfo.StartDate AND BAInfo.EndDate OR BAInfo.StartDate IS NULL OR BAInfo.StartDate = '')
    LEFT OUTER JOIN WellFacilityLink ON WellEventInfo.WellEvent = WellFacilityLink.WellEvent
    AND (DATE('{proddate}') BETWEEN WellFacilityLink.StartDate AND WellFacilityLink.EndDate OR WellFacilityLink.StartDate IS NULL OR WellFacilityLink.StartDate = '')
    LEFT OUTER JOIN FacilityInfo ON FacilityInfo.Facility = WellFacilityLink.Facility
    AND (DATE('{proddate}') BETWEEN FacilityInfo.StartDate AND FacilityInfo.EndDate OR FacilityInfo.StartDate IS NULL OR FacilityInfo.StartDate = '')
    LEFT OUTER JOIN WellEventLoc ON WellEventInfo.WellEvent = WellEventLoc.WellEvent
    LEFT OUTER JOIN WellInfo ON WellEventInfo.Well = WellInfo.Well
    AND (DATE('{proddate}') BETWEEN WellInfo.StartDate AND WellInfo.EndDate OR WellInfo.StartDate IS NULL OR WellInfo.StartDate = '')
    LEFT OUTER JOIN WellLicence ON WellLicence.WellLicence = WellInfo.WellLicence
    AND (DATE('{proddate}') BETWEEN WellLicence.StartDate AND WellLicence.EndDate OR WellLicence.StartDate IS NULL OR WellLicence.StartDate = '')
    WHERE (DATE('{proddate}') BETWEEN WellEventInfo.StartDate AND WellEventInfo.EndDate OR WellEventInfo.StartDate IS NULL OR WellEventInfo.StartDate = '')""".format(proddate=get_proddate())

    db = config.get_database()
    # the following allows us to check incoming arguments against a dictionary of allowed ones and match them with a relevant table name:
    argument_tables = {'WellEvent': 'WellEventInfo', 'Licensee': 'WellLicence', 'RTPOperator': 'RTAHeader', 'LSD': 'WellEventInfo', 'Section': 'WellEventInfo', 'Township': 'WellEventInfo', 'Range': 'WellEventInfo', 'Meridian': 'WellEventInfo'}
    kwargs = dict((k, v) for k, v in request.args.items() if v)  # this is to get rid of empty values coming from forms
    search_arguments = ""
    for arg in kwargs:
        if arg in argument_tables:
            compound = argument_tables[arg] + '.' + arg + '=' + '"' + kwargs[arg] + '"'
            search_arguments += " AND " + compound

    results = db.select_sql(statement + search_arguments)
    d = request.args.to_dict()
    output = 'browse'
    print('The Request is:',request.args.to_dict())
    if 'Output' in d:
        if d['Output'] == 'map':
            output = "map"
        elif d['Output'] == 'excel':
            output = "excel"
    print('The output is:',output)
    if results:
        if output == 'map':
            points = []
            for result in results:
                if result.Long:
                    json_obj = {}
                    json_obj['type'] = 'Feature'
                    json_obj['properties'] = {}
                    json_obj['properties']['name'] = result.WellEvent
                    json_obj['properties']['popupContent'] = '<b>%s</b> <br> Pool Name: %s<br><a href="/wellevent/%s">Details</a>' % (
                        result.WellEvent, result.RTPOperator, result.WellEvent)
                    json_obj['geometry'] = {}
                    json_obj['geometry']['type'] = 'Point'
                    json_obj['geometry']['coordinates'] = [round(result.Long * -1, 5), round(result.Lat, 5)]
                    points.append(json_obj)
            print('***** points: ', json.dumps(points))
            print('Center is...:',center_point(points))
            return render_template('map.html', results=json.dumps(points), center=center_point(points))

        elif output == 'excel':
            """ Export relies on python's csv module to generate csv, StringIO writer to simulate a file for csv,
                as we don't need to save it on hard drive, and dbi.execute and cursor to get raw results of a query
                as that's what we need for csv to work properly"""
            db.dbi.execute(statement + search_arguments)
            output = io.StringIO()
            writer = csv.writer(output, quoting=csv.QUOTE_NONNUMERIC)
            writer.writerow([i[0] for i in db.dbi.cursor.description])
            writer.writerows(db.dbi.cursor)
            return Response(output.getvalue(), mimetype="text/csv", headers={"Content-disposition": "attachment; filename=WellEvent_export.csv"})

        else:
            return render_template('wellevents/search.html', results=results, search_terms=request.args.to_dict())
    else:
        flash('No well events found.', 'error')
        return render_template('wellevents/search.html', search_terms=request.args.to_dict())