Magento 1.6, Google Shopping / Products / Content - magento-1.6

Magento 1.6 was out at the beginning of this week but upgrading from 1.5.1 with the mage_googleshopping extension (http://www.magentocommerce.com/magento-connect/Magento+Core/extension/6887/mage_googleshopping) up to v.1.6 was not something feasible.
mage_googleshopping remained compatible only with 1.5. Any working alternative to have the mage_googleshopping extension available on a clean Magento 1.6 installation or we have to wait for a stable extension release which goes with v.1.6?
Cheers,
Bogdan

I have browsed the Internet and searched for a problem to this, eventually I've turned into this script which runes separately but it connects to the Magento DB. The scripts generates the file, which can be uploaded following a schedule to Google.
Besides the fact that the script is totally editable, you can fully monitor all the processes behind it. The Magento script still can't be removed from a 1.6 Magento version.
The script wasn't developed by me but I did update it according with the latest rules enforced from 22/9/2011 by Google.
<code>
<?php
define('SAVE_FEED_LOCATION','google_base_feed.txt');
set_time_limit(1800);
require_once '../app/Mage.php';
Mage::app('default');
try{
$handle = fopen(SAVE_FEED_LOCATION, 'w');
$heading = array('id','mpn','title','description','link','image_link','price','brand','product_type','condition', 'google_product_category', 'manufacturer', 'availability');
$feed_line=implode("\t", $heading)."\r\n";
fwrite($handle, $feed_line);
$products = Mage::getModel('catalog/product')->getCollection();
$products->addAttributeToFilter('status', 1);
$products->addAttributeToFilter('visibility', 4);
$products->addAttributeToSelect('*');
$prodIds=$products->getAllIds();
$product = Mage::getModel('catalog/product');
$counter_test = 0;
foreach($prodIds as $productId) {
if (++$counter_test < 30000){
$product->load($productId);
$product_data = array();
$product_data['sku'] = $product->getSku();
$product_data['mpn'] = $product->getSku();
$title_temp = $product->getName();
if (strlen($title_temp) > 70){
$title_temp = str_replace("Supply", "", $title_temp);
$title_temp = str_replace(" ", " ", $title_temp);
}
$product_data['title'] = $title_temp;
$product_data['description'] = substr(iconv("UTF-8","UTF-8//IGNORE",$product->getDescription()), 0, 900);
$product_data['Deeplink'] = "http://www.directmall.co.uk/".$product->getUrlPath();
$product_data['image_link'] = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA).'catalog/product'.$product->getImage();
$price_temp = round($product->getPrice(),2);
$product_data['price'] = round($product->getPrice(),2) + 5;
$product_data['brand'] = $product->getData('brand');
$product_data['product_type'] = 'Laptop Chargers & Adapters';
$product_data['condition'] = "new";
$product_data['category'] = $product_data['brand'];
$product_data['manufacturer'] = $product_data['brand'];
$product_data['availability'] = "in stock";
foreach($product_data as $k=>$val){
$bad=array('"',"\r\n","\n","\r","\t");
$good=array(""," "," "," ","");
$product_data[$k] = '"'.str_replace($bad,$good,$val).'"';
}
echo $counter_test . " ";
$feed_line = implode("\t", $product_data)."\r\n";
fwrite($handle, $feed_line);
fflush($handle);
}
}
fclose($handle);
}
catch(Exception $e){
die($e->getMessage());
}</code>
Change www.directmall.co.uk into what you need.
Assign the proper permissions.
Fully updated according with Google's requirements.

Related

How to place order with paypal express checkout in Magento 1.9 Rest api

