import { google , sheets_v4 } from "googleapis" ; import Schema$Sheet = sheets_v4 . Schema$Sheet ; import { logger } from "../api-utils/logger" ; const sheets = google . sheets ( "v4" ) ; export const createCopiedSheet = async ( meta ) => { const token = meta . token ; const originalSheet = meta . originalSheet ; const originalSheetTitle = originalSheet ?. properties ?. title ; const originalSheetId = originalSheet ?. properties ?. sheetId ; if ( ! originalSheetTitle || ! originalSheetId ) { throw new Error ( "Can not fetch original properties" ) ; } const copiedSheetResponse = await sheets . spreadsheets . sheets . copyTo ( { oauth_token : token , spreadsheetId : meta . spreadsheetId , sheetId : originalSheetId , requestBody : { destinationSpreadsheetId : meta . spreadsheetId } } ) ; const copiedSheetId = copiedSheetResponse . data . sheetId ; if ( ! copiedSheetId ) { throw new Error ( "Fail to create copy" ) ; } logger . info ( "Create copy" , { originalSheetId : originalSheetId , copiedSheetId : copiedSheetId } ) ; return { copiedSheetId , async completeOperation ( newSheetName = originalSheetTitle ) { await sheets . spreadsheets . batchUpdate ( { oauth_token : token , spreadsheetId : meta . spreadsheetId , fields : "*" , requestBody : { requests : [ { deleteSheet : { sheetId : originalSheetId } } ] } } ) ; logger . info ( "Delete original sheet" ) ; await sheets . spreadsheets . batchUpdate ( { oauth_token : token , spreadsheetId : meta . spreadsheetId , fields : "*" , requestBody : { requests : [ { updateSheetProperties : { fields : "title" , properties : { sheetId : copiedSheetId , title : newSheetName } } } ] } } ) ; logger . info ( "Rename copied sheet" , { copiedSheetId , newSheetName } ) ; logger . info ( "Complete operation!" , { originalSheetId : originalSheetId , copiedSheetId : copiedSheetId } ) ; } , async revertOperation ( ) { await sheets . spreadsheets . batchUpdate ( { oauth_token : token , spreadsheetId : meta . spreadsheetId , fields : "*" , requestBody : { requests : [ { deleteSheet : { sheetId : copiedSheetId } } ] } } ) ; logger . info ( "revert operation - delete copy" , { copiedSheetId } ) ; } } ; } ;