Untitled

mail@pastecode.io avatarunknown
plain_text
a month ago
7.3 kB
1
Indexable
Never
import firebase_admin
from firebase_admin import credentials, firestore, storage

if not firebase_admin._apps:
    cred = credentials.Certificate('tgbot-374816-126a04adfbcc.json')
    app = firebase_admin.initialize_app(cred, {'storageBucket': 'tgbot-374816.appspot.com'})
# def add_to_base(arr, n = None, is_new = None):
# # arr = ['-1']*22
#
#
#     # file = arr[19].replace("_",".").split(".")
#     photo_url = arr[19]
#     file = arr[19].split("/")[1]
#     print(file)
#     f_num = file.replace("_",".").split('.')
#     print(f_num)
#     name = '0'*(10 - len(f_num[1])) + f_num[1]
#     db = firestore.client()
#     col = db.collection("TgBot")
#     docs = col.stream()
#     # *_, last = docs
#     conf = db.collection("Conf")
#     data = conf.document("Data")
#     ls = data.get().to_dict()
#     last = int(ls["LastID"].replace("0",''))
#     print(last)
#     if is_new == True:
#         name+=n
#     print(name)
#     print(last)
#     # return 1
#     # ls = int(last.id.replace('0', ''))
#     # last = 0
#     # id = arr[18]
#     # for doc in docs:
#     #     last = max(last, int(doc.id))
#
#     print(last)
#     if int(f_num[1] + n) <= last:
#         print("Старое фото")
#         return {"1": "Старое фото",
#                 "type": arr[12],
#                 "time": arr[1]}
#     # photo_path = "crops\et.PNG"
#     ######### Только wiriteoff
#     if is_new is not None:
#         photo_path = arr[17]
#         print("path ", photo_path)
#         storage_filename = f"TgPhotoes/{photo_path}"
#
#         print("номер ", n, is_new)
#         bucket = storage.bucket()
#         blob = bucket.blob(storage_filename)
#         blob.upload_from_filename(photo_path)
#         blob.make_public()
#         photo_url = blob.public_url
#         # photo_url = blob._get_download_url()
#         print(photo_url)
#         # return 0
#     g = lambda x: x[:-1] if len(x)>10 else x
#
#
#     # return 0
#     # print(last)
#     doc_ref = col.document(name)
#
#     s = {'Doc_ID':ls["nums"] + 1,'Статус':arr[0], 'time':arr[1], 'Chat_id':arr[2], 'Название_чата':arr[3], 'type':arr[4], 'id':arr[5], 'username':arr[6],
#          'nikname':arr[7], 'm_id':arr[8], 'id_группы':arr[9], 'id_сообщения-ответ':arr[10], 'дата-ответ':arr[11], 'reptype':arr[12], 'категория':arr[13],
#          'url':arr[14], 'report':arr[15], 'Группа':arr[16], 'docurl':photo_url, 'fileid':arr[18], 'filen':arr[19], 'lmd':arr[20], 'text':arr[21]}
#
#     doc_ref.set(s)
#     data.set({"LastID": g(name),
#               "nums":ls["nums"] + 1})
#     return {"0":"Фото новое"}
def add_to_base(n = '1', name= "0000000026", photo_path = "", mark = None):
    db = firestore.client()
    col = db.collection("TgBot")
    doc = col.document(name)
    subcol = doc.collection("mark")
    doc = subcol.document(name + '-' + n)
    storage_filename = f"TgPhotoes/{photo_path}"



    bucket = storage.bucket()
    blob = bucket.blob(storage_filename)
    blob.upload_from_filename(photo_path)
    blob.make_public()
    photo_url = blob.public_url
    # photo_url = blob._get_download_url()
    print(photo_url)


    doc.set({
        "Продукт":mark["product"],
        "Сотрудник":mark["worker"],
        "Приготовил":mark["cooked"],
        "Списать":mark["write-off"],
        "Время списания":"",
        "Статус":mark["status"],
        "url": photo_url,
        "TF": True,
    })