I made payment via paypal.I am new in this framework. Don't have any idea, in which table I have to update. I f you guys give some ideas about implementation flow then it will be very helpful.
Below I have tried yet
$quoteId=128551;
$customerId=29395;
$store = Mage::app()->getStore();
$website = Mage::app()->getWebsite();
$quote = Mage::getModel('sales/quote')->setStoreId($store->getStoreId())->load($quoteId);
$customer = Mage::getModel('customer/customer')->load($customerId);
//Assign the customer to quote
$quote->assignCustomer($customer);
//Set currency for the quote
$quote->setCurrency(Mage::app()->getStore()->getBaseCurrencyCode());
$billingAddressId=29971;
$customAddress = Mage::getModel('customer/address')->load($billingAddressId);
$quoteShippingAddress = Mage::getModel('sales/quote_address');
$quoteShippingAddress->setData($customAddress);
$quote->setShippingAddress($quoteShippingAddress);
// fixed shipping method
$quote->getShippingAddress()->setShippingMethod('freeshipping_freeshipping');
$quote->getShippingAddress()->setPaymentMethod('paypal_express');
$quote->getShippingAddress()->setCollectShippingRates(true);
$quote->getShippingAddress()->collectShippingRates();
//Set payment method for the quote
$quote->getPayment()->importData(array('method' => 'paypal_express'));
try {
$quote->collectTotals()->save();
//Create order from quote
$service = Mage::getModel('sales/service_quote', $quote);
$service->submitAll();
$increment_id = $service->getOrder()->getRealOrderId();
$orderId = $service->getOrder()->getId();
Mage::getSingleton('checkout/session')
->setLastQuoteId($quote->getId())
->setLastSuccessQuoteId($quote->getId())
->clearHelperData();
echo $msg = 'Order has been successfully created.';
} catch (Exception $e) {
$msg = $e->getMessage();
}

html2PDF work on local , but wont create a pdf on server (blank page)

I'm coding since 2 year and learning cakePHP since a few weeks , and i'm actually in internship trying to deploy a website.
I have trouble with Html2PDF , as it work well on the local version, but not on the server (a new page is opened , with the right url , but the pdf is blank).
the newly opened blank page contain this error message (displayed on the f12 debug console) :
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
the Html2PDF code :
function exportFicheVie() {
$Equipement = $this->Equipement->getEquipement($_GET['Id']);
$PersonnesRessources = $this->Equipement->getPersonnesRessourcesOfEquipement($_GET['Id']);
$Prestataire = $this->Equipement->getPrestataireOfEquipement($_GET['Id']);
$Verifications = $this->Equipement->getVerif($_GET['Id']);
$Contrat = $this->Equipement->getContrat($_GET['Id']);
if (count($Contrat)==0)
$Contrat[0] = "Non";
$Vide = array(
"Prenom"=>"",
"Nom"=>"",
"NumPoste"=>"",
"Mail"=>"",
"Adresse"=>"",
"Fax"=>"",
"Telephone"=>""
);
if (count($PersonnesRessources)==0)
$PersonnesRessources = array($Vide, $Vide);
elseif (count($PersonnesRessources)==1)
$PersonnesRessources[] = $Vide;
if (count($Prestataire)==0)
$Prestataire = $Vide;
// convert in PDF
require_once(__DIR__.'/../webroot/theme/plugins/html2pdf/vendor/autoload.php');
try
{
$Html2pdf = new HTML2PDF('P', 'A4', 'fr');
$NbPages = $Html2pdf->pdf->getAliasNbPages();
$NumPage = $Html2pdf->pdf->getAliasNumPage();
include($Html2pdf->getHtmlFromPage(__DIR__.'/../View/Equipements/export_fiche_vie.ctp', $Equipement, $PersonnesRessources, $Prestataire, $NbPages, $NumPage));
$Content = ob_get_clean();
//$Html2pdf->setModeDebug();
$Html2pdf->addFont('Century Gothic', 'normal', __DIR__.'/../webroot/theme/plugins/html2pdf/vendor/tecnickcom/tcpdf/fonts/centurygothic.php');
$Html2pdf->addFont('Century Gothic Bold', 'normal', __DIR__.'/../webroot/theme/plugins/html2pdf/vendor/tecnickcom/tcpdf/fonts/centurygothic.php');
$Html2pdf->setDefaultFont('Century Gothic');
$Html2pdf->writeHTML($Content, isset($_GET['vuehtml']));
$Html2pdf->Output('\FS-'.$_GET['Id'].'.pdf');
}
catch(HTML2PDF_exception $e)
{
echo $e;
exit;
}
}
I don't expect an miracle answer , because this question appear a lot without any clear solution , but any hint, advice or supposition would be welcome .it's my first time putting a website on a real server they might be some obvious things I miss.

