commit d86877f11480f038143b9704d0280aeb94e739e4
parent cebf7276aaf4cc7cfb6017c0883fe64caa6e38f3
Author: Bharatvaj Hemanth <bharatvaj@yahoo.com>
Date: Mon, 14 Sep 2026 08:45:47 +0530
parent cebf7276aaf4cc7cfb6017c0883fe64caa6e38f3
Author: Bharatvaj Hemanth <bharatvaj@yahoo.com>
Date: Mon, 14 Sep 2026 08:45:47 +0530
my-original: snapshot original workbook and Basic modules
9 files changed, 3156 insertions(+), 336 deletions(-)
M
|
1280
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------
diff --git a/.gitattributes b/.gitattributes @@ -0,0 +1 @@ +*.ods binary
diff --git a/AdGenerate.bas b/AdGenerate.bas @@ -0,0 +1,38 @@ +REM ***** BASIC ***** +Global Const PRODUCT_NAME = "2BurnerSS" + +Sub GenerateAd + Dim oDoc: oDoc = ThisComponent + Dim oSlides + Dim oProduct + + oDoc = GetFirstOpenDocument("com.sun.star.presentation.PresentationDocument") + If IsNull(oDoc) Then + ErrorLocal$ = "Please open a Presentation Document" + Exit Sub + End If + + oSlides = oDoc.getDrawPages() + Dim oShape + + oSheet = oDoc.Sheets("PriceList") + If IsNull(oSheet) Then + ErrorLocal$ = "Cannot find PriceList sheet" + Exit Sub + End If + + oProduct = ReadProductFromSheet(oSheet, PRODUCT_NAME) + + UpdateDocumentFromPriceList(oDoc, oSlides, oProduct) + + Dim oPres + oPres = oDoc.getPresentation() + + 'Stove WithPrevious + 'Price AfterPrev + 'Description AfterPrev + + oPres.IsAutomatic = True + oPres.AllowAnimations = True + oPres.Start() +End Sub
diff --git a/BrochureGenerate.bas b/BrochureGenerate.bas @@ -0,0 +1,68 @@ +REM ***** BASIC ***** +Option Explicit + +Global Const PRODUCT_NAME = "2BurnerSS" + +' TODO make presets based on festivals and discounts +Global Const CURRENT_PRESET = "FESTIVE" + +Sub UpdateDocumentFromPriceList(oDoc, oDrawPages, oProduct) + Dim i,j as Integer + Dim oPage + Dim oShape + For i = 0 To oDrawPages.getCount() - 1 + oPage = oDrawPages.getByIndex(i) + For j = 0 To oPage.getCount() - 1 + oShape = oPage.getByIndex(j) + SubstituteContent(oDoc, oShape, oProduct) + Next j + Next i +End Sub + +Sub BrochureGenerate + Dim oDrawPages + Dim oDoc: oDoc = ThisComponent + Dim oProduct + + ' TODO Iterate through StarDesktop, and get both + ' DrawingDocument and SpreadsheetDocument + + oDoc = GetFirstOpenDocument("com.sun.star.drawing.DrawingDocument") + If IsNull(oDoc) Then + ErrorLocal$ = "The given document should a Draw Document" + Exit Sub + End If + + oProduct = ReadProductFromSheet(oDoc, PRODUCT_NAME) + + oDrawPages = oDoc.getDrawPages() + UpdateDocumentFromPriceList(oDoc, oDrawPages, oProduct) + + GlobalScope.BasicLibraries.LoadLibrary("MRILib") + Dim oText: oText = oProduct.Title + Dim oEnum: oEnum = oText.createEnumeration() + Dim oSection + Dim s, v + Do While oEnum.hasMoreElements() + v = oEnum.nextElement() + Dim oSubSection + Dim oSecEnum + REM Now create an enumeration of the paragraphs. + REM We can enumerate the sections of the paragraph to + REM obtain the text field and other paragraph content. + oSecEnum = v.createEnumeration() + s = "Enumerating section type: " & v.ImplementationName + Do While oSecEnum.hasMoreElements() + oSubSection = oSecEnum.nextElement() + s = s & CHR$(10) & oSubSection.TextPortionType + If oSubSection.TextPortionType = "TextField" Then + s = s & " <== Type " & oSubSection.TextField.ImplementationName + End If + Loop + MsgBox s, 0, "Enumerate Single Paragraph" + Loop + Exit Sub + 'Print oSlide.dbg_methods() + MRI oProduct.Title + Exit Sub +End Sub
diff --git a/CylinderAutomation.bas b/CylinderAutomation.bas @@ -1,263 +1,1171 @@ -REM ***** BASIC ***** +'Copyright 2023-2025 Bharatvaj Hemanth <bharatvaj@yahoo.com> + +'Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +'1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +'2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following +'disclaimer in the documentation and/or other materials provided with the distribution. + +'3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote +'products derived from this software without specific prior written permission. + +'THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND +'ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +'WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +'DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +'FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +'DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +'SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED +'AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +'(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +'SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + 'Option VBASupport 1 Option Explicit -Global Const rowsToSkip = 1 -Global Const roughHeaderMatch = True +Type SondageSettings + oFieldAliasesRange as Variant +End Type + +Type SondageContext + oDoc as Variant + oSheet as Variant + oRange as Variant + headerRow& + startColumn& + startRow& + endColumn& + endRow& +End Type + +Private GlobalSondageSettings as New SondageSettings + +' Options read from sheet + +Private orgCode As String +Private exportPrefix As String +' Allowed values, +' EKYC, PENDING, INSPECTION, SBC, POPULATE +'The number of columns that are copied and the column size will be affected +Private reportType As String +Private inputType As String +'Holds filter information such as ONLINE +Private reportFilter As String +' The days below 'thorgCodee maximum date in report' to show as bad +Private priorityThreshold As Integer +Private highlightColor As Long +Private priorityColor As Long +Private isHeadless As Boolean +Private isDBRequired as Boolean +' True if you want to create sheets with Area specific data +Private enableGroupReports As Boolean +Private organizeInputsFolder as String +Private removeInputFileAfterSuccess as Boolean +Private gvtSoftwareFolder$ +Private debugInputFile$ +Private customerDBFile$ +Private shouldSyncWithGVT as Boolean +Private ErrorLocal$ +Private pendingRemarksValidateList$ +Private ekycRemarksList$ + +Private stateName As String +Private cityName As String + Global Const highlightBasedOn = "Payment Option" ' A yellow background is drawn that matches this column and 'highlightSearchString' Global Const highlightSearchString = "Online" ' Does partial match Global Const highlightRemoveColumn = True ' True if you want remove the column once the highlight is done -Global Const reportType = "PENDING" ' Allowed values are "PENDING", "SAFETY" and "SBC". The number of columns that are copied and the column size will be affected +Global Const shouldRunSubtotals = True Global Const shouldExportPDF = True ' If True this will export all the created sheets with Area specific data individually TODO change name to easily understand -Global Const badDayThreshold = 4 ' The days below 'the maximum date in report' to show as bad -Global Const shouldSegregateAreaWise = True' True if you want to create sheets with Area specific data -Global Const exportFolderPrefix = "C:\Users\bhara\Sync\" +Global Const shouldExportSummaryEditable = True ' If True this will export summary editable +'Private shouldExportSummaryPDF as Boolean' If True the first page will be exported as PDF +Global Const shouldCreateDataPivot = False +Global Const CURRENCY_UNIT = "" + +Global Const CSV_FILTER_NAME = "Text - txt - csv (StarCalc)" +' Refer https://help.libreoffice.org/latest/en-US/text/shared/guide/csv_params.html +Global Const PENDING_CSV_FILTER_OPTIONS = "44,34,76,1,5/9/6/4/7/1/8/9/9/9/10/9" +Global Const PENDING_PSV_FILTER_OPTIONS = "124,34,76,1,5/9/6/4/7/1/8/9/9/9/10/9" +Global Const INSPECTION_CSV_FILTER_OPTIONS = "44,34,76,4,1/9/7/9/8/9/9/9" +Global Const INSPECTION_PSV_FILTER_OPTIONS = "124,34,76,4,1/9/7/9/8/9/9/9" +Global Const TUBE_CSV_FILTER_OPTIONS = "44,34,76,4,1/9/7/9/9/9/10/9" +Global Const CONSUMERS_CSV_FILTER_OPTIONS = "44,34,76,4,1/9/2/1/3/2/4/9/5/9/6/9/7/9/8/9/9/9/10/9/11/9/12/9/13/9/14/1/15/9/16/2/17/9/18/9/19/9/20/9/21/9/22/9/23/9/24/9/25/9/26/9/27/9/28/9/29/9/30/9/31/9/32/2/33/1/34/1/35/9/36/9/37/9/38/9/39/1/40/1/41/9/42/9/43/9/44/3/45/9/46/9/47/9/48/9/49/9/50/9/51/9" +Global Const REFILL_CSV_FILTER_OPTIONS = "44,34,76,4,1/9/2/1/3/9/4/9/5/1/6/1/7/3/8/9/9/9/10/9/11/2/12/9/13/2/14/9/15/2/16/1" +Global Const NCTC_CSV_FILTER_OPTIONS = "44,34,76,1,1/1/2/9/3/9/4/1/5/1/6/9/7/9/8/9/9/9/10/1/11/1/12/9" ' Values are loaded from the document -Private tillDate as Date -Private tillDateStr as String -Private sheetNameSuffix as String -Private exportFolder as String +' Move all these to SondageContext? Which contain sheet, {start,end}{Column,Row} and others common things +Private tillDate As Date +Private tillDateStr As String +Private fromDate As Date +Private fromDateStr As String +Private sheetNameSuffix As String +Private exportDestDir As String -'Private shouldExportSummaryPDF as Boolean' If True the first page will be exported as PDF +Sub CleanupProductCode(oSheet as Object, endColumn as Long, endRow as Long) + MsgBox "Not implemented: productNames" +End Sub -Sub Main - Dim oDoc : oDoc = ThisComponent - Dim s as Object - Dim cursor as Object - Dim c as Integer - Dim destSheet as Variant - Dim sheetName$, d$, a$ - Dim areaColumn%, areaNames as New Collection - Dim startColumn%, startRow%, endColumn%, endRow% - Dim rowsToRemove%, iArea% - Dim areaRange, idRange, bookRange - Dim dColumns as Object - Dim headerRange as Object - Dim cellRangeToCopy as Object - Dim pageStyle as Object - Dim oCellStyles - Dim oConFormat - Dim oCondition(2) as new com.sun.star.beans.PropertyValue - Dim T4Style +Sub IterateTableAndAct() + ' Call it Sub-table in Sondage + ' Segregate Sondage as sondage-basic, sondage-db, etc? + Dim oDoc, oSheet, oCell + Dim iRow&, startColumn% + Dim oCursor As Object + Dim oTableRange As Object + Dim nLastRow As Long + Dim nRow As Long + Dim tableCount As Integer + + oDoc = ReturnComponentIfOpen("C:\Users\bhara\Downloads\ViewTransactionDetail.csv") + If IsNull(oDoc) Then + Print "Error opening Transaction Details" + Exit Sub + End If + oSheet = oDoc.getSheets().getByIndex(0) + + ' 1. Find the final used row on the entire sheet to know when to stop looping + oCursor = oSheet.createCursor() + oCursor.gotoEndOfUsedArea(False) + nLastRow = oCursor.RangeAddress.EndRow + + tableCount = 0 + nRow = 0 + + ' 2. Loop down Column A to find individual tables + Do While nRow <= nLastRow + oCell = oSheet.getCellByPosition(0, nRow) - ' Initialize Globals - ' Casting to Long removes the time component - tillDate = CLng(Now()) + If oCell.Type <> com.sun.star.table.CellContentType.EMPTY Then + tableCount = tableCount + 1 + oCursor = oSheet.createCursorByRange(oCell) + oCursor.collapseToCurrentRegion() + oTableRange = oCursor.RangeAddress - s = oDoc.Sheets(0) - cursor = UsedRangeCursor(s) + 'MsgBox "Found Table " & tableCount & " at Range: " & oTableRange.StartRow - ' NaiveLastTable gives us the last non-blank table's - rowsToRemove = NaiveLastTable(s) - If rowsToRemove <> 0 Then - s.getRows().removeByIndex(0, rowsToRemove + 1) - End If + Dim oCurrentCell, sCurrentCell + oCurrentCell = oSheet.getCellByPosition(oTableRange.startColumn, oTableRange.startRow) + sCurrentCell = oCurrentCell.getString() + If InStr(sCurrentCell, "ConsumerNumber") Then + Act1(oSheet, oTableRange) + End If - startRow = 1 - startColumn = 0 - endRow = cursor.RangeAddress.EndRow - endColumn = cursor.RangeAddress.EndColumn + nRow = oCursor.RangeAddress.EndRow + 1 + Else + ' Move to the next row if this one is empty + nRow = nRow + 1 + End If + Loop + + MsgBox "Finished! Total tables found: " & tableCount +End Sub - ' TODO move this to knowledge base - oCellStyles = ThisComponent.StyleFamilies("CellStyles") - If Not oCellStyles.hasByName("T4") Then - T4Style = oDoc.createInstance("com.sun.star.style.CellStyle") - oCellStyles.insertByName("T4", T4Style) - oCellStyles.getByName("T4").CellBackColor = RGB(255, 0, 0) - End If +Function SondageContextSetRange(ByRef ctx as SondageContext, oRangeAddr, Optional hasHeader as Boolean) + If IsMissing(hasHeader) Then hasHeader = True + ctx.headerRow = oRangeAddr.StartRow + ctx.startColumn = oRangeAddr.startColumn + ctx.startRow = IIf(hasHeader, oRangeAddr.StartRow + 1, oRangeAddr.StartRow) + ctx.endColumn = oRangeAddr.endColumn + ctx.endRow = oRangeAddr.endRow +End Function - If ThisComponent.CurrentController.hasFrozenPanes() Then - Call UnFreezeSelection - End If +Function Act1(oSheet, oRangeAddr) + Dim ctx as SondageContext + Dim iRow& + Dim iMainColumn% + ctx.oSheet = oSheet + SondageContextSetRange(ctx, oRangeAddr) + ' TODO Make this more flexible with regex, so this can + ' be set easily in the sheet + iMainColumn = GetHeaderPosition(ctx, "ConsumerNumber", True) + + If iMainColumn = -1 Then Exit Function + For iRow = ctx.startRow To ctx.endRow + Print ctx.oSheet.getCellByPosition(iMainColumn, iRow).getString() + Next iRow +End Function + +Function CreatePivotForRefill(ByRef ctx as SondageContext, ByRef sonConf as SondageConfiguration, oDestSheet) + Dim oTables, oTDescriptor, oFields, oField, iField% + Dim oCellAddress as new com.sun.star.table.CellAddress + + oCellAddress.Sheet = oDestSheet + oCellAddress.Column = 0 + oCellAddress.Row = 0 - ' TODO pass the column name/index as an argument - ' Transformations to be applied to the Main sheet before splitting the sheet by Area Name - cursor = UsedRangeCursor(s) + oTables = ctx.oSheet.getDataPilotTables() + oTDescriptor = oTables.createDataPilotDescriptor() + oTDescriptor.setSourceRange(ctx.oRange.getRangeAddress()) + + oFields = oTDescriptor.getDataPilotFields() - Call CleanColumnHeaders(s, endColumn) + iField = GetHeaderPosition("Operator Name") + oField = oFields.getByIndex(iField) + oField.Orientation = com.sun.star.sheet.DataPilotFieldOrientation.ROW - areaColumn = GetHeaderPosition(s, endColumn, "Area") - Call ShortenDirections(s, areaColumn) + iField = GetHeaderPosition("Type") + oField = oFields.getByIndex(iField) + oField.Orientation = com.sun.star.sheet.DataPilotFieldOrientation.COLUMN + + iField = GetHeaderPosition("Cylinder Qty") + oField = oFields.getByIndex(iField) + oField.Orientation = com.sun.star.sheet.DataPilotFieldOrientation.DATA + oField.Function = com.sun.star.sheet.GeneralFunction.SUM + + oTables.insertNewByName("REFILLDataPilot", oCellAddress, OTDescriptor) +End Function + +Function ReadSettings() as Boolean + Dim oDoc + Dim oSheet + Dim rangeAddress + Dim oRange + ReadSettings = False + + oSheet = ThisComponent.Sheets.getByName("Settings") + rangeAddress = UsedRangeCursor(oSheet).RangeAddress + oRange = oSheet.getCellRangeByPosition(0, 0, rangeAddress.EndColumn, rangeAddress.EndRow) + + isHeadless = True + ' Organization Details + orgCode = GetValueForKey(oRange, "OrgCode").String + stateName = GetValueForKey(oRange, "StateName").String + cityName = GetValueForKey(oRange, "CityName").String + highlightColor = GetValueForKey(oRange, "HighlightColor").CellBackColor + reportType = GetValueForKey(oRange, "ReportType").String + reportFilter = GetValueForKey(oRange, "ReportFilter").String + exportPrefix = GetValueForKey(oRange, "ExportFolder").String + priorityThreshold = CInt(GetValueForKey(oRange, "PriorityThreshold").String) + priorityColor = GetValueForKey(oRange, "PriorityColor").CellBackColor + enableGroupReports = CBool(GetValueForKey(oRange, "EnableGroupReports").String) + organizeInputsFolder = GetValueForKey(oRange, "OrganizeInputsFolder").String + removeInputFileAfterSuccess = CBool(GetValueForKey(oRange, "RemoveInputFileAfterSuccess").String) + gvtSoftwareFolder = GetValueForKey(oRange, "GVTSoftwareFolder").String + debugInputFile = GetValueForKey(oRange, "DebugInputFile").String + customerDBFile = GetValueForKey(oRange, "CustomerDBFile").String + shouldSyncWithGVT = GetValueForKey(oRange, "ShouldSyncWithGVT").String + pendingRemarksValidateList = GetValueForKey(oRange, "PendingRemarksValidateList").String + ekycRemarksList = GetValueForKey(oRange, "EkycRemarksList").String + ' Skip check if the path is not given + If shouldSyncWithGVT Then + If Not FileExists(gvtSoftwareFolder) Then + MsgBox "Please enter correct one and rerun the macro", 16, "Given GVT Advance Path does not exist" + Exit Function + End If + End If + + 'If IsNull(oCell) Then + ' MsgBox "Setting not found, throw error" + ' Exit Sub + 'End If + ReadSettings = True +End Function + +Function CreateValidationList(ctx as SondageContext, columnName$, sValidationList) + Dim oValidation, oRange, oCell + Dim aItems, sFirstItem$,finalFormula$ + oRange = GetColumnRange(ctx, columnName) + + Dim listDelim: listDelim = CHR(10) + + oValidation = oRange.Validation + oValidation.Type = com.sun.star.sheet.ValidationType.LIST + aItems = Split(sValidationList, listDelim) + + If LBound(aItems) <> -1 Then + sFirstItem = aItems(LBound(aItems)) + Else + sFirstItem = sValidationList + End If + + oCell = oRange.getCellByPosition(0, 0) + oCell.setString(sFirstItem) + + oRange.fillSeries(com.sun.star.sheet.FillDirection.TO_BOTTOM, com.sun.star.sheet.FillMode.SIMPLE, 0, 0, ctx.endRow) + + finalFormula = """" & Join(Split(sValidationList, listDelim), """;""") & """" + oValidation.setFormula1(finalFormula) + oRange.Validation = oValidation +End Function + +Function ValidateDoc(oDoc as Object, docType$) as String + Dim _err$ : _err = "" + if IsEmpty(oDoc)Then + _err = "Failed to get Document for " & sInputFile + ElseIf Not oDoc.supportsService(docType) Then + _err = sInputFile & " is not a valid Spreadsheet Document" + ElseIf oDoc.CurrentController.ViewControllerName = "PrintPreview" Then + _err = "Cannot run this macro in 'Print Preview', please close it and try again" + End If + ValidateDoc = _err +End Function + +Function AssertColumn(ctx as SondageContext, sCol$) as Boolean + Dim iCol% + AssertColumn = True + iCol = GetHeaderPosition(ctx, sCol) + If iCol = -1 Then + ErrorLocal$ = "Cannot proceed, " & sCol & " column is " & iCol + AssertColumn = False + End If +End Function + +Function SondageAppendColumn(ByRef ctx as SondageCtx, sColumnName$) + Dim oCell + Dim oRange + ctx.endColumn = ctx.endColumn + 1 + 'ctx.oSheet.getColumns().insertByIndex(ctx.endColumn, 1) + oCell = ctx.oSheet.getCellByPosition(ctx.endColumn, 0) + oCell.setString(sColumnName) + oRange = GetColumnRange(ctx, sColumnName) + oCell.CellStyle = "Heading 1" +End Function + +Function GetColumnSettings(sheetName$) as Boolean + Dim oDoc, oSheet + GetColumnSettings = False + oDoc = ThisComponent + oSheet = oDoc.getSheets().getByName(sheetName) + If IsNull(oSheet) Then Exit Function +End Function + +Function SondageGetContext(oSheet as Variant) as SondageContext + Dim ctx as New SondageContext + ctx.oSheet = oSheet + ctx.oDoc = oSheet.DrawPage.Forms.Parent + ctx.oRange = UsedRangeCursor(oSheet) + ctx.headerRow = 0 + ctx.startColumn = 0 + ctx.startRow = 1 + ctx.endRow = ctx.oRange.RangeAddress.EndRow + ctx.endColumn = ctx.oRange.RangeAddress.EndColumn + SondageGetContext = ctx +End Function + +Function SondageJoinVertical(ctx as SondageContext, sIdColumn$) + Dim i&: i = 1 + Dim iIdColumn%: iIdColumn = GetHeaderPosition(ctx, sIdColumn) + ' TODO Add mismatching content as array, rather than discarding them entirely + For i = ctx.startRow To ctx.endRow + With ctx.oSheet + If .getCellByPosition(iIdColumn, i).String = .getCellByPosition(iIdColumn, i + 1).String Then + .getRows().removeByIndex(i + 1, 1) + ctx.endRow = ctx.endRow - 1 + End If + End With + Next +End Function + +Function RemoveRows(ByRef ctx as SondageContext, rowsToRemove&) + If rowsToRemove <> 0 Then + ctx.oSheet.getRows().removeByIndex(0, rowsToRemove + 1) + ' FIXME Check this calculation again, this could be reason, West Mambalam is + ' not appearing on the list sometimes + ctx.endRow = ctx.endRow - (rowsToRemove + 1) + End If +End Function + +Function SondageConditionalHorizontalCopy(ctx as SondageContext, sDstColumn$, sSrcColumn$) + iSrcColumn = GetHeaderPosition(ctx, sSrcColumn) + iDstColumn = GetHeaderPosition(ctx, sDstColumn) + + Dim i&: i = 1 + ' Remove duplicates, Move value from 'Phone' if "Mobile' has no value + For i = ctx.startRow To ctx.endRow + With ctx.oSheet + If .getCellByPosition(iDstColumn, i).Value = 0 Then + .getCellByPosition(iDstColumn, i).Value = .getCellByPosition(iSrcColumn, i).Value + End If + End With + Next i +End Function + +Function SondageInit(oDoc) + Dim oFieldAliasesSheet as Variant + oFieldAliasesSheet = oDoc.getSheets().getByName("FieldAliases") + + GlobalSondageSettings.oFieldAliasesRange = UsedRangeCursor(oFieldAliasesSheet) +End Function + +Function SondageGetPropVal(aContainer, sProp$, Optional sDefaultValue) as String + Dim oParent + On Error Goto ErrorHandler + For Each oParent In aContainer + If oParent.Name = sProp Then + SondageGetPropVal = oParent.Value + Exit Function + End If + Next oParent + ErrorHandler: + If Not IsMissing(sDefaultValue) then SondageGetPropVal = sDefaultValue +End Function + +Function SondageReflectionQuickAccess(aContainer, sProp$, oVal, Optional callByNameArg%) as Variant + Dim oParent + If IsMissing(callByNameArg) Then callByNameArg = 2 ' 2 = Get operation + On Error Goto ErrorHandler + For Each oParent In aContainer + Dim propertyValue + propertyValue = CallByName(oParent, sProp, callByNameArg) + If propertyValue = oVal Then + SondageReflectionQuickAccess = oParent + Exit Function + End If + Next oParent + ErrorHandler: +End Function + +Function GetHeaderIndex(aHeader, sProperty$) as Long + Dim i% + GetHeaderIndex = -1 + For i = LBound(aHeader) To UBound(aHeader) + If aHeader(i) = sProperty Then + GetHeaderIndex = i + Exit Function + End If + Next i +End Function + +Function SondageTransformSheet(ctx, sonConf, reportType, sWidthColumn$) + Dim i%, iWidthColumn%, sWidth$ + Dim sField$ + Dim aReports, oReport + + aReports = sonConf.Reports + oReport = SondageReflectionQuickAccess(aReports, "Title", reportType) + + ' TODO Throw error + If IsEmpty(sonConf) Then Exit Function + + iWidthColumn = GetHeaderIndex(sonConf.Headers, sWidthColumn) + + Dim aColumns2D(UBound(oReport.Fields), 1) + For i = 0 To UBound(oReport.Fields) + sField = oReport.Fields(i).Field + aColumns2D(i, 0) = oReport.Fields(i).Field + sWidth = oReport.Fields(i).Values(iWidthColumn) + If sWidth <> "" Then + aColumns2D(i, 1) = CLng(sWidth) + End If + Next i + SondageRestructureColumns(ctx, aColumns2D) +End Function - If Left(reportType, 1) = "P" Then - Call ApplyTheme "millennium.ots" - endColumn = RemoveColumnsExcept(s, endColumn, Array( _ +Sub _SondageTransformSheet(ctx, reportType$) + Dim oDoc + 'TODO This should be set through GroupHeader logic + oDoc = ctx.oDoc + + If reportType = "PENDING" Then + ApplyTheme(oDoc, "millennium.ots") + RemoveColumnsExcept(ctx, Array( _ "Area", _ + "Address", _ "ID", _ "Name", _ "Mobile", _ "Book", _ - "Payment Option" _ + "Payment Option", _ + "Code" _ )) - - endColumn = HighlightRowWithColumn(s, endColumn, endRow, _ - "Payment Option", "Online Payment", True, _ - RGB(255, 255, 0)) - - ' Justify Leftmost cells to left and Rightmost cells to right - - bookRange = GetColumnRange(s, endColumn, endRow, "Book") - bookRange.setPropertyValue("HoriJustify", com.sun.star.table.CellHoriJustify.RIGHT) - - FormatRangeAsNumber(s, new com.sun.star.lang.Locale, oDoc.getNumberFormats(), bookRange, "DD/MM") - - tillDate = FindHighestDateAsString(s, "Book", endColumn, endRow) - - With oCondition(0) : .Name = "Operator" : .Value = com.sun.star.sheet.ConditionOperator.LESS_EQUAL : End With - oCondition(1).Name = "Formula1" : oCondition(1).Value = CLng(tillDate - badDayThreshold) - With oCondition(2) : .Name = "StyleName" : .Value = "T4" : End With - oConFormat = bookRange.ConditionalFormat - oConFormat.clear() : oConFormat.addNew(oCondition) - SetWidths(s, endColumn, Array( _ + SetWidths(ctx, Array( _ Array("Area", 0), _ Array("ID", 0), _ + Array("Code", 1000), _ Array("Name", 7000), _ Array("Mobile", 0), _ Array("Book", 0) _ )) - ElseIf reportType = "SBC" Then - Call ApplyTheme "pumpkin.ots" - endColumn = RemoveColumnsExcept(s, endColumn, Array( _ - "ID", _ - "Name", _ - "Address", _ - "Mobile", _ - "Area", _ - "No Of Cylinder" _ + ElseIf reportType = "INSPECTION" Then + ApplyTheme(oDoc, "green_grapes.ots") + RemoveColumnsExcept(ctx, Array( _ + "Area", _ + "ID", _ + "Name", _ + "Address", _ + "Mobile" _ + )) + ElseIf reportType = "TUBE" Then + ApplyTheme(oDoc, "pumpkin.ots") + endColumn = RemoveColumnsExcept(ctx, Array( _ + "Area", _ + "ID", _ + "Name", _ + "Address", _ + "Mobile" _ + )) + ElseIf reportType = "REFILL" Then + ApplyTheme(oDoc, "pumpkin.ots") + RemoveColumnsExcept(ctx, Array( _ + "ID", _ + "Name", _ + "Code", _ + "Operator Name" _ + )) + '"Block Reason" _ + SetWidths(ctx, Array( _ + Array("ID", 0), _ + Array("Name", 3000), _ + Array("Code", 2000), _ + Array("Operator Name", 4000) _ + )) + ElseIf reportType = "DORMANT" Then + ApplyTheme(oDoc, "pumpkin.ots") + RemoveColumnsExcept(ctx, Array( _ + "Area", _ + "ID", _ + "Name", _ + "Address", _ + "Mobile" _ )) - SetWidths(s, endColumn, Array( _ + '"Block Reason" _ + SetWidths(ctx, Array( _ + Array("Area", 1000), _ + Array("ID", 0), _ + Array("Name", 3000), _ + Array("Address", 8000), _ + Array("Mobile", 2000) _ + )) + ElseIf reportType = "SBC"Then + ApplyTheme(oDoc, "pumpkin.ots") + RemoveColumnsExcept(ctx, Array( _ + "ID", _ + "Name", _ + "Address", _ + "Mobile", _ + "Area", _ + "No Of Cylinder" _ + )) + SetWidths(ctx, Array( _ Array("ID", 0), _ Array("Name", 3000), _ Array("Address", 8000), _ Array("Mobile", 0), _ Array("Area", 0) _ )) + ElseIf reportType = "EKYC" Then + ApplyTheme(oDoc, "nature.ots") + enableGroupReports = True + + RemoveColumnsExcept(ctx, Array( _ + "Area", _ + "ID", _ + "Name", _ + "Address", _ + "Mobile" _ + )) + SetWidths(ctx, Array( _ + Array("Area", 2000), _ + Array("ID", 0), _ + Array("Name", 3000), _ + Array("Address", 8500), _ + Array("Mobile", 2000) _ + )) + ElseIf reportType = "VIP" Then + ApplyTheme(oDoc, "green_grapes.ots") + RemoveColumnsExcept(ctx, Array( _ + "Area", _ + "ID", _ + "Name", _ + "Address", _ + "Mobile" _ + )) + SetWidths(ctx, Array( _ + Array("Area", 0), _ + Array("ID", 0), _ + Array("Name", 3000), _ + Array("Address", 8000), _ + Array("Mobile", 0) _ + )) + Else + ErrorLocal$ = "Unknown reportType: '" & reportType & "'" + Exit Sub End If - - idRange = GetColumnRange(s , endColumn, endRow, "ID") _ - .setPropertyValue("HoriJustify", com.sun.star.table.CellHoriJustify.LEFT) +End Sub + +Function SegregateEKYCDoneOnline() + ' Array +End Function + +Sub Main(Optional sInputFiles as Variant) + Dim aInputFiles, sInputFile$ + Dim aDoc as Variant, oDoc, oDBDoc, oDispatcher + Dim oOrigSheet, oSheet, oDBSheet, oSheets as Object + Dim oCursor, oTextCursor + Dim sonConf, sonReport, aSettings + + Dim sTheme$, badStyleName$ + Dim idColumn%, mobileColumn%, phoneColumn%, addressColumn%, nameColumn% + Dim groupByColumn%, areaNames as New Collection + Dim rowsToRemove% + Dim highlightedCount as Integer, formatNum as Integer + Dim idRange, bookRange, nameRange + Dim dColumns as Object + Dim headerRange as Object + Dim statusBar as Variant + Dim ctx as New SondageContext + Dim dbCtx as New SondageContext + Dim sGroupBy$, iGroupByColumn% + + Dim cellRangeToCopy as Object + Dim pageStyle as Object + Dim oLocale as new com.sun.star.lang.Locale + + ' Setup args + aInputFiles = Split(sInputFiles, ";") + + ' Initialize Globals + SondageInit(ThisComponent) + If Not ReadSettings() Then Exit Sub + ' TODO Move this to read settings? + sonConf = SondageParseFieldConfiguration() + + ' Casting to Long removes the time component + tillDate = CLng(Now()) + badStyleName = "T4" + enableGroupReports = True + + For Each sInputFile in aInputFiles + If IsMissing(sInputFile) Or TypeName(sInputFile) <> "String" Then + If debugInputFile <> "" Then + sInputFile = debugInputFile + isHeadless = False + Else + MsgBox "Please give an input file", 16, "No input given" + GoTo FinalFallback + End If + End If + Next sInputFile + + sInputFile = aInputFiles(0) + + sonReport = SondageInferDocumentType(sonConf.Reports, aInputFiles) + If IsEmpty(sonReport) Then + ErrorLocal = "Cannot infer report configuration for '" & sInputFile & "'" + Goto ErrorHandler + End If + inputType = sonReport.Title + + If reportType = "AUTO" Then + reportType = inputType + End If + + aSettings = sonReport.Settings + sGroupBy = SondageGetPropVal(aSettings, "GroupBy") + + 'If reportType = "PENDING" Then + ' isDBRequired = True + 'End If - Call SortColumn(s, endColumn, endRow, "Area") + If isDBRequired Then + oDBDoc = SondageImportFile(sonReport, customerDBFile, "com.sun.star.sheet.SpreadsheetDocument", True, False) + If ErrorLocal$ <> "" Then Goto ErrorHandler + End If + + ' FIXME The isHidden = False value is hardcoded, but use value from settings + aDoc = SondageImportFiles(sonReport, aInputFiles, "com.sun.star.sheet.SpreadsheetDocument", True, False) + If ErrorLocal$ <> "" Then Goto ErrorHandler + oDoc = aDoc(0) + statusBar = oDoc.CurrentController.StatusIndicator + + If oDoc.CurrentController.hasFrozenPanes() Then + Call UnFreezeSelection(oDoc) + End If + + ctx = SondageGetContext(oDoc.Sheets(0)) + + If ctx.oSheet.IsProtected Then + ctx.oSheet.Unprotect(reportType) + End If + + ' NaiveLastTable gives us the last non-blank table's + ' TODO The name 'rowsToRemove' is misleading + rowsToRemove = NaiveLastTable(ctx) + RemoveRows(ctx, rowsToRemove) + + 'If oDoc.Sheets.Count <> 1 Then oDoc.Sheets.removeByName("CONSUMERSWorkingCopy") + + ' Copy the first, sheet if there is only one sheet in document + If oDoc.Sheets.Count = 1 Then + If shouldCreateDataPivot = False Then + oDoc.Sheets.copyByName(ctx.oSheet.Name, reportType & "WorkingCopy", 1) + End If + End If + + oDoc.lockControllers() + ' Register Styles + SetCustomBadStyle(oDoc, oLocale, badStyleName) : If ErrorLocal$ <> "" Then Goto ErrorHandler + + ctx.oSheet.Protect(reportType) + + If isDBRequired Then + dbCtx = SondageGetContext(oDBDoc.Sheets(0)) + Call CleanColumnHeaders(dbCtx) + End If + + ctx = SondageGetContext(oDoc.Sheets(1)) + + If ctx.oSheet.Name = reportType & "WorkingCopy" Then + ' It's not possible to create a style even if only one sheet is blocked + Call CleanColumnHeaders(ctx) + If GetHeaderPosition(ctx, sGroupBy) = -1 Then + ErrorLocal$ = "Cannot proceed, '" & sGroupBy & "' column not found" + Goto ErrorHandler + End If + End If + + ' FIXME Enable normal Consumer List Generation Later + If shouldSyncWithGVT Then + ReducedPopulateConsumerDetails(gvtSoftwareFolder, ctx.oSheet) + 'PopulateConsumerDetails(gvtSoftwareFolder, ctx.oSheet) + GoTo FinalFallback + End If + + 'Call CleanupProductCode(ctx, endRow) + + ' Filter - Remove unrequired fields + If reportType = "INSPECTION" Then + Call FilterColumn(ctx, "Area", orgCode & "_PortIn", com.sun.star.sheet.FilterOperator.NOT_EQUAL) + Call FilterColumn(ctx, "Inspection Due Now", "Over Due") + Call FilterColumn(ctx, "Mobile", 0, com.sun.star.sheet.FilterOperator.NOT_EQUAL) + ElseIf reportType = "TUBE" Then + Call FilterColumn(ctx, "Area", orgCode & "_PortIn", com.sun.star.sheet.FilterOperator.NOT_EQUAL) + Call FilterColumn(ctx, "Tube Change Due Now", "Over Due") + Call FilterColumn(ctx, "Mobile", 0, com.sun.star.sheet.FilterOperator.NOT_EQUAL) + ElseIf reportType = "VIP" Then + Call FilterColumn(ctx, "Category", "VIP") + ElseIf reportType = "DORMANT" Then + Call FilterColumn(ctx, "Block Reason", "Dormant") + ElseIf reportType = "REFILL" Then + Call FilterColumn(ctx, "Type", "Domestic", com.sun.star.sheet.FilterOperator.NOT_EQUAL) + End If + + ' Expensive Operation, run after filter + If inputType = "CONSUMERS" Then + ' TODO Sort will not lose it character after filter. This should be above filter + Call SortColumn(ctx, "ID") + SondageJoinVertical(ctx, "ID") + SondageConditionalHorizontalCopy(ctx, "Mobile", "Phone") + End If + + ' TODO Should this be automatic and obtained from ctx? + oCursor = UsedRangeCursor(ctx.oSheet) + + If reportType = "PENDING" Then + ' If the reportFilter is ONLINE, filter it, else highlight + ' TODO Add this feature to Sondage + If reportFilter = "ONLINE" Then + Call FilterColumn(ctx, "Payment Option", "Online Payment", com.sun.star.sheet.FilterOperator.EQUAL) + Else + highlightedCount = HighlightRowWithColumn(ctx, _ + "Payment Option", "Online Payment", RGB(255, 255, 0)) + End If + + ' Justify Leftmost cells to left and Rightmost cells to right + bookRange = GetColumnRange(ctx, "Book") + bookRange.setPropertyValue("HoriJustify", com.sun.star.table.CellHoriJustify.RIGHT) + + FormatRangeAsNumber(oLocale, oDoc.getNumberFormats(), bookRange, "DD/MM") - ' Setup exportFolder and sheetName - tillDateStr = Replace(CDate(tillDate), "/", "-") - tillDateStr = Trim(tillDateStr) + tillDate = ComputeOnRange(ctx, "Book", com.sun.star.sheet.GeneralFunction.MAX) + fromDate = ComputeOnRange(ctx, "Book", com.sun.star.sheet.GeneralFunction.MIN) + + SetupConditionalForHighPriority(ctx.oDoc, oLocale, bookRange, badStyleName, "><", 1000, tillDate - priorityThreshold) + ElseIf reportType = "EKYC" Then + highlightedCount = HighlightRowWithColumn(ctx, _ + "Consumer Type", "PMUY", RGB(175, 255, 175)) + End If + + SondageTransformSheet(ctx, sonConf, reportType, "Group Width") + + If ErrorLocal$ <> "" Then Goto ErrorHandler + + If inputType = "PENDING" Then + if isDBRequired Then + If Not AssertColumn(dbCtx, "Address") Then GoTo ErrorHandler + End If + End If + + Call ShortenDirections(ctx, groupByColumn) + Call SortColumn(ctx, sGroupBy) + + If reportType = "PENDING" and isDBRequired Then + Call ColumnJoin(CHR(10), "ID", ctx, "Name", dbCtx, "Address") + End If + + sTheme = SondageGetPropVal(aSettings , "Theme") + If Not IsEmpty(sTheme) Then ApplyTheme(ctx.oDoc, sTheme) + + idRange = GetColumnRange(ctx, "ID") + idRange.setPropertyValue("HoriJustify", com.sun.star.table.CellHoriJustify.LEFT) + + ' Setup exportPrefix and sheetName + tillDateStr = Format(tillDate, "yyyy-mm-dd") sheetNameSuffix = " - " & reportType & " " & tillDateStr - exportFolder = exportFolderPrefix & "/" & reportType & " " & tillDateStr + exportDestDir = tillDateStr & " " & reportType - headerRange = s.getCellRangeByPosition(0, 0, endColumn, 0) + headerRange = ctx.oSheet.getCellRangeByPosition(0, 0, ctx.endColumn, 0) headerRange.CellStyle = "Heading 1" - - pageStyle = ThisComponent.StyleFamilies.getByName("PageStyles").getByName("Default") + + pageStyle = ctx.oDoc.StyleFamilies.getByName("PageStyles").getByName("Default") pageStyle.setPropertyValue("PrintGrid", True) pageStyle.setPropertyValue("CenterHorizontally", True) - ' Make the margins 0.2" thick - + + pageStyle.HeaderIsOn = True + pageStyle.HeaderShared = True + pageStyle.FirstPageHeaderIsShared = True + + ' TODO simplify this logic, recalculate everytime + If highlightedCount <> 0 Then + If reportType = "PENDING" Then + Call SetHeader(pageStyle, Date() & " | FROM: " & fromDate, , "ONLINE: " & CStr(highlightedCount)) + ElseIf reportType ="EKYC" Then + Call SetHeader(pageStyle, "GENERATED ON: " & Date(), , "PMUY: " & CStr(highlightedCount)) + End If + End if + pageStyle.setPropertyValue("LeftMargin", 0.2 * 2540) pageStyle.setPropertyValue("RightMargin", 0.2 * 2540) ' Change original sheet name - s.Name = "SUMMARY" & sheetNameSuffix + ctx.oSheet.Name = "ALL" & sheetNameSuffix + + ' Clear subtotals if any before exporting area wise + If shouldRunSubtotals Then oCursor.removeSubtotals() + + If enableGroupReports Then + iGroupByColumn = GetHeaderPosition(ctx, sGroupBy) + If iGroupByColumn = -1 Then Goto ErrorHandler + If GenerateIndividualSheets(ctx, sonConf, reportType, sGroupBy, statusBar, False) = False Then + Goto ErrorHandler + End If + End If + + Dim summaryCtx as SondageContext: summaryCtx = ctx + summaryCtx.oSheet = oDoc.getSheets().getByIndex(1) + + Dim sValidationList$ + If reportType = "PENDING" Then + sValidationList = pendingRemarksValidateList + ElseIf reportType = "EKYC" Then + sValidationList = ekycRemarksList + End If + + If sValidationList <> "" Then + ' FIXME Add this check dynamically from config sheet + CreateValidationList(ctx, "Remarks", sValidationList) + End If + + If shouldRunSubtotals Then + Call RunSubtotals(oCursor, groupByColumn, statusBar) + Call ReArrangeResultToHeader(summaryCtx) + End If + + If statusBar Then statusBar.end() ' Export summary If shouldExportPDF Then - ExportPDF(s, exportFolder) + ExportAs(oDoc, ctx.oSheet, exportPrefix, exportDestDir, "pdf") End If - If NOT shouldSegregateAreaWise Then Exit Sub - - Dim statusBar - statusBar = oDoc.CurrentController.StatusIndicator - statusBar.start("Creating Area Wise", 10) - - areaRange = s.getCellRangeByPosition(areaColumn, startRow, areaColumn, endRow) - a = areaRange.getCellByPosition(0, startRow).getString() - 'On Error Goto ErrorHandler - For iArea = startRow To endRow - 1 - d = areaRange.getCellByPosition(0, iArea).getString() - If d = "" Then + if shouldExportSummaryEditable Then + ExportAs(oDoc, ctx.oSheet, exportPrefix, exportDestDir, "ods") + End If + + FinalFallback: + If Not IsEmpty(organizeInputsFolder) Then + If Not FileExists(organizeInputsFolder) Then MkDir(organizeInputsFolder) + + Dim sBackupInputFile: sBackupInputFile = organizeInputsFolder & GetPathSeparator() & tillDateStr & " " & reportType & ".csv" + If sBackupInputFile <> sInputFile Then + FileCopy(sInputFile, sBackupInputFile) + End If + End If + + If Environ("USERPROFILE") <> "" Then + ' Assume this is windows + Shell(Environ("COMSPEC"), 1, "/c start "" " & QS(QS(exportPrefix & GetPathSeparator() & exportDestDir))) + End If + If isHeadless Then + ' ThisComponent.Close(True) will close all open documents, we don't want that + ThisComponent.CurrentController.Frame.Close(True) + End If + + ErrorHandler: + If statusBar Then statusBar.end() + + ' This is the target document, so we close it everytime when not debugging + If Not IsNull(oDBDoc) and debugInputFile = False Then + oDoc.unlockControllers() + oDoc.Close(True) + End If + + ' Only close the DB file, when we are not debugging + If Not IsNull(oDBDoc) and debugInputFile = False Then + oDBDoc.unlockControllers() + oDBDoc.Close(True) + End If + + If ErrorLocal$ <> "" Then + MsgBox ErrorLocal$, 16, "FATAL Subfunction Error" + Exit Sub + End If + + If Erl <> 0 Then + MsgBox "Line " & Erl & ": "& Error$, 16, "FATAL Main Error" + On Error GoTo 0 + Exit Sub + End If + + If removeInputFileAfterSuccess Then + Kill(sInputFile) + End If +End Sub + +Function CopyRange(dstCtx as SondageContext, srcCtx as SondageContext, startRow&, endRow&) + ' Calculation for selecting the proper range + ' start end + '1 : endColumn 0 4 + 'groupByColumn + 1 : endColumn 2 4 + '0 : endColumn - 1 4 4 + + ' Copy Header + srcCtx.oSheet.copyRange(dstCtx.oSheet.getCellRangeByName("A1").CellAddress, _ + srcCtx.oSheet.getCellRangeByPosition( _ + srcCtx.startColumn, _ + 0, srcCtx.endColumn, 0).RangeAddress) + + ' Copy Contents + srcCtx.oSheet.copyRange(dstCtx.oSheet.getCellRangeByName("A2").CellAddress, _ + srcCtx.oSheet.getCellRangeByPosition(_ + srcCtx.startColumn, _ + startRow, _ + srcCtx.endColumn, _ + endRow).RangeAddress) +End Function + +Function GenerateIndividualSheets(ctx as SondageContext, sonConf as SondageConfiguration, reportType, sGroupByColumn$, statusBar as Variant, Optional sortColumn as Boolean) as Boolean + ' WARNING: This function requires a sorted column, unless specied as False in sortColumn + ' In that case, the column is assumed sorted + Dim oSheet as Variant, dstSheet as Variant + Dim startRow& + Dim d$, a$, sheetName$ + Dim iRow&, iGroupBy% + Dim subjectRange as Variant + Dim dstCtx as New SondageContext + GenerateIndividualSheets = False + + statusBar.start("Creating " & sGroupByColumn & " Wise", 100) + startRow = ctx.startRow + oSheet = ctx.oSheet + subjectRange = GetColumnRange(ctx, sGroupByColumn) + a = subjectRange.getCellByPosition(0, startRow).getString() + + ' FIXME We assume the groupBy will be at the start, this will change + iGroupBy = GetHeaderPosition(ctx, sGroupByColumn) + If iGroupBy > 0 And iGroupBy < ctx.endColumn Then + ErrorLocal$ = "Cannot have '" & sGroupByColumn & "' column in the middle" + Exit Function + End If + + ctx.startColumn = iGroupBy + 1 + + If IsMissing(sortColumn) Then sortColumn = True + For iRow = startRow To ctx.endRow - 1 + d = subjectRange.getCellByPosition(0, iRow).getString() + If a = "" And d = "" Then Exit For End If - If a <> d Or iArea = (endRow - 1) Then - statusBar.setValue((iArea / endRow) * 100) + If a <> d Or iRow = (ctx.endRow - 1) Then + statusBar.setText("Generating report for " & d) + statusBar.setValue((iRow / ctx.endRow) * 100) ' FIXME Get the columns automatically from the sheet ' FIXME Covert the end column from endColumn above - Goto Con: - Dim cName - s.Rows.insertByIndex(startRow, 1) - cName = s.getCellByPosition(startColumn, startRow) - cName.setString(d) - startRow = startRow + 1 - endRow = endRow + 1 - - Con: ' TODO maybe there is an elegant way than ' writing this two times sheetName = a & sheetNameSuffix - ' TODO subtotals might solve this - 's.group(areaRange.RangeAddress, 1) - ' Prepare Destination sheet - destSheet = NewSheet(sheetName) - - - ' Copy the Headers from the Main Document - If areaColumn > 0 And areaColumn < endColumn Then - MsgBox "Can't have Area column in the middle", 16 - Exit Sub - End If + dstSheet = NewSheet(ctx.oDoc, sheetName) + dstCtx = SondageGetContext(dstSheet) + dstCtx.endRow = ctx.endRow + dstCtx.endColumn = ctx.endColumn + CopyRange(dstCtx, ctx, startRow, iRow) - ' start end - '1 : endColumn 0 4 - 'areaColumn + 1 : endColumn 2 4 - '0 : endColumn - 1 4 4 - - ' Copy Header - s.copyRange(destSheet.getCellRangeByName("A1").CellAddress, _ - s.getCellRangeByPosition( _ - (endColumn - areaColumn)/ endColumn, _ - 0, endcolumn - CInt(areaColumn/endColumn), 0).RangeAddress) - - ' Copy Contents - s.copyRange(destSheet.getCellRangeByName("A2").CellAddress, _ - s.getCellRangeByPosition(_ - (endColumn - areaColumn)/ endColumn, _ - startRow, _ - endcolumn - CInt(areaColumn/endColumn), _ - iArea).RangeAddress) - - ' Customize the Destination Sheet's Columns - If Left(reportType, 1) = "P" Then - SetWidths(destSheet, endColumn, Array( _ - Array("ID", 0), _ - Array("Name", 7000), _ - Array("Mobile", 0), _ - Array("Book", 0) _ - )) - ElseIf reportType = "SBC" Then - SetWidths(destSheet, endColumn, Array( _ - Array("ID", 0), _ - Array("Name", 4000), _ - Array("Address", 11000), _ - Array("Mobile", 0) _ - )) + ' TODO Copy only required cells, instead of copying and deleting for GroupBys + Dim testAreaColumn: testAreaColumn = GetHeaderPosition(dstCtx, sGroupByColumn) + if testAreaColumn > 0 Then + dstSheet.getColumns().removeByIndex(testAreaColumn, 1) End If - + + SondageTransformSheet(dstCtx, sonConf, reportType, "Width") + If shouldExportPDF Then - ExportPDF(destSheet, exportFolder) + if ExportAs(dstCtx.oDoc, dstCtx.oSheet, exportPrefix, exportDestDir, "pdf") = False Then Exit Function End If - Continue: - startRow = (iArea + 1) + startRow = (iRow + 1) a = d End If - Next iArea + Next iRow + GenerateIndividualSheets = True +End Function - ErrorHandler: - statusBar.end() - Reset +Function RunSubtotals(oCursor, iColumn, Optional statusBar as Variant) + If Not IsMissing(statusBar) Then statusBar.setText("Running subtotals") + Dim oSubtotalDesc : oSubtotalDesc = oCursor.createSubTotalDescriptor(true) + Dim oSubtotalColumn(0) as new com.sun.star.sheet.SubTotalColumn + + With oSubtotalColumn(0) + .Column = iColumn + .Function = com.sun.star.sheet.GeneralFunction.COUNT + End With + oSubtotalDesc.addNew(oSubtotalColumn, iColumn) + oCursor.applySubtotals(oSubtotalDesc, true) +End Function + +Sub SubstituteContent(oDoc, oShape, oProduct) + ' TODO Maybe change from If Not to If and show error? + If oShape.getName() = "" Then + Exit Sub + End If + If oShape.getName() = "StovePrice" Then + If oProduct.Price <> 0 Then + oShape.setString(CURRENCY_UNIT & CStr(oProduct.Price)) + End If + ElseIf oShape.getName() = "ProductBlurb" Then + If oProduct.Description <> "" Then + oShape.setString(oProduct.Description) + End If + ElseIf oShape.getName() = "ProductTitle" Then + If IsEmpty(oProduct.Title) Then + oShape.setString(oProduct.Title) + End If + End If +End Sub + +Function GetFirstOpenDocument(docType as String) + Dim oComponents: oComponents = StarDesktop.getComponents() + Dim oDoc + Dim oDocs: oDocs = oComponents.createEnumeration() + Do While oDocs.hasMoreElements() + oDoc = oDocs.nextElement() + If oDoc.supportsService(docType) Then + GetFirstOpenDocument = oDoc + Exit Function + End If + Loop +End Function + +Sub Dialog1Show + With GlobalScope.BasicLibraries + If Not .IsLibraryLoaded("Tools") Then .LoadLibrary("Tools") + End With + Dim oAddBtn + Dim oDialog1 + Dim oColorTbl, oHeaders, oColumn1, oColumn2, oColumn3, oComboBox, oDataModel + oDialog1 = Tools.ModuleControls.LoadDialog("Standard", "Dialog1") + oAddBtn = oDialog1.getControl("AddBtn").getModel() + oColorTbl = oDialog1.getControl("ColorTable").getModel() + oColorTbl.Width = 150 ' TODO get width value from column + + oColumn1 = createUnoService( "com.sun.star.awt.grid.GridColumn") + oColumn2 = createUnoService( "com.sun.star.awt.grid.GridColumn") + oColumn3 = createUnoService( "com.sun.star.awt.grid.GridColumn") + + oColumn1.Title = "Condition" + oColumn1.MaxWidth = 30 + oColumn2.Title = "Value" + oColumn2.MaxWidth = 30 + oColumn3.Title = "Color" + + ' Print oColumn3.dbg_properties() + oHeaders = createUnoService("com.sun.star.awt.grid.DefaultGridColumnModel") + oDataModel = createUnoService( "com.sun.star.awt.grid.DefaultGridDataModel") + + oHeaders.addColumn(oColumn1) + oHeaders.addColumn(oColumn2) + oHeaders.addColumn(oColumn3) + + oColorTbl.GridDataModel = oDataModel + + oColorTbl.ColumnModel = oHeaders + oDataModel.addRow("1", Array(">", "45", "#ff0000")) + oDialog1.Execute() +End Sub + +Sub SetCustomBadStyle(oDoc, oLocale, styleName as String) + Dim oCellStyles + Dim oStyle + Dim formatNum% + oCellStyles = oDoc.StyleFamilies("CellStyles") + If oCellStyles.hasByName(styleName) Then + oCellStyles.removeByName(styleName) + End If + oStyle = oDoc.createInstance("com.sun.star.style.CellStyle") + oCellStyles.insertByName(styleName, oStyle) + oStyle = oCellStyles.getByName(styleName) + oStyle.CellBackColor = RGB(255, 0, 0) + formatNum = GetNumberFormatNumber(oLocale, oDoc.getNumberFormats(), "DD/MM") + If formatNum = -1 Then + ErrorLocal$ = "WARNING: Cannot add '" & formatStr & "' as NumberFormat" + Exit Sub + End If + oStyle.NumberFormat = formatNum +End Sub + +Sub SetupConditionalForHighPriority(oDoc, oLocale, oRange, styleName$, _ + opCond$, formula1 as Variant, Optional formula2 as Variant) + + ' TODO Rework this function to automagically handle dates + Dim oConFormat + Dim oCondition(3) as new com.sun.star.beans.PropertyValue + + 'BasicLibraries.LoadLibrary("Sondage") + + ' FIXME This may very well crash on some operations, I have no idea, because + ' I have not tested it + If IsMissing(formula2) Then formula2 = "0" + + If TypeName(formula1) = "Date" Then + formula1 = CStr(CLng(formula1)) + End If + + If TypeName(formula2) = "Date" Then + formula2 = CStr(CLng(formula2)) + End If + + With oCondition(0) + .Name = "Operator" + .Value = SondageGetCondTypeFromString(opCond) + End With + With oCondition(1) + .Name = "Formula1" + .Value = formula1 + End With + With oCondition(2) + .Name = "Formula2" + .Value = formula2 + End With + With oCondition(3) + .Name = "StyleName" + .Value = styleName + End With + + oConFormat = oRange.ConditionalFormat + oConFormat.clear() + oConFormat.addNew(oCondition) + oRange.ConditionalFormat = oConFormat +End Sub + +Sub ShowFilterOptions() + Dim args(), i% + args() = StarDesktop.CurrentComponent.getArgs() + For i = 0 to uBound(Args()) + If args(i).Name = "FilterOptions" then inputbox args(i).Name,"",cStr(args(i).value) + Next End Sub
diff --git a/GVTAdvance.bas b/GVTAdvance.bas @@ -0,0 +1,254 @@ +REM ***** BASIC ***** +Option Explicit + +Global Const GVT_INSERT_PHONEBOOK_QUERY = "INSERT INTO `phonbook`(num,nam,adrs,stat,cty,zipc,eml,cid,num1,oth1,oth2,oth3,oth4,oth5,oth6,oth7,oth8,oth9,oth10) VALUES" +Global Const GVT_INSERT_BROADCAST_QUERY = "INSERT INTO `fctnum`(usr,nam,num,stt,cty,callon,stts,fedbck,oth1,oth2,oth3,oth4,oth5,oth6,oth7,oth8,oth9,oth10,dispo,clientID) VALUES" +Function QS(sQueryValue) as String + QS = CHR(34) & sQueryValue & CHR(34) +End Function + +Function GenerateEmptyDoubleQuotes(iEmptyCount as Integer) as String + Dim i% + Dim sQuery as String + For i = 1 To iEmptyCount + sQuery = sQuery & "," & QS("") + Next i + GenerateEmptyDoubleQuotes = sQuery +End Function + +Function ConstructSQLValues(sQueryValues, iEmptyAppend as Integer) as String + Dim i + Dim sQuery as String + sQuery = "(" + For i = LBound(sQueryValues) To UBound(sQueryValues) + ' TODO Simplif sQuery assignment + If TypeName(sQueryValues(i)) = "String" Then + sQuery = sQuery & IIf(sQueryValues(i)="", QS(""), QS(sQueryValues(i))) + Else + sQuery = sQuery & sQueryValues(i) + End If + If i <> UBound(sQueryValues) Then sQuery = sQuery & "," + Next i + + sQuery = sQuery & GenerateEmptyDoubleQuotes(iEmptyAppend) + sQuery = sQuery & ")" + ConstructSQLValues = sQuery +End Function + +Sub PopulateConsumerDetails(dbFilePath, ctx as Object) + ' Connect using JDBC to Advance.mdb + ' INSERT INTO phonbook(id, name, mobile) values (...) + Dim oManager, oCon, oStatement, oPrepStatement, oResult + Dim oParms(2) As New com.sun.star.beans.PropertyValue + Dim sURL as String, sSQL as String + + ' TODO Remove this, and use ctx directly to avoid confusion + Dim oSheet: oSheet = ctx.oSheet + + ' TODO Save memory and improve speed by switching to jackhess API + sURL = "jdbc:ucanaccess://" & dbFilePath & GetPathSeparator() & "Advance.mdb" + oManager = CreateUnoService("com.sun.star.sdbc.DriverManager") + oParms(0).Name = "user" + oParms(0).Value = "" + oParms(1).Name = "password" + oParms(1).Value = "" + oParms(2).Name = "JavaDriverClass" + oParms(2).Value = "net.ucanaccess.jdbc.UcanloadDriver" + oCon = oManager.GetConnectionWithInfo(sURL, oParms()) + oStatement = oCon.CreateStatement() + + Dim iIDCol%, iEmailCol%, iNameCol%, iAddressCol%, iPincodeCol%, iMobileCol%, iPhoneCol% + iIDCol = GetHeaderPosition(ctx, "ID") + iEmailCol = GetHeaderPosition(ctx, "Email") + iNameCol = GetHeaderPosition(ctx, "Name") + iAddressCol = GetHeaderPosition(ctx, "Address") + iPincodeCol = GetHeaderPosition(ctx, "Pin Code") + iMobileCol = GetHeaderPosition(ctx, "Mobile") + iPhoneCol = GetHeaderPosition(ctx, "Phone") + + + Dim i as Long + Dim id as Double + Dim sIdq as String + ' Indian phone numbers are 10 digits, Doucbe can hold ~15 digits in LO Basic + Dim num as Double + Dim num1 as Double + Dim zipc as Double + + Dim adrs as String + Dim nam as String + Dim eml as String + + 'On Error Goto SQLCmdErrorHandle + For i = 1 To oSheet.getRows().getCount() - 1 + id = CLng(oSheet.getCellByPosition(iIDCol, i).Value) + sIdq = QS(CStr(id)) + nam = oSheet.getCellByPosition(iNameCol, i).String + 'eml = oSheet.getCellByPosition(iEmailCol, i).String + adrs = oSheet.getCellByPosition(iAddressCol, i).String + 'zipc = oSheet.getCellByPosition(iPincodeCol, i).Value + num = oSheet.getCellByPosition(iMobileCol, i).Value + 'num1 = oSheet.getCellByPosition(iPhoneCol, i).Value + + ' Check if id exists in phonbook + sSQL = "SELECT * FROM `phonbook` WHERE cid=" & sIdq + oResult = oStatement.executeQuery(sSQL) + If oResult.next() Then + ' id exists in phonbook, we should do an update + sSQL = "UPDATE `phonbook` SET " & _ + "num=?, nam=?, adrs=?,zipc=?,eml=?,num1=?" & _ + " WHERE cid=" & sIdq + oPrepStatement = oCon.prepareStatement(sSQL) + With oPrepStatement + .setString(1, num) + .setString(2, nam) + .setString(3, adrs) + .setString(4, zipc) + .setString(5, eml) + .setString(6, num1) + End With + + 'oResult = oStatement.prepareStatement(sSQL) + oPrepStatement.executeUpdate() + Else + ' GVT Advance has additonal fields which we cannot ignore during an insert(results in a NULL CONSTRAINT violation) + ' So we are expanding `""` 10 times to make UCanaccess happy + ' This can be grarcefully handled by using Jackcess API + sSQL = GVT_INSERT_PHONEBOOK_QUERY & _ + "(?,?,?,?,?,?,?,?,?" & _ + GenerateEmptyDoubleQuotes(10) & ")" + 'ConstructSQLValues(Array(num, nam, adrs, stateName, cityName, zipc, eml, id, num1), 10) + + 'https://stackoverflow.com/a/35844168/4816020 + 'oStatement.executeUpdate(sSQL) + oPrepStatement = oCon.prepareStatement(sSQL) + With oPrepStatement + .setString(1, num) + .setString(2, nam) + .setString(3, adrs) + .setString(4, stateName) + .setString(5, cityName) + .setString(6, zipc) + .setString(7, eml) + .setString(8, id) + .setString(9, num1) + End With + oPrepStatement.executeUpdate() + End If + Next i + + oCon.Close() + Exit Sub + SQLCmdErrorHandle: + ErrorLocal$ = "SQL Update error: Error while executing: " & sSQL & CHR(10) & Erl() & ": " & Error() + Reset + oCon.Close() +End Sub + +Sub ReducedPopulateConsumerDetails(dbFilePath, oSheet as Object) + ' Connect using JDBC to Advance.mdb + ' INSERT INTO phonbook(id, name, mobile) values (...) + Dim oManager, oCon + Dim oCheckStatement, oInsertStatement, oUpdateStatement, oResult + Dim oParms(2) As New com.sun.star.beans.PropertyValue + Dim sURL as String, sSQL as String + Dim oUsedRange: oUsedRange = UsedRangeCursor(oSheet) + + Dim endRow&: endRow = oUsedRange.RangeAddress.EndRow + + ' TODO Save memory and improve speed by switching to jackhess API + sURL = "jdbc:ucanaccess://" & dbFilePath & GetPathSeparator() & "Advance.mdb" + oManager = CreateUnoService("com.sun.star.sdbc.DriverManager") + oParms(0).Name = "user" + oParms(0).Value = "" + oParms(1).Name = "password" + oParms(1).Value = "" + oParms(2).Name = "JavaDriverClass" + oParms(2).Value = "net.ucanaccess.jdbc.UcanloadDriver" + oCon = oManager.GetConnectionWithInfo(sURL, oParms()) + + Dim endColumn%, iIDCol%, iNameCol%, iAddressCol%, iMobileCol% + endColumn = UsedRangeCursor(oSheet).RangeAddress.EndColumn + iIDCol = GetHeaderPosition(oSheet, endColumn, "ID") + iNameCol = GetHeaderPosition(oSheet, endColumn, "Name") + iAddressCol = GetHeaderPosition(oSheet, endColumn, "Address") + iMobileCol = GetHeaderPosition(oSheet, endColumn, "Mobile") + + Dim i as Long + Dim sIdq as String + ' Indian phone numbers are 10 digits, Doucbe can hold ~15 digits in LO Basic + Dim id as Double + Dim nam as String + Dim adrs as String + Dim num as Double + + oCheckStatement = oCon.createStatement() + 'oResult = oCheckStatement.executeQuery("DELETE FROM `fctnum`") + 'oResult = oCheckStatement.executeQuery("UPDATE `fctnum` SET usr=" & QS("Somen")) + + 'oCheckStatement = oCon.prepareStatement("SELECT * FROM `phonbook` WHERE cid=?") + Dim sCheck$: sCheck = "SELECT * FROM `fctnum` WHERE clientID=" + oUpdateStatement = oCon.prepareStatement("UPDATE `fctnum` SET nam=?, num=? WHERE clientID=?") + + sSQL = GVT_INSERT_BROADCAST_QUERY & _ + "(" & QS("admin") & ",?,?," & _ + QS(stateName) & "," & _ + QS(cityName) & "," & _ + QS("01-Jan-01") & _ + GenerateEmptyDoubleQuotes(13) & "," & _ + "?)" + oInsertStatement = oCon.prepareStatement(sSQL) + 'On Error Goto SQLCmdErrorHandle + For i = 1 To endRow + id = CLng(oSheet.getCellByPosition(iIDCol, i).Value) + nam = oSheet.getCellByPosition(iNameCol, i).String + 'adrs = oSheet.getCellByPosition(iAddressCol, i).String + num = oSheet.getCellByPosition(iMobileCol, i).Value + + sIdq = QS(CStr(id)) + sSQL = sCheck & sIdq + ' Check if id exists in phonbook + 'oCheckStatement.setString(1, sIdq) + oResult = oCheckStatement.executeQuery(sSQL) + If oResult.next() Then + With oUpdateStatement + .setString(1, nam) + .setString(2, num) + '.setString(3, adrs) + .setString(3, id) + '.setString(4, zipc) + '.setString(5, eml) + '.setString(6, num1) + End With + + 'oResult = oStatement.prepareStatement(sSQL) + oUpdateStatement.executeUpdate() + Else + ' GVT Advance has additonal fields which we cannot ignore during an insert(results in a NULL CONSTRAINT violation) + ' So we are expanding `""` 10 times to make UCanaccess happy + ' This can be grarcefully handled by using Jackcess API + + 'https://stackoverflow.com/a/35844168/4816020 + 'oStatement.executeUpdate(sSQL) + With oInsertStatement + .setString(1, nam) + .setString(2, num) + '.setString(3, adrs) + '.setString(4, stateName) + '.setString(5, cityName) + '.setString(6, zipc) + '.setString(7, eml) + .setString(3, id) + '.setString(9, num1) + End With + oInsertStatement.executeUpdate() + End If + Next i + + oCon.Close() + Exit Sub + SQLCmdErrorHandle: + ErrorLocal$ = "SQL Update error: Error while executing: " & sSQL & CHR(10) & Erl() & ": " & Error() + Reset + oCon.Close() +End Sub
diff --git a/HandyTools.bas b/HandyTools.bas @@ -1,38 +1,124 @@ REM ***** BASIC ***** Option Explicit -Function GetFriendlyWords() as Variant - GetFriendlyWords = Array( _ - "AreaCodeDesc", "Area", _ - "AreaDescription", "Area", _ - "ConsumerNumber", "ID", _ - "ConsumerName", "Name", _ - "MobileNumber", "Mobile", _ - "BookDate", "Book"_ - ) - If (UBound(GetFriendlyWords) Mod 2) <> 1 Then - Print "Mismatch in friendlyWords array" - Exit Function +Type SondageSettings + oFieldAliasesRange as Variant +End Type + +Type SondageContext + oDoc as Variant + oSheet as Variant + oRange as Variant + headerRow& + startColumn& + startRow& + endColumn& + endRow& +End Type + +Private priceListPath as String + +Public Function Env(Value As Variant) As String + Env = Environ(Value) +End Function + +Type Product + Title as Variant ' com.sun.star.text.XText + Price as Integer + Description as String +End Type + +'https://ask.libreoffice.org/t/how-to-know-if-the-file-is-open/77760/7 +Function ReturnComponentIfOpen(Byval filePath As String) as Object + Dim oComp + filePath=ConvertToUrl(filePath) + For Each oComp In StarDesktop.Components + If HasUnoInterfaces(oComp, "com.sun.star.frame.XModel") Then ' component which has URL + If oComp.Url=filePath Then + ReturnComponentIfOpen = oComp + Exit Function + End If End If + Next oComp End Function -Sub FormatRangeAsNumber(oSheet, oLocale, ByRef oFormats, oRange, formatStr as String) +Function CreateProperty(key as String, val as Variant) as com.sun.star.beans.PropertyValue + Dim oProp As New com.sun.star.beans.PropertyValue + oProp.Name = key + oProp.Value = val + CreateProperty = oProp +End Function + +Function GetHomePath() as Object + Dim oPathSub + oPathSub = CreateUnoService("com.sun.star.util.PathSubstitution") + GetHomePath = oPathSub.getSubstituteVariable("home") & "/" +End Function + +Function ReadProductFromSheet(oSheet as Object, sProductName as String) as Product + ' TODO FIX: Return the correct Product details instead of first item + Dim oProduct as Product + Dim iPrice + Dim oTitle + Dim iChannel as Integer + Dim oCalcDoc + Dim oCursor, oCell + Dim bProductFound: bProductFound = False + Dim i, j, iRow, iColumn as Integer + Dim sCalcFile: sCalcFile = ConvertToUrl(priceListPath) + + Dim oArgs(0) as new com.sun.star.beans.PropertyValue + oArgs(0).Name = "Hidden" + oArgs(0).Value = True + + oCursor = UsedRangeCursor(oSheet) + iRow = oCursor.getRows().Count() + iColumn = oCursor.getColumns().getCount() + + ' TODO Use Column headers for retrieving data + For i = 1 To iRow - 1 + oCell = oSheet.getCellByPosition(0, i) + If oCell.String = sProductName Then + bProductFound = True + Goto CLOSE_SHEET_AND_REFLECT: + End If + Next i + +CLOSE_SHEET_AND_REFLECT: + If bProductFound Then + oTitle = oSheet.getCellByPosition(1, i).getString() + oProduct.Title = oCursor + '############################ + oProduct.Price = oSheet.getCellByPosition(3, i).getValue() + End If + ReadProductFromSheet = oProduct + oCalcDoc.close(True) +End Function + +Function GetNumberFormatNumber(oLocale as com.sun.star.lang.Locale, ByRef oFormats, formatStr as String) as Integer + Dim formatNum as Long + GetNumberFormatNumber = -1 + formatNum = oFormats.queryKey(formatStr, oLocale, False) + ' add formatStr if it doesn't exist + If formatNum = -1 Then + formatNum = oFormats.addNew(formatStr, oLocale) + End If + GetNumberFormatNumber = formatNum +End Function + +Sub FormatRangeAsNumber(oLocale as com.sun.star.lang.Locale, ByRef oFormats, oRange, formatStr as String) ' BASIC equivalent of 'Text to Columns' Dim formatNum as Long, i as Integer Dim oReplace oReplace = oRange.createReplaceDescriptor() If oRange.getCellByPosition(0,0).getValue() = 0 Then - formatNum = oFormats.queryKey(formatStr, oLocale, False) - ' add formatStr if it doesn't exist + formatNum = GetNumberFormatNumber(oLocale, oFormats, formatStr) If formatNum = -1 Then - formatNum = oFormats.addNew(formatStr, oLocale) - If formatNum = -1 Then - MsgBox "Cannot add " & formatStr & " as NumberFormat", 0, "Fatal" - Exit Sub - End If + ErrolLocal$ = "Cannot add " & formatStr & " as NumberFormat" + Exit Sub End If - + ' https://ask.libreoffice.org/t/macro-calc-convert-column-to-date-similar-text-to-columns/92168/20 With oReplace .searchString = ".+" .replaceString = "&" @@ -44,40 +130,41 @@ Sub FormatRangeAsNumber(oSheet, oLocale, ByRef oFormats, oRange, formatStr as St End If End Sub -Function GetColumnRange(oSheet, endColumn as Long, endRow as Long, searchString as String) as Object +Function GetColumnRange(ctx as SondageContext, columnName as String, Optional shouldIncludeHeader as Boolean) as Object Dim iHeaderPos - 'GetColumn = -1 - iHeaderPos = GetHeaderPosition(oSheet, endColumn, searchString) + If IsMissing(shouldIncludeHeader) Then shouldIncludeHeader = False + iHeaderPos = GetHeaderPosition(ctx, columnName) If iHeaderPos = -1 Then + GetColumnRange = ctx.oSheet.getCellRangeByPosition(0, 0, 0, 0) Exit Function End If - GetColumnRange = oSheet.getCellRangeByPosition(iHeaderPos, 1, iHeaderPos, endRow) + GetColumnRange = ctx.oSheet.getCellRangeByPosition(iHeaderPos, IIf(shouldIncludeHeader, ctx.headerRow, ctx.startRow), iHeaderPos, ctx.endRow) End Function -Function RemoveColumns(oSheet, endColumn as Integer, columnNames) as Long +Function RemoveColumns(ctx as SondageContext, columnNames) as Long Dim columnName as String Dim iHeader as Integer - RemoveColumns = endColumn + RemoveColumns = ctx.endColumn For Each columnName in columnNames - iHeader = GetHeaderPosition(oSheet, endColumn, columnName) + iHeader = GetHeaderPosition(ctx, columnName) If iHeader <> -1 Then - oSheet.getColumns().removeByIndex(iHeader, 1) - endColumn = endColumn - 1 + ctx.oSheet.getColumns().removeByIndex(iHeader, 1) + ctx.endColumn = ctx.endColumn - 1 End If Next - RemoveColumns = endColumn + RemoveColumns = ctx.endColumn End Function -Function RemoveColumnsExcept(oSheet as Object, endColumn as Integer, columnNames as Variant) as Long +Function RemoveColumnsExcept(ctx as SondageContext, columnNames as Variant) as Long Dim headerStr as String, columnName as String Dim i% : i = 0 Dim rI% : rI = 0 - Dim columnsToRemove(endColumn) as String + Dim columnsToRemove(ctx.endColumn) as String Dim headerRange, headerData Dim found as Boolean : found = False - RemoveColumnsExcept = endColumn + RemoveColumnsExcept = ctx.endColumn - headerRange = oSheet.getCellRangeByPosition(0, 0, endColumn, 0) + headerRange = ctx.oSheet.getCellRangeByPosition(0, 0, ctx.endColumn, 0) headerData = headerRange.getFormulaArray() ' TODO Handle condition when columnNames does not have valid header @@ -101,18 +188,22 @@ Function RemoveColumnsExcept(oSheet as Object, endColumn as Integer, columnNames Exit Function End If + If rI = 0 Then + RemoveColumnsExcept = ctx.endColumn + Exit Function + End If ReDim Preserve columnsToRemove(rI - 1) - RemoveColumnsExcept = RemoveColumns(oSheet, endColumn, columnsToRemove) + RemoveColumnsExcept = RemoveColumns(ctx, columnsToRemove) End Function -Sub ApplyTheme(sFileName As String) +Sub ApplyTheme(ByRef oDoc, sFileName As String) Dim oFamilies Dim aOptions(0) as New com.sun.star.beans.PropertyValue Dim stylesDir() Dim StylePath as String GlobalScope.BasicLibraries.loadLibrary("Tools") - oFamilies = ThisComponent.StyleFamilies + oFamilies = oDoc.StyleFamilies StylesDir = GetOfficeSubPath("Template", "wizard/styles/") StylePath = StylesDir & sFileName aOptions(0).Name = "OverwriteStyles" @@ -120,18 +211,16 @@ Sub ApplyTheme(sFileName As String) oFamilies.loadStylesFromURL(StylePath, aOptions()) End Sub -Function NaiveLastTable(oSheet) as Long +Function NaiveLastTable(ctx as SondageContext) as Long ' Return the row position last table that is separated by an empty row Dim oRows Dim iRow as Long Dim usedRange NaiveLastTable = 0 - - oRows = UsedRangeCursor(oSheet).Rows + oRows = ctx.oRange.Rows For iRow = 0 To oRows.getCount() - 1 - 'Print rows(i).dbg_methods() - If oRows.getByIndex(iRow).computeFunction(com.sun.star.sheet.GeneralFunction.COUNT) = 0 Then + If oRows.getByIndex(iRow).computeFunction(com.sun.star.sheet.GeneralFunction.COUNT) = 0Then NaiveLastTable = iRow End If Next @@ -152,30 +241,58 @@ Function IsValidFileName(fileName as String) as Boolean IsValidFileName = True End Function -Sub ExportPDF(oSheet, exportFolder as String) +Function ExportAs(oDoc, oSheet, exportPrefix$, exportDestDir$, exportExt$) as Boolean Dim cursor as Object Dim args(2) as New com.sun.star.beans.PropertyValue Dim fd(2) as New com.sun.star.beans.PropertyValue - Dim fileName as String - + Dim fileName as String, fileUrl + ExportAs = False + On Error GoTo ErrorHandler + If Not IsValidFileName(oSheet.Name) Then - Exit Sub + ErrorLocal$ = "Sheet has invalid characters for file export" + Exit Function End If - - fileName = exportFolder & "/" & oSheet.Name & ".pdf" + 'If Right(exportPrefix, 1) = "/" Or Right(exportPrefix, 1) = "\" Then + ' exportPrefix = Left(exportPrefix, Len(exportPrefix) - 1) + + fileUrl = ConvertToUrl(exportPrefix) + If Not FileExists(fileUrl) Then + ErrorLocal$ = "FATAL: " & fileUrl & " does not exist" + Exit Function + End If + + fileUrl = ConvertToUrl(exportPrefix & GetPathSeparator() & exportDestDir) + If Not FileExists(fileUrl) Then + Mkdir fileUrl + End If + + fileName = exportPrefix & GetPathSeparator() & exportDestDir & GetPathSeparator() & oSheet.Name & "." & exportExt + fileUrl = ConvertToUrl(fileName) + WIth fd(0) : .Name = "Selection" : .Value = UsedRangeCursor(oSheet) : End With ' Disabled, because it conflicts with selection With fd(1) : .Name = "SinglePageSheets" : .Value = False : End With With fd(2) : .Name = "IsSkipEmptyPages" : .Value = True : End With - With args(0) : .Name = "FilterName" : .Value = "calc_pdf_Export" : End With + If exportExt = "pdf" Then + With args(0) : .Name = "FilterName" : .Value = "calc_pdf_Export" : End With + ElseIf exportExt = "ods" Then + With args(0) : .Name = "FilterName" : .Value = "calc8" : End With + Else + ErrorLocal$ = "FATAL: Export type '" & exportExt & "' not handled" + End If + With args(1) : .Name = "FilterData" : .Value = fd : End With With args(2) : .Name = "Overwrite" : .Value = True : End With - ThisComponent.storeToURL(ConvertToUrl(fileName), args) -End Sub - + oDoc.storeToURL(fileUrl, args) + ExportAs = True + Exit Function +ErrorHandler: + ErrorLocal$ = "FATAL: ExportPDF: Unknown error" +End Function Sub ListOfActiveCustomers() Dim oSheet, destSheet, cursor, oRange @@ -192,7 +309,7 @@ Sub ListOfActiveCustomers() cursor = UsedRangeCursor(oSheet) ' Skip Header - startRow = NaiveLastTable(ThisComponent, cursor) + startRow = NaiveLastTable(cursor) endRow = cursor.RangeAddress.EndRow endColumn = cursor.RangeAddress.EndColumn ' TODO Use data from PhoneNumber if some MobileNumber is missing @@ -209,7 +326,7 @@ Sub ListOfActiveCustomers() End If Next iRequiredField Next iColumn - destSheet = NewSheet("SBC Connection") + destSheet = NewSheet(oDoc, "SBC Connection") Print Join(requiredFieldIndices) @@ -220,16 +337,115 @@ Sub ListOfActiveCustomers() ' Copy the cells in 'requiredFieldIndices' to 'destSheet' End Sub +Sub CombineFiles(sFolder as String, fileRegex as String) + Dim sFile + Dim sFiles as Variant + Dim i as Integer: i = 0 + Dim oDoc as Variant + Dim dstSheet + Dim oDstCursor + Dim oSrcCursor + Dim rangeAddress + Dim oSheet + If Not FileExists(sFolder) Then + ErrorLocal$ = "sFolder path: '" & sFolder & "' does not exist" + Exit Sub + End If + + sFile = Dir( sFolder & "\" & fileRegex, 0) + + If IsEmpty(oDoc) Then + oDoc = ImportReportFile(sFolder & "\" & sFile, False) + if IsEmpty(oDoc) Then + ErrorLocal$ = "Failed to get Document for " & sInputFile + Exit Sub + End If + If Not oDoc.supportsService( "com.sun.star.sheet.SpreadsheetDocument") Then + Print "The imported document is not a sheet document" + End If + dstSheet = oDoc.getSheets().getByIndex(0) + End If + + sFile = Dir() + Do While(sFile <> "") + oDstCursor = UsedRangeCursor(dstSheet) + i = i + 1 -Function UsedRangeCursor(Optional ByRef oSheet as Object) as Object - Dim cursor as Object - if IsNull(oSheet) Or IsMissing(oSheet) Then - oSheet = ThisComponent.getCurrentController().getActiveSheet() + oDoc.getSheets().insertNewByName(CStr(i), i) + oSheet = oDoc.getSheets().getByIndex(i) + If IsEmpty(oSheet) Then + ErrorLocal$ = "Cannot create new sheet" + Exit Sub + End If + + oSheet.link(ConvertToUrl(sFolder & "\" & sFile), CStr(i), CSV_FILTER_NAME, PENDING_CSV_FILTER_OPTIONS, com.sun.star.sheet.SheetLinkMode.NORMAL) + + oSrcCursor = UsedRangeCursor(oSheet, 1) + + dstSheet.copyRange(dstSheet.getCellByPosition(0, oDstCursor.RangeAddress.EndRow + 1).getCellAddress(), oSrcCursor.RangeAddress) + sFile = Dir() + Loop +End Sub + +Function UsedRangeCursor(oSheet as Variant, Optional rowsToSkip as Integer) as Variant + Dim oCursor + Dim i as Integer + oCursor = oSheet.createCursor() + oCursor.gotoStartOfUsedArea(False) + If Not IsMissing(rowsToSkip) Then oCursor.gotoOffset(0, rowsToSkip, False) + oCursor.gotoEndOfUsedArea(True) + UsedRangeCursor = oCursor +End Function + +Function GetProductNames() as Variant + GetProductNames = Array( _ + 5300, "14.2", _ + 5350, "14.2s", _ + ) + ' TODO finish deploying the extension and push extension to git +End Function + +Function ProductDescrption(productCode as Integer) as String + Dim i as Long + Dim productNames: productNames = GetProductNames() + ProductDescription = "" + For i = 0 To UBound(productNames) Step 2 + If productNames(i) = productCode Then + ProductDescription = productNames(i + 1) + End If + Next i +End Function + +Function GetValueForKey(oRange as Variant, key as String, Optional valueOffset%) as Object + ' Returns a ScCellObj + Dim oSearchRange + Dim oSearchDescriptor + Dim oCell + + If oRange.Columns.Count < 2 Then + MsgBox "GetValueForKeyCannot have columns less than 2", 16 + GetValueForKey = oCell + Exit Function + End If + + oSearchRange = oRange.getCellRangeByPosition(0, 0, 0, oRange.Rows.Count - 1) + oSearchDescriptor = oSearchRange.createSearchDescriptor() + With oSearchDescriptor + .SearchString = key + .SearchWords = True + .SearchCaseSensitive = True + End With + oCell = oSearchRange.findFirst(oSearchDescriptor) + + If Not IsNull(oCell) Then + If IsMissing(valueOffset) Then + valueOffset = oCell.RangeAddress.StartColumn + 1 + End If + oCell = oRange.getCellByPosition( valueOffset, _ + oCell.RangeAddress.StartRow _ + ) End If - cursor = oSheet.createCursor() - cursor.gotoStartOfUsedArea(False) - cursor.gotoEndOfUsedArea(True) - UsedRangeCursor = cursor + GetValueForKey = oCell End Function Function UserFriendlyName(str as String) as String @@ -238,20 +454,18 @@ Function UserFriendlyName(str as String) as String Dim l as Long Dim c as String Dim i as Long - Dim prevChar as String - Dim friendlyWords : friendlyWords = GetFriendlyWords() + Dim prevChar$ + Dim oValCell + str = Trim(str) - ' Check if Len(str) is really called multiple times + oValCell = GetValueForKey(GlobalSondageSettings.oFieldAliasesRange, str) + If Not IsNull(oValCell) Then + UserFriendlyName = oValCell.String + Exit Function + End If + l = Len(str) ' Check with header "database" - - For i = 0 To UBound(friendlyWords) Step 2 - If friendlyWords(i) = str Then - UserFriendlyName = friendlyWords(i + 1) - Exit Function - End If - Next i - For i = 0 To l c = Mid(str, i + 1, 1) If i > 1 And (c > "A" And c < "Z") Then @@ -265,60 +479,63 @@ Function UserFriendlyName(str as String) as String Next End Function -Sub SortColumn(oSheet As Variant, endColumn as Integer, endRow as Integer, columnName as String) - Dim oRange as Object - Dim iHeaderPos as Integer +Sub SortColumn(ctx as SondageContext, columnName1 as String, Optional columnName2 as String) + Dim iHeaderPos as Long Dim oSortFields(1) as new com.sun.star.util.SortField Dim oSortDesc(0) as new com.sun.star.beans.PropertyValue - - oRange = oSheet.getCellRangeByPosition(0, 1, endColumn, endRow) - ThisComponent.getCurrentController.select(oRange) - - iHeaderPos = GetHeaderPosition(oSheet, endColumn, columnName) + + iHeaderPos = GetHeaderPosition(ctx, columnName1) If iHeaderPos = -1 Then Exit Sub End If + + ' Area oSortFields(0).Field = iHeaderPos oSortFields(0).SortAscending = True - - ' TODO Enable this later - ' Date - 'oSortFields(1).Field = 4 - 'oSortFields(1).SortAscending = True - + + ' FIXME This should be handled from the sheet settings + If Not IsMissing(columnName2) Then + iHeaderPos = GetHeaderPosition(ctx, columnName2) + If iHeaderPos = -1 Then + Exit Sub + End If + oSortFields(1).Field = iHeaderPos + oSortFields(1).SortAscending = True + End If + oSortDesc(0).Name = "SortFields" oSortDesc(0).Value = oSortFields - oRange.Sort(oSortDesc) + ctx.oRange.Sort(oSortDesc) End Sub -Function NewSheet(sheetName as String) as Object +Function NewSheet(oDoc, sheetName as String) as Object Dim sheets as Object - sheets = ThisComponent.Sheets() + sheets = oDoc.Sheets() If Not sheets.hasByName(sheetName) Then sheets.insertNewByName(sheetName, sheets.getCount()) End If NewSheet = sheets.getByName(sheetName) End Function -Sub CleanColumnHeaders(oSheet as Object, endColumn as Integer) +Sub CleanColumnHeaders(ctx as SondageContext) Dim cell as Object Dim neatName as String Dim i as Integer - For i = 0 To endColumn - cell = oSheet.getCellByPosition(i, 0) + For i = ctx.startColumn To ctx.endColumn + cell = ctx.oSheet.getCellByPosition(i, ctx.headerRow) neatName = cell.getString() neatName = UserFriendlyName(neatName) cell.setString(neatName) Next End Sub -Sub RemoveExtraMergeCells(oSheet as Object, oRangeAddress as Variant) +Sub RemoveExtraMergeCells(oDoc as Object, oSheet as Object, oRangeAddress as Variant) Dim oRange as Object Dim oSortFields(0) as new com.sun.star.util.SortField Dim oSortDesc(0) as new com.sun.star.beans.PropertyValue - Dim endRow as Integer + Dim endRow as Long endRow = oRangeAddress.EndRow lastColumn = oRangeAddress.EndColumn @@ -327,7 +544,7 @@ Sub RemoveExtraMergeCells(oSheet as Object, oRangeAddress as Variant) 'oRange = oSheet.getCellRangeByName("A2:F20") oRange = oSheet.getCellRangeByPosition(0, 0, lastColumn, 0) - ThisComponent.getCurrentController.select(oRange) + oDoc.getCurrentController().select(oRange) initialColumnCount = oRange.Columns.getCount() - 1 deletedColumns = 0 For j = 0 To (initialColumnCount - deletedColumns) @@ -342,90 +559,148 @@ Sub RemoveExtraMergeCells(oSheet as Object, oRangeAddress as Variant) Next End Sub - -Sub UnFreezeSelection - Dim document as Object +Sub UnFreezeSelection(oDoc as Object) Dim dispatcher as Object - document = ThisComponent.CurrentController.Frame dispatcher = createUnoService("com.sun.star.frame.DispatchHelper") - dispatcher.executeDispatch(document, ".uno:FreezePanes", "", 0, Array()) + dispatcher.executeDispatch(oDoc.getCurrentController().getFrame(), ".uno:FreezePanes", "", 0, Array()) End Sub -Function GetHeaderPosition(ByRef oSheet as Object, endColumn as Integer, searchString as String) as Integer +Function GetHeaderPosition(ctx as SondageContext, searchString$, Optional isRoughHeaderMatch as Boolean) as Integer Dim iColumn as Integer Dim oCell as Object Dim cellString as String GetHeaderPosition = -1 + If IsMissing(isRoughHeaderMatch) Then isRoughHeaderMatch = False If searchString = "" Then Exit Function End If - If roughHeaderMatch Then - searchString = UserFriendlyName(searchString) - End If - For iColumn = 0 To endColumn - oCell = oSheet.getCellByPosition(iColumn, 0) + + For iColumn = ctx.startColumn To ctx.endColumn + oCell = ctx.oSheet.getCellByPosition(iColumn, ctx.headerRow) cellString = oCell.String If cellString = "" Then - 'MsgBox "Cannot have empty column, endColumn is " & CStr(endColumn), 16, "Bad argument" + 'ErrorLocal$ = "BAD ARGUMENT: Cannot have empty columns within UsedRange, endColumn is " & CStr(endColumn) Exit Function End If - If roughHeaderMatch Then - cellString = UserFriendlyName(cellString) - End If - If cellString = searchString OR Instr(cellString, searchString) = 1 Then + + ' TODO Implement regex matching + If isRoughHeaderMatch = True Then + If InStr(cellString, searchString) Then + GetHeaderPosition = iColumn + Exit Function + End If + ElseIf cellString = searchString Then GetHeaderPosition = iColumn - Exit For + Exit Function End If Next iColumn End Function -Function HighlightRowWithColumn(ByRef oSheet as Object, endColumn as Long, endRow as Long, highlightColumnName, highlightValue, removeColumn as Boolean, Optional highlightColor as Long) as Long +Function HighlightRowWithColumn(ctx as SondageContext, _ + highlightColumnName, highlightValue, Optional highlightColor as Long) as Long Dim currentStr as String Dim oCell as Object Dim oCellRange as Object Dim str as String Dim iSearchColumn as Long Dim i as Integer - HighlightRowWithColumn = endColumn + Dim highlightCount as Long + If IsMissing(highlightColor) Then + highlightColor = RGB(255, 255, 0) + End If ' Search for column position that has highlightBasedOn - iSearchColumn = GetHeaderPosition(oSheet, endColumn, highlightColumnName) + iSearchColumn = GetHeaderPosition(ctx, highlightColumnName) If iSearchColumn = -1 Then Exit Function - For i = 0 To endRow - 1 - oCell = oSheet.getCellByPosition(iSearchColumn, i) - If InStr(oCell.getString(), highlightValue) > 0 Then - oCellRange = oSheet.getCellRangeByPosition(0, i, endColumn, i) + For i = ctx.startRow To ctx.endRow - 1 + oCell = ctx.oSheet.getCellByPosition(iSearchColumn, i) + If oCell.getString() = highlightValue Then + oCellRange = ctx.oSheet.getCellRangeByPosition(0, i, ctx.endColumn, i) oCellRange.CellBackColor = highlightColor + highlightCount = highlightCount + 1 End If Next i - - If removeColumn Then - oSheet.Columns.removeByIndex(iSearchColumn, 1) - endColumn = endColumn - 1 - End If + HighlightRowWithColumn = highlightCount End Function -Function FindHighestDateAsString(oSheet as Object, columnName as String, endColumn as Integer, endRow as Integer) as Date - Dim dateHeaderPos - Dim dateColumn - Dim dateVal - dateHeaderPos = GetHeaderPosition(oSheet, endColumn, columnName) - If dateHeaderPos = -1 Then - MsgBox "Cannot find a column header that starts with '" & columnName & "'", 0, "Bad column name" +Function ComputeOnRange(ctx as SondageContext, columnName as String, computeFunc%) as Long + Dim headerPos + Dim column + Dim val + headerPos = GetHeaderPosition(ctx, columnName) + If headerPos = -1 Then + ErrorLocal$ = "Cannot find a column header that starts with '" & columnName & "'" Exit Function End If ' TODO Check if the column we are searching, actually has date values. - dateColumn = oSheet.getCellRangeByPosition(dateHeaderPos, 1, dateHeaderPos, endRow) - dateVal = dateColumn.computeFunction(com.sun.star.sheet.GeneralFunction.MAX) - If dateVal = 0 Then MsgBox "Invalid date found in column '" & columnName & "' - " & dateHeaderPos & "", 16, "Bad date found" - FindHighestDateAsString = dateVal + column = ctx.oSheet.getCellRangeByPosition(headerPos, 1, headerPos, ctx.endRow) + ComputeOnRange = column.computeFunction(computeFunc) End Function +Sub ColumnJoin(joinChar$, idColumnName, dstCtx as SondageContext, dstColumnName$, srcCtx as SondageContext, srcColumnName$) + Dim i&, j& + Dim dstEndRow&, dstEndColumn%, srcEndRow&, srcEndColumn% + Dim dstColumnIdx%, srcColumnIdx% + Dim dstStr$, dstCell + Dim dstRange, srcRange, srcRangeAddress, dstRangeAddress + Dim oTextCursor, oService, statusBar + statusBar = ThisComponent.CurrentController.StatusIndicator + oService = CreateUNOService("com.sun.star.sheet.FunctionAccess") + + dstRange = UsedRangeCursor(dstCtx.oSheet) + dstRangeAddress = dstRange.RangeAddress + srcRange = UsedRangeCursor(srcCtx.oSheet) + srcRangeAddress = srcRange.RangeAddress + + dstEndRow = dstRangeAddress.EndRow + srcEndRow = srcRangeAddress.EndRow + + dstColumnIdx = GetHeaderPosition(dstCtx, dstColumnName) + srcColumnIdx = GetHeaderPosition(srcCtx, srcColumnName) + + + Dim srcColumnIdIdx: srcColumnIdIdx = GetHeaderPosition(srcCtx, idColumnName) + Dim newSrcRange + newSrcRange = srcSheet.getCellRangeByPosition(srcColumnIdIdx, srcCtx.startRow, srcCtx.endColumn, srcCtx.endRow) + + Dim dstColumnIdIdx: dstColumnIdIdx = GetHeaderPosition(dstCtx, idColumnName) + + statusBar.start("Merging Columns", 100) + For i = dstStartRow To dstEndRow + Dim srcCell + Dim srcStr$ + Dim what$ + + statusBar.setText("Merging " & CStr(i) & "/" & dstEndRow) + statusBar.setValue((i / dstEndRow) * 100) + + dstCell = dstRange.getCellByPosition(dstColumnIdx, i) + dstStr = dstCell.getText().String + what = dstRange.getCellByPosition(dstColumnIdIdx, i).getText().String + + srcStr = oService.callFunction("VLOOKUP", Array(what, newSrcRange, srcColumnIdx, True)) + + + dstCell.getText().setString(dstStr & joinChar & srcStr) + + oTextCursor = dstCell.getText().createTextCursor() + oTextCursor.gotoStart(False) + oTextCursor.goRight(Len(dstStr), True) + 'oTextCursor.CharWeight = com.sun.star.awt.FontWeight.BOLD + oTextCursor.goRight(1, False) + oTextCursor.gotoEnd(True) + oTextCursor.CharHeight = 7 + srcStr = "" + what = "" + Next + statusBar.end() +End Sub + ' TODO Use a general function that takes arrays ' and instead of the function ShortenDirections, use ' ReplaceArrays to make it more usable across other projects. -Sub ShortenDirections(oSheet as Object, columnIdx as Integer) +Sub ShortenDirections(ctx as SondageContext, columnIdx as Integer) 'Shorten East as E. etc Dim toReplace() as String Dim toReplaceWith() as String @@ -433,7 +708,7 @@ Sub ShortenDirections(oSheet as Object, columnIdx as Integer) Dim oDescriptor Dim oColumn Dim columnToReplace - oColumn = oSheet.getColumns().getByIndex(columnIdx) + oColumn = ctx.oSheet.getColumns().getByIndex(columnIdx) ' TODO arrange it with convention toReplace() = Array("East", "West", "South", "North") toReplaceWith() = Array("E.", "W.", "S.", "N.") @@ -446,24 +721,487 @@ Sub ShortenDirections(oSheet as Object, columnIdx as Integer) oColumn.replaceAll(oDescriptor) Next i End Sub + +Sub FilterColumn(ctx as SondageContext, filterColumnName as String, filterContent as Variant, Optional filterOperator as Variant, Optional filterUseRegex as Boolean) + Dim oFilterDesc + Dim filterRange, oRange + Dim oCursor, o, oDescriptor + 'Dim oColumnHeader + Dim newColumn : newColumn = ctx.endColumn + 1 + Dim oFields(0) as new com.sun.star.sheet.TableFilterField + Dim filterCount as Long + + If IsMissing(filterOperator) Then filterOperator = com.sun.star.sheet.FilterOperator.EQUAL + If IsMissing(filterUseRegex) Then filterUseRegex = False + + 'On Error Goto ErrorHandler + + oRange = ctx.oSheet.getCellRangeByPosition(newColumn, 0, newColumn, ctx.endRow) + 'oColumnHeader = oRange.getCellByPosition(0, 0) + 'oColumnHeader.setString("0") + + oDescriptor = ctx.oSheet.createReplaceDescriptor() + + filterRange = GetColumnRange(ctx, filterColumnName) + oFilterDesc = filterRange.createFilterDescriptor(True) + + With oFields(0) + .Field = filterRange.RangeAddress.StartColumn + .IsNumeric = IsNumeric(filterContent) + .Operator = filterOperator + .StringValue = filterContent + .NumericValue = filterContent + End With + + oFilterDesc.setFilterFields(oFields()) + oFilterDesc.ContainsHeader = True + oFilterDesc.UseRegularExpressions = filterUseRegex + ctx.oSheet.filter(oFilterDesc) + + ' TODO Check if there is a way to remove the 50,000 limit + 'oRange.fillSeries(com.sun.star.sheet.FillDirection.TO_BOTTOM, com.sun.star.sheet.FillMode.SIMPLE, 0, 1, 50000) + 'SortColumn(ctx.oSheet, 0, 1, newColumn, endRow, "0") + + 'filterCount = oRange.computeFunction(com.sun.star.sheet.GeneralFunction.COUNT) + 'ctx.oSheet.Rows.removeByIndex(filterCount, (ctx.endRow - filterCount) + 1) + +'ErrorHandler: + 'ctx.oSheet.filter(ctx.oSheet.createFilterDescriptor(True)) + 'ctx.oSheet.Columns.removeByIndex(newColumn, 1) + 'Reset +End Sub + +Sub SetHeader(ByRef oPageStyle, Optional sLeftHeader$, Optional sCenterHeader$, Optional sRightHeader) + Dim oHeader + Dim oText + Dim oTextCursor + + oHeader = oPageStyle.RightPageHeaderContent + + If Not IsMissing(sLeftHeader) Then + oText = oHeader.LeftText + oTextCursor = oText.createTextCursor() + oText.insertString(oTextCursor, sLeftHeader, true) + End If + + If Not IsMissing(sCenterHeader) Then + oText = oHeader.CenterText + oTextCursor = oText.createTextCursor() + oText.insertString(oTextCursor, sCenterHeader, true) + End If + + If Not IsMissing(sRightHeader) Then + oText = oHeader.RightText + oTextCursor = oText.createTextCursor() + oText.insertString(oTextCursor, sRightHeader, true) + End If + + oPageStyle.RightPageHeaderContent = oHeader +End Sub -Sub SetWidths(oSheet, endColumn as Integer, columnWidthArray() as Variant) +Sub SondageRestructureColumns(ctx as SondageContext, aColumnWidth as Variant) ' columnWidthArray has values like Array(Array("Area", 0), Array("ID", 2000)) ' 0 means autofill - Dim i as Integer - Dim columnWidth + Dim columnWidth, iField% + Dim sField$, iWidth as Variant + Dim oColumn Dim iHeaderColumn - For Each columnWidth in columnWidthArray - iHeaderColumn = GetHeaderPosition(oSheet, endColumn, columnWidth(0)) - If iHeaderColumn = -1 Then - Print "Cannot find: " & columnWidth(0) & " in headers" - Exit Sub + + For iField = LBound(aColumnWidth) To UBound(aColumnWidth) + sField = aColumnWidth(iField, 0) + iWidth = aColumnWidth(iField, 1) + + If Not IsEmpty(iWidth) Then + iHeaderColumn = GetHeaderPosition(ctx, sField) + If iHeaderColumn = -1 Then + If iWidth = -1 Then + ' No-Op as the field already does not exist + ElseIf iWidth >= 0 Then + SondageAppendColumn(ctx, sField) + iHeaderColumn = GetHeaderPosition(ctx, sField) + Else + ErrorLocal$ = "Cannot find: " & sField & " in headers": Exit Sub + End If + End If + + If iHeaderColumn <> -1 Then + oColumn = ctx.oSheet.getColumns().getByIndex(iHeaderColumn) + If iWidth = -1 Then + 'ctx.oSheet.getColumns().removeByIndex(iHeaderColumn, 1) + oColumn.IsVisible = False + 'ctx.endColumn = ctx.endColumn - 1 + Else + If iWidth = 0 Then + oColumn.OptimalWidth = True + Else + oColumn.Width = iWidth + End If + End if End If - if columnWidth(1) = 0 Then - oSheet.getColumns().getByIndex(iHeaderColumn).OptimalWidth = True + End If + Next iField + ErrorLocal$ = "" +End Sub + +Sub ReArrangeResultToHeader(ctx as SondageContext, Optional headerStyle$) + Dim startRow&, nRow&, nCol&, insertRow& + Dim oDoc, oRange, oUsedRangeAddress + Dim resultRanges + Dim oAddrs() + Dim oAddr + Dim oFound, oCells + Dim insertRowCell + Dim oSearchDesc + + If IsMissing(headerStyle) Then headerStyle = "Accent 1" + startRow = 1 + + oUsedRangeAddress = UsedRangeCursor(ctx.oSheet).RangeAddress + oRange = ctx.oSheet.getCellRangeByPosition(0, startRow, 0, oUsedRangeAddress.EndRow) + + oSearchDesc = oRange.createSearchDescriptor() + oSearchDesc.SearchStyles = True + oSearchDesc.SearchString = "Result" + + Dim sResult, sGroupBy + Dim oRows, oCols, emptyValue as Object + oRows = ctx.oSheet.getRows() + oCols = ctx.oSheet.getColumns() + Dim colRange + + ' Construct first row and column to be same as others + oRows.insertByIndex(startRow, 1) + insertRowCell = ctx.oSheet.getCellByPosition(0, startRow) + insertRowCell.CellStyle = "Result" + + oFound = ctx.oSheet.findFirst(oSearchDesc) + Do While Not IsNull (oFound) + 'Print "Name is: " & oFound.getText().getString() + insertRowCell = ctx.oSheet.getCellByPosition(1, startRow) + startRow = oFound.RangeAddress.StartRow + If startRow > oUsedRangeAddress.EndRow Then + oFound = emptyValue Else - oSheet.getColumns().getByIndex(iHeaderColumn).Width = columnWidth(1) + sResult = ctx.oSheet.getCellByPosition(0, startRow).getText().String + sGroupBy = ctx.oSheet.getCellByPosition(0, startRow - 1).getText().String + colRange = ctx.oSheet.getCellRangeByPosition(1, startRow, 5, startRow) + colRange.merge(True) + colRange.CellStyle = headerStyle + insertRowCell.getText().setString(sGroupBy & " (" & sResult & ")") + + oRange = ctx.oSheet.getCellRangeByPosition(0, startRow, 0, oUsedRangeAddress.EndRow) + oFound = ctx.oSheet.findNext(oRange, oSearchDesc) End If + Loop + + oCols.removeByIndex(0, 1) +End Sub + + + + + + + + + + + + + + +sub FiltersToCalc + Dim oFF ' FilterFactory service + Dim oFilterNames ' Array of filter names. + Dim oDoc ' Document created to hold the filter names. + Dim oSheet ' Sheet that will hold the filter information. + Dim oCell ' Cell to update + + Dim i% ' Index Variable. + Dim fProps() ' Properties for each filter. + Dim fp% ' Filter property index + Dim fpCol% ' Column for the specified filter data. + Dim s$ ' Work string that holds some property values. + Dim iUserData% ' For enumerating array property values. + Dim oProp ' A single property. + Dim oArrayData ' Array of user properties. + Dim sPropNames(7) As String + Dim flags As Long + sPropNames(0) = "Name" + sPropNames(1) = "Import" + sPropNames(2) = "Export" + sPropNames(3) = "Options" + sPropNames(4) = "Visible" + sPropNames(5) = "Flags" + sPropNames(6) = "DocumentService" + sPropNames(7) = "UIName" + oFF = createUnoService( "com.sun.star.document.FilterFactory" ) + oFilterNames = oFF.getElementNames() + ' Create a Calc doc and save the filter names to it. + oDoc = StarDesktop.loadComponentFromURL( "private:factory/scalc", "_blank", 0, Array() ) + oSheet = oDoc.getSheets().getByIndex(0) + ' Print the filter names into a document. + For i = LBound( oFilterNames ) To UBound( oFilterNames ) + fProps() = oFF.getByName(oFilterNames(i)) + For fp = LBound(fProps) To UBound(fProps) + oCell = oSheet.getCellByPosition(fp, i+1) + oProp = fProps(fp) + fpCol = FindInArrayAdd(oProp.Name, sPropNames) + If fpCol > UBound(sPropNames) Then + ReDim Preserve sPropNames(fpCol) As String + sPropNames(fpCol) = oProp.Name + End If + oCell = oSheet.getCellByPosition(fpCol, i+1) + If Not IsArray(oProp.Value) Then + oCell.setString(oProp.Value) + If oProp.Name = "Flags" Then + flags = oProp.Value + oCell.setString(CStr(flags) & " = " & flags_int2str(flags)) + If flags and 1 Then + oCell = oSheet.getCellByPosition(FindInArrayAdd("Import", sPropNames), i+1) + oCell.setString("X") + Endif + If flags and 2 Then + oCell = oSheet.getCellByPosition(FindInArrayAdd("Export", sPropNames), i+1) + oCell.setString("X") + Endif + If flags and 128 Then + oCell = oSheet.getCellByPosition(FindInArrayAdd("Options", sPropNames), i+1) + oCell.setString("X") + Endif + If ((flags and 4096) or (flags and 8192)) Then + oCell = oSheet.getCellByPosition(FindInArrayAdd("Visible", sPropNames), i+1) + oCell.setString("X") + Endif + End If + ElseIf LBound(oProp.Value) <= UBound(oProp.Value) Then + s = "" + oArrayData = oProp.Value + For iUserData = LBound(oArrayData) To UBound(oArrayData) + If VarType(oArrayData(iUserData)) = 8 Then + s = s & "(String:" & oArrayData(iUserData) & ")" + Else + s = s & "(" & oArrayData(iUserData).Name & ":" & oArrayData(iUserData).Value & ")" + End If + Next + oCell.setString(s) + End If + Next Next + For fp = LBound(sPropNames) To Ubound(sPropNames) + oCell = oSheet.getCellByPosition(fp, 0) + oCell.setString(sPropnames(fp)) + Next + FinalFormat(oDoc) End Sub +function flags_int2str(flags as long) as string +Dim cflags as long +Dim strval as string +Dim curFlag As Long +cflags = flags +strval = "" +if cflags and &H00000001 then +strval = strval + " Import" +cflags = cflags-1 +endif +if cflags and &H00000002 then +strval = strval + " Export" +cflags = cflags-2 +endif +if cflags and &H00000004 then +strval = strval + " Template" +cflags = cflags-4 +endif +if cflags and &H00000008 then +strval = strval + " Internal" +cflags = cflags-8 +endif + + if cflags and &H00000010 then +strval = strval + " TemplatePath" +cflags = cflags-16 +endif +if cflags and &H00000020 then +strval = strval + " Own" +cflags = cflags-32 +endif +if cflags and &H00000040 then +strval = strval + " Alien" +cflags = cflags-64 +endif +if cflags and &H00000080 then +strval = strval + " UseOptions" +cflags = cflags-128 +endif +if cflags and &H00000100 then +strval = strval + " Default" +cflags = cflags-256 +endif +if cflags and &H00000200 then +strval = strval + " Executable" +cflags = cflags-512 +endif +if cflags and &H00000400 then +strval = strval + " SupportSelection" +cflags = cflags-1024 +endif +if cflags and &H00000800 then +strval = strval + " MapToAppPlug" +cflags = cflags-2048 +endif +if cflags and &H00001000 then +strval = strval + " NotInFileDialog" +cflags = cflags-4096 +endif +if cflags and &H00002000 then +strval = strval + " NotInChooser" +cflags = cflags-8192 +endif +if cflags and &H00004000 then +strval = strval + " Acynchronas" +cflags = cflags-16384 +endif +if cflags and &H00008000 then +strval = strval + " Creator" +cflags = cflags-32768 +endif +if cflags and &H00010000 then +strval = strval + " Readonly" +cflags = cflags-65536 +endif +if cflags and &H00020000 then + + strval = strval + " NotInstalled" +cflags = cflags-131072 +endif +if cflags and &H00040000 then +strval = strval + " ConsultService" +cflags = cflags-262144 +endif +if cflags and &H00080000 then +strval = strval + " 3rdPartyFilter" +cflags = cflags-524288 +endif +if cflags and &H00100000 then +strval = strval + " Packed" +cflags = cflags-1048576 +endif +if cflags and &H00200000 then +strval = strval + " SilentExport" +cflags = cflags-2097152 +endif +if cflags and &H00400000 then +strval = strval + " BrowserPreferred" +cflags = cflags-4194304 +endif +if cflags and &H00800000 then +strval = strval + " [H00800000]" +cflags = cflags-8388608 +endif +if cflags and &H01000000 then +strval = strval + " [H01000000]" +cflags = cflags-16777216 +endif +if cflags and &H02000000 then +strval = strval + " [H02000000]" +cflags = cflags-33554432 +endif +if cflags and &H10000000 then +strval = strval + " Preferred" +cflags = cflags-268435456 +endif +if cflags <> 0 then +strval = strval + " !!! ATTENTION: unsupported flag ["+cflags+"] detected !!!" +endif +flags_int2str = strval +end function +Function FindInArrayAdd(sName$, nameArray) As Integer +Dim i As Integer +For i = LBound(nameArray()) To UBound(nameArray()) + + 'Print nameArray(i) & " and " & sName +If nameArray(i) = sName Then +FindInArrayAdd = i +Exit Function +End If +Next +i = UBound(nameArray()) + 1 +FindInArrayAdd = i +End Function +sub FinalFormat(oDoc) +rem ---------------------------------------------------------------------- +rem define variables +Dim document as object +Dim dispatcher as object +rem ---------------------------------------------------------------------- +rem get access to the document +document = oDoc.CurrentController.Frame +dispatcher = createUnoService("com.sun.star.frame.DispatchHelper") +rem ---------------------------------------------------------------------- +Dim args1(0) as new com.sun.star.beans.PropertyValue +args1(0).Name = "ToPoint" +args1(0).Value = "$A$1" +dispatcher.executeDispatch(document, ".uno:GoToCell", "", 0, args1()) +rem ---------------------------------------------------------------------- +Dim args2(1) as new com.sun.star.beans.PropertyValue +args2(0).Name = "By" +args2(0).Value = 1 +args2(1).Name = "Sel" +args2(1).Value = true +dispatcher.executeDispatch(document, ".uno:GoRightToEndOfData", "", 0, args2()) +rem ---------------------------------------------------------------------- +Dim args3(2) as new com.sun.star.beans.PropertyValue +args3(0).Name = "FontHeight.Height" +args3(0).Value = 12 +args3(1).Name = "FontHeight.Prop" +args3(1).Value = 100 +args3(2).Name = "FontHeight.Diff" +args3(2).Value = 0 +dispatcher.executeDispatch(document, ".uno:FontHeight", "", 0, args3()) +rem ---------------------------------------------------------------------- +Dim args4(0) as new com.sun.star.beans.PropertyValue +args4(0).Name = "Bold" +args4(0).Value = true +dispatcher.executeDispatch(document, ".uno:Bold", "", 0, args4()) + +rem ---------------------------------------------------------------------- +Dim args5(0) as new com.sun.star.beans.PropertyValue +args5(0).Name = "HorizontalAlignment" +args5(0).Value = com.sun.star.table.CellHoriJustify.CENTER +dispatcher.executeDispatch(document, ".uno:HorizontalAlignment", "", 0, args5()) +rem ---------------------------------------------------------------------- +Dim args6(1) as new com.sun.star.beans.PropertyValue +args6(0).Name = "By" +args6(0).Value = 1 +args6(1).Name = "Sel" +args6(1).Value = true +dispatcher.executeDispatch(document, ".uno:GoDownToEndOfData", "", 0, args6()) +rem ---------------------------------------------------------------------- +Dim args7(0) as new com.sun.star.beans.PropertyValue +args7(0).Name = "aExtraWidth" +args7(0).Value = 254 +dispatcher.executeDispatch(document, ".uno:SetOptimalColumnWidth", "", 0, args7()) +rem ---------------------------------------------------------------------- +Dim args8(8) as new com.sun.star.beans.PropertyValue +args8(0).Name = "ByRows" +args8(0).Value = true +args8(1).Name = "HasHeader" +args8(1).Value = true +args8(2).Name = "CaseSensitive" +args8(2).Value = false +args8(3).Name = "IncludeAttribs" +args8(3).Value = true +args8(4).Name = "UserDefIndex" +args8(4).Value = 0 +args8(5).Name = "Col1" +args8(5).Value = 7 +args8(6).Name = "Ascending1" +args8(6).Value = true +args8(7).Name = "Col2" +args8(7).Value = 1 +args8(8).Name = "Ascending2" +args8(8).Value = true +dispatcher.executeDispatch(document, ".uno:DataSort", "", 0, args8()) +dispatcher.executeDispatch(document, ".uno:GoToCell", "", 0, args1()) +end sub
diff --git a/PendingAutomation.ods b/PendingAutomation.ods Binary files differ.
diff --git a/Scrap.bas b/Scrap.bas @@ -0,0 +1,67 @@ +REM ***** BASIC ***** + +Sub _ColumnJoin(joinChar$, idColumnName, dstSheet as Object, dstColumnName$, dstStartRow%, srcSheet as Object, srcColumnName$, srcStartRow, statusBar as Variant) + Dim i&, j& + Dim dstEndRow&, dstEndColumn%, srcEndRow&, srcEndColumn% + Dim dstColumnIdx%, srcColumnIdx% + Dim dstStr$, dstCell + Dim dstRange, srcRange, srcRangeAddress, dstRangeAddress + Dim oTextCursor + + dstRange = UsedRangeCursor(dstSheet) + dstRangeAddress = dstRange.RangeAddress + srcRange = UsedRangeCursor(srcSheet) + srcRangeAddress = srcRange.RangeAddress + + dstEndRow = dstRangeAddress.EndRow + srcEndRow = srcRangeAddress.EndRow + + dstColumnIdx = GetHeaderPosition(dstCtx, dstColumnName, dstStartRow) + srcColumnIdx = GetHeaderPosition(srcCtx, srcColumnName, srcStartRow) + + Dim srcColumnIdIdx: srcColumnIdIdx = GetHeaderPosition(srcCtx, idColumnName, srcStartRow) + 'srcRange = srcSheet.getCellRangeByPosition(srcColumnIdIdx, srcStartRow, srcValueOffset, srcEndRow) + + Dim srcLastColumnIdx%: srcLastColumnIdx = srcRangeAddress.EndColumn - 1 + Dim dstColumnIdIdx: dstColumnIdIdx = GetHeaderPosition(dstCtx, idColumnName, dstStartRow) + + statusBar.start("Merging Columns", 100) + For i = dstStartRow To dstEndRow + Dim srcCell + Dim srcStr$ + Dim what$ + + statusBar.setText("Merging" & CStr(i) & "/" & dstEndRow) + statusBar.setValue((i / dstEndRow) * 100) + + dstCell = dstRange.getCellByPosition(dstColumnIdx, i) + dstStr = dstCell.getText().String + what = dstRange.getCellByPosition(dstColumnIdIdx, i).getText().String + + srcCell = GetValueForKey(srcRange, idColumnName, srcLastColumnIdx) + For j = srcStartRow To srcEndRow + If srcRange.getCellByPosition(srcColumnIdIdx, j).getText().String = what Then + srcCell = srcRange.getCellByPosition(srcColumnIdx, j) + 'j = srcEndRow + Exit For + End If + Next + + If Not IsNull(srcCell) Then + srcStr = srcCell.getText().String + End If + dstCell.getText().setString(dstStr & joinChar & srcStr) + + oTextCursor = dstCell.getText().createTextCursor() + oTextCursor.gotoStart(False) + oTextCursor.goRight(Len(dstStr), True) + 'oTextCursor.CharWeight = com.sun.star.awt.FontWeight.BOLD + oTextCursor.goRight(1, False) + oTextCursor.gotoEnd(True) + oTextCursor.CharHeight = 7 + srcCell = Nothing + srcStr = "" + what = "" + Next + statusBar.end() +End Sub
diff --git a/Sondage.bas b/Sondage.bas @@ -0,0 +1,746 @@ +REM ***** BASIC ***** +Option Explicit + +Const FieldOperationLimit = 10 + +Type SondageOperation + OpName as String + OpLocation as String +End Type + +Type SondageStatement + Cond as Integer + Operand as String + OpIds() as Integer +End Type + +Type SondageField + Field as String + Width as Long + Statements() as SondageStatement + Values() as String +End Type + +Type SondageReport + Title as String + Settings() as com.sun.star.PropertyValue + Fields() as SondageField +End Type + +Type SondageConfiguration + Reports() as SondageReport + Headers() as String +End Type + +' FIXME Remove the 100 hard limit later +Dim OperationTable(100) as SondageOperation +Dim OperationTableLen% + +Function ColorRow(ByRef oSheet as Object, oRanges as Variant, highlightColor as Variant) + Dim oRange + For oRange = LBound(oRanges) To UBound(oRanges) + oRange.CellBackColor = highlightColor + Next +End Function + +Function ColumnOperation(ByRef oSheet as Object, oRanges as Variant, highlightColor as Variant) + Dim oRange + For oRange = LBound(oRanges) To UBound(oRanges) + oRange.CellBackColor = highlightColor + Next +End Function + +Function ColorCell(ByRef oSheet as Object, oRanges as Variant, highlightColor as Variant) + Dim oRange + For oRange = LBound(oRanges) To UBound(oRanges) + oRange.CellBackColor = highlightColor + Next +End Function + +Function Delete(ByRef oSheet as Object, oRanges as Variant, sArgs() as String) + Dim oRange + For Each oRange In oRanges + oSheet.removeByIndex(oRange.RangeAddress.StartRow) + Next oRange +End Function + +Sub SondageRegisterFunction(macroLocation$, macroName$) + OperationTable(OperationTableLen).OpLocation = macroLocation + OperationTable(OperationTableLen).OpName = macroName + OperationTableLen = OperationTableLen + 1 +End Sub + +Function _ReadUntilEndOrCharacter(ByRef sCell$, startIndex%, expect$, ByRef endIndex as Variant) as String + Dim c$, i% + c = Left(sCell, startIndex) + + For i = startIndex To Len(sCell) + If c = expect Then + _ReadUntilEndOrCharacter = Mid(sCell, startIndex, i - startIndex - 1) + endIndex = i + Exit Function + End If + + If c = "\n" Or c = ";" Then + ErrorLocal$ = "Expected '" & expect & "' got '" & c & "'" + Exit Function + End If + c = Mid(sCell, i, 1) + Next + _ReadUntilEndOrCharacter = Mid(sCell, startIndex, i - startIndex) + endIndex = i - 1 +End Function + +Function _ReadUntilCharacters(ByRef sCell$, startIndex%, expects() as Variant, ByRef endIndex&) as String + Dim c$, expect$ + + For endIndex = startIndex To Len(sCell) + c = Mid(sCell, endIndex, 1) + For Each expect In expects + If c = expect Then + _ReadUntilCharacters = Mid(sCell, startIndex, endIndex - startIndex) + Exit Function + End If + If c = "\n" Or c = ";" Then + ErrorLocal$ = "Expected '" & expect & "' got '" & c & "'" + Exit Function + End If + Next + Next + ErrorLocal$ = "Expected '" & expect & "' but reached end of cell" +End Function + +Sub TestSub + Dim sCell$, colName$ + Dim iCell% + sCell = "${variable with space} " & CHR(34) & "quoted string" & CHR(34) + colName = _ReadUntilCharacters(sCell, 3, Array("}"), iCell) + Print colName + If ErrorLocal$ <> "" Then + Print "Some error occurred: " & ErrorLocal + Exit Sub + End If + colName = _ReadUntilCharacters(sCell, iCell +3 , Array(CHR(34)), iCell) + If ErrorLocal$ <> "" Then + Print "Some error occurred: " & ErrorLocal + Exit Sub + End If + Print colName + 'If ErrorLocal$ <> "" Then + ' Print "Some error occurred: " & ErrorLocal + ' Exit Sub + 'End If +End Sub + +Function FunctionCall(colName$, actions) + Dim action$ + For Each action in actions + Print colName & " acts on " & action + Next 'action +End Function + +Function TokenDriver(Optional sCell) + Dim sonVars: sonVars = SondageReadSettings() + Dim si%: si = 1 + Dim tok$ + Dim tokType$ 'mode + If IsMissing(sCell) Then sCell = "${OrgCode}_Portln then @Area(.BadStyle @SomeOther Sort-ASCENDING)" + sCell = SondageExpandVariables(sCell, sonVars) + + Dim sCellLen: sCellLen = Len(sCell) + tok = GetToken(sCell, si, tokType) + While tok <> "" + Select Case tokType + Case "@" + Print "Some column types: "& tok + Case "(" + Print "Open Bracket: " & tok + Dim fi%: fi = 1 + Dim ftok$, ftokType$ + ftok = GetToken(tok, fi, ftokType) + While ftok <> "" + Print ftok + ftok = GetToken(tok, fi, ftokType) + Wend + Case "m" + Print "mode" + End Select + tok = GetToken(sCell, si, tokType) + Wend +End Function + +Function GetToken(sCell$, ByRef si%, ByRef m$) as String + Dim sonVars: sonVars = SondageReadSettings() + Dim sonState: SondageStatement: sonState = new SondageStatement + sCell = SondageExpandVariables(sCell, sonVars) + Dim sCellLen: sCellLen = Len(sCell) + Dim c$ 'current char + Dim endIndex& + Dim extract$ + Dim func$ + + For si = si To sCellLen + c = Mid(sCell, si, 1) + If c = "(" Then + extract = _ReadUntilCharacters(sCell, si + 1, Array(")"), endIndex) + si = endIndex + m = "(" + GetToken = extract + ElseIf c = "@" Or c = "." Then + m = c + If si + 1 < sCellLen Then + si = si + 1 + c = Mid(sCell, si, 1) + If c = "{" Then + extract = _ReadUntilCharacter(sCell, si + 1, "}", endIndex) + Else + extract = _ReadUntilCharacters(sCell, si, Array(" ", "(", ""), endIndex) + EndIf + If ErrorLocal$ <> "" Or endIndex > sCellLen Then + Print ErrorLocal$ + Exit Function + End If + If m = "@" Then 'Column mode + Print "Column is '" & extract & "'" + ElseIf m = "." Then + Print "Style is '" & extract & "'" + Else + Print "Probably a function: " & extract + End If + si = endIndex + GetToken = extract + Exit Function + End If + Else + m = "" + End If + Next 'si +End Function + +Function SondageGetOpId(macroName$) as Integer + Dim i% + SondageGetOpId = -1 + For i = 0 To OperationTableLen + If OperationTable(i).OpName = macroName Then + SondageGetOpId = i + Exit Function + End If + Next +End Function + +Function SondageValidateDoc(oDoc as Object, docType$) as String + Dim _err$ : _err = "" + If Not oDoc.supportsService(docType) Then + _err = oDoc.Title & " is not a valid Spreadsheet Document" + ElseIf oDoc.CurrentController.ViewControllerName = "PrintPreview" Then + _err = "Cannot run this macro in 'Print Preview', please close it and try again" + End If + SondageValidateDoc = _err +End Function + +Sub SondageCall(opId%, oSheet, Ranges) + Dim sonOp as SondageOperation: sonOp = OperationTable(opId) + Dim script + script=ThisComponent.scriptProvider.getScript("vnd.sun.star.script:" & sonOp.OpLocation & "." & sonOp.OpName & "?language=Basic&location=document") + script.invoke(Array(oSheet, Ranges), Array(), Array()) +End Sub + +Function SondageInferDocumentType(sonReports, aInputFiles as Variant) as SondageReport + Dim sonReport as SondageReport + Dim sonSetting as Object + Dim sMatch$, iMatch% + Dim aMatch as Variant + Dim sInputFile, iInputFile% + Dim matchCount + Dim iMatchLen%, iInputFileLen% + iInputFileLen = UBound(aInputFiles) + + For Each sonReport In sonReports + sMatch = SondageGetPropVal(sonReport.Settings, "Match") + If sMatch <> "" Then + aMatch = Split(sMatch, ";") + iMatchLen = UBound(aMatch) + if iMatchLen <> iInputFileLen Then Goto SONDAGE_REPORT_LOOP_END + SONDAGE_MATCH_LOOP_START: + For iMatch = iMatch To iMatchLen + sMatch = aMatch(iMatch) + For iInputFile = 0 To iInputFileLen + sInputFile = aInputFiles(iInputFile) + If (InStr(LCase(sInputFile), sMatch)) Then + iMatch = iMatch + 1 + Goto SONDAGE_MATCH_LOOP_START + End If + Next iInputFile + Next iMatch + End If + If iMatch = iInputFileLen + 1 Then + SondageInferDocumentType = sonReport + Exit Function + End If + SONDAGE_REPORT_LOOP_END: + Next sonReport +End Function + +Function SondageImportFiles(sondageReport as SondageReport, aInputFile as Variant, sDocType$, returnAlreadyOpenDoc as Boolean, Optional isHidden as Boolean) as Variant + Dim oDocs(0) as Variant + Dim iInputFile%, sInputFile$ + ReDim oDocs(0 To UBound(aInputFile)) as Variant + + For iInputFile = 0 To UBound(aInputFile) + sInputFile = aInputFile(iInputFile) + oDocs(iInputFile) = SondageImportFile(sondageReport, sInputFile, sDocType, returnAlreadyOpenDoc, isHidden) + If ErrorLocal$ <> "" Then Exit Function + Next iInputFile + SondageImportFiles = oDocs +End Function + +Function SondageImportFile(sondageReport as SondageReport, sInputFile$, sDocType$, returnAlreadyOpenDoc as Boolean, Optional isHidden as Boolean) as Variant + ' TODO Use import values from sheet + Dim oDoc + Dim fileUrl + Dim p(2) as new com.sun.star.beans.PropertyValue + If IsMissing(isHidden) Then isHidden = True + Dim delimiterList + Dim reportType$: reportType = sondageReport.Title + + If returnAlreadyOpenDoc Then + oDoc = ReturnComponentIfOpen(sInputFile) + If Not IsNull(oDoc) Then + SondageImportFile = oDoc + Exit Function + End If + End If + + delimiterList = Array(",", "|") + p(0).Name = "FilterName" + p(0).Value = CSV_FILTER_NAME + p(1).Name = "Hidden" + p(1).Value = isHidden + p(2).Name = "FilterOptions" + If reportType= "PENDING" Then + p(2).Value = PENDING_CSV_FILTER_OPTIONS + ElseIf reportType = "INSPECTION" Then + p(2).Value = INSPECTION_CSV_FILTER_OPTIONS + ElseIf reportType = "TUBE" Then + p(2).Value = TUBE_CSV_FILTER_OPTIONS + ElseIf reportType = "CONSUMERS" Then + p(2).Value = CONSUMERS_CSV_FILTER_OPTIONS + ElseIf reportType = "REFILL" Then + p(2).Value = REFILL_CSV_FILTER_OPTIONS + ElseIf reportType = "NCTC" Then + p(2).Value = NCTC_CSV_FILTER_OPTIONS + End If + fileUrl = ConvertToUrl(sInputFile) + If Not FileExists(fileUrl) Then + ErrorLocal = "Cannot open file '" & fileUrl & "'" + Exit Function + End If + oDoc = StarDesktop.loadComponentFromURL(fileUrl, "_blank", 0, p()) + ' We may check if imported the correct file, by checking the number of columns + 'If oDoc.Sheets(0).Columns.Count = 2 Then + ' MsgBox "Single column psv" + 'End If + + if IsEmpty(oDoc)Then + ErrorLocal = "Failed to get Document for " & sInputFile + Exit Function + End If + + ErrorLocal = SondageValidateDoc(oDoc, sDocType) + If ErrorLocal <> "" Then + Exit Function + End If + SondageImportFile = oDoc +End Function + +Sub SondageGenerateReport(sondageReport, oDoc) + Print sondageReport.Title +End Sub + +Function SondageReadSettings() as Variant + Dim oDoc + Dim oSheet + Dim rangeAddress + Dim oRange + Dim iCell%, sKey$, sVal$ + Dim sonVars: sonVars = new Collection + + oSheet = ThisComponent.Sheets.getByName("Settings") + If IsNull(oSheet) Then + ErrorLocal$ = "Cannot find 'Settings' sheet" + Exit Function + End If + oRange = UsedRangeCursor(oSheet)'.RangeAddress + rangeAddress = oRange.RangeAddress + + For iCell = rangeAddress.StartRow To rangeAddress.EndRow + sKey = oRange.getCellByPosition(0, iCell).String + If sKey <> "" Then + sVal = oRange.getCellByPosition(1, iCell).String + sonVars.Add(item := sVal, key := sKey) + End If + Next 'iCell + SondageReadSettings = sonVars +End Function + +Sub SondageMain() + Dim sonReports() as Variant + Dim sonFields() as Variant + Dim sonReport, sonField, sonStatement + Dim iOpsLen%, iOp%, opId% + Dim sInputFile$: sInputFile = "C:\Users\bhara\Desktop\GetPendingOrderConsumerDetailsDateRange(36).csv" + Dim oDoc, oSheet, oUsedRange + + sonConf = SondageParseFieldConfiguration() + If ErrorLocal$ <> "" Then + MsgBox ErrorLocal$, 16 + Exit Sub + End If + + sonReports = sonConf.Reports + sonReport = SondageInferDocumentType(sonReports, sInputFile) + oDoc = SondageImportFile(sonReport, sInputFile, True, False) + + ' Copy the first, sheet if there is only one sheet in document + If oDoc.Sheets.Count = 1 Then + oDoc.Sheets.copyByName(oOrigSheet.Name, reportType & "WorkingCopy", 1) + End If + oSheet = oDoc.Sheets(1) + 'oSheet = oDoc.getSheets().getByIndex(0) + oUsedRange = UsedRangeCursor(oSheet) + If IsNull(oSheet) Then + MsgBox "Input file is null", 16 + Exit Sub + End If + + sonFields = sonReport.Fields + Dim str$ + + For Each sonField In sonFields + 'If Not IsEmpty(sonField) Then + str = sonReport.Title & ": Field Variables: " & sonField.Field & ", with width: " & sonField.Width & " with " & UBound(sonField.Statements) & " statements" + For Each sonStatement In sonField.Statements + iOpsLen = UBound(sonStatement.OpIds) + str = str & " has condition " & sonStatement.Cond & " for " & sonStatement.Operand & " " & "Operations: " & " " + Call SondageFilterColumn(oSheet, endColumn, endRow, "Area", orgCode & "_PortIn", sonStatement.Cond) + For iOp = 0 To iOpsLen + opId = sonStatement.OpIds(iOp) + str = str & opId + SondageCall(opId, oSheet, oRange) + Next + Print str + Next + Next +End Sub + +Sub SondageFilterColumns(oSheet) + Dim oFilterDesc + Dim filterRange, oRange + Dim oCursor, o, oColumnHeader, oDescriptor + Dim newColumn : newColumn = endColumn + 1 + Dim oFields(0) as new com.sun.star.sheet.TableFilterField + Dim filterCount as Long + Dim filterColumnName as String + Dim endRow& + Dim filterContent as Variant, filterOperator as Variant + + If IsMissing(filterOperator) Then filterOperator = com.sun.star.sheet.FilterOperator.EQUAL + Print filterOperator + + On Error Goto ErrorHandler + + oRange = oSheet.getCellRangeByPosition(newColumn, 0, newColumn, endRow) + oColumnHeader = oRange.getCellByPosition(0, 0) + oColumnHeader.setString("0") + + oDescriptor = oSheet.createReplaceDescriptor() + + filterRange = GetColumnRange(oSheet, endColumn, endRow, filterColumnName) + oFilterDesc = filterRange.createFilterDescriptor(True) + + With oFields(0) + .Field = filterRange.RangeAddress.StartColumn + .IsNumeric = IsNumeric(filterContent) + .Operator = filterOperator + .StringValue = filterContent + .NumericValue = filterContent + End With + + oFilterDesc.setFilterFields(oFields()) + oFilterDesc.ContainsHeader = True + oFilterDesc.UseRegularExpressions = False + oSheet.filter(oFilterDesc) + + ' TODO Check if there is a way to remove the 50,000 limit + oRange.fillSeries(com.sun.star.sheet.FillDirection.TO_BOTTOM, com.sun.star.sheet.FillMode.SIMPLE, 0, 1, 50000) + SortColumn(oSheet, 0, 1, newColumn, endRow, "0") + +ErrorHandler: + oSheet.filter(oSheet.createFilterDescriptor(True)) + oSheet.Columns.removeByIndex(newColumn, 1) + Reset +End Sub + +Function SondageExpandVariables(sCell$, sonVars as Variant, Optional varType$) as String + Dim sCellLen: sCellLen = Len(sCell) + Dim c$ + Dim si%, endIndex as Long + Dim extract$, varState as Boolean + + If IsMissing(varType) Then varType = "$" + + For si = 1 To sCellLen + c = Mid(sCell, si, 1) + If c = varType Then + varState = True + ElseIf varState = True Then + c = Mid(sCell, si, 1) + If c = "{" Then + extract = _ReadUntilCharacters(sCell, si + 1, Array("}"), endIndex) + Else + extract = _ReadUntilEndOrCharacter(sCell, si, " ", endIndex) + EndIf + If ErrorLocal$ <> "" Or endIndex > sCellLen Then + Print ErrorLocal$ + Exit Function + End If + SondageExpandVariables = SondageExpandVariables & sonVars.Item(extract) + si = endIndex + varState = False + Else + SondageExpandVariables = SondageExpandVariables & c + End If + Next 'si +End Function + +Function SondageGetCondTypeFromString(opCond$) as Integer + Dim condType% + condType = com.sun.star.sheet.ConditionOperator.EQUAL + SondageGetCondTypeFromString = condType + + If TypeName(opCond) <> "String" or Len(opCond) = 0Then + condType = com.sun.star.sheet.ConditionOperator.NONE + Exit Function + End If + + Select Case opCond + Case "<=" + condType = com.sun.star.sheet.ConditionOperator.LESS_EQUAL + Case ">=" + condType = com.sun.star.sheet.ConditionOperator.GREATER_EQUAL + Case "<>" + condType = com.sun.star.sheet.ConditionOperator.NOT_EQUAL + Case "><" + condType = com.sun.star.sheet.ConditionOperator.BETWEEN + Case "==" + condType = com.sun.star.sheet.ConditionOperator.EQUAL + Case Else + ' Check the first letter + Select Case Left(opCond, 1) + Case "<" + condType = com.sun.star.sheet.ConditionOperator.LESS + Case ">" + condType = com.sun.star.sheet.ConditionOperator.GREATER + Case "+" + condType = com.sun.star.sheet.ConditionOperator.FORMULA + End Select + End Select + SondageGetCondTypeFromString = condType +End Function + +Function _RemoveAllPrivateNamedRanges() + Dim aNamedRanges, sNamedRange, i% + aNamedRanges = ThisComponent.NamedRanges + For i = 0 To aNamedRanges.getCount() - 1 + sNamedRange = aNamedRanges.getByIndex(i).Name + If InStr(1, sNamedRange, "Sondage_", 0) = 1 Then ' sNamedRange starts with Sondage + aNamedRanges.removeByName(sNamedRange) + End If + Next i +End Function + +Function SondageParseFieldConfiguration() as SondageConfiguration + Dim reportNames, aValues + Dim oDoc, oSheet, oRange, oSearchRange + Dim startRow&, endRow&, endColumn&, iRow&, iCol& + Dim sCell, oCell + + ' Used for ReDim Statements and Fields + Dim sonConf as SondageConfiguration + Dim sonReports() as SondageReport + Dim sonStatements() as Variant + Dim sonFields() as Variant + Dim sonSettings() as Variant + Dim opIds() as Integer + + ' Remove OperationLimit later + Dim stTokens(200) as String + + Dim sonReport as new SondageReport + Dim sonField as new SondageField + Dim sonStatement as new SondageStatement + + Dim iWidth + Dim sStatements() as String, aHeaders() as String, sStatement$, sWidth$, opCond$ + Dim opTokens() as String + + SondageRegisterFunction("Standard.Sondage", "Select") + ' TODO Stub operation delete later + ' This is probably the modern verision of VLOOKUP that is based on column name + ' If something exists like this in Excel or Calc, just use its name + SondageRegisterFunction("Standard.Sondage", "ColumnOperation") + SondageRegisterFunction("Standard.Sondage", "ColorCell") + SondageRegisterFunction("Standard.Sondage", "ColorRow") + SondageRegisterFunction("Standard.Sondage", "Delete") + + oDoc = ThisComponent + oSheet = oDoc.getSheets().getByName("FieldConfiguration") + + oRange = UsedRangeCursor(oSheet) + startRow = 0 + endRow = oRange.RangeAddress.EndRow + endColumn = oRange.RangeAddress.EndColumn + + ReDim Preserve aHeaders(endColumn) as String + For iCol = 0 To endColumn + aHeaders(iCol) = oSheet.getCellByPosition(iCol, iRow).getString() + Next iCol + + For iRow = startRow To endRow + oCell = oSheet.getCellByPosition(0, iRow) + sCell = oCell.getText().String + If Left(sCell, 1) = "[" Then + ReDim Preserve sonReports(UBound(sonReports) + 1) as SondageReport + sonReport = sonReports(UBound(sonReports)) + sonReport.Fields = Array() + sonReport.Settings = Array() + ' TODO Restrict the Title to certain values + sonReport.Title = Mid(sCell, 2, Len(sCell) - 2) + oCell.CellStyle = "Heading1" + 'Print sonReport.Title + ElseIf Len(sonReport.Title) <> 0 Then + If Left(sCell, 1) = "@" Then + sonField = new SondageField + sonField.Field = Mid(sCell, 2) + + aValues = sonField.Values + ReDim aValues(endColumn) + For iCol = 0 To endColumn + aValues(iCol) = oSheet.getCellByPosition(iCol, iRow).getString() + Next iCol + sonField.Values = aValues + + sonField.Statements = Array() + sStatements = Split( _ + Trim(oSheet.getCellByPosition(1, iRow).getText().String), _ + CHR(13) _ + ) + sWidth = oSheet.getCellByPosition(2, iRow).getText().String + If sWidth = "0" Then + iWidth = 0 + ElseIf sWidth = "-1" or Len(sWidth) = 0 Then + ' Mark for deletion + iWidth = -1 + Else + iWidth = CLng(sWidth) + End If + sonField.Width = iWidth + For Each sStatement In sStatements + Dim ci: ci = 0 + Dim c$, pc$ + + For ci = 1 To Len(sStatement) + c = Mid(sStatement, ci, 1) + If c = "$" Then + ' Read the rest of the word and store in a variable + ' This variable should be replaced with content from a collection above + ' Essentially implementing a variable like function + End If + Next + stTokens = Split(sStatement, " then ") + sonStatement = new SondageStatement + + Dim stToken + Dim opToken$ + + If UBound(stTokens) = 0 Then + ' Operand Only + sonStatement.Operand = Trim(stTokens(0)) + 'Print sonReport.Title & "Operand Only: " & stTokens(0) + opTokens = Array() + ElseIf UBound(stTokens) > 0 Then + ' Cond then Op + opCond = Left(stTokens(0), 2) + + sonStatement.Cond = SondageGetCondTypeFromString(opCond) + + If sonStatement.Cond = com.sun.star.sheet.ConditionOperator.EQUAL Then + sonStatement.Operand = Trim(stTokens(0)) + Else + sonStatement.Operand = Trim(Right(stTokens(0), Len(stTokens(0)) - 2) ) + End If + End If 'UBound(stTokens) + + ' After Reading the condition, save the operation after finding the Id + If UBound(stTokens) > 0 Then + opTokens = Split(stTokens(1), ",") + For Each opToken In opTokens + Dim opPureTokens() as String + Dim opPureToken$ + Dim sonOpId%: sonOpId = -1 + opPureTokens = Split(Trim(opToken), "(") + If UBound(opPureTokens) = -1 Then + ErrorLocal$ = "FATAL: Error in row: " & iRow & ", Operation is malformed" + Exit Function + End If + opPureToken = Trim(opPureTokens(0)) + If Left(opPureToken, 1) = "@" Then + Print "This is a @ column thing: " & opPureToken + ' TODO Construct optoken and id and push the instructions to list + ' FIXME This does not do much now + sonOpId = SondageGetOpId("ColumnOperation") + Else + sonOpId = SondageGetOpId(opPureToken) + End If + If sonOpId = -1 Then + ErrorLocal$ = "FATAL: Cannot retrieve the operation " & opPureToken & " in row " & iRow + Exit Function + End If + opIds = sonStatement.OpIds + ReDim Preserve opIds(UBound(sonStatement.OpIds) + 1) as Integer + sonStatement.OpIds = opIds + sonStatement.OpIds(UBound(sonStatement.OpIds)) = sonOpId + Next 'opToken + Else + opTokens = Array(0) + End If + + sonStatements = sonField.Statements + ReDim Preserve sonStatements(UBound(sonField.Statements) + 1) as Variant + sonField.Statements = sonStatements + sonField.Statements(UBound(sonField.Statements)) = sonStatement + Next 'sOp + + sonFields = sonReport.Fields + ReDim Preserve sonFields(UBound(sonFields) + 1) as Variant + sonReport.Fields = sonFields + sonReport.Fields(UBound(sonReport.Fields)) = sonField + Else ' If != [ and != @ + sonSettings = sonReport.Settings + ReDim Preserve sonSettings(UBound(sonSettings) + 1) as Variant + sonSettings(UBound(sonSettings)) = CreateObject("com.sun.star.beans.PropertyValue") + sonSettings(UBound(sonSettings)).Name = sCell + sonSettings(UBound(sonSettings)).Value = oSheet.getCellByPosition(1, iRow).getText().String + oCell.CellStyle = "Card" + sonReport.Settings = sonSettings + End If + Else + MsgBox "Syntax Error: should start with [HEADER] element", 16 + Exit Function + End If + Next 'iRow + sonConf.Reports = sonReports + sonConf.Headers = aHeaders + SondageParseFieldConfiguration = sonConf +End Function +
: bharatvaj/lobasic-macros