def upl_base(arr, mark = None):
    file = arr[19].split("/")[1]
    print(file)
    f_num = file.replace("_", ".").split('.')
    print(f_num)
    name = '0' * (10 - len(f_num[1])) + f_num[1]
    db = firestore.client()
    col = db.collection("TgBot")
    docs = col.stream()
    # *_, last = docs
    conf = db.collection("Conf")
    data = conf.document("Data")
    ls = data.get().to_dict()
    last = int(ls["LastID"].replace("0", ''))
    print(last)
    print(name)
    print(last)

    print(last)
    if int(f_num[1]) <= last:
        print("Старое фото")
        return {"1": "Старое фото",
                "type": arr[12],
                "time": arr[1]}
    doc_ref = col.document(name)

    s = {'Doc_ID': ls["nums"] + 1, 'Статус': arr[0], 'time': arr[1], 'Chat_id': arr[2], 'Название_чата': arr[3],
         'type': arr[4], 'id': arr[5], 'username': arr[6], 'nikname': arr[7], 'm_id': arr[8], 'id_группы': arr[9],
         'id_сообщения-ответ': arr[10], 'дата-ответ': arr[11], 'reptype': arr[12], 'категория': arr[13], 'url': arr[14],
         'report': arr[15], 'Группа': arr[16], 'docurl': "", 'fileid': arr[18], 'filen': arr[19], 'lmd': arr[20],
         'text': arr[21]}
    if mark is not None:
        subcol = doc_ref.collection("mark")
        subcol.add({})
    doc_ref.set(s)
    # data.set({"LastID": name,
    #           "nums": ls["nums"] + 1})
    return {"0": "Фото новое",
            "name": name}

def get_data():
    db = firestore.client()
    arr = []
    query = db.collection_group(u'mark').where(u'TF', u'==', True)
    results = query.stream()
    # print(results)
    for r in results:
        res = r.to_dict()
        # print(r.id)
        arr.append([r.id,res["Продукт"],res["Сотрудник"], res["Приготовил"], res["Списать"],res["Списать"] -  res["Приготовил"],  res["url"]])
    # print(len(arr))
    return arr
# get_data()
def delete_doc(docs):

    # document_path = f"mark/{subcollection_name}/{document_id}"

    db = firestore.client()
    batch = db.batch()
    for doc in docs:
        print(doc)
        main_doc = doc.split('-')[0]
        path = f'TgBot/{main_doc}/mark/{doc}'
        print(path)
        doc_ref = db.document(path)
        batch.delete(doc_ref)
    batch.commit()
def upd_doc(docs, status):
    db = firestore.client()
    batch = db.batch()
    for doc in docs:
        print(doc)
        main_doc = doc.split('-')[0]
        path = f'TgBot/{main_doc}/mark/{doc}'
        print(path)
        doc_ref = db.document(path)
        batch.update(doc_ref, {"TF": False, "Статус": "Списано"})
    batch.commit()

def createColl(name):
    db = firestore.client()
    col = db.collection("TgBot")
    doc = col.document(name)
    # db.collection('TgBot').document(name).delete()
# delete_doc()
# delete_doc(['0000000036-0'])
# res = upl_base(['add', '24.07.2023, 09:50:40', 1720207138, None, 'private', 1720207138, None, 'Gleb', 982, None, 981, '07.24.2023, 09:50:38', 'Маркировка', 'День', 'https://api.telegram.org/file/bot6268498821:AAGGDDITcRI2RFtyljkGUff5IB39ihtWtOk/photos/file_26.jpg', 'Фото: Маркировка\nДень 24.07.2023, 12:50', None, '','AgACAgIAAxkBAAID1mS-SXBKWYSGqZmzI-usQPAgEudgAALayTEbFEjwSZjx0YeSoooXAQADAgADbQADLwQ', 'photos/file_26.jpg', 'lmd', 'OCR'])
#
# name = res["name"]
# names = ["(1)file_26.jpg","(2)file_26.jpg"]
# i = 1
# for file in names:
#     add_to_base(name=name, photo_path=file, n=str(i))
#     i+=1