Snappy / WKHTMLtoPDF - How to change the save folder

I'm using Laravel with the snappy wrapper. It is all working except that it saves the PDF's into the public folder. I want it to go to a different folder. There is nothing obvious on the snappy git site, nor in the config. And the wkhtlptopdf docs are very sparse imho. How do I change the $pdf->save() statement so it goes where I want it to go ?
My PDF is generated by laravel like this:
if( $email == 'email'){
$quotation = $this->quotation->get_PdfQuote($ref);
$pdf = PDF::loadView('quotations/pdf_quotation',compact('quotation') );
$pdf->save($ref.'.pdf'); //THIS SAVES INTO THE PUBLIC FOLDER.
$title = 'Your Quotation';
$firstname = $customer['firstname1'];
$pathtoFile = '/var/www/auburntree/public/'.$ref.'.pdf';
Mail::send('emails.quotation', ['title' => $title, 'firstname'=>$firstname ], function ($m) use($customer,$pathtoFile) {
$m->from('myemail#gmail.com', 'Auburntree');
$m->to($customer['email1'],($customer['firstname1'] . $customer['lastname1']))->subject('Your Quotation');
$m->attach($pathtoFile);
});
Flash::success('The Quote Has Been Saved. An Email has ben sent to the customer ');
return redirect ('quotes');
} else
Ok, I hope this helps someone else.
$quotation = $this->quotation->get_PdfQuote($ref); //pulled in from DB
$pdf = PDF::loadView('quotations/pdf_quotation',compact('quotation') );
$filename = base_path('public/pdf/'.$ref.'.pdf');
$pdf->save($filename);

Google API for getting maximum number of licenses in a Google Apps domain

I have a Google Apps Script function used for setting up accounts for new employees in our Google Apps domain.
The first thing it does is makes calls to the Google Admin Settings API and retrieves the currentNumberOfUsers and maximumNumberOfUsers, so it can see if there are available seats (otherwise a subsequent step where the user is created using the Admin SDK Directory API would fail).
It's been working fine until recently when our domain had to migrate from Postini to Google Vault for email archiving.
Before the migration, when creating a Google Apps user using the Admin SDK Directory API, it would increment the currentNumberOfUsers by 1 and the new user account user would automatically have access to all Google Apps services.
Now after the migration, when creating a Google Apps user, they aren't automatically assigned a "license," so I modified my script to use the Enterprise License Manager API and now it assigns a "Google-Apps-For-Business" license. That works fine.
However, the currentNumberOfUsers is now different from the number of assigned licenses, and "Google-Apps-For-Business" is only one of several different types of licenses available.
I can get the current number of assigned "Google-Apps-For-Business" licenses by running this:
var currentXml = AdminLicenseManager.LicenseAssignments.listForProductAndSku('Google-Apps', 'Google-Apps-For-Business', 'domain.com', {maxResults: 1000});
var current = currentXml.items.toString().match(/\/sku\/Google-Apps-For-Business\/user\//g).length;
But the number that produces is different from currentNumberOfUsers.
All I really need to do now is get the maximum number of owned "Google-Apps-For-Business" licenses so the new employee setup script can determine whether there are any available.
I checked the API Reference documentation for the following APIs but...
Enterprise License Manager API → Doesn't have a method for getting the maximum or available number of licenses.
Google Admin Settings API → Doesn't deal with licenses, only "users."
Admin SDK Directory API User resource → Doesn't deal with licenses.
Google Apps Reseller API → This API seems to have what I need, but it's only for Reseller accounts.
I know I can program my new employee setup script to just have a try/catch seeing if it would be able to create the user and assign the license, and end the script execution gracefully if it can't, but that doesn't seem efficient.
Also, part of the old script was that if there were less than X seats available, it would email me a heads-up to order more. I can program a loop that attempts to repeatedly create dummy users and assign them licenses and count the number of times it can do that before it fails, then delete all the dummy users, but, once again, that's not efficient at all.
Any ideas?
Update 3/11/2020: Since the Admin Settings API had shut down a few years ago I've been using the Enterprise License Manager API to get the current number of used licenses, like this:
function getCurrentNumberOfUsedGoogleLicenses(skuId) {
var success = false, error = null, count = 0;
var adminEmail = 'admin#domain.com';
var gSuiteDomain = adminEmail.split('#')[1];
// for more information on the domain-wide delegation:
// https://developers.google.com/identity/protocols/OAuth2ServiceAccount#delegatingauthority
// the getDomainWideDelegationService() function uses this:
// https://github.com/gsuitedevs/apps-script-oauth2
var service = getDomainWideDelegationService('EnterpriseLicenseManager: ', 'https://www.googleapis.com/auth/apps.licensing', adminEmail);
if (skuId == 'Google-Apps-Unlimited') var productId = 'Google-Apps';
else return { success: success, error: "Unsupported skuId", count: count };
var requestBody = {};
requestBody.headers = {'Authorization': 'Bearer ' + service.getAccessToken()};
requestBody.method = "GET";
requestBody.muteHttpExceptions = false;
var data, pageToken, pageTokenString;
var maxAttempts = 5;
var currentAttempts = 0;
var pauseBetweenAttemptsSeconds = 3;
loopThroughPages:
do {
if (typeof pageToken === 'undefined') pageTokenString = "";
else pageTokenString = "&pageToken=" + encodeURIComponent(pageToken);
var url = 'https://www.googleapis.com/apps/licensing/v1/product/' + productId + '/sku/' + skuId + '/users?maxResults=1000&customerId=' + gSuiteDomain + pageTokenString;
try {
currentAttempts++;
var response = UrlFetchApp.fetch(url, requestBody);
var result = JSON.parse(response.getContentText());
if (result.items) {
var licenseAssignments = result.items;
var licenseAssignmentsString = '';
for (var i = 0; i < licenseAssignments.length; i++) {
licenseAssignmentsString += JSON.stringify(licenseAssignments[i]);
}
if (skuId == 'Google-Apps-Unlimited') count += licenseAssignmentsString.match(/\/sku\/Google-Apps-Unlimited\/user\//g).length;
currentAttempts = 0; // reset currentAttempts before the next page
}
} catch(e) {
error = "Error: " + e.message;
if (currentAttempts >= maxAttempts) {
error = 'Exceeded ' + maxAttempts + ' attempts to get license count: ' + error;
break loopThroughPages;
}
} // end of try catch
if (result) pageToken = result.nextPageToken;
} while (pageToken);
if (!error) success = true;
return { success: success, error: error, count: count };
}
However, there still does not appear to be a way to get the maximum number available to the domain using this API.
Use CustomerUsageReports.
jay0lee is kind enough to provide the GAM source code in Python. I crudely modified the doGetCustomerInfo() function into Apps Script thusly:
function getNumberOfLicenses() {
var tryDate = new Date();
var dateString = tryDate.getFullYear().toString() + "-" + (tryDate.getMonth() + 1).toString() + "-" + tryDate.getDate().toString();
while (true) {
try {
var response = AdminReports.CustomerUsageReports.get(dateString,{parameters : "accounts:gsuite_basic_total_licenses,accounts:gsuite_basic_used_licenses"});
break;
} catch(e) {
//Logger.log(e.warnings.toString());
tryDate.setDate(tryDate.getDate()-1);
dateString = tryDate.getFullYear().toString() + "-" + (tryDate.getMonth() + 1).toString() + "-" + tryDate.getDate().toString();
continue;
}
};
var availLicenseCount = response.usageReports[0].parameters[0].intValue;
var usedLicenseCount = response.usageReports[0].parameters[1].intValue;
Logger.log("Available licenses:" + availLicenseCount.toString());
Logger.log("Used licenses:" + usedLicenseCount.toString());
return availLicenseCount;
}
I would recommend exploring GAM which is a tool that gives command line access to the administration functions of your domain.

Efficient Way to do batch import XMI in Enterprise Architect

Our team are using Enterprise Architect version 10 and SVN for the repository.
Because the EAP file size is quite big (e.g. 80 MB), we exports each packages into separate XMI and stored it into SVN. The EAP file itself is committed after some milestone. The problem is to synchronize the EAP file with work from co worker during development, we need to import lots of XMI (e.g. total can be 500 files).
I know that once the EAP file is updated, we can use Package Control -> Get All Latest. Therefore this problem occurs only during parallel development.
We have used keyboard shorcuts to do the import as follow:
Ctrl+Alt+I (Import package from XMI file)
Select the file name to import
Alt+I (Import)
Enter (Yes)
Repeat step number 2 to 4 until module finished
But still, importing hundreds of file is inefficient.
I've checked that the Control Package has Batch Import/Export. The batch import/export are working when I explicitly hard-coded the XMI Filename, but the options are not available if using version control (batch import/export options are greyed).
Is there any better ways to synchronize EAP and XMI files?
There is a scripting interface in EA. You might be able to automate the import using that. I've not used it but its probably quite good.
I'm not sure I fully understand your working environment, but I have some general points that may be of interest. It might be that if you use EA in a different way (especially my first point below), the need to batch import might go away.
Multiworker
First, multiple people can work on the same EAP file at a time. The EAP file is nothing more than an Access database file, and EA uses locking to stop multiple people editing the same package at the same time. But you can comfortably have multiple people editing different packages in one EAP file at the same time. Putting the EAP file on a file share somewhere is a good way of doing it.
Inbuilt Revision Control
Secondly, EA can interact directly with SVN (and other revision control systems). See this. In short, you can setup your EAP file so that individual packages (and everything below them) is SVN controlled. You can then check out an individual package, edit it, check it back in. Or indeed you can check out the whole branch below a package (including sub packages that are themselves SVN controlled).
Underneath the hood EA is importing and exporting XMI files and checking them in and out of SVN, whilst the EAP file is always the head revision. Just like what you're doing by hand, but automated. It makes sense given that you can all use the one single EAP file. You do have to be a bit careful rolling back - links originating from objects in older versions of one package might be pointing at objects that no longer exist (but you can look at the import log errors to see if this is the case). It takes a bit of getting used to, but it works pretty well.
There's also the built in package baselining functionality - that might be all you need anyway, and works quite well especially if you're all using the same EAP file.
Bigger Database Engine
Thirdly, you don't have to have an EAP file at all. The model's database can be in any suitable database system (MySQL, SQL Server, Oracle, etc). So that gives you all sorts of options for scaling up how its used, what its like over a WAN/Internet, etc.
In short Sparx have been quite sensible about how EA can be used in a multi-worker environment, and its worth exploiting that.
I have created the EA script using JScript for the automation
Here is the script to do the export:
!INC Local Scripts.EAConstants-JScript
/*
* Script Name : Export List of SVN Packages
* Author : SDK
* Purpose : Export a package and all of its subpackages information related to version
* controlled. The exported file then can be used to automatically import
* the XMIs
* Date : 30 July 2013
* HOW TO USE : 1. Select the package that you would like to export in the Project Browser
* 2. Change the output filepath in this script if necessary.
* By default it is "D:\\EAOutput.txt"
* 3. Send the output file to your colleague who wanted to import the XMIs
*/
var f;
function main()
{
// UPDATE THE FOLLOWING OUTPUT FILE PATH IF NECESSARY
var filename = "D:\\EAOutput.txt";
var ForReading = 1, ForWriting = 2, ForAppending = 8;
Repository.EnsureOutputVisible( "Script" );
Repository.ClearOutput( "Script" );
Session.Output("Start generating output...please wait...");
var treeSelectedType = Repository.GetTreeSelectedItemType();
switch ( treeSelectedType )
{
case otPackage:
{
var fso = new ActiveXObject("Scripting.FileSystemObject");
f = fso.OpenTextFile(filename, ForWriting, true);
var selectedObject as EA.Package;
selectedObject = Repository.GetContextObject();
reportPackage(selectedObject);
loopChildPackages(selectedObject);
f.Close();
Session.Output( "Done! Check your output at " + filename);
break;
}
default:
{
Session.Prompt( "This script does not support items of this type.", promptOK );
}
}
}
function loopChildPackages(thePackage)
{
for (var j = 0 ; j < thePackage.Packages.Count; j++)
{
var child as EA.Package;
child = thePackage.Packages.GetAt(j);
reportPackage(child);
loopChildPackages(child);
}
}
function getParentPath(childPackage)
{
if (childPackage.ParentID != 0)
{
var parentPackage as EA.Package;
parentPackage = Repository.GetPackageByID(childPackage.ParentID);
return getParentPath(parentPackage) + "/" + parentPackage.Name;
}
return "";
}
function reportPackage(thePackage)
{
f.WriteLine("GUID=" + thePackage.PackageGUID + ";"
+ "NAME=" + thePackage.Name + ";"
+ "VCCFG=" + getVCCFG(thePackage) + ";"
+ "XML=" + thePackage.XMLPath + ";"
+ "PARENT=" + getParentPath(thePackage).substring(1) + ";"
);
}
function getVCCFG(thePackage)
{
if (thePackage.IsVersionControlled)
{
var array = new Array();
array = (thePackage.Flags).split(";");
for (var z = 0 ; z < array.length; z++)
{
var pos = array[z].indexOf('=');
if (pos > 0)
{
var key = array[z].substring(0, pos);
var value = array[z].substring(pos + 1);
if (key=="VCCFG")
{
return (value);
}
}
}
}
return "";
}
main();
And the script to do the import:
!INC Local Scripts.EAConstants-JScript
/*
* Script Name : Import List Of SVN Packages
* Author : SDK
* Purpose : Imports a package with all of its sub packages generated from
* "Export List Of SVN Packages" script
* Date : 01 Aug 2013
* HOW TO USE : 1. Get the output file generated by "Export List Of SVN Packages" script
* from your colleague
* 2. Get the XMIs in the SVN local copy
* 3. Change the path to the output file in this script if necessary (var filename).
* By default it is "D:\\EAOutput.txt"
* 4. Change the path to local SVN
* 5. Run the script
*/
var f;
var svnPath;
function main()
{
// CHANGE THE FOLLOWING TWO LINES ACCORDING TO YOUR INPUT AND LOCAL SVN COPY
var filename = "D:\\EAOutput.txt";
svnPath = "D:\\svn.xxx.com\\yyy\\docs\\design\\";
var ForReading = 1, ForWriting = 2, ForAppending = 8;
Repository.EnsureOutputVisible( "Script" );
Repository.ClearOutput( "Script" );
Session.Output("[INFO] Start importing packages from " + filename + ". Please wait...");
var fso = new ActiveXObject("Scripting.FileSystemObject");
f = fso.OpenTextFile(filename, ForReading);
// Read from the file and display the results.
while (!f.AtEndOfStream)
{
var r = f.ReadLine();
parseLine(r);
Session.Output("--------------------------------------------------------------------------------");
}
f.Close();
Session.Output("[INFO] Finished");
}
function parseLine(line)
{
Session.Output("[INFO] Parsing " + line);
var array = new Array();
array = (line).split(";");
var guid;
var name;
var isVersionControlled;
var xmlPath;
var parentPath;
isVersionControlled = false;
xmlPath = "";
for (var z = 0 ; z < array.length; z++)
{
var pos = array[z].indexOf('=');
if (pos > 0)
{
var key = array[z].substring(0, pos);
var value = array[z].substring(pos + 1);
if (key=="GUID") {
guid = value;
} else if (key=="NAME") {
name = value;
} else if (key=="VCCFG") {
if (value != "") {
isVersionControlled = true;
}
} else if (key=="XML") {
if (isVersionControlled) {
xmlPath = value;
}
} else if (key=="PARENT") {
parentPath = value;
}
}
}
// Quick check for target if already exist to speed up process
var targetPackage as EA.Package;
targetPackage = Repository.GetPackageByGuid(guid);
if (targetPackage != null)
{
// target exists, do not do anything
Session.Output("[DEBUG] Target package \"" + name + "\" already exist");
return;
}
var paths = new Array();
var packages = new Array(paths.Count);
for (var i = 0; i < paths.Count; i++)
{
packages[i] = null;
}
paths = (parentPath).split("/");
if (paths.Count < 2)
{
Session.Output("[INFO] Skipped root or level1");
return;
}
packages[0] = selectRoot(paths[0]);
packages[1] = selectPackage(packages[0], paths[1]);
if (packages[1] == null)
{
Session.Output("[ERROR] Cannot find " + paths[0] + "/" + paths[1] + "in Project Browser");
return;
}
for (var j = 2; j < paths.length; j++)
{
packages[j] = selectPackage(packages[j - 1], paths[j]);
if (packages[j] == null)
{
Session.Output("[DEBUG] Creating " + packages[j].Name);
// create the parent package
var parent as EA.Package;
parent = Repository.GetPackageByGuid(packages[j-1].PackageGUID);
packages[j] = parent.Packages.AddNew(paths[j], "");
packages[j].Update();
parent.Update();
parent.Packages.Refresh();
break;
}
}
// Check if name (package to import) already exist or not
var targetPackage = selectPackage(packages[paths.length - 1], name);
if (targetPackage == null)
{
if (xmlPath == "")
{
Session.Output("[DEBUG] Creating " + name);
// The package is not SVN controlled
var newPackage as EA.Package;
newPackage = packages[paths.length - 1].Packages.AddNew(name,"");
Session.Output("New GUID = " + newPackage.PackageGUID);
newPackage.Update();
packages[paths.length - 1].Update();
packages[paths.length - 1].Packages.Refresh();
}
else
{
// The package is not SVN controlled
Session.Output("[DEBUG] Need to import: " + svnPath + xmlPath);
var project as EA.Project;
project = Repository.GetProjectInterface;
var result;
Session.Output("GUID = " + packages[paths.length - 1].PackageGUID);
Session.Output("GUID XML = " + project.GUIDtoXML(packages[paths.length - 1].PackageGUID));
Session.Output("XMI file = " + svnPath + xmlPath);
result = project.ImportPackageXMI(project.GUIDtoXML(packages[paths.length - 1].PackageGUID), svnPath + xmlPath, 1, 0);
Session.Output(result);
packages[paths.length - 1].Update();
packages[paths.length - 1].Packages.Refresh();
}
}
else
{
// target exists, do not do anything
Session.Output("[DEBUG] Target package \"" + name + "\" already exist");
}
}
function selectPackage(thePackage, childName)
{
var childPackage as EA.Package;
childPackage = null;
if (thePackage == null)
return null;
for (var i = 0; i < thePackage.Packages.Count; i++)
{
childPackage = thePackage.Packages.GetAt(i);
if (childPackage.Name == childName)
{
Session.Output("[DEBUG] Found " + childName);
return childPackage;
}
}
Session.Output("[DEBUG] Cannot find " + childName);
return null;
}
function selectRoot(rootName)
{
for (var y = 0; y < Repository.Models.Count; y++)
{
root = Repository.Models.GetAt(y);
if (root.Name == rootName)
{
return root;
}
}
return null;
}
